Skip to content
Merged
12 changes: 12 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,13 @@ dotnet add test/LayeredCraft.Cdk.Constructs.Tests/ package PackageName
- Includes automatic asset deployment with cache invalidation
- Exposes `SiteDomain` property containing the fully qualified domain name

**PrivateStaticAssetsConstruct** (`src/LayeredCraft.Cdk.Constructs/PrivateStaticAssetsConstruct.cs`)
- Immutable, versioned web assets in a private bucket (Block Public Access, SSE-S3, SSL-only, versioned, no website endpoint, retained by default)
- CloudFront with `S3BucketOrigin.WithOriginAccessControl` (bucket policy scoped to the distribution's `AWS:SourceArn`), HTTPS-only and `CACHING_OPTIMIZED` by default
- `BucketDeployment` with destination key prefix, `Prune` (default false), `RetainOnDelete` (default true), cache-control and optional invalidation paths
- Optional custom DNS (`PrivateStaticAssetsDomainOptions`), SPA routing and error responses; all off by default
- Exposes `Bucket`, `Distribution` and `DomainName`

**DynamoDbTableConstruct** (`src/LayeredCraft.Cdk.Constructs/DynamoDbTableConstruct.cs`)
- Comprehensive CDK construct for DynamoDB table creation and configuration
- Supports partition keys, sort keys, and global secondary indexes
Expand All @@ -83,6 +90,7 @@ dotnet add test/LayeredCraft.Cdk.Constructs.Tests/ package PackageName
- `LambdaFunctionConstructProps`: Main configuration interface and record for Lambda construct
- `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
- `PrivateStaticAssetsConstructProps`, `PrivateStaticAssetsDomainOptions`: configuration for the private static-assets 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`)

Expand Down Expand Up @@ -180,6 +188,10 @@ The library includes comprehensive testing helpers for consumers:
- Fluent builder for creating static site test props with scenario-based configurations
- Methods like `WithDomainName()`, `WithAlternateDomains()`, `WithApiDomain()`, `ForBlog()`, `ForDocumentation()`, `ForSinglePageApp()`

**PrivateStaticAssetsConstructAssertions** / **PrivateStaticAssetsConstructPropsBuilder**:
- `ShouldHavePrivateBucket()`, `ShouldNotHaveWebsiteEndpoint()`, `ShouldHaveOacOnlyOrigin()`, `ShouldScopeBucketPolicyToDistribution()`, `ShouldHaveHttpsOnlyViewerPolicy()`, `ShouldHaveBucketDeployment()`, `ShouldHaveDnsRecords()`
- Builder methods such as `WithDestinationKeyPrefix()`, `WithCacheControl()`, `WithDomain()`, `WithSpaRouting()`

**DynamoDbTableConstructAssertions** (`DynamoDbTableConstructAssertions.cs`):
- Extension methods for Template assertions specific to DynamoDB tables
- `ShouldHaveDynamoTable()`, `ShouldHavePartitionKey()`, `ShouldHaveSortKey()`, `ShouldHaveGlobalSecondaryIndex()`, `ShouldHaveTableStream()`, `ShouldHaveTimeToLiveAttribute()`, `ShouldHaveTableOutputs()`, etc.
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ A comprehensive library of reusable AWS CDK constructs for .NET projects, design
- **🚀 Lambda Functions**: Comprehensive Lambda construct with configurable OpenTelemetry support, IAM management, and environment configuration
- **🕸️ Web Functions**: AWS Lambda Web Functions served from an S3 artifact, with IAM or application-managed endpoints, endpoint-scoped grants, and CloudFront OAC origin integration
- **🌐 Static Sites**: Complete static website hosting with S3, CloudFront, SSL certificates, and Route53 DNS management
- **🔒 Private Static Assets**: Immutable, versioned assets in a private bucket behind CloudFront OAC, with optional custom DNS
- **📊 DynamoDB Tables**: Full-featured DynamoDB construct with streams, TTL, and global secondary indexes
- **🔐 Cognito User Pools**: Complete Cognito user pool with custom domains, resource servers, OAuth clients, and Managed Login branding
- **🧪 Testing Helpers**: Extensive testing utilities with fluent assertions and builders
Expand Down Expand Up @@ -130,6 +131,7 @@ public class MyStack : Stack

- **[Lambda Function Construct](https://layeredcraft.github.io/cdk-constructs/constructs/lambda-function)** - Full-featured Lambda functions with OpenTelemetry, IAM, and more
- **[Web Function Construct](https://layeredcraft.github.io/cdk-constructs/constructs/web-function)** - Lambda Web Functions with S3 artifacts, IAM/application-managed endpoints, and CloudFront OAC
- **[Private Static Assets Construct](https://layeredcraft.github.io/cdk-constructs/constructs/private-static-assets)** - Private S3 bucket, CloudFront OAC, HTTPS-only, immutable versioned deployments
- **[Static Site Construct](https://layeredcraft.github.io/cdk-constructs/constructs/static-site)** - Complete static website hosting with CloudFront and SSL
- **[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
Expand Down
18 changes: 0 additions & 18 deletions docs/constructs/cognito-user-pool.md
Original file line number Diff line number Diff line change
Expand Up @@ -321,24 +321,6 @@ template.ShouldExportUserPoolArn("test-stack", "auth-pool");
template.ShouldExportAppClientId("test-stack", "auth-pool", "web-app");
```

### AutoFixture Integration

```csharp
[Theory]
[CognitoUserPoolConstructAutoData]
public void Should_Create_User_Pool(CognitoUserPoolConstructProps props)
{
// props generated with sensible defaults (no branding)
}

[Theory]
[CognitoUserPoolConstructAutoData(includeBranding: true)]
public void Should_Create_User_Pool_With_Branding(CognitoUserPoolConstructProps props)
{
// props generated with Managed Login branding included
}
```

## Examples

For more real-world examples, see the [Examples](../examples/index.md) section.
176 changes: 176 additions & 0 deletions docs/constructs/private-static-assets.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
# Private Static Assets Construct

The `PrivateStaticAssetsConstruct` hosts **immutable, versioned web assets** in a private S3 bucket and serves
them through a CloudFront distribution that reaches the bucket with an **origin access control (OAC)**. It is
the private counterpart to [`StaticSiteConstruct`](static-site.md): there is no public website endpoint, no
public bucket access, and no Route53 requirement. Optional custom DNS, SPA routing and error rewrites are off
by default.

## :lock: Features

- **:lock: Private S3 bucket**: Block Public Access fully on, SSE-S3 encryption, SSL-only bucket policy,
versioning enabled, and no static website endpoint
- **:shield: CloudFront with OAC**: the distribution reaches the bucket only through an origin access control;
the bucket policy grants `cloudfront.amazonaws.com` `s3:GetObject`, scoped to the distribution's `SourceArn`
- **:closed_lock_with_key: HTTPS-only by default**: the default viewer protocol policy is `https-only`
(`redirect-to-https` is available)
- **:zap: Caching**: `CachePolicy.CACHING_OPTIMIZED` by default, configurable
- **:package: Immutable deployment**: `BucketDeployment` with a destination key prefix, `Prune` off by default,
`RetainOnDelete` on by default, cache-control metadata, and optional invalidation paths
- **:globe_with_meridians: Optional custom DNS**: domain names, a certificate (or a hosted-zone lookup) and A/AAAA
alias records
- **:curly_loop: Optional SPA routing and error rewrites**: off by default

## Basic Usage

```csharp
using Amazon.CDK;
using LayeredCraft.Cdk.Constructs;
using LayeredCraft.Cdk.Constructs.Models;

public class MyStack : Stack
{
public MyStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
{
var assets = new PrivateStaticAssetsConstruct(this, "GameAssets", new PrivateStaticAssetsConstructProps
{
AssetPath = "./dist"
});

// assets.Bucket -> IBucket
// assets.Distribution -> IDistribution
// assets.DomainName -> the distribution's CloudFront domain name (no custom DNS configured)
}
}
```

## Immutable, versioned deployment

Deploy immutable game assets under a versioned prefix, keep the previous versions (no prune), retain the
objects when the deployment resource is removed, and serve them with a long-lived immutable cache-control
header:

```csharp
var assets = new PrivateStaticAssetsConstruct(this, "GameAssets", new PrivateStaticAssetsConstructProps
{
AssetPath = "./dist/game",
DestinationKeyPrefix = $"game/{buildVersion}/",
Prune = false,
RetainOnDelete = true,
CacheControl =
[
CacheControl.SetPublic(),
CacheControl.MaxAge(Duration.Days(365)),
CacheControl.Immutable(),
],
});
```

This produces objects at `game/<version>/...` with `Cache-Control: public, max-age=31536000, immutable`,
without deleting older versions.

## Configuration Properties

### Required Properties

| Property | Type | Description |
|----------|------|-------------|
| `AssetPath` | `string` | Path to the asset directory (or file) deployed to the bucket |

### Optional Properties

| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `DestinationKeyPrefix` | `string?` | `null` | Key prefix in the bucket for the deployed assets |
| `Prune` | `bool` | `false` | Delete objects that are not in the asset during deployment |
| `RetainOnDelete` | `bool` | `true` | Retain deployed objects when the deployment resource is removed |
| `CacheControl` | `CacheControl[]` | `[]` | `Cache-Control` metadata applied to every deployed object |
| `InvalidationPaths` | `string[]?` | `null` | When set (non-empty), invalidate these CloudFront paths after deployment |
| `RemovalPolicy` | `RemovalPolicy` | `RemovalPolicy.RETAIN` | Removal policy for the bucket |
| `ViewerProtocolPolicy` | `ViewerProtocolPolicy` | `HTTPS_ONLY` | Viewer protocol policy for the default behavior |
| `CachePolicy` | `ICachePolicy` | `CachePolicy.CACHING_OPTIMIZED` | Cache policy for the default behavior |
| `Comment` | `string?` | `null` | CloudFront distribution comment |
| `SpaRouting` | `bool` | `false` | Rewrite extensionless paths to `/index.html` for SPAs |
| `ErrorResponses` | `IErrorResponse[]` | `[]` | Custom error responses for the distribution |
| `DefaultRootObject` | `string?` | `null` | Default root object for the distribution |
| `Domain` | `PrivateStaticAssetsDomainOptions?` | `null` | Optional custom DNS configuration |

## Construct Properties

| Property | Type | Description |
|----------|------|-------------|
| `Bucket` | `IBucket` | The private S3 bucket that stores the assets |
| `Distribution` | `IDistribution` | The CloudFront distribution that serves the assets |
| `DomainName` | `string` | The first custom domain name when DNS is configured, otherwise the distribution's CloudFront domain name |

## Custom DNS

Custom DNS is off by default (the CloudFront domain is used). When configured, the distribution gets the domain
names as aliases, and when a hosted zone is available, A and AAAA alias records are created for every domain
name.

```csharp
var assets = new PrivateStaticAssetsConstruct(this, "GameAssets", new PrivateStaticAssetsConstructProps
{
AssetPath = "./dist/game",
DestinationKeyPrefix = $"game/{buildVersion}/",
CacheControl = [CacheControl.SetPublic(), CacheControl.MaxAge(Duration.Days(365)), CacheControl.Immutable()],
Domain = new PrivateStaticAssetsDomainOptions
{
DomainNames = ["assets.example.com", "cdn.example.com"],
// Either supply a certificate, or a hosted zone (or hosted-zone name) so one can be created.
HostedZoneName = "example.com",
},
});
```

`PrivateStaticAssetsDomainOptions`:

| Property | Type | Description |
|----------|------|-------------|
| `DomainNames` | `string[]` | The custom domain names (at least one) |
| `Certificate` | `ICertificate?` | Certificate for the domain names; created (DNS-validated) when omitted. Because CloudFront only accepts viewer certificates from `us-east-1`, the construct rejects certificate creation when the stack region is resolved and is not `us-east-1`; supply a certificate created in `us-east-1` instead. A supplied certificate is accepted in any stack region |
| `HostedZone` | `IHostedZone?` | Hosted zone for validation and records; mutually exclusive with `HostedZoneName` |
| `HostedZoneName` | `string?` | Hosted-zone name looked up with `HostedZone.FromLookup`; mutually exclusive with `HostedZone` |

Validation at construction (`ArgumentException`):

- no domain names;
- both `HostedZone` and `HostedZoneName` set;
- neither a `Certificate` nor a hosted zone (or hosted-zone name) available;
- no `Certificate` and the stack region is resolved and is not `us-east-1` (a CloudFront viewer certificate must
be created in `us-east-1`; supply a `Certificate` created there). An environment-agnostic stack (unresolved
region) cannot be checked at synthesis and keeps creating the certificate.

## CloudFront Configuration

- **Origin**: the S3 bucket through an origin access control (`S3BucketOrigin.WithOriginAccessControl`); no
website endpoint and no public access
- **Viewer protocol**: `https-only` by default (`redirect-to-https` optional)
- **Caching**: `CACHING_OPTIMIZED` by default
- **SPA routing**: off by default; when enabled, a viewer-request CloudFront Function rewrites extensionless
paths to `/index.html` (requests with a file extension pass through unchanged)
- **Error responses**: none by default
- **Default root object**: none by default

## S3 Bucket Configuration

- **Block Public Access**: fully on
- **Encryption**: SSE-S3 (`AES256`)
- **SSL-only**: a bucket policy denies non-TLS requests
- **Versioning**: enabled
- **No static website endpoint**
- **Removal policy**: `RETAIN` by default
- **No auto-delete objects**: with `RemovalPolicy.DESTROY`, CloudFormation cannot delete the bucket while it
still holds objects or object versions, so empty it first or keep the default `RETAIN`

## Testing

See the [Testing Guide](../testing/index.md) for comprehensive testing utilities. The library ships
`PrivateStaticAssetsConstructAssertions` (for example `ShouldHavePrivateBucket`, `ShouldHaveOacOnlyOrigin`,
`ShouldScopeBucketPolicyToDistribution`, `ShouldHaveHttpsOnlyViewerPolicy`, `ShouldHaveBucketDeployment`,
`ShouldHaveDnsRecords`) and `PrivateStaticAssetsConstructPropsBuilder`.

## Examples

For more real-world examples, see the [Examples](../examples/index.md) section.
10 changes: 10 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ A comprehensive library of reusable AWS CDK constructs for .NET projects, design
- **🚀 Lambda Functions**: Comprehensive Lambda construct with configurable OpenTelemetry support, IAM management, and environment configuration
- **🕸️ Web Functions**: AWS Lambda Web Functions served from an S3 artifact, with IAM or application-managed endpoints, endpoint-scoped grants, and CloudFront OAC origin integration
- **🌐 Static Sites**: Complete static website hosting with S3, CloudFront, SSL certificates, and Route53 DNS management
- **🔒 Private Static Assets**: Immutable, versioned assets in a private bucket behind CloudFront OAC
- **📊 DynamoDB Tables**: Full-featured DynamoDB construct with streams, TTL, and global secondary indexes
- **🧪 Testing Helpers**: Extensive testing utilities with fluent assertions and builders
- **📝 Type Safety**: Full TypeScript-style intellisense and compile-time validation
Expand Down Expand Up @@ -92,6 +93,15 @@ Complete static website hosting with:
- Route53 DNS
- API proxy support

### [Private Static Assets Construct](constructs/private-static-assets.md)

Private, immutable web assets behind CloudFront:

- Private S3 bucket (Block Public Access, SSE-S3, SSL-only, versioned)
- CloudFront with origin access control, HTTPS-only by default
- Versioned deployment prefix, no prune, retained objects, cache-control
- Optional custom DNS, SPA routing and error responses (off by default)

### [DynamoDB Table Construct](constructs/dynamodb-table.md)

Production-ready DynamoDB tables with:
Expand Down
Loading