diff --git a/CLAUDE.md b/CLAUDE.md index 5352a9f..fe1e161 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -45,12 +45,13 @@ dotnet add test/LayeredCraft.Cdk.Constructs.Tests/ package PackageName **LambdaFunctionConstruct** (`src/LayeredCraft.Cdk.Constructs/LambdaFunctionConstruct.cs`) - Main CDK construct that creates Lambda functions with comprehensive configuration -- Automatically creates IAM roles and policies with CloudWatch Logs permissions +- Automatically creates an IAM role whose logging policy is scoped to the construct's own log group (`logs:CreateLogStream`, `logs:PutLogEvents` on the log group ARN) +- Code from a local asset (`AssetPath`) or any `Code` source such as an S3 artifact (`Code.FromBucketV2`); exactly one is required - Supports configurable OpenTelemetry layer integration via AWS managed layer (disabled by default) - Configurable OTEL layer version and architecture (amd64/arm64) - Supports AWS Lambda SnapStart for improved cold start performance -- Creates function versions and aliases for deployment management -- Handles Lambda permissions for multiple targets (function, version, alias) +- Creates a version on every deployment and an alias (`AliasName`, default `live`); both are public (`Version`, `Alias`) +- Applies each `LambdaPermission` to its `Targets` (`LambdaPermissionTargets` flags; default alias only) **WebFunctionConstruct** (`src/LayeredCraft.Cdk.Constructs/WebFunctionConstruct.cs`) - Creates an AWS Lambda Web Function from a versioned S3 artifact (`WebFunctionCode.FromBucket`), plus its immutable revision, default endpoint, execution role (optional), logging (optional), and the function's **single** resource-based policy @@ -80,7 +81,7 @@ dotnet add test/LayeredCraft.Cdk.Constructs.Tests/ package PackageName **Configuration Models** (`src/LayeredCraft.Cdk.Constructs/Models/`) - `LambdaFunctionConstructProps`: Main configuration interface and record for Lambda construct -- `LambdaPermission`: Record for defining Lambda invocation permissions +- `LambdaPermission`: Record for defining Lambda invocation permissions; `Targets` (`LambdaPermissionTargets`) selects function, version and/or alias (default alias) - `StaticSiteConstructProps`: Configuration interface and record for static site construct - `DynamoDbTableConstructProps`: Configuration interface and record for DynamoDB table construct - `WebFunctionConstructProps`, `WebFunctionCode`/`WebFunctionCodeFromBucketOptions`/`WebFunctionCodeBucketPolicy`, `WebFunctionEndpointOptions`/`IWebFunctionEndpointOptions`, `WebFunctionEndpointAttributes`, `WebFunctionLogs`, `WebFunctionRuntime`, `WebFunctionAuthType`, `WebFunctionEndpointType`, `WebFunctionCallerPolicy`/`WebFunctionInvokeGrantOptions`, `WebFunctionOriginProps`/`WebFunctionOriginWithOacProps`/`WebFunctionOriginPermissions`: Web Function configuration (see `docs/constructs/web-function.md`) @@ -93,9 +94,9 @@ dotnet add test/LayeredCraft.Cdk.Constructs.Tests/ package PackageName 1. **Construct Pattern**: Uses AWS CDK construct pattern for reusable infrastructure components 2. **Interface + Record Pattern**: Props classes use both interface and record for flexibility and immutability -3. **Multi-Target Permissions**: Automatically applies permissions to function, version, and alias +3. **Least-Privilege Permissions**: Invocation permissions go on the alias by default; function and version targets are opt-in 4. **OpenTelemetry Integration**: Configurable support for AWS OTEL collector layer with version and architecture options -5. **Versioning Strategy**: Creates new versions on every deployment with "live" alias +5. **Versioning Strategy**: Creates new versions on every deployment with a configurable alias (default "live") ### Target Frameworks - .NET 10 and .NET 11 diff --git a/README.md b/README.md index 077414c..b92f7f2 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,7 @@ public class MyStack : Stack - **[DynamoDB Table Construct](https://layeredcraft.github.io/cdk-constructs/constructs/dynamodb-table)** - Production-ready DynamoDB tables with streams and indexes - **[Cognito User Pool Construct](https://layeredcraft.github.io/cdk-constructs/constructs/cognito-user-pool)** - Full-featured Cognito user pool with custom domains, OAuth clients, and branding - **[Testing Guide](https://layeredcraft.github.io/cdk-constructs/testing)** - Comprehensive testing utilities and patterns +- **[Upgrading to 3.0](https://layeredcraft.github.io/cdk-constructs/migration/v3)** - Breaking changes and migration steps from 2.x - **[Examples](https://layeredcraft.github.io/cdk-constructs/examples)** - Real-world usage examples and patterns - **[Web Function Workloads](https://layeredcraft.github.io/cdk-constructs/examples/web-functions)** - Next.js, ASP.NET Core, and Blazor Static SSR recipes diff --git a/docs/constructs/lambda-function.md b/docs/constructs/lambda-function.md index 8479258..681f7b8 100644 --- a/docs/constructs/lambda-function.md +++ b/docs/constructs/lambda-function.md @@ -5,12 +5,13 @@ The `LambdaFunctionConstruct` provides a comprehensive, production-ready Lambda ## :rocket: Features - **:chart_with_upwards_trend: OpenTelemetry Integration**: Configurable AWS OpenTelemetry collector layer with version and architecture support -- **:shield: IAM Management**: Automatic role and policy creation with CloudWatch Logs permissions +- **:shield: IAM Management**: Automatic role and policy creation with a CloudWatch Logs policy scoped to the construct's own log group - **:gear: Environment Configuration**: Easy environment variable management - **:link: Function URLs**: Optional HTTP endpoint generation - **:rocket: SnapStart Support**: Improved cold start performance for Java runtimes -- **:label: Versioning & Aliases**: Automatic version management with "live" alias -- **:key: Lambda Permissions**: Multi-target permission management (function, version, alias) +- **:label: Versioning & Aliases**: Automatic version management with a configurable alias name (default `"live"`) +- **:key: Lambda Permissions**: Permission targets per permission (function, version, alias) with an alias-only default +- **:package: Artifact Sources**: Deploy from a local asset (`AssetPath`) or existing Lambda code such as an S3 object (`Code`) ## Basic Usage @@ -44,14 +45,23 @@ public class MyStack : Stack |----------|------|-------------| | `FunctionName` | `string` | Base name of the Lambda function | | `FunctionSuffix` | `string` | Suffix appended to function name (e.g., "prod", "dev") | -| `AssetPath` | `string` | Path to Lambda deployment package | | `RoleName` | `string` | Name of the IAM role | | `PolicyName` | `string` | Name of the IAM policy | +### Artifact Code (exactly one required) + +Exactly one of `AssetPath` or `Code` must be set. Providing both or neither throws an `ArgumentException` at construction. + +| Property | Type | Description | +|----------|------|-------------| +| `AssetPath` | `string?` | Path to a local Lambda deployment package (asset) | +| `Code` | `Code?` | Existing Lambda code, for example `Code.FromBucketV2(bucket, key, options)` | + ### Optional Properties | Property | Type | Default | Description | |----------|------|---------|-------------| +| `AliasName` | `string` | `"live"` | Name of the alias pointing at the published version | | `MemorySize` | `double` | `1024` | Memory allocation in MB | | `TimeoutInSeconds` | `double` | `6` | Function timeout in seconds | | `PolicyStatements` | `PolicyStatement[]` | `[]` | Additional IAM policy statements | @@ -59,10 +69,17 @@ public class MyStack : Stack | `IncludeOtelLayer` | `bool` | `false` | Enable OpenTelemetry layer | | `OtelLayerVersion` | `string` | `"0-117-0"` | OpenTelemetry layer version | | `Architecture` | `string` | `"amd64"` | Lambda architecture applied to both the function and OTEL layer (amd64/arm64) | -| `Permissions` | `List` | `[]` | Lambda invocation permissions | +| `Permissions` | `List` | `[]` | Lambda invocation permissions, each with its own `Targets` | | `EnableSnapStart` | `bool` | `false` | Enable SnapStart (Java runtimes only; the default `PROVIDED_AL2023` runtime is not eligible) | | `GenerateUrl` | `bool` | `false` | Generate Function URL for HTTP access | +!!! warning "Breaking changes in 3.0.0" + - Lambda permissions now default to the **alias only**; the function and version permission + resources are no longer created unless `Targets` requests them. + - The execution-role logging policy is scoped to the construct's own log group ARN. It no longer + grants `logs:CreateLogGroup` or `logs:TagResource` and no longer uses a wildcard log-group resource. + - `AssetPath` is no longer required: provide exactly one of `AssetPath` or `Code`. + ## Advanced Examples ### Lambda with DynamoDB Access @@ -112,12 +129,16 @@ var functionUrl = lambda.LiveAliasFunctionUrlDomain; ### Lambda with API Gateway Permissions +By default a permission is granted on the **alias only**. Set `Targets` to grant it on the +function, the version, and/or the alias. + ```csharp var apiPermission = new LambdaPermission { Principal = "apigateway.amazonaws.com", Action = "lambda:InvokeFunction", SourceArn = "arn:aws:execute-api:us-east-1:123456789012:abcdef123/*" + // Targets defaults to LambdaPermissionTargets.Alias }; var lambda = new LambdaFunctionConstruct(this, "MyLambda", new LambdaFunctionConstructProps @@ -131,6 +152,52 @@ var lambda = new LambdaFunctionConstruct(this, "MyLambda", new LambdaFunctionCon }); ``` +To restore the 2.x behavior (function, version, and alias), opt in explicitly: + +```csharp +var apiPermission = new LambdaPermission +{ + Principal = "apigateway.amazonaws.com", + Action = "lambda:InvokeFunction", + SourceArn = "arn:aws:execute-api:us-east-1:123456789012:abcdef123/*", + Targets = LambdaPermissionTargets.Function + | LambdaPermissionTargets.Version + | LambdaPermissionTargets.Alias +}; +``` + +### Lambda with an S3 Artifact + +Provide existing code instead of a local asset. With `Code.FromBucketV2` the construct adds no +bucket grants to the execution role. + +```csharp +var bucket = Bucket.FromBucketName(this, "ArtifactBucket", "my-lambda-artifacts"); + +var lambda = new LambdaFunctionConstruct(this, "MyLambda", new LambdaFunctionConstructProps +{ + FunctionName = "my-api", + FunctionSuffix = "prod", + Code = Code.FromBucketV2(bucket, "my-api/app.zip", new BucketOptions()), + RoleName = "my-api-role", + PolicyName = "my-api-policy" +}); +``` + +### Lambda with a Custom Alias Name + +```csharp +var lambda = new LambdaFunctionConstruct(this, "MyLambda", new LambdaFunctionConstructProps +{ + FunctionName = "my-api", + FunctionSuffix = "prod", + AssetPath = "./lambda-deployment.zip", + AliasName = "prod", + RoleName = "my-api-role", + PolicyName = "my-api-policy" +}); +``` + ### Lambda with SnapStart ```csharp @@ -177,6 +244,22 @@ var underlyingFunction = lambda.LambdaFunction; underlyingFunction.AddEnvironment("CUSTOM_VAR", "value"); ``` +### Alias + +The deployed alias as an `IAlias`: + +```csharp +var alias = lambda.Alias; +``` + +### Version + +The published version backing the alias as an `IVersion`: + +```csharp +var version = lambda.Version; +``` + ### LiveAliasFunctionUrlDomain Get the domain of the Function URL (if enabled): @@ -206,20 +289,23 @@ The Lambda functions use the following runtime configuration: The construct automatically creates: -1. **CloudWatch Logs Permissions**: +1. **CloudWatch Logs Permissions** (scoped to the construct's own log group ARN): - `logs:CreateLogStream` - - `logs:CreateLogGroup` - - `logs:TagResource` - `logs:PutLogEvents` + The construct creates the log group itself, so it does not grant `logs:CreateLogGroup`, + `logs:TagResource`, or a wildcard log-group resource. + 2. **Custom Policy Statements**: Any additional policies you provide -3. **Lambda Permissions**: Applied to function, version, and alias +3. **Lambda Permissions**: Each `LambdaPermission` is applied to its `Targets` + (`Function`, `Version`, and/or `Alias`). The default is **alias only**. `LambdaPermissionTargets.None` + is invalid and throws an `ArgumentException` at construction. ## Versioning Strategy - Creates a new version on every deployment -- Maintains a "live" alias pointing to the latest version +- Maintains an alias pointing to the latest version; the alias name is configurable (`AliasName`, default `"live"`) - Versions have `RemovalPolicy.RETAIN` to prevent deletion ## Testing diff --git a/docs/designs/v3-modernization.md b/docs/designs/v3-modernization.md index 23767a5..f95914e 100644 --- a/docs/designs/v3-modernization.md +++ b/docs/designs/v3-modernization.md @@ -2,7 +2,7 @@ | | | |---|---| -| **Status** | **Proposed** (revision 1, 2026-11-24), awaiting owner review. Approval of this document is an acceptance criterion of [#109](https://github.com/LayeredCraft/cdk-constructs/issues/109); it does not authorize [#110](https://github.com/LayeredCraft/cdk-constructs/issues/110), [#111](https://github.com/LayeredCraft/cdk-constructs/issues/111) or [#112](https://github.com/LayeredCraft/cdk-constructs/issues/112). | +| **Status** | **Accepted** (revision 2, 2026-11-24). The owner approved the design on 2026-11-24 ([#109 comment](https://github.com/LayeredCraft/cdk-constructs/issues/109#issuecomment-7131032469)) and authorized [#110](https://github.com/LayeredCraft/cdk-constructs/issues/110) and [#111](https://github.com/LayeredCraft/cdk-constructs/issues/111). [#112](https://github.com/LayeredCraft/cdk-constructs/issues/112) and the stable release remain owner-gated. | | **Milestone** | [v3.0.0](https://github.com/LayeredCraft/cdk-constructs/milestone/1), epic [#108](https://github.com/LayeredCraft/cdk-constructs/issues/108) | | **Authority** | This document is the design record for 3.0.0. No standalone ADRs are written. | | **Target frameworks** | `net10.0`, `net11.0` | @@ -279,16 +279,23 @@ on this construct): `StaticSiteConstruct`. 7. **Consumer test projects** — no change required; the library's own tests moved to Compono. -## 11. Open questions for the owner +## 11. Owner decisions (2026-11-24) -1. Approve this design (an acceptance criterion of #109). -2. Approve or decline the proposed Web Function L2 spike issue ([§9.5](#95-recommendation)). -3. Confirm U7's shape: `Code` as an alternative to `AssetPath` (additive) rather than replacing - `AssetPath`. -4. Confirm the working name `PrivateStaticAssetsConstruct` for U6. +1. The design is approved: .NET 10/11 only, updated dependencies and tooling, Compono-first tests, + U1–U4 and U7, U6. +2. `WebFunctionConstruct` keeps its current implementation for 3.0.0 (option A). The composition + investigation ([§9.5](#95-recommendation)) is tracked separately and deferred in + [#114](https://github.com/LayeredCraft/cdk-constructs/issues/114); it does not block 3.0.0, and no + Web Function refactor is authorized. +3. U7: `Code` is an alternative to `AssetPath`; existing asset-based usage is preserved. +4. U6 is named `PrivateStaticAssetsConstruct`. + +The §7 open question (exposing Lambda logging configuration) was not taken up in #110: no consumer +needs it, and adding it would need its own owner decision. ## 12. Revision history | Revision | Date | Change | |---|---|---| | 1 | 2026-11-24 | Initial proposal for owner review | +| 2 | 2026-11-24 | Accepted; owner decisions recorded in §11; Web Function investigation deferred to #114 | diff --git a/docs/migration/v3.md b/docs/migration/v3.md new file mode 100644 index 0000000..75656f5 --- /dev/null +++ b/docs/migration/v3.md @@ -0,0 +1,125 @@ +# Upgrading to 3.0 + +3.0.0 is a major release. This page lists every change that can affect an existing consumer, with +what to do about it. Changes are marked **intentional** (a deliberate behavior or support change) or +**upgrade-induced** (a consequence of the newer AWS CDK). + +## 1. .NET 8 and .NET 9 are no longer supported (intentional) + +The package targets `net10.0` and `net11.0` only. Projects on .NET 8 or 9 should stay on 2.x or move +to .NET 10 or 11. + +## 2. `Amazon.CDK.Lib` 2.278.0 or later (upgrade-induced) + +The minimum AWS CDK version is now 2.278.0. That release adds AWS's own Web Function L2 types to +`Amazon.CDK.AWS.Lambda`, and eight of their names match this library's: + +- `IWebFunctionEndpoint` (namespace `LayeredCraft.Cdk.Constructs`); +- `WebFunctionCode`, `WebFunctionRuntime`, `WebFunctionAuthType`, `WebFunctionEndpointType`, + `WebFunctionEndpointOptions`, `IWebFunctionEndpointOptions` and `WebFunctionEndpointAttributes` + (namespace `LayeredCraft.Cdk.Constructs.Models`). + +A file that imports both `Amazon.CDK.AWS.Lambda` and these namespaces gets `CS0104` (ambiguous +reference). Add file-local aliases for the types the file uses: + +```csharp +using Amazon.CDK.AWS.Lambda; +using LayeredCraft.Cdk.Constructs.Models; +using WebFunctionCode = LayeredCraft.Cdk.Constructs.Models.WebFunctionCode; +using WebFunctionRuntime = LayeredCraft.Cdk.Constructs.Models.WebFunctionRuntime; +``` + +This is a source-only change: synthesized templates are unchanged. + +## 3. `LambdaFunctionConstruct`: invocation permissions default to the alias only (intentional) + +Each `LambdaPermission` now has `Targets` (`LambdaPermissionTargets` flags: `Function`, `Version`, +`Alias`). The default is `Alias`. In 2.x every permission was added to the function, the current +version and the alias. + +At the default, the function and version `AWS::Lambda::Permission` resources disappear from the +template; the alias permission is unchanged (same logical ID): + +```json +// 2.x: three resources per permission +"…permissionfn0…": { "Type": "AWS::Lambda::Permission", "Properties": { "FunctionName": { "Fn::GetAtt": ["…function…", "Arn"] }, … } }, +"…permissionver0…": { "Type": "AWS::Lambda::Permission", "Properties": { "FunctionName": { "Ref": "…CurrentVersion…" }, … } }, +"…permissionalias0…": { "Type": "AWS::Lambda::Permission", "Properties": { "FunctionName": { "Ref": "…alias…" }, … } } + +// 3.0 default: the alias permission only +"…permissionalias0…": { "Type": "AWS::Lambda::Permission", "Properties": { "FunctionName": { "Ref": "…alias…" }, … } } +``` + +Callers that invoke the alias (for example an Alexa skill or API Gateway integration pointing at the +alias ARN) need no change. To keep the 2.x output exactly, opt into all three targets: + +```csharp +new LambdaPermission +{ + Principal = "apigateway.amazonaws.com", + Action = "lambda:InvokeFunction", + SourceArn = apiArn, + Targets = LambdaPermissionTargets.Function | LambdaPermissionTargets.Version | LambdaPermissionTargets.Alias, +} +``` + +A permission with no targets is rejected at synthesis. + +## 4. `LambdaFunctionConstruct`: logging policy scoped to the construct's log group (intentional) + +The execution role's logging policy now allows only `logs:CreateLogStream` and `logs:PutLogEvents` +on the construct's own log group. `logs:CreateLogGroup`, `logs:TagResource` and the wildcard +log-group ARN are removed; the construct creates the log group itself. + +```json +// 2.x +{ "Action": ["logs:CreateLogStream", "logs:CreateLogGroup", "logs:TagResource"], "Effect": "Allow", + "Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/my-function-dev*:*" }, +{ "Action": "logs:PutLogEvents", "Effect": "Allow", + "Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/my-function-dev*:*:*" } + +// 3.0 +{ "Action": ["logs:CreateLogStream", "logs:PutLogEvents"], "Effect": "Allow", + "Resource": { "Fn::GetAtt": ["…loggroup…", "Arn"] } } +``` + +Deploying this updates the inline policy in place. If the function writes to other log groups, +add statements through `PolicyStatements`. + +## 5. New `LambdaFunctionConstruct` options (additive) + +- **`AliasName`** (default `live`): the alias name. The alias keeps its logical ID, but CloudFormation + replaces an alias whose name changes, so callers using the old alias ARN must be updated. +- **`Alias`** and **`Version`**: the alias (`IAlias`) and current version (`IVersion`) are public + properties. +- **`Code`**: any `Amazon.CDK.AWS.Lambda.Code` source as an alternative to `AssetPath`, for example an + immutable artifact in an existing bucket. Exactly one of `AssetPath` and `Code` must be set. + `AssetPath` is no longer `required` (it is `string?`); existing `AssetPath` usage is unchanged. + + ```csharp + var artifacts = Bucket.FromBucketName(this, "Artifacts", "my-artifacts-bucket"); + new LambdaFunctionConstruct(this, "Worker", new LambdaFunctionConstructProps + { + FunctionName = "worker", + FunctionSuffix = "dev", + Code = Code.FromBucketV2(artifacts, "worker/1.2.3/worker.zip"), + RoleName = "worker-dev-role", + PolicyName = "worker-dev-policy", + }); + ``` + + The construct grants the function no access to the bucket and adds no bucket permissions. + +`ILambdaFunctionConstructProps` gained `Code` and `AliasName`, and `AssetPath` became nullable. +Custom implementations of the interface need those members. + +**Testing helpers:** `LambdaFunctionConstructPropsBuilder` gained `WithAliasName` and `WithCode`, and +`WithApiGatewayPermission`/`WithAlexaPermission` take an optional `targets`. +`LambdaFunctionConstructAssertions.ShouldHaveLambdaPermissions` counts per selected target (default +alias only), and `ShouldHaveCloudWatchLogsPermissions` asserts the scoped policy; its `region` and +`account` parameters are kept for source compatibility and are ignored. + +## 6. Consumer test projects + +No change is required. The library's own tests moved from AutoFixture/NSubstitute to Compono; that +does not affect the shipped `Testing` helpers' dependencies. diff --git a/docs/testing/index.md b/docs/testing/index.md index f511594..858e32a 100644 --- a/docs/testing/index.md +++ b/docs/testing/index.md @@ -102,6 +102,7 @@ var (app, stack) = CdkTestHelper.CreateTestStack("stack-name" var props = CdkTestHelper.CreatePropsBuilder(AssetPathExtensions.GetTestLambdaZipPath()) .WithFunctionName("my-function") .WithFunctionSuffix("prod") + .WithAliasName("prod") .WithMemorySize(1024) .WithTimeoutInSeconds(30) .WithEnvironmentVariable("LOG_LEVEL", "info") @@ -117,6 +118,30 @@ var props = CdkTestHelper.CreatePropsBuilder(AssetPathExtensions.GetTestLambdaZi // SnapStart is only supported for Java runtimes; avoid enabling it with the default runtime. ``` +To use existing code instead of a local asset, call `WithCode`; it clears the builder's asset path so +exactly one source is configured: + +```csharp +var props = CdkTestHelper.CreatePropsBuilder() + .WithCode(Code.FromBucketV2(bucket, "app.zip", new BucketOptions())) + .Build(); +``` + +`WithApiGatewayPermission` and `WithAlexaPermission` accept an optional `LambdaPermissionTargets` +argument (default `Alias`). For a custom permission, set `LambdaPermission.Targets` directly: + +```csharp +var props = CdkTestHelper.CreatePropsBuilder(AssetPathExtensions.GetTestLambdaZipPath()) + .WithApiGatewayPermission( + "arn:aws:execute-api:us-east-1:123456789012:abcdef123/*", + targets: LambdaPermissionTargets.Alias) + .Build(); + +var allTargets = LambdaPermissionTargets.Function + | LambdaPermissionTargets.Version + | LambdaPermissionTargets.Alias; +``` + ### OpenTelemetry Configuration (v2.0+) The props builder includes new methods for configuring OpenTelemetry settings: @@ -148,8 +173,11 @@ template.ShouldHaveFunctionUrl(); template.ShouldHaveFunctionUrlOutput("test-stack", "test-construct"); // IAM and permissions -template.ShouldHaveCloudWatchLogsPermissions("my-function-prod"); -template.ShouldHaveLambdaPermissions(1); // Count of permission objects +template.ShouldHaveCloudWatchLogsPermissions("my-function-prod"); // scoped to the construct's log group +template.ShouldHaveLambdaPermissions(1); // one permission applied to the alias only (default) +template.ShouldHaveLambdaPermissions( + 1, + LambdaPermissionTargets.Function | LambdaPermissionTargets.Version | LambdaPermissionTargets.Alias); // Environment and configuration template.ShouldHaveEnvironmentVariables(new Dictionary @@ -160,6 +188,12 @@ template.ShouldHaveVersionAndAlias("live"); template.ShouldHaveLogGroup("my-function-prod", 14); ``` +`ShouldHaveCloudWatchLogsPermissions` asserts the scoped policy: exactly `logs:CreateLogStream` and +`logs:PutLogEvents` on the construct's log-group ARN (`Fn::GetAtt`), with no `logs:CreateLogGroup`, +`logs:TagResource`, or wildcard log-group resource. `ShouldHaveLambdaPermissions` takes the +`LambdaPermissionTargets` (default `Alias`) and multiplies by the number of permission objects, so +the alias-only default expects one resource per permission. + SnapStart-specific assertions (`template.ShouldHaveSnapStart()`) apply only when you are using a Java runtime; the default `PROVIDED_AL2023` runtime does not support SnapStart. ## Static Site Testing diff --git a/mkdocs.yml b/mkdocs.yml index 8cd6117..8c606b0 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -112,6 +112,7 @@ nav: - Cognito User Pool: constructs/cognito-user-pool.md - Web Function: constructs/web-function.md - Testing: testing/index.md + - Upgrading to 3.0: migration/v3.md - Examples: - Overview: examples/index.md - Web Function Workloads: examples/web-functions.md diff --git a/src/LayeredCraft.Cdk.Constructs/LambdaFunctionConstruct.cs b/src/LayeredCraft.Cdk.Constructs/LambdaFunctionConstruct.cs index c4ba003..051088a 100644 --- a/src/LayeredCraft.Cdk.Constructs/LambdaFunctionConstruct.cs +++ b/src/LayeredCraft.Cdk.Constructs/LambdaFunctionConstruct.cs @@ -20,41 +20,28 @@ public class LambdaFunctionConstruct : Construct /// The underlying Lambda function for advanced configuration. /// public readonly Function LambdaFunction; + + /// + /// The published Lambda version backing the alias. + /// + public readonly IVersion Version; + + /// + /// The Lambda alias pointed at the published version. + /// + public readonly IAlias Alias; + public LambdaFunctionConstruct(Construct scope, string id, ILambdaFunctionConstructProps props) : base(scope, id) { var region = Stack.Of(this).Region; - var account = Stack.Of(this).Account; + ValidatePermissionTargets(props.Permissions); + var code = ResolveCode(props); + var policy = new Policy(this, $"{id}-policy", new PolicyProps { - PolicyName = props.PolicyName, - Statements = - [ - new PolicyStatement(new PolicyStatementProps - { - Actions = - [ - "logs:CreateLogStream", - "logs:CreateLogGroup", - "logs:TagResource" - ], - Resources = [$"arn:aws:logs:{region}:{account}:log-group:/aws/lambda/{props.FunctionName}-{props.FunctionSuffix}*:*"], - Effect = Effect.ALLOW - }), - new PolicyStatement(new PolicyStatementProps - { - Actions = - [ - "logs:PutLogEvents" - ], - Resources = - [$"arn:aws:logs:{region}:{account}:log-group:/aws/lambda/{props.FunctionName}-{props.FunctionSuffix}*:*:*"], - Effect = Effect.ALLOW - }) - ] + PolicyName = props.PolicyName }); - policy.AddStatements(props.PolicyStatements); - var role = new Role(this, $"{id}-role", new RoleProps { AssumedBy = new ServicePrincipal("lambda.amazonaws.com"), @@ -70,12 +57,25 @@ public LambdaFunctionConstruct(Construct scope, string id, ILambdaFunctionConstr RemovalPolicy = RemovalPolicy.DESTROY }); + policy.AddStatements(new PolicyStatement(new PolicyStatementProps + { + Actions = + [ + "logs:CreateLogStream", + "logs:PutLogEvents" + ], + Resources = [logGroup.LogGroupArn], + Effect = Effect.ALLOW + })); + + policy.AddStatements(props.PolicyStatements); + LambdaFunction = new Function(this, $"{id}-function", new FunctionProps { FunctionName = $"{props.FunctionName}-{props.FunctionSuffix}", Runtime = Runtime.PROVIDED_AL2023, Handler = "bootstrap", - Code = Code.FromAsset(props.AssetPath), + Code = code, Role = role, MemorySize = props.MemorySize, Timeout = Duration.Seconds(props.TimeoutInSeconds), @@ -96,6 +96,7 @@ public LambdaFunctionConstruct(Construct scope, string id, ILambdaFunctionConstr // ✅ Create a new version on every deployment var currentVersion = LambdaFunction.CurrentVersion; + Version = currentVersion; if (props.EnableSnapStart) { @@ -113,15 +114,16 @@ public LambdaFunctionConstruct(Construct scope, string id, ILambdaFunctionConstr var alias = new Alias(this, $"{id}-alias", new AliasProps { - AliasName = "live", + AliasName = props.AliasName, Version = currentVersion, }); - + Alias = alias; + AddPermissionsToAllTargets( baseId: $"{id}-permission", function: LambdaFunction, - version: LambdaFunction.CurrentVersion, - alias: alias, + version: Version, + alias: Alias, permissions: props.Permissions ); @@ -158,9 +160,60 @@ private void AddPermissionsToAllTargets(string baseId, IFunction function, IVers SourceArn = perm.SourceArn }; - function.AddPermission($"{baseId}-fn-{index}", permission); - version.AddPermission($"{baseId}-ver-{index}", permission); - alias?.AddPermission($"{baseId}-alias-{index}", permission); + if (perm.Targets.HasFlag(LambdaPermissionTargets.Function)) + { + function.AddPermission($"{baseId}-fn-{index}", permission); + } + + if (perm.Targets.HasFlag(LambdaPermissionTargets.Version)) + { + version.AddPermission($"{baseId}-ver-{index}", permission); + } + + if (alias is not null && perm.Targets.HasFlag(LambdaPermissionTargets.Alias)) + { + alias.AddPermission($"{baseId}-alias-{index}", permission); + } + } + } + + private static Code ResolveCode(ILambdaFunctionConstructProps props) + { + var assetPath = props.AssetPath; + var code = props.Code; + + if (assetPath is not null && code is not null) + { + throw new ArgumentException( + "Exactly one of AssetPath or Code must be set; both were provided.", + nameof(props)); + } + + if (code is not null) + { + return code; + } + + if (!string.IsNullOrWhiteSpace(assetPath)) + { + return Code.FromAsset(assetPath); + } + + throw new ArgumentException( + "Exactly one of AssetPath or Code must be set; neither was provided.", + nameof(props)); + } + + private static void ValidatePermissionTargets(List permissions) + { + foreach (var (permission, index) in permissions.Select((p, i) => (p, i))) + { + if (permission.Targets == LambdaPermissionTargets.None) + { + throw new ArgumentException( + $"Permission at index {index} has no targets. Set LambdaPermission.Targets to one or more of Function, Version, or Alias.", + nameof(permissions)); + } } } diff --git a/src/LayeredCraft.Cdk.Constructs/Models/LambdaFunctionConstructProps.cs b/src/LayeredCraft.Cdk.Constructs/Models/LambdaFunctionConstructProps.cs index d787bfc..9749740 100644 --- a/src/LayeredCraft.Cdk.Constructs/Models/LambdaFunctionConstructProps.cs +++ b/src/LayeredCraft.Cdk.Constructs/Models/LambdaFunctionConstructProps.cs @@ -1,4 +1,5 @@ using Amazon.CDK.AWS.IAM; +using Amazon.CDK.AWS.Lambda; namespace LayeredCraft.Cdk.Constructs.Models; @@ -6,7 +7,16 @@ public interface ILambdaFunctionConstructProps { string FunctionName { get; set; } string FunctionSuffix { get; set; } - string AssetPath { get; set; } + + /// Path to a local Lambda deployment package. Exactly one of or must be set. + string? AssetPath { get; set; } + + /// Existing Lambda code source. Exactly one of or must be set. + Code? Code { get; set; } + + /// Name of the alias pointing at the published version (default: live). + string AliasName { get; set; } + string RoleName { get; set; } string PolicyName { get; set; } double MemorySize { get; set; } @@ -24,7 +34,16 @@ public sealed record LambdaFunctionConstructProps : ILambdaFunctionConstructProp { public required string FunctionName { get; set; } public required string FunctionSuffix { get; set; } - public required string AssetPath { get; set; } + + /// Path to a local Lambda deployment package. Exactly one of or must be set. + public string? AssetPath { get; set; } + + /// Existing Lambda code source. Exactly one of or must be set. + public Code? Code { get; set; } + + /// Name of the alias pointing at the published version (default: live). + public string AliasName { get; set; } = "live"; + public required string RoleName { get; set; } public required string PolicyName { get; set; } public double MemorySize { get; set; } = 1024; diff --git a/src/LayeredCraft.Cdk.Constructs/Models/LambdaPermission.cs b/src/LayeredCraft.Cdk.Constructs/Models/LambdaPermission.cs index 290d1bf..c4c8bd3 100644 --- a/src/LayeredCraft.Cdk.Constructs/Models/LambdaPermission.cs +++ b/src/LayeredCraft.Cdk.Constructs/Models/LambdaPermission.cs @@ -6,4 +6,9 @@ public sealed record LambdaPermission public required string Action { get; set; } public string? EventSourceToken { get; set; } public string? SourceArn { get; set; } + + /// + /// The targets this permission is applied to. Defaults to . + /// + public LambdaPermissionTargets Targets { get; set; } = LambdaPermissionTargets.Alias; } \ No newline at end of file diff --git a/src/LayeredCraft.Cdk.Constructs/Models/LambdaPermissionTargets.cs b/src/LayeredCraft.Cdk.Constructs/Models/LambdaPermissionTargets.cs new file mode 100644 index 0000000..3a50185 --- /dev/null +++ b/src/LayeredCraft.Cdk.Constructs/Models/LambdaPermissionTargets.cs @@ -0,0 +1,22 @@ +using System; + +namespace LayeredCraft.Cdk.Constructs.Models; + +/// +/// Specifies which Lambda resources a grants invocation on. +/// +[Flags] +public enum LambdaPermissionTargets +{ + /// No target. Not valid for a permission. + None = 0, + + /// The unqualified function. + Function = 1 << 0, + + /// The published version pinned by this construct. + Version = 1 << 1, + + /// The alias (the default, matching least-privilege deployments). + Alias = 1 << 2, +} \ No newline at end of file diff --git a/src/LayeredCraft.Cdk.Constructs/Testing/LambdaFunctionConstructAssertions.cs b/src/LayeredCraft.Cdk.Constructs/Testing/LambdaFunctionConstructAssertions.cs index 6895d89..1938636 100644 --- a/src/LayeredCraft.Cdk.Constructs/Testing/LambdaFunctionConstructAssertions.cs +++ b/src/LayeredCraft.Cdk.Constructs/Testing/LambdaFunctionConstructAssertions.cs @@ -1,4 +1,5 @@ using Amazon.CDK.Assertions; +using LayeredCraft.Cdk.Constructs.Models; namespace LayeredCraft.Cdk.Constructs.Testing; @@ -22,36 +23,44 @@ public static void ShouldHaveLambdaFunction(this Template template, string funct } /// - /// Asserts that the template contains CloudWatch Logs permissions for the specified function. + /// Asserts that the execution role's logging policy is scoped to the construct's own log group: + /// only logs:CreateLogStream and logs:PutLogEvents on the log group ARN. /// /// The CDK template to assert against - /// The function name to check permissions for - /// AWS region (default: us-east-1) - /// AWS account ID (default: 123456789012) - public static void ShouldHaveCloudWatchLogsPermissions(this Template template, string functionName, + /// The function name whose log group scopes the policy + /// Unused; retained for source compatibility + /// Unused; retained for source compatibility + public static void ShouldHaveCloudWatchLogsPermissions(this Template template, string functionName, string region = "us-east-1", string account = "123456789012") { + var logGroups = template.FindResources("AWS::Logs::LogGroup", new Dictionary + { + { "Properties", Match.ObjectLike(new Dictionary + { + { "LogGroupName", $"/aws/lambda/{functionName}" } + }) + } + }); + + var logGroupLogicalId = logGroups.Keys.Single(); + template.HasResourceProperties("AWS::IAM::Policy", Match.ObjectLike(new Dictionary { { "PolicyDocument", Match.ObjectLike(new Dictionary { { "Statement", Match.ArrayWith([ - // CloudWatch Logs permissions Match.ObjectLike(new Dictionary { { "Effect", "Allow" }, { "Action", Match.ArrayWith([ "logs:CreateLogStream", - "logs:CreateLogGroup", - "logs:TagResource" + "logs:PutLogEvents" ]) }, - { "Resource", $"arn:aws:logs:{region}:{account}:log-group:/aws/lambda/{functionName}*:*" } - }), - Match.ObjectLike(new Dictionary - { - { "Effect", "Allow" }, - { "Action", "logs:PutLogEvents" }, - { "Resource", $"arn:aws:logs:{region}:{account}:log-group:/aws/lambda/{functionName}*:*:*" } + { "Resource", new Dictionary + { + { "Fn::GetAtt", new object[] { logGroupLogicalId, "Arn" } } + } + } }) ]) } }) } @@ -107,14 +116,21 @@ public static void ShouldHaveEnvironmentVariables(this Template template, IDicti } /// - /// Asserts that the template contains Lambda permissions for the specified count (function + version + alias). + /// Asserts that the template contains the expected number of Lambda permission resources for the + /// given permission count and targets. /// /// The CDK template to assert against - /// Number of permission objects (will be multiplied by 3 for function, version, alias) - public static void ShouldHaveLambdaPermissions(this Template template, int permissionCount) + /// Number of permission objects + /// Targets applied to each permission (default: alias only) + public static void ShouldHaveLambdaPermissions(this Template template, int permissionCount, + LambdaPermissionTargets targets = LambdaPermissionTargets.Alias) { - var expectedPermissionCount = permissionCount * 3; // function + version + alias - template.ResourceCountIs("AWS::Lambda::Permission", expectedPermissionCount); + var targetCount = 0; + if (targets.HasFlag(LambdaPermissionTargets.Function)) targetCount++; + if (targets.HasFlag(LambdaPermissionTargets.Version)) targetCount++; + if (targets.HasFlag(LambdaPermissionTargets.Alias)) targetCount++; + + template.ResourceCountIs("AWS::Lambda::Permission", permissionCount * targetCount); } /// diff --git a/src/LayeredCraft.Cdk.Constructs/Testing/LambdaFunctionConstructPropsBuilder.cs b/src/LayeredCraft.Cdk.Constructs/Testing/LambdaFunctionConstructPropsBuilder.cs index c1b5cc0..ca20502 100644 --- a/src/LayeredCraft.Cdk.Constructs/Testing/LambdaFunctionConstructPropsBuilder.cs +++ b/src/LayeredCraft.Cdk.Constructs/Testing/LambdaFunctionConstructPropsBuilder.cs @@ -1,4 +1,5 @@ using Amazon.CDK.AWS.IAM; +using Amazon.CDK.AWS.Lambda; using LayeredCraft.Cdk.Constructs.Models; namespace LayeredCraft.Cdk.Constructs.Testing; @@ -11,7 +12,9 @@ public class LambdaFunctionConstructPropsBuilder { private string _functionName = "test-function"; private string _functionSuffix = "test"; - private string _assetPath = "./test-lambda.zip"; + private string? _assetPath = "./test-lambda.zip"; + private Code? _code; + private string _aliasName = "live"; private string _roleName = "test-role"; private string _policyName = "test-policy"; private double _memorySize = 1024; @@ -55,6 +58,31 @@ public LambdaFunctionConstructPropsBuilder WithFunctionSuffix(string functionSuf public LambdaFunctionConstructPropsBuilder WithAssetPath(string assetPath) { _assetPath = assetPath; + _code = null; + return this; + } + + /// + /// Sets the Lambda artifact code from an existing source (for example an S3 bucket). + /// This replaces the asset path; provide exactly one of AssetPath or Code. + /// + /// The Lambda code source + /// The builder instance for method chaining + public LambdaFunctionConstructPropsBuilder WithCode(Code code) + { + _code = code; + _assetPath = null; + return this; + } + + /// + /// Sets the Lambda alias name applied to the deployed version. + /// + /// The alias name (default: live) + /// The builder instance for method chaining + public LambdaFunctionConstructPropsBuilder WithAliasName(string aliasName) + { + _aliasName = aliasName; return this; } @@ -157,16 +185,18 @@ public LambdaFunctionConstructPropsBuilder WithS3Access(string bucketName, /// /// The API Gateway execution ARN /// Optional event source token + /// Targets to apply the permission to (default: alias) /// The builder instance for method chaining public LambdaFunctionConstructPropsBuilder WithApiGatewayPermission(string apiArn, - string? eventSourceToken = null) + string? eventSourceToken = null, LambdaPermissionTargets targets = LambdaPermissionTargets.Alias) { _permissions.Add(new LambdaPermission { Principal = "apigateway.amazonaws.com", Action = "lambda:InvokeFunction", SourceArn = apiArn, - EventSourceToken = eventSourceToken + EventSourceToken = eventSourceToken, + Targets = targets }); return this; } @@ -175,14 +205,17 @@ public LambdaFunctionConstructPropsBuilder WithApiGatewayPermission(string apiAr /// Adds Alexa Skills Kit invoke permission. /// /// The Alexa skill ID + /// Targets to apply the permission to (default: alias) /// The builder instance for method chaining - public LambdaFunctionConstructPropsBuilder WithAlexaPermission(string skillId) + public LambdaFunctionConstructPropsBuilder WithAlexaPermission(string skillId, + LambdaPermissionTargets targets = LambdaPermissionTargets.Alias) { _permissions.Add(new LambdaPermission { Principal = "alexa-appkit.amazon.com", Action = "lambda:InvokeFunction", - EventSourceToken = skillId + EventSourceToken = skillId, + Targets = targets }); return this; } @@ -290,6 +323,8 @@ public LambdaFunctionConstructProps Build() FunctionName = _functionName, FunctionSuffix = _functionSuffix, AssetPath = _assetPath, + Code = _code, + AliasName = _aliasName, RoleName = _roleName, PolicyName = _policyName, MemorySize = _memorySize, diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/ExistingConstructsGoldenTemplateTests.cs b/test/LayeredCraft.Cdk.Constructs.Tests/ExistingConstructsGoldenTemplateTests.cs index 643a4a8..dbbf6c5 100644 --- a/test/LayeredCraft.Cdk.Constructs.Tests/ExistingConstructsGoldenTemplateTests.cs +++ b/test/LayeredCraft.Cdk.Constructs.Tests/ExistingConstructsGoldenTemplateTests.cs @@ -2,7 +2,9 @@ using Amazon.CDK.AWS.CertificateManager; using Amazon.CDK.AWS.Cognito; using Amazon.CDK.AWS.DynamoDB; +using Amazon.CDK.AWS.Lambda; using Amazon.CDK.AWS.Route53; +using Amazon.CDK.AWS.S3; using LayeredCraft.Cdk.Constructs.Models; using LayeredCraft.Cdk.Constructs.Testing; using LayeredCraft.Cdk.Constructs.Tests.TestKit.Golden; @@ -65,6 +67,87 @@ public void LambdaFunctionConstruct_ShouldMatchGoldenTemplate( GoldenTemplate.AssertMatches(stack, goldenFileName); } + [Fact] + public void LambdaFunctionConstruct_AllPermissionTargets_ShouldMatchGoldenTemplate() + { + var (_, stack) = CdkTestHelper.CreateTestStack("golden-lambda"); + + var props = new LambdaFunctionConstructProps + { + FunctionName = "golden-function", + FunctionSuffix = "test", + AssetPath = CdkTestHelper.GetTestLambdaZipPath(), + RoleName = "golden-role", + PolicyName = "golden-policy", + MemorySize = 1024, + TimeoutInSeconds = 6, + EnvironmentVariables = new Dictionary { ["TABLE_NAME"] = "golden-table" }, + Permissions = + [ + new LambdaPermission + { + Principal = "apigateway.amazonaws.com", + Action = "lambda:InvokeFunction", + SourceArn = "arn:aws:execute-api:us-east-1:123456789012:api-id/*/GET/golden", + Targets = LambdaPermissionTargets.Function + | LambdaPermissionTargets.Version + | LambdaPermissionTargets.Alias + } + ] + }; + + _ = new LambdaFunctionConstruct(stack, "golden-lambda", props); + + GoldenTemplate.AssertMatches(stack, "lambda-permissions-all-targets.json"); + } + + [Fact] + public void LambdaFunctionConstruct_S3Code_ShouldMatchGoldenTemplate() + { + var (_, stack) = CdkTestHelper.CreateTestStack("golden-lambda"); + + var bucket = Bucket.FromBucketName(stack, "artifact-bucket", "golden-artifacts"); + + var props = new LambdaFunctionConstructProps + { + FunctionName = "golden-function", + FunctionSuffix = "test", + Code = Code.FromBucketV2(bucket, "app.zip", new BucketOptions()), + RoleName = "golden-role", + PolicyName = "golden-policy", + MemorySize = 1024, + TimeoutInSeconds = 6, + EnvironmentVariables = new Dictionary { ["TABLE_NAME"] = "golden-table" } + }; + + _ = new LambdaFunctionConstruct(stack, "golden-lambda", props); + + GoldenTemplate.AssertMatches(stack, "lambda-s3-code.json"); + } + + [Fact] + public void LambdaFunctionConstruct_CustomAliasName_ShouldMatchGoldenTemplate() + { + var (_, stack) = CdkTestHelper.CreateTestStack("golden-lambda"); + + var props = new LambdaFunctionConstructProps + { + FunctionName = "golden-function", + FunctionSuffix = "test", + AssetPath = CdkTestHelper.GetTestLambdaZipPath(), + AliasName = "prod", + RoleName = "golden-role", + PolicyName = "golden-policy", + MemorySize = 1024, + TimeoutInSeconds = 6, + EnvironmentVariables = new Dictionary { ["TABLE_NAME"] = "golden-table" } + }; + + _ = new LambdaFunctionConstruct(stack, "golden-lambda", props); + + GoldenTemplate.AssertMatches(stack, "lambda-alias-name.json"); + } + [Theory] [InlineData("static-site-default.json", false, false)] [InlineData("static-site-api.json", true, false)] diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-alias-name.json b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-alias-name.json new file mode 100644 index 0000000..fc1d1b0 --- /dev/null +++ b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-alias-name.json @@ -0,0 +1,121 @@ +{ + "Resources": { + "goldenlambdagoldenlambdapolicy4C9B84B1": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": [ + "logs:CreateLogStream", + "logs:PutLogEvents" + ], + "Effect": "Allow", + "Resource": { + "Fn::GetAtt": [ + "goldenlambdagoldenlambdaloggroup1F5BB451", + "Arn" + ] + } + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "golden-policy", + "Roles": [ + { + "Ref": "goldenlambdagoldenlambdarole9BB93118" + } + ] + } + }, + "goldenlambdagoldenlambdarole9BB93118": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": { + "Service": "lambda.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + }, + "RoleName": "golden-role" + } + }, + "goldenlambdagoldenlambdaloggroup1F5BB451": { + "Type": "AWS::Logs::LogGroup", + "Properties": { + "LogGroupName": "/aws/lambda/golden-function-test", + "RetentionInDays": 14 + }, + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete" + }, + "goldenlambdagoldenlambdafunctionFCFBEB49": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Architectures": [ + "x86_64" + ], + "Code": { + "S3Bucket": "cdk-hnb659fds-assets-123456789012-us-east-1", + "S3Key": ".zip" + }, + "Environment": { + "Variables": { + "TABLE_NAME": "golden-table" + } + }, + "FunctionName": "golden-function-test", + "Handler": "bootstrap", + "LoggingConfig": { + "LogGroup": { + "Ref": "goldenlambdagoldenlambdaloggroup1F5BB451" + } + }, + "MemorySize": 1024, + "Role": { + "Fn::GetAtt": [ + "goldenlambdagoldenlambdarole9BB93118", + "Arn" + ] + }, + "Runtime": "provided.al2023", + "Timeout": 6 + }, + "DependsOn": [ + "goldenlambdagoldenlambdarole9BB93118" + ] + }, + "goldenlambdagoldenlambdafunctionCurrentVersionCD044A9B6e87bab96cf0cea4545a0a4ae59a2774": { + "Type": "AWS::Lambda::Version", + "Properties": { + "FunctionName": { + "Ref": "goldenlambdagoldenlambdafunctionFCFBEB49" + } + }, + "UpdateReplacePolicy": "Retain", + "DeletionPolicy": "Retain" + }, + "goldenlambdagoldenlambdaaliasB00D58F9": { + "Type": "AWS::Lambda::Alias", + "Properties": { + "FunctionName": { + "Ref": "goldenlambdagoldenlambdafunctionFCFBEB49" + }, + "FunctionVersion": { + "Fn::GetAtt": [ + "goldenlambdagoldenlambdafunctionCurrentVersionCD044A9B6e87bab96cf0cea4545a0a4ae59a2774", + "Version" + ] + }, + "Name": "prod" + } + } + } +} \ No newline at end of file diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-default.json b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-default.json index 403ce59..a12d2f7 100644 --- a/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-default.json +++ b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-default.json @@ -8,16 +8,15 @@ { "Action": [ "logs:CreateLogStream", - "logs:CreateLogGroup", - "logs:TagResource" + "logs:PutLogEvents" ], "Effect": "Allow", - "Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/golden-function-test*:*" - }, - { - "Action": "logs:PutLogEvents", - "Effect": "Allow", - "Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/golden-function-test*:*:*" + "Resource": { + "Fn::GetAtt": [ + "goldenlambdagoldenlambdaloggroup1F5BB451", + "Arn" + ] + } } ], "Version": "2012-10-17" diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-otel-amd64.json b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-otel-amd64.json index 5561dbb..99b1252 100644 --- a/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-otel-amd64.json +++ b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-otel-amd64.json @@ -8,16 +8,15 @@ { "Action": [ "logs:CreateLogStream", - "logs:CreateLogGroup", - "logs:TagResource" + "logs:PutLogEvents" ], "Effect": "Allow", - "Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/golden-function-test*:*" - }, - { - "Action": "logs:PutLogEvents", - "Effect": "Allow", - "Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/golden-function-test*:*:*" + "Resource": { + "Fn::GetAtt": [ + "goldenlambdagoldenlambdaloggroup1F5BB451", + "Arn" + ] + } } ], "Version": "2012-10-17" diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-otel-arm64.json b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-otel-arm64.json index 0c7d701..8e580e8 100644 --- a/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-otel-arm64.json +++ b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-otel-arm64.json @@ -8,16 +8,15 @@ { "Action": [ "logs:CreateLogStream", - "logs:CreateLogGroup", - "logs:TagResource" + "logs:PutLogEvents" ], "Effect": "Allow", - "Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/golden-function-test*:*" - }, - { - "Action": "logs:PutLogEvents", - "Effect": "Allow", - "Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/golden-function-test*:*:*" + "Resource": { + "Fn::GetAtt": [ + "goldenlambdagoldenlambdaloggroup1F5BB451", + "Arn" + ] + } } ], "Version": "2012-10-17" diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-otel-url-permissions.json b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-otel-url-permissions.json index e1bceca..31d5e97 100644 --- a/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-otel-url-permissions.json +++ b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-otel-url-permissions.json @@ -8,16 +8,15 @@ { "Action": [ "logs:CreateLogStream", - "logs:CreateLogGroup", - "logs:TagResource" + "logs:PutLogEvents" ], "Effect": "Allow", - "Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/golden-function-test*:*" - }, - { - "Action": "logs:PutLogEvents", - "Effect": "Allow", - "Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/golden-function-test*:*:*" + "Resource": { + "Fn::GetAtt": [ + "goldenlambdagoldenlambdaloggroup1F5BB451", + "Arn" + ] + } } ], "Version": "2012-10-17" @@ -134,31 +133,6 @@ "UpdateReplacePolicy": "Retain", "DeletionPolicy": "Retain" }, - "goldenlambdagoldenlambdafunctionCurrentVersiongoldenlambdapermissionver05EF4D9BA": { - "Type": "AWS::Lambda::Permission", - "Properties": { - "Action": "lambda:InvokeFunction", - "FunctionName": { - "Ref": "goldenlambdagoldenlambdafunctionCurrentVersionCD044A9Be5d9ec424ac6ba1a553bc90e6cedba75" - }, - "Principal": "apigateway.amazonaws.com", - "SourceArn": "arn:aws:execute-api:us-east-1:123456789012:api-id/*/GET/golden" - } - }, - "goldenlambdagoldenlambdafunctiongoldenlambdapermissionfn08E91234F": { - "Type": "AWS::Lambda::Permission", - "Properties": { - "Action": "lambda:InvokeFunction", - "FunctionName": { - "Fn::GetAtt": [ - "goldenlambdagoldenlambdafunctionFCFBEB49", - "Arn" - ] - }, - "Principal": "apigateway.amazonaws.com", - "SourceArn": "arn:aws:execute-api:us-east-1:123456789012:api-id/*/GET/golden" - } - }, "goldenlambdagoldenlambdaaliasB00D58F9": { "Type": "AWS::Lambda::Alias", "Properties": { diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-permissions-all-targets.json b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-permissions-all-targets.json new file mode 100644 index 0000000..82d92ad --- /dev/null +++ b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-permissions-all-targets.json @@ -0,0 +1,157 @@ +{ + "Resources": { + "goldenlambdagoldenlambdapolicy4C9B84B1": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": [ + "logs:CreateLogStream", + "logs:PutLogEvents" + ], + "Effect": "Allow", + "Resource": { + "Fn::GetAtt": [ + "goldenlambdagoldenlambdaloggroup1F5BB451", + "Arn" + ] + } + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "golden-policy", + "Roles": [ + { + "Ref": "goldenlambdagoldenlambdarole9BB93118" + } + ] + } + }, + "goldenlambdagoldenlambdarole9BB93118": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": { + "Service": "lambda.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + }, + "RoleName": "golden-role" + } + }, + "goldenlambdagoldenlambdaloggroup1F5BB451": { + "Type": "AWS::Logs::LogGroup", + "Properties": { + "LogGroupName": "/aws/lambda/golden-function-test", + "RetentionInDays": 14 + }, + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete" + }, + "goldenlambdagoldenlambdafunctionFCFBEB49": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Architectures": [ + "x86_64" + ], + "Code": { + "S3Bucket": "cdk-hnb659fds-assets-123456789012-us-east-1", + "S3Key": ".zip" + }, + "Environment": { + "Variables": { + "TABLE_NAME": "golden-table" + } + }, + "FunctionName": "golden-function-test", + "Handler": "bootstrap", + "LoggingConfig": { + "LogGroup": { + "Ref": "goldenlambdagoldenlambdaloggroup1F5BB451" + } + }, + "MemorySize": 1024, + "Role": { + "Fn::GetAtt": [ + "goldenlambdagoldenlambdarole9BB93118", + "Arn" + ] + }, + "Runtime": "provided.al2023", + "Timeout": 6 + }, + "DependsOn": [ + "goldenlambdagoldenlambdarole9BB93118" + ] + }, + "goldenlambdagoldenlambdafunctionCurrentVersionCD044A9B6e87bab96cf0cea4545a0a4ae59a2774": { + "Type": "AWS::Lambda::Version", + "Properties": { + "FunctionName": { + "Ref": "goldenlambdagoldenlambdafunctionFCFBEB49" + } + }, + "UpdateReplacePolicy": "Retain", + "DeletionPolicy": "Retain" + }, + "goldenlambdagoldenlambdafunctionCurrentVersiongoldenlambdapermissionver05EF4D9BA": { + "Type": "AWS::Lambda::Permission", + "Properties": { + "Action": "lambda:InvokeFunction", + "FunctionName": { + "Ref": "goldenlambdagoldenlambdafunctionCurrentVersionCD044A9B6e87bab96cf0cea4545a0a4ae59a2774" + }, + "Principal": "apigateway.amazonaws.com", + "SourceArn": "arn:aws:execute-api:us-east-1:123456789012:api-id/*/GET/golden" + } + }, + "goldenlambdagoldenlambdafunctiongoldenlambdapermissionfn08E91234F": { + "Type": "AWS::Lambda::Permission", + "Properties": { + "Action": "lambda:InvokeFunction", + "FunctionName": { + "Fn::GetAtt": [ + "goldenlambdagoldenlambdafunctionFCFBEB49", + "Arn" + ] + }, + "Principal": "apigateway.amazonaws.com", + "SourceArn": "arn:aws:execute-api:us-east-1:123456789012:api-id/*/GET/golden" + } + }, + "goldenlambdagoldenlambdaaliasB00D58F9": { + "Type": "AWS::Lambda::Alias", + "Properties": { + "FunctionName": { + "Ref": "goldenlambdagoldenlambdafunctionFCFBEB49" + }, + "FunctionVersion": { + "Fn::GetAtt": [ + "goldenlambdagoldenlambdafunctionCurrentVersionCD044A9B6e87bab96cf0cea4545a0a4ae59a2774", + "Version" + ] + }, + "Name": "live" + } + }, + "goldenlambdagoldenlambdaaliasgoldenlambdapermissionalias0A5CE46E8": { + "Type": "AWS::Lambda::Permission", + "Properties": { + "Action": "lambda:InvokeFunction", + "FunctionName": { + "Ref": "goldenlambdagoldenlambdaaliasB00D58F9" + }, + "Principal": "apigateway.amazonaws.com", + "SourceArn": "arn:aws:execute-api:us-east-1:123456789012:api-id/*/GET/golden" + } + } + } +} \ No newline at end of file diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-permissions.json b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-permissions.json index 6351604..461f925 100644 --- a/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-permissions.json +++ b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-permissions.json @@ -8,16 +8,15 @@ { "Action": [ "logs:CreateLogStream", - "logs:CreateLogGroup", - "logs:TagResource" + "logs:PutLogEvents" ], "Effect": "Allow", - "Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/golden-function-test*:*" - }, - { - "Action": "logs:PutLogEvents", - "Effect": "Allow", - "Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/golden-function-test*:*:*" + "Resource": { + "Fn::GetAtt": [ + "goldenlambdagoldenlambdaloggroup1F5BB451", + "Arn" + ] + } } ], "Version": "2012-10-17" @@ -103,31 +102,6 @@ "UpdateReplacePolicy": "Retain", "DeletionPolicy": "Retain" }, - "goldenlambdagoldenlambdafunctionCurrentVersiongoldenlambdapermissionver05EF4D9BA": { - "Type": "AWS::Lambda::Permission", - "Properties": { - "Action": "lambda:InvokeFunction", - "FunctionName": { - "Ref": "goldenlambdagoldenlambdafunctionCurrentVersionCD044A9B6e87bab96cf0cea4545a0a4ae59a2774" - }, - "Principal": "apigateway.amazonaws.com", - "SourceArn": "arn:aws:execute-api:us-east-1:123456789012:api-id/*/GET/golden" - } - }, - "goldenlambdagoldenlambdafunctiongoldenlambdapermissionfn08E91234F": { - "Type": "AWS::Lambda::Permission", - "Properties": { - "Action": "lambda:InvokeFunction", - "FunctionName": { - "Fn::GetAtt": [ - "goldenlambdagoldenlambdafunctionFCFBEB49", - "Arn" - ] - }, - "Principal": "apigateway.amazonaws.com", - "SourceArn": "arn:aws:execute-api:us-east-1:123456789012:api-id/*/GET/golden" - } - }, "goldenlambdagoldenlambdaaliasB00D58F9": { "Type": "AWS::Lambda::Alias", "Properties": { diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-s3-code.json b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-s3-code.json new file mode 100644 index 0000000..5494480 --- /dev/null +++ b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-s3-code.json @@ -0,0 +1,121 @@ +{ + "Resources": { + "goldenlambdagoldenlambdapolicy4C9B84B1": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": [ + "logs:CreateLogStream", + "logs:PutLogEvents" + ], + "Effect": "Allow", + "Resource": { + "Fn::GetAtt": [ + "goldenlambdagoldenlambdaloggroup1F5BB451", + "Arn" + ] + } + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "golden-policy", + "Roles": [ + { + "Ref": "goldenlambdagoldenlambdarole9BB93118" + } + ] + } + }, + "goldenlambdagoldenlambdarole9BB93118": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": { + "Service": "lambda.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + }, + "RoleName": "golden-role" + } + }, + "goldenlambdagoldenlambdaloggroup1F5BB451": { + "Type": "AWS::Logs::LogGroup", + "Properties": { + "LogGroupName": "/aws/lambda/golden-function-test", + "RetentionInDays": 14 + }, + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete" + }, + "goldenlambdagoldenlambdafunctionFCFBEB49": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Architectures": [ + "x86_64" + ], + "Code": { + "S3Bucket": "golden-artifacts", + "S3Key": "app.zip" + }, + "Environment": { + "Variables": { + "TABLE_NAME": "golden-table" + } + }, + "FunctionName": "golden-function-test", + "Handler": "bootstrap", + "LoggingConfig": { + "LogGroup": { + "Ref": "goldenlambdagoldenlambdaloggroup1F5BB451" + } + }, + "MemorySize": 1024, + "Role": { + "Fn::GetAtt": [ + "goldenlambdagoldenlambdarole9BB93118", + "Arn" + ] + }, + "Runtime": "provided.al2023", + "Timeout": 6 + }, + "DependsOn": [ + "goldenlambdagoldenlambdarole9BB93118" + ] + }, + "goldenlambdagoldenlambdafunctionCurrentVersionCD044A9B8dfd84a5a7290a13ce5588d4d8188e3d": { + "Type": "AWS::Lambda::Version", + "Properties": { + "FunctionName": { + "Ref": "goldenlambdagoldenlambdafunctionFCFBEB49" + } + }, + "UpdateReplacePolicy": "Retain", + "DeletionPolicy": "Retain" + }, + "goldenlambdagoldenlambdaaliasB00D58F9": { + "Type": "AWS::Lambda::Alias", + "Properties": { + "FunctionName": { + "Ref": "goldenlambdagoldenlambdafunctionFCFBEB49" + }, + "FunctionVersion": { + "Fn::GetAtt": [ + "goldenlambdagoldenlambdafunctionCurrentVersionCD044A9B8dfd84a5a7290a13ce5588d4d8188e3d", + "Version" + ] + }, + "Name": "live" + } + } + } +} \ No newline at end of file diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-url.json b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-url.json index d0c16fc..d97e3c7 100644 --- a/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-url.json +++ b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/lambda-url.json @@ -8,16 +8,15 @@ { "Action": [ "logs:CreateLogStream", - "logs:CreateLogGroup", - "logs:TagResource" + "logs:PutLogEvents" ], "Effect": "Allow", - "Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/golden-function-test*:*" - }, - { - "Action": "logs:PutLogEvents", - "Effect": "Allow", - "Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/golden-function-test*:*:*" + "Resource": { + "Fn::GetAtt": [ + "goldenlambdagoldenlambdaloggroup1F5BB451", + "Arn" + ] + } } ], "Version": "2012-10-17" diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/LambdaFunctionConstructTests.cs b/test/LayeredCraft.Cdk.Constructs.Tests/LambdaFunctionConstructTests.cs index 6f875b0..f43b175 100644 --- a/test/LayeredCraft.Cdk.Constructs.Tests/LambdaFunctionConstructTests.cs +++ b/test/LayeredCraft.Cdk.Constructs.Tests/LambdaFunctionConstructTests.cs @@ -1,5 +1,8 @@ using System; +using System.Text.Json; using Amazon.CDK; +using Amazon.CDK.AWS.Lambda; +using Amazon.CDK.AWS.S3; using Amazon.CDK.Assertions; using AwesomeAssertions; using Compono.XunitV3; @@ -89,34 +92,13 @@ public void Construct_ShouldIncludeCloudWatchLogsPermissions(LambdaFunctionConst _ = new LambdaFunctionConstruct(stack, "test-construct", props); var template = Template.FromStack(stack); - // Verify the policy exists with correct name + // Verify the policy exists with correct name and is scoped to the construct's log group template.HasResourceProperties("AWS::IAM::Policy", Match.ObjectLike(new Dictionary { - { "PolicyName", props.PolicyName }, - { "PolicyDocument", Match.ObjectLike(new Dictionary - { - { "Statement", Match.ArrayWith([ - // First statement: logs:CreateLogStream, logs:CreateLogGroup, logs:TagResource - Match.ObjectLike(new Dictionary - { - { "Effect", "Allow" }, - { "Action", Match.ArrayWith([ - "logs:CreateLogStream", - "logs:CreateLogGroup", - "logs:TagResource" - ]) }, - { "Resource", $"arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/{props.FunctionName}-{props.FunctionSuffix}*:*" } - }), - // Second statement: logs:PutLogEvents - Match.ObjectLike(new Dictionary - { - { "Effect", "Allow" }, - { "Action", "logs:PutLogEvents" }, - { "Resource", $"arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/{props.FunctionName}-{props.FunctionSuffix}*:*:*" } - }) - ]) } - }) } + { "PolicyName", props.PolicyName } })); + + template.ShouldHaveCloudWatchLogsPermissions($"{props.FunctionName}-{props.FunctionSuffix}"); } [Theory] @@ -221,24 +203,231 @@ public void Construct_ShouldCreateVersionAndAlias(LambdaFunctionConstructProps p })); } + [Fact] + public void Construct_ShouldUseLiveAliasNameByDefault() + { + var stack = CdkTestHelper.CreateTestStackMinimal(); + + var props = CdkTestHelper.CreatePropsBuilder(AssetPathExtensions.GetTestLambdaZipPath()).Build(); + + _ = new LambdaFunctionConstruct(stack, "test-construct", props); + var template = Template.FromStack(stack); + + template.ShouldHaveVersionAndAlias("live"); + } + + [Fact] + public void Construct_ShouldUseConfiguredAliasName() + { + var stack = CdkTestHelper.CreateTestStackMinimal(); + + var props = CdkTestHelper.CreatePropsBuilder(AssetPathExtensions.GetTestLambdaZipPath()) + .WithAliasName("prod") + .Build(); + + _ = new LambdaFunctionConstruct(stack, "test-construct", props); + var template = Template.FromStack(stack); + + template.ShouldHaveVersionAndAlias("prod"); + } + + [Fact] + public void Construct_ShouldScopeLoggingPolicyToItsLogGroup() + { + var stack = CdkTestHelper.CreateTestStackMinimal(); + + var props = CdkTestHelper.CreatePropsBuilder(AssetPathExtensions.GetTestLambdaZipPath()) + .Build(); + + _ = new LambdaFunctionConstruct(stack, "test-construct", props); + var template = Template.FromStack(stack); + + var logGroupName = $"/aws/lambda/{props.FunctionName}-{props.FunctionSuffix}"; + var logGroupLogicalId = template.FindResources("AWS::Logs::LogGroup").Keys.Single(); + + template.HasResourceProperties("AWS::IAM::Policy", Match.ObjectLike(new Dictionary + { + { "PolicyDocument", Match.ObjectLike(new Dictionary + { + { "Statement", Match.ArrayWith([ + Match.ObjectLike(new Dictionary + { + { "Effect", "Allow" }, + { "Action", Match.ArrayWith(["logs:CreateLogStream", "logs:PutLogEvents"]) }, + { "Resource", new Dictionary + { + { "Fn::GetAtt", new object[] { logGroupLogicalId, "Arn" } } + } + } + }) + ]) } + }) + } + })); + + var templateJson = JsonSerializer.Serialize(template.ToJSON()); + templateJson.Should().NotContain("logs:CreateLogGroup"); + templateJson.Should().NotContain("logs:TagResource"); + templateJson.Should().NotContain($"log-group:{logGroupName}*"); + } + + [Fact] + public void Construct_ShouldUseProvidedBucketCodeAndAddNoBucketGrants() + { + var stack = CdkTestHelper.CreateTestStackMinimal(); + var bucket = Bucket.FromBucketName(stack, "artifact-bucket", "my-lambda-artifacts"); + var code = Code.FromBucketV2(bucket, "lambda/app.zip", new BucketOptions()); + + var props = CdkTestHelper.CreatePropsBuilder(AssetPathExtensions.GetTestLambdaZipPath()) + .WithFunctionName("s3-code") + .WithCode(code) + .Build(); + + _ = new LambdaFunctionConstruct(stack, "test-construct", props); + var template = Template.FromStack(stack); + + template.HasResourceProperties("AWS::Lambda::Function", Match.ObjectLike(new Dictionary + { + { "Code", Match.ObjectLike(new Dictionary + { + { "S3Bucket", "my-lambda-artifacts" }, + { "S3Key", "lambda/app.zip" } + }) + } + })); + + var templateJson = JsonSerializer.Serialize(template.ToJSON()); + templateJson.Should().NotContain("s3:"); + } + + [Fact] + public void Construct_ShouldRejectBothAssetPathAndCode() + { + var stack = CdkTestHelper.CreateTestStackMinimal(); + var bucket = Bucket.FromBucketName(stack, "artifact-bucket", "my-lambda-artifacts"); + + var props = new LambdaFunctionConstructProps + { + FunctionName = "both-sources", + FunctionSuffix = "test", + AssetPath = AssetPathExtensions.GetTestLambdaZipPath(), + Code = Code.FromBucketV2(bucket, "lambda/app.zip", new BucketOptions()), + RoleName = "both-sources-role", + PolicyName = "both-sources-policy" + }; + + Action act = () => _ = new LambdaFunctionConstruct(stack, "test-construct", props); + + act.Should().Throw().WithMessage("*exactly one*"); + } + + [Fact] + public void Construct_ShouldRejectNeitherAssetPathNorCode() + { + var stack = CdkTestHelper.CreateTestStackMinimal(); + + var props = new LambdaFunctionConstructProps + { + FunctionName = "no-source", + FunctionSuffix = "test", + RoleName = "no-source-role", + PolicyName = "no-source-policy" + }; + + Action act = () => _ = new LambdaFunctionConstruct(stack, "test-construct", props); + + act.Should().Throw().WithMessage("*exactly one*"); + } + + [Fact] + public void Construct_ShouldExposeAliasAndVersion() + { + var stack = CdkTestHelper.CreateTestStackMinimal(); + + var props = CdkTestHelper.CreatePropsBuilder(AssetPathExtensions.GetTestLambdaZipPath()) + .WithAliasName("prod") + .Build(); + + var construct = new LambdaFunctionConstruct(stack, "test-construct", props); + var template = Template.FromStack(stack); + + construct.Alias.Should().NotBeNull(); + construct.Version.Should().NotBeNull(); + construct.Version.Should().BeSameAs(construct.LambdaFunction.CurrentVersion); + construct.Alias.Should().BeOfType(); + construct.Alias?.AliasName.Should().Be("prod"); + + template.ResourceCountIs("AWS::Lambda::Version", 1); + template.ShouldHaveVersionAndAlias("prod"); + } + [Theory] [Compose(LambdaFunctionConstructPropsOptions.Permissions)] - public void Construct_ShouldAddPermissionsToAllTargets(LambdaFunctionConstructProps props) + public void Construct_ShouldApplyProfilePermissionsToAliasByDefault(LambdaFunctionConstructProps props) { - var app = new App(); - var stack = new Stack(app, "test-stack", new StackProps + var stack = CdkTestHelper.CreateTestStackMinimal(); + + _ = new LambdaFunctionConstruct(stack, "test-construct", props); + var template = Template.FromStack(stack); + + template.ResourceCountIs("AWS::Lambda::Permission", 1); + template.HasResourceProperties("AWS::Lambda::Permission", Match.ObjectLike(new Dictionary { - Env = new Amazon.CDK.Environment { Account = "123456789012", Region = "us-east-1" } - }); - + { "FunctionName", new Dictionary + { + { "Ref", Match.StringLikeRegexp(".*alias.*") } + } + } + })); + } + + [Theory] + [InlineData(LambdaPermissionTargets.Function, 1)] + [InlineData(LambdaPermissionTargets.Version, 1)] + [InlineData(LambdaPermissionTargets.Alias, 1)] + [InlineData(LambdaPermissionTargets.Function | LambdaPermissionTargets.Version, 2)] + [InlineData(LambdaPermissionTargets.Function | LambdaPermissionTargets.Alias, 2)] + [InlineData(LambdaPermissionTargets.Version | LambdaPermissionTargets.Alias, 2)] + [InlineData(LambdaPermissionTargets.Function | LambdaPermissionTargets.Version | LambdaPermissionTargets.Alias, 3)] + public void Construct_ShouldApplyPermissionsToOnlyTheSelectedTargets( + LambdaPermissionTargets targets, + int expectedPermissionCount) + { + var stack = CdkTestHelper.CreateTestStackMinimal(); + + var props = CdkTestHelper.CreatePropsBuilder(AssetPathExtensions.GetTestLambdaZipPath()) + .WithFunctionName("permission-target") + .WithApiGatewayPermission( + "arn:aws:execute-api:us-east-1:123456789012:api-id/*/GET/test", + targets: targets) + .Build(); + _ = new LambdaFunctionConstruct(stack, "test-construct", props); var template = Template.FromStack(stack); - if (props.Permissions.Count == 0) return; - var expectedPermissionCount = props.Permissions.Count * 3; // function + version + alias template.ResourceCountIs("AWS::Lambda::Permission", expectedPermissionCount); } + [Fact] + public void Construct_ShouldRejectPermissionWithNoTargets() + { + var stack = CdkTestHelper.CreateTestStackMinimal(); + + var props = CdkTestHelper.CreatePropsBuilder(AssetPathExtensions.GetTestLambdaZipPath()) + .WithCustomPermission(new LambdaPermission + { + Principal = "apigateway.amazonaws.com", + Action = "lambda:InvokeFunction", + SourceArn = "arn:aws:execute-api:us-east-1:123456789012:api-id/*/GET/test", + Targets = LambdaPermissionTargets.None + }) + .Build(); + + Action act = () => _ = new LambdaFunctionConstruct(stack, "test-construct", props); + + act.Should().Throw().WithMessage("*no targets*"); + } + [Theory] [Compose(LambdaFunctionConstructPropsOptions.None)] public void Construct_ShouldHandleEmptyPermissionsList(LambdaFunctionConstructProps props) diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/Testing/TestingHelpersTests.cs b/test/LayeredCraft.Cdk.Constructs.Tests/Testing/TestingHelpersTests.cs index 6c0b2c1..7f83beb 100644 --- a/test/LayeredCraft.Cdk.Constructs.Tests/Testing/TestingHelpersTests.cs +++ b/test/LayeredCraft.Cdk.Constructs.Tests/Testing/TestingHelpersTests.cs @@ -1,4 +1,5 @@ using Amazon.CDK.Assertions; +using Amazon.CDK.AWS.Lambda; using AwesomeAssertions; using Compono.XunitV3; using LayeredCraft.Cdk.Constructs; @@ -117,10 +118,83 @@ public void AssertionHelpers_ShouldVerifyLambdaPermissions() // Create template AFTER adding constructs to the stack var template = Template.FromStack(stack); - // Should have 2 permissions * 3 targets (function + version + alias) = 6 total resources + // Each permission is applied to the alias by default template.ShouldHaveLambdaPermissions(2); } + [Fact] + public void AssertionHelpers_ShouldVerifyLambdaPermissionsForExplicitTargets() + { + var stack = CdkTestHelper.CreateTestStackMinimal(); + + var allTargets = LambdaPermissionTargets.Function + | LambdaPermissionTargets.Version + | LambdaPermissionTargets.Alias; + + var props = CdkTestHelper.CreatePropsBuilder(AssetPathExtensions.GetTestLambdaZipPath()) + .WithFunctionName("permission-targets-test") + .WithApiGatewayPermission( + "arn:aws:execute-api:us-east-1:123456789012:abcdef123/prod/GET/test", + targets: allTargets) + .WithAlexaPermission("amzn1.ask.skill.test-skill-id", allTargets) + .Build(); + + _ = new LambdaFunctionConstruct(stack, "TestConstruct", props); + + var template = Template.FromStack(stack); + + template.ShouldHaveLambdaPermissions(2, allTargets); + } + + [Fact] + public void PropsBuilder_ShouldConfigureAliasName() + { + var props = CdkTestHelper.CreatePropsBuilder(AssetPathExtensions.GetTestLambdaZipPath()) + .WithAliasName("staging") + .Build(); + + props.AliasName.Should().Be("staging"); + } + + [Fact] + public void PropsBuilder_ShouldConfigureCodeInsteadOfAssetPath() + { + var code = Code.FromInline("exports.handler = async () => {};"); + + var props = CdkTestHelper.CreatePropsBuilder(AssetPathExtensions.GetTestLambdaZipPath()) + .WithCode(code) + .Build(); + + props.Code.Should().BeSameAs(code); + props.AssetPath.Should().BeNull(); + } + + [Fact] + public void PropsBuilder_ShouldConfigurePermissionTargets() + { + var props = CdkTestHelper.CreatePropsBuilder(AssetPathExtensions.GetTestLambdaZipPath()) + .WithApiGatewayPermission( + "arn:aws:execute-api:us-east-1:123456789012:abcdef123/prod/GET/test", + targets: LambdaPermissionTargets.Function | LambdaPermissionTargets.Version) + .Build(); + + props.Permissions.Should().ContainSingle(); + props.Permissions[0].Targets.Should().Be( + LambdaPermissionTargets.Function | LambdaPermissionTargets.Version); + } + + [Fact] + public void LambdaPermission_ShouldDefaultToAliasTarget() + { + var permission = new LambdaPermission + { + Principal = "apigateway.amazonaws.com", + Action = "lambda:InvokeFunction" + }; + + permission.Targets.Should().Be(LambdaPermissionTargets.Alias); + } + [Fact] public void PropsBuilder_ShouldConfigureS3Access() {