From 7568d9eaa790a09e38933721e9ba74b33584f025 Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Tue, 24 Nov 2026 07:25:47 -0500 Subject: [PATCH 1/6] feat(static-assets): add PrivateStaticAssetsConstruct private bucket and OAC distribution --- .../PrivateStaticAssetsConstructProps.cs | 169 ++++ .../PrivateStaticAssetsConstruct.cs | 200 ++++ .../PrivateStaticAssetsConstructTests.cs | 904 ++++++++++++++++++ ...rivateStaticAssetsConstructPropsProfile.cs | 22 + 4 files changed, 1295 insertions(+) create mode 100644 src/LayeredCraft.Cdk.Constructs/Models/PrivateStaticAssetsConstructProps.cs create mode 100644 src/LayeredCraft.Cdk.Constructs/PrivateStaticAssetsConstruct.cs create mode 100644 test/LayeredCraft.Cdk.Constructs.Tests/PrivateStaticAssetsConstructTests.cs create mode 100644 test/LayeredCraft.Cdk.Constructs.Tests/TestKit/Profiles/PrivateStaticAssetsConstructPropsProfile.cs diff --git a/src/LayeredCraft.Cdk.Constructs/Models/PrivateStaticAssetsConstructProps.cs b/src/LayeredCraft.Cdk.Constructs/Models/PrivateStaticAssetsConstructProps.cs new file mode 100644 index 0000000..174e8e6 --- /dev/null +++ b/src/LayeredCraft.Cdk.Constructs/Models/PrivateStaticAssetsConstructProps.cs @@ -0,0 +1,169 @@ +using Amazon.CDK; +using Amazon.CDK.AWS.CertificateManager; +using Amazon.CDK.AWS.CloudFront; +using Amazon.CDK.AWS.Route53; +using Amazon.CDK.AWS.S3.Deployment; + +namespace LayeredCraft.Cdk.Constructs.Models; + +/// +/// Interface defining configuration properties for . +/// Describes immutable, versioned web assets stored in a private S3 bucket and served through a CloudFront +/// distribution that reaches the bucket with an origin access control. +/// +public interface IPrivateStaticAssetsConstructProps +{ + /// + /// Path to the asset directory that is deployed to the bucket (a file or folder passed to + /// Source.Asset). + /// + string AssetPath { get; set; } + + /// + /// Optional key prefix in the destination bucket for the deployed assets. Recommended so a deployment + /// only ever manages its own objects. Defaults to null (the bucket root). + /// + string? DestinationKeyPrefix { get; set; } + + /// + /// Whether objects in the destination bucket that are not in the asset are deleted during deployment. + /// Defaults to false. + /// + bool Prune { get; set; } + + /// + /// Whether the deployed objects are retained when the deployment resource is deleted or replaced. + /// Defaults to true. + /// + bool RetainOnDelete { get; set; } + + /// + /// Cache-Control metadata applied to every deployed object. Defaults to none. + /// + CacheControl[] CacheControl { get; set; } + + /// + /// Optional CloudFront invalidation paths. When set (a non-empty array), the distribution is invalidated + /// for those paths after deployment; when omitted, no invalidation occurs. Defaults to null. + /// + string[]? InvalidationPaths { get; set; } + + /// + /// Removal policy for the bucket. Defaults to . + /// + RemovalPolicy RemovalPolicy { get; set; } + + /// + /// Viewer protocol policy for the default behavior. Defaults to + /// . + /// + ViewerProtocolPolicy ViewerProtocolPolicy { get; set; } + + /// + /// Cache policy for the default behavior. Defaults to + /// . + /// + ICachePolicy CachePolicy { get; set; } + + /// Optional comment for the CloudFront distribution. Defaults to none. + string? Comment { get; set; } + + /// + /// Whether to attach a viewer-request CloudFront Function that rewrites extensionless paths to + /// /index.html for single-page applications. Defaults to false. + /// + bool SpaRouting { get; set; } + + /// + /// Custom error responses for the distribution. Defaults to none. + /// + IErrorResponse[] ErrorResponses { get; set; } + + /// Optional default root object for the distribution. Defaults to null. + string? DefaultRootObject { get; set; } + + /// + /// Optional custom DNS configuration. When omitted, the distribution's CloudFront domain name is used + /// and no certificate or DNS records are created. Defaults to null. + /// + PrivateStaticAssetsDomainOptions? Domain { get; set; } +} + +/// +/// Implementation record for . Required members use +/// required; optional members carry the construct's documented defaults. +/// +public record PrivateStaticAssetsConstructProps : IPrivateStaticAssetsConstructProps +{ + /// + public required string AssetPath { get; set; } + + /// + public string? DestinationKeyPrefix { get; set; } + + /// + public bool Prune { get; set; } + + /// + public bool RetainOnDelete { get; set; } = true; + + /// + public CacheControl[] CacheControl { get; set; } = []; + + /// + public string[]? InvalidationPaths { get; set; } + + /// + public RemovalPolicy RemovalPolicy { get; set; } = Amazon.CDK.RemovalPolicy.RETAIN; + + /// + public ViewerProtocolPolicy ViewerProtocolPolicy { get; set; } = Amazon.CDK.AWS.CloudFront.ViewerProtocolPolicy.HTTPS_ONLY; + + /// + public ICachePolicy CachePolicy { get; set; } = Amazon.CDK.AWS.CloudFront.CachePolicy.CACHING_OPTIMIZED; + + /// + public string? Comment { get; set; } + + /// + public bool SpaRouting { get; set; } + + /// + public IErrorResponse[] ErrorResponses { get; set; } = []; + + /// + public string? DefaultRootObject { get; set; } + + /// + public PrivateStaticAssetsDomainOptions? Domain { get; set; } +} + +/// +/// Optional custom DNS configuration for . At least one domain name +/// is required. Provide a certificate, or a hosted zone (or hosted-zone name) so a DNS-validated certificate +/// can be created. A hosted zone and a hosted-zone name are mutually exclusive; when a zone is available, +/// A and AAAA alias records are created for every domain name. +/// +public record PrivateStaticAssetsDomainOptions +{ + /// The custom domain names to associate with the distribution. At least one is required. + public required string[] DomainNames { get; set; } + + /// + /// Optional certificate for the domain names. When omitted, a DNS-validated certificate is created using + /// the hosted zone. + /// + public ICertificate? Certificate { get; set; } + + /// + /// Optional hosted zone used for certificate validation and alias records. Mutually exclusive with + /// . + /// + public IHostedZone? HostedZone { get; set; } + + /// + /// Optional hosted-zone name looked up with HostedZone.FromLookup. Mutually exclusive with + /// . + /// + public string? HostedZoneName { get; set; } +} diff --git a/src/LayeredCraft.Cdk.Constructs/PrivateStaticAssetsConstruct.cs b/src/LayeredCraft.Cdk.Constructs/PrivateStaticAssetsConstruct.cs new file mode 100644 index 0000000..58ac75e --- /dev/null +++ b/src/LayeredCraft.Cdk.Constructs/PrivateStaticAssetsConstruct.cs @@ -0,0 +1,200 @@ +using Amazon.CDK; +using Amazon.CDK.AWS.CertificateManager; +using Amazon.CDK.AWS.CloudFront; +using Amazon.CDK.AWS.CloudFront.Origins; +using Amazon.CDK.AWS.Route53; +using Amazon.CDK.AWS.Route53.Targets; +using Amazon.CDK.AWS.S3; +using Amazon.CDK.AWS.S3.Deployment; +using Constructs; +using LayeredCraft.Cdk.Constructs.Models; + +namespace LayeredCraft.Cdk.Constructs; + +/// +/// AWS CDK construct for hosting immutable, versioned web assets in a private S3 bucket and serving them +/// through a CloudFront distribution that reaches the bucket with an origin access control (OAC). No website +/// endpoint and no public access are used; optional custom DNS, SPA routing and error rewrites are off by +/// default. +/// +public class PrivateStaticAssetsConstruct : Construct +{ + /// Gets the private S3 bucket that stores the assets. + public IBucket Bucket { get; } + + /// Gets the CloudFront distribution that serves the assets. + public IDistribution Distribution { get; } + + /// + /// Gets the primary domain name: the first configured custom domain name when DNS is configured, otherwise + /// the distribution's CloudFront domain name. + /// + public string DomainName { get; } + + /// Initializes a new instance of the class. + /// The parent construct. + /// The construct ID. + /// Configuration properties for the construct. + public PrivateStaticAssetsConstruct(Construct scope, string id, IPrivateStaticAssetsConstructProps props) + : base(scope, id) + { + ArgumentNullException.ThrowIfNull(props); + + var bucket = new Bucket(this, $"{id}-bucket", new BucketProps + { + BlockPublicAccess = BlockPublicAccess.BLOCK_ALL, + Encryption = BucketEncryption.S3_MANAGED, + EnforceSSL = true, + Versioned = true, + RemovalPolicy = props.RemovalPolicy, + }); + + Bucket = bucket; + + ResolveDomain(props.Domain, id, out var domainNames, out var certificate, out var zone); + + Amazon.CDK.AWS.CloudFront.Function? spaRewriteFunction = null; + if (props.SpaRouting) + { + spaRewriteFunction = new Amazon.CDK.AWS.CloudFront.Function(this, $"{id}-spa-rewrite", + new FunctionProps + { + Code = FunctionCode.FromInline(""" + function handler(event) { + var uri = event.request.uri; + if (!uri.match(/\.[a-zA-Z0-9]+$/)) { + event.request.uri = '/index.html'; + } + return event.request; + } + """), + Runtime = FunctionRuntime.JS_2_0, + Comment = "Rewrite SPA routes to /index.html for client-side routing", + }); + } + + FunctionAssociation[]? functionAssociations = spaRewriteFunction is null + ? null + : + [ + new FunctionAssociation + { + Function = spaRewriteFunction, + EventType = FunctionEventType.VIEWER_REQUEST, + }, + ]; + + var distribution = new Distribution(this, $"{id}-cdn", new DistributionProps + { + DefaultBehavior = new BehaviorOptions + { + Origin = S3BucketOrigin.WithOriginAccessControl(bucket), + AllowedMethods = AllowedMethods.ALLOW_GET_HEAD, + Compress = true, + ViewerProtocolPolicy = props.ViewerProtocolPolicy, + CachePolicy = props.CachePolicy, + FunctionAssociations = functionAssociations, + }, + Comment = props.Comment, + ErrorResponses = props.ErrorResponses.Length > 0 ? props.ErrorResponses : null, + DefaultRootObject = props.DefaultRootObject, + DomainNames = domainNames, + Certificate = certificate, + }); + + Distribution = distribution; + DomainName = domainNames is not null ? domainNames[0] : distribution.DomainName; + + if (zone is not null && domainNames is not null) + { + for (var index = 0; index < domainNames.Length; index++) + { + _ = new ARecord(this, $"{id}-a-record-{index}", new ARecordProps + { + Zone = zone, + RecordName = domainNames[index], + Target = RecordTarget.FromAlias(new CloudFrontTarget(distribution)), + }); + + _ = new AaaaRecord(this, $"{id}-aaaa-record-{index}", new AaaaRecordProps + { + Zone = zone, + RecordName = domainNames[index], + Target = RecordTarget.FromAlias(new CloudFrontTarget(distribution)), + }); + } + } + + var deploymentProps = new BucketDeploymentProps + { + Sources = [Source.Asset(props.AssetPath)], + DestinationBucket = bucket, + DestinationKeyPrefix = props.DestinationKeyPrefix, + Prune = props.Prune, + RetainOnDelete = props.RetainOnDelete, + CacheControl = props.CacheControl.Length > 0 ? props.CacheControl : null, + }; + + if (props.InvalidationPaths is { Length: > 0 } invalidationPaths) + { + deploymentProps.Distribution = distribution; + deploymentProps.DistributionPaths = invalidationPaths; + } + + _ = new BucketDeployment(this, $"{id}-deployment", deploymentProps); + } + + private void ResolveDomain( + PrivateStaticAssetsDomainOptions? domain, + string id, + out string[]? domainNames, + out ICertificate? certificate, + out IHostedZone? zone) + { + domainNames = null; + certificate = null; + zone = null; + + if (domain is null) + { + return; + } + + if (domain.DomainNames.Length == 0) + { + throw new ArgumentException( + "At least one domain name is required when a custom domain is configured.", nameof(domain)); + } + + if (domain.HostedZone is not null && domain.HostedZoneName is not null) + { + throw new ArgumentException( + "Specify either HostedZone or HostedZoneName, not both.", nameof(domain)); + } + + zone = domain.HostedZone + ?? (domain.HostedZoneName is not null + ? HostedZone.FromLookup(this, $"{id}-zone", new HostedZoneProviderProps + { + DomainName = domain.HostedZoneName, + }) + : null); + + if (domain.Certificate is null && zone is null) + { + throw new ArgumentException( + "A custom domain requires a Certificate, or a HostedZone (or HostedZoneName) to create one.", + nameof(domain)); + } + + certificate = domain.Certificate + ?? new Certificate(this, $"{id}-certificate", new CertificateProps + { + DomainName = domain.DomainNames[0], + SubjectAlternativeNames = domain.DomainNames.Length > 1 ? domain.DomainNames[1..] : null, + Validation = CertificateValidation.FromDns(zone), + }); + + domainNames = domain.DomainNames; + } +} diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/PrivateStaticAssetsConstructTests.cs b/test/LayeredCraft.Cdk.Constructs.Tests/PrivateStaticAssetsConstructTests.cs new file mode 100644 index 0000000..0e44c99 --- /dev/null +++ b/test/LayeredCraft.Cdk.Constructs.Tests/PrivateStaticAssetsConstructTests.cs @@ -0,0 +1,904 @@ +using Amazon.CDK; +using Amazon.CDK.AWS.CertificateManager; +using Amazon.CDK.AWS.CloudFront; +using Amazon.CDK.AWS.Route53; +using Amazon.CDK.AWS.S3.Deployment; +using Amazon.CDK.Assertions; +using AwesomeAssertions; +using Compono.XunitV3; +using LayeredCraft.Cdk.Constructs; +using LayeredCraft.Cdk.Constructs.Models; +using LayeredCraft.Cdk.Constructs.Testing; +using LayeredCraft.Cdk.Constructs.Tests.TestKit.Profiles; + +namespace LayeredCraft.Cdk.Constructs.Tests; + +/// +/// Behavior tests for : the private bucket contract (Block Public +/// Access, SSE-S3, SSL-only, versioning, no website endpoint), the OAC-only CloudFront origin, the immutable +/// deployment, optional SPA routing, error responses and custom DNS, and the public properties. +/// +[Collection("CDK Tests")] +public class PrivateStaticAssetsConstructTests +{ + private const string AssetPath = "TestAssets/static-site"; + + private static PrivateStaticAssetsConstructProps CreateProps() => new() + { + AssetPath = CdkTestHelper.GetTestAssetPath(AssetPath), + }; + + // ---- Bucket: Block Public Access, SSE-S3, versioning, no website endpoint ---- + + [Fact] + public void Construct_ShouldBlockAllPublicAccessOnBucket() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::S3::Bucket", Match.ObjectLike(new Dictionary + { + ["PublicAccessBlockConfiguration"] = Match.ObjectLike(new Dictionary + { + ["BlockPublicAcls"] = true, + ["BlockPublicPolicy"] = true, + ["IgnorePublicAcls"] = true, + ["RestrictPublicBuckets"] = true, + }), + })); + } + + [Fact] + public void Construct_ShouldEncryptBucketWithSseS3() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::S3::Bucket", Match.ObjectLike(new Dictionary + { + ["BucketEncryption"] = Match.ObjectLike(new Dictionary + { + ["ServerSideEncryptionConfiguration"] = Match.ArrayWith(new object[] + { + Match.ObjectLike(new Dictionary + { + ["ServerSideEncryptionByDefault"] = Match.ObjectLike(new Dictionary + { + ["SSEAlgorithm"] = "AES256", + }), + }), + }), + }), + })); + } + + [Fact] + public void Construct_ShouldVersionBucket() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::S3::Bucket", Match.ObjectLike(new Dictionary + { + ["VersioningConfiguration"] = Match.ObjectLike(new Dictionary + { + ["Status"] = "Enabled", + }), + })); + } + + [Fact] + public void Construct_ShouldNotConfigureWebsiteEndpoint() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::S3::Bucket", Match.Not(Match.ObjectLike(new Dictionary + { + ["WebsiteConfiguration"] = Match.AnyValue(), + }))); + } + + [Fact] + public void Construct_ShouldEnforceSslOnlyBucketPolicy() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::S3::BucketPolicy", Match.ObjectLike(new Dictionary + { + ["PolicyDocument"] = Match.ObjectLike(new Dictionary + { + ["Statement"] = Match.ArrayWith(new object[] + { + Match.ObjectLike(new Dictionary + { + ["Effect"] = "Deny", + ["Action"] = "s3:*", + ["Condition"] = Match.ObjectLike(new Dictionary + { + ["Bool"] = Match.ObjectLike(new Dictionary + { + ["aws:SecureTransport"] = "false", + }), + }), + }), + }), + }), + })); + } + + // ---- Bucket removal policy ---- + + [Fact] + public void Construct_ShouldRetainBucketByDefault() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.HasResource("AWS::S3::Bucket", Match.ObjectLike(new Dictionary + { + ["DeletionPolicy"] = "Retain", + })); + } + + [Fact] + public void Construct_ShouldHonorConfiguredRemovalPolicy() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var props = CreateProps(); + props.RemovalPolicy = RemovalPolicy.DESTROY; + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.HasResource("AWS::S3::Bucket", Match.ObjectLike(new Dictionary + { + ["DeletionPolicy"] = "Delete", + })); + } + + // ---- CloudFront: OAC-only origin, scoped bucket policy, viewer and cache policy ---- + + [Fact] + public void Construct_ShouldCreateDistributionWithOriginAccessControl() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::CloudFront::OriginAccessControl", Match.ObjectLike(new Dictionary + { + ["OriginAccessControlConfig"] = Match.ObjectLike(new Dictionary + { + ["OriginAccessControlOriginType"] = "s3", + }), + })); + + template.HasResourceProperties("AWS::CloudFront::Distribution", Match.ObjectLike(new Dictionary + { + ["DistributionConfig"] = Match.ObjectLike(new Dictionary + { + ["Origins"] = Match.ArrayWith(new object[] + { + Match.ObjectLike(new Dictionary + { + ["OriginAccessControlId"] = Match.AnyValue(), + }), + }), + }), + })); + } + + [Fact] + public void Construct_ShouldScopeBucketPolicyToDistribution() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::S3::BucketPolicy", Match.ObjectLike(new Dictionary + { + ["PolicyDocument"] = Match.ObjectLike(new Dictionary + { + ["Statement"] = Match.ArrayWith(new object[] + { + Match.ObjectLike(new Dictionary + { + ["Effect"] = "Allow", + ["Action"] = "s3:GetObject", + ["Principal"] = Match.ObjectLike(new Dictionary + { + ["Service"] = "cloudfront.amazonaws.com", + }), + ["Condition"] = Match.ObjectLike(new Dictionary + { + ["StringEquals"] = Match.ObjectLike(new Dictionary + { + ["AWS:SourceArn"] = Match.AnyValue(), + }), + }), + }), + }), + }), + })); + } + + [Fact] + public void Construct_ShouldNotGrantPublicBucketAccess() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::S3::BucketPolicy", Match.Not(Match.ObjectLike(new Dictionary + { + ["PolicyDocument"] = Match.ObjectLike(new Dictionary + { + ["Statement"] = Match.ArrayWith(new object[] + { + Match.ObjectLike(new Dictionary + { + ["Principal"] = "*", + }), + }), + }), + }))); + } + + [Fact] + public void Construct_ShouldUseHttpsOnlyViewerPolicyByDefault() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::CloudFront::Distribution", Match.ObjectLike(new Dictionary + { + ["DistributionConfig"] = Match.ObjectLike(new Dictionary + { + ["DefaultCacheBehavior"] = Match.ObjectLike(new Dictionary + { + ["ViewerProtocolPolicy"] = "https-only", + }), + }), + })); + } + + [Fact] + public void Construct_ShouldHonorRedirectViewerPolicy() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var props = CreateProps(); + props.ViewerProtocolPolicy = ViewerProtocolPolicy.REDIRECT_TO_HTTPS; + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::CloudFront::Distribution", Match.ObjectLike(new Dictionary + { + ["DistributionConfig"] = Match.ObjectLike(new Dictionary + { + ["DefaultCacheBehavior"] = Match.ObjectLike(new Dictionary + { + ["ViewerProtocolPolicy"] = "redirect-to-https", + }), + }), + })); + } + + [Fact] + public void Construct_ShouldUseCachingOptimizedPolicyByDefault() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::CloudFront::Distribution", Match.ObjectLike(new Dictionary + { + ["DistributionConfig"] = Match.ObjectLike(new Dictionary + { + ["DefaultCacheBehavior"] = Match.ObjectLike(new Dictionary + { + ["CachePolicyId"] = "658327ea-f89d-4fab-a63d-7e88639e58f6", + }), + }), + })); + } + + [Fact] + public void Construct_ShouldHonorCustomCachePolicy() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var props = CreateProps(); + props.CachePolicy = CachePolicy.CACHING_DISABLED; + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::CloudFront::Distribution", Match.ObjectLike(new Dictionary + { + ["DistributionConfig"] = Match.ObjectLike(new Dictionary + { + ["DefaultCacheBehavior"] = Match.ObjectLike(new Dictionary + { + ["CachePolicyId"] = "4135ea2d-6df8-44a3-9df3-4b5a84be39ad", + }), + }), + })); + } + + // ---- SPA routing and error rewrites (off by default) ---- + + [Fact] + public void Construct_ShouldNotAddSpaFunctionByDefault() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.ResourceCountIs("AWS::CloudFront::Function", 0); + template.HasResourceProperties("AWS::CloudFront::Distribution", Match.Not(Match.ObjectLike(new Dictionary + { + ["DistributionConfig"] = Match.ObjectLike(new Dictionary + { + ["DefaultCacheBehavior"] = Match.ObjectLike(new Dictionary + { + ["FunctionAssociations"] = Match.AnyValue(), + }), + }), + }))); + } + + [Fact] + public void Construct_ShouldNotAddErrorResponsesByDefault() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::CloudFront::Distribution", Match.Not(Match.ObjectLike(new Dictionary + { + ["DistributionConfig"] = Match.ObjectLike(new Dictionary + { + ["CustomErrorResponses"] = Match.AnyValue(), + }), + }))); + } + + [Fact] + public void Construct_ShouldNotSetDefaultRootObjectByDefault() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::CloudFront::Distribution", Match.Not(Match.ObjectLike(new Dictionary + { + ["DistributionConfig"] = Match.ObjectLike(new Dictionary + { + ["DefaultRootObject"] = Match.AnyValue(), + }), + }))); + } + + [Fact] + public void Construct_ShouldAddSpaRewriteFunctionWhenEnabled() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var props = CreateProps(); + props.SpaRouting = true; + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::CloudFront::Function", Match.ObjectLike(new Dictionary + { + ["FunctionConfig"] = Match.ObjectLike(new Dictionary + { + ["Runtime"] = "cloudfront-js-2.0", + }), + })); + template.HasResourceProperties("AWS::CloudFront::Distribution", Match.ObjectLike(new Dictionary + { + ["DistributionConfig"] = Match.ObjectLike(new Dictionary + { + ["DefaultCacheBehavior"] = Match.ObjectLike(new Dictionary + { + ["FunctionAssociations"] = Match.ArrayWith(new object[] + { + Match.ObjectLike(new Dictionary + { + ["EventType"] = "viewer-request", + }), + }), + }), + }), + })); + } + + [Fact] + public void Construct_ShouldSetErrorResponses() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var props = CreateProps(); + props.ErrorResponses = + [ + new ErrorResponse + { + HttpStatus = 403, + ResponseHttpStatus = 200, + ResponsePagePath = "/index.html", + }, + ]; + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::CloudFront::Distribution", Match.ObjectLike(new Dictionary + { + ["DistributionConfig"] = Match.ObjectLike(new Dictionary + { + ["CustomErrorResponses"] = Match.ArrayWith(new object[] + { + Match.ObjectLike(new Dictionary + { + ["ErrorCode"] = 403, + ["ResponseCode"] = 200, + ["ResponsePagePath"] = "/index.html", + }), + }), + }), + })); + } + + [Fact] + public void Construct_ShouldSetDefaultRootObject() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var props = CreateProps(); + props.DefaultRootObject = "index.html"; + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::CloudFront::Distribution", Match.ObjectLike(new Dictionary + { + ["DistributionConfig"] = Match.ObjectLike(new Dictionary + { + ["DefaultRootObject"] = "index.html", + }), + })); + } + + [Fact] + public void Construct_ShouldSetComment() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var props = CreateProps(); + props.Comment = "Private game assets"; + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::CloudFront::Distribution", Match.ObjectLike(new Dictionary + { + ["DistributionConfig"] = Match.ObjectLike(new Dictionary + { + ["Comment"] = "Private game assets", + }), + })); + } + + // ---- Immutable deployment ---- + + [Fact] + public void Construct_ShouldNotPruneByDefault() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.HasResourceProperties("Custom::CDKBucketDeployment", Match.ObjectLike(new Dictionary + { + ["Prune"] = false, + })); + } + + [Fact] + public void Construct_ShouldPruneWhenConfigured() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var props = CreateProps(); + props.Prune = true; + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.HasResourceProperties("Custom::CDKBucketDeployment", Match.ObjectLike(new Dictionary + { + ["Prune"] = true, + })); + } + + [Fact] + public void Construct_ShouldApplyDestinationKeyPrefix() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var props = CreateProps(); + props.DestinationKeyPrefix = "game/abc123/"; + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.HasResourceProperties("Custom::CDKBucketDeployment", Match.ObjectLike(new Dictionary + { + ["DestinationBucketKeyPrefix"] = "game/abc123/", + })); + } + + [Fact] + public void Construct_ShouldRetainDeploymentByDefault() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.HasResourceProperties("Custom::CDKBucketDeployment", Match.ObjectLike(new Dictionary + { + ["RetainOnDelete"] = true, + })); + } + + [Fact] + public void Construct_ShouldHonorRetainOnDeleteFalse() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var props = CreateProps(); + props.RetainOnDelete = false; + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.HasResourceProperties("Custom::CDKBucketDeployment", Match.ObjectLike(new Dictionary + { + ["RetainOnDelete"] = false, + })); + } + + [Fact] + public void Construct_ShouldNotApplyCacheControlByDefault() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.HasResourceProperties("Custom::CDKBucketDeployment", Match.Not(Match.ObjectLike(new Dictionary + { + ["SystemMetadata"] = Match.AnyValue(), + }))); + } + + [Fact] + public void Construct_ShouldApplyCacheControl() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var props = CreateProps(); + props.CacheControl = [CacheControl.SetPublic(), CacheControl.MaxAge(Duration.Days(365)), CacheControl.Immutable()]; + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.HasResourceProperties("Custom::CDKBucketDeployment", Match.ObjectLike(new Dictionary + { + ["SystemMetadata"] = Match.ObjectLike(new Dictionary + { + ["cache-control"] = "public, max-age=31536000, immutable", + }), + })); + } + + [Fact] + public void Construct_ShouldNotInvalidateWhenNoPathsAreSet() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.HasResourceProperties("Custom::CDKBucketDeployment", Match.Not(Match.ObjectLike(new Dictionary + { + ["DistributionId"] = Match.AnyValue(), + }))); + template.HasResourceProperties("Custom::CDKBucketDeployment", Match.Not(Match.ObjectLike(new Dictionary + { + ["DistributionPaths"] = Match.AnyValue(), + }))); + } + + [Fact] + public void Construct_ShouldInvalidateWhenPathsAreSet() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var props = CreateProps(); + props.InvalidationPaths = ["/index.html", "/assets/*"]; + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.HasResourceProperties("Custom::CDKBucketDeployment", Match.ObjectLike(new Dictionary + { + ["DistributionId"] = Match.AnyValue(), + ["DistributionPaths"] = Match.ArrayWith(new object[] { "/index.html", "/assets/*" }), + })); + } + + // ---- Custom DNS (off by default) ---- + + [Fact] + public void Construct_ShouldNotConfigureDnsByDefault() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + var construct = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + var template = Template.FromStack(stack); + template.ResourceCountIs("AWS::CertificateManager::Certificate", 0); + template.ResourceCountIs("AWS::Route53::RecordSet", 0); + template.HasResourceProperties("AWS::CloudFront::Distribution", Match.Not(Match.ObjectLike(new Dictionary + { + ["DistributionConfig"] = Match.ObjectLike(new Dictionary + { + ["Aliases"] = Match.AnyValue(), + }), + }))); + + construct.DomainName.Should().Be(construct.Distribution.DistributionDomainName); + } + + [Fact] + public void Construct_ShouldConfigureCustomDomainWithCertificateAndRecords() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + var zone = HostedZone.FromHostedZoneAttributes(stack, "HostedZone", new HostedZoneAttributes + { + HostedZoneId = "Z1234567890ABC", + ZoneName = "example.com", + }); + + var certificate = Certificate.FromCertificateArn( + stack, + "Certificate", + "arn:aws:acm:us-east-1:123456789012:certificate/11111111-2222-3333-4444-555555555555"); + + var props = CreateProps(); + props.Domain = new PrivateStaticAssetsDomainOptions + { + DomainNames = ["assets.example.com", "cdn.example.com"], + Certificate = certificate, + HostedZone = zone, + }; + + var construct = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::CloudFront::Distribution", Match.ObjectLike(new Dictionary + { + ["DistributionConfig"] = Match.ObjectLike(new Dictionary + { + ["Aliases"] = Match.ArrayWith(new object[] { "assets.example.com", "cdn.example.com" }), + ["ViewerCertificate"] = Match.ObjectLike(new Dictionary + { + ["AcmCertificateArn"] = "arn:aws:acm:us-east-1:123456789012:certificate/11111111-2222-3333-4444-555555555555", + }), + }), + })); + + template.ResourceCountIs("AWS::Route53::RecordSet", 4); + template.HasResourceProperties("AWS::Route53::RecordSet", Match.ObjectLike(new Dictionary + { + ["Name"] = "assets.example.com.", + ["Type"] = "A", + })); + template.HasResourceProperties("AWS::Route53::RecordSet", Match.ObjectLike(new Dictionary + { + ["Name"] = "assets.example.com.", + ["Type"] = "AAAA", + })); + template.HasResourceProperties("AWS::Route53::RecordSet", Match.ObjectLike(new Dictionary + { + ["Name"] = "cdn.example.com.", + ["Type"] = "A", + })); + template.HasResourceProperties("AWS::Route53::RecordSet", Match.ObjectLike(new Dictionary + { + ["Name"] = "cdn.example.com.", + ["Type"] = "AAAA", + })); + + construct.DomainName.Should().Be("assets.example.com"); + } + + [Fact] + public void Construct_ShouldCreateDnsValidatedCertificateWhenCertificateOmitted() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + var zone = HostedZone.FromHostedZoneAttributes(stack, "HostedZone", new HostedZoneAttributes + { + HostedZoneId = "Z1234567890ABC", + ZoneName = "example.com", + }); + + var props = CreateProps(); + props.Domain = new PrivateStaticAssetsDomainOptions + { + DomainNames = ["assets.example.com", "cdn.example.com"], + HostedZone = zone, + }; + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::CertificateManager::Certificate", Match.ObjectLike(new Dictionary + { + ["DomainName"] = "assets.example.com", + ["SubjectAlternativeNames"] = Match.ArrayWith(new object[] { "cdn.example.com" }), + ["ValidationMethod"] = "DNS", + })); + } + + [Fact] + public void Construct_ShouldLookUpHostedZoneByName() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + var props = CreateProps(); + props.Domain = new PrivateStaticAssetsDomainOptions + { + DomainNames = ["assets.example.com"], + HostedZoneName = "example.com", + }; + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.HasResourceProperties("AWS::CertificateManager::Certificate", Match.ObjectLike(new Dictionary + { + ["DomainName"] = "assets.example.com", + ["ValidationMethod"] = "DNS", + })); + template.ResourceCountIs("AWS::Route53::RecordSet", 2); + template.HasResourceProperties("AWS::Route53::RecordSet", Match.ObjectLike(new Dictionary + { + ["Name"] = "assets.example.com.", + ["Type"] = "A", + })); + template.HasResourceProperties("AWS::Route53::RecordSet", Match.ObjectLike(new Dictionary + { + ["Name"] = "assets.example.com.", + ["Type"] = "AAAA", + })); + } + + // ---- DNS validation ---- + + [Fact] + public void Construct_ShouldThrowWhenDomainHasNoNames() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var props = CreateProps(); + props.Domain = new PrivateStaticAssetsDomainOptions { DomainNames = [] }; + + var act = () => new PrivateStaticAssetsConstruct(stack, "assets", props); + + act.Should().Throw(); + } + + [Fact] + public void Construct_ShouldThrowWhenBothZoneOptionsAreSet() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var zone = HostedZone.FromHostedZoneAttributes(stack, "HostedZone", new HostedZoneAttributes + { + HostedZoneId = "Z1234567890ABC", + ZoneName = "example.com", + }); + var props = CreateProps(); + props.Domain = new PrivateStaticAssetsDomainOptions + { + DomainNames = ["assets.example.com"], + HostedZone = zone, + HostedZoneName = "example.com", + }; + + var act = () => new PrivateStaticAssetsConstruct(stack, "assets", props); + + act.Should().Throw(); + } + + [Fact] + public void Construct_ShouldThrowWhenNoCertificateAndNoZone() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var props = CreateProps(); + props.Domain = new PrivateStaticAssetsDomainOptions + { + DomainNames = ["assets.example.com"], + }; + + var act = () => new PrivateStaticAssetsConstruct(stack, "assets", props); + + act.Should().Throw(); + } + + // ---- Public properties and composed props ---- + + [Fact] + public void Construct_ShouldExposePublicProperties() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + var construct = new PrivateStaticAssetsConstruct(stack, "assets", CreateProps()); + + construct.Bucket.Should().NotBeNull(); + construct.Distribution.Should().NotBeNull(); + construct.DomainName.Should().NotBeNullOrEmpty(); + } + + [Theory] + [Compose] + public void Construct_WithComposedProps_ShouldCreatePrivateAssets(PrivateStaticAssetsConstructProps props) + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.ResourceCountIs("AWS::S3::Bucket", 1); + template.HasResourceProperties("AWS::S3::Bucket", Match.ObjectLike(new Dictionary + { + ["PublicAccessBlockConfiguration"] = Match.ObjectLike(new Dictionary + { + ["BlockPublicAcls"] = true, + ["BlockPublicPolicy"] = true, + ["IgnorePublicAcls"] = true, + ["RestrictPublicBuckets"] = true, + }), + })); + template.HasResourceProperties("AWS::CloudFront::Distribution", Match.ObjectLike(new Dictionary + { + ["DistributionConfig"] = Match.ObjectLike(new Dictionary + { + ["DefaultCacheBehavior"] = Match.ObjectLike(new Dictionary + { + ["ViewerProtocolPolicy"] = "https-only", + }), + }), + })); + } +} diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/TestKit/Profiles/PrivateStaticAssetsConstructPropsProfile.cs b/test/LayeredCraft.Cdk.Constructs.Tests/TestKit/Profiles/PrivateStaticAssetsConstructPropsProfile.cs new file mode 100644 index 0000000..91b9d7f --- /dev/null +++ b/test/LayeredCraft.Cdk.Constructs.Tests/TestKit/Profiles/PrivateStaticAssetsConstructPropsProfile.cs @@ -0,0 +1,22 @@ +using Compono; +using LayeredCraft.Cdk.Constructs.Models; +using LayeredCraft.Cdk.Constructs.Testing; + +namespace LayeredCraft.Cdk.Constructs.Tests.TestKit.Profiles; + +/// +/// Supplies deterministic test data. The required +/// is a real test asset directory; every other member +/// keeps the construct's documented default so tests can assert that default explicitly. +/// +public sealed class PrivateStaticAssetsConstructPropsProfile : ICompositionProfile +{ + // Compono does not provide this because the required AssetPath must point at a real, existing test asset + // directory (composition would generate an arbitrary string that fails at synthesis), so a registration + // factory supplies the whole value. + public void Configure(CompositionBuilder builder) => + builder.Register(() => new PrivateStaticAssetsConstructProps + { + AssetPath = CdkTestHelper.GetTestAssetPath("TestAssets/static-site"), + }); +} From f16fd6c1c65aa73f1fff891dad05e6ed180fa178 Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Tue, 24 Nov 2026 07:25:50 -0500 Subject: [PATCH 2/6] feat(testing): add PrivateStaticAssetsConstruct assertions and props builder --- .../PrivateStaticAssetsConstructAssertions.cs | 203 +++++++++++++ ...rivateStaticAssetsConstructPropsBuilder.cs | 147 +++++++++ ...taticAssetsConstructTestingHelpersTests.cs | 278 ++++++++++++++++++ 3 files changed, 628 insertions(+) create mode 100644 src/LayeredCraft.Cdk.Constructs/Testing/PrivateStaticAssetsConstructAssertions.cs create mode 100644 src/LayeredCraft.Cdk.Constructs/Testing/PrivateStaticAssetsConstructPropsBuilder.cs create mode 100644 test/LayeredCraft.Cdk.Constructs.Tests/Testing/PrivateStaticAssetsConstructTestingHelpersTests.cs diff --git a/src/LayeredCraft.Cdk.Constructs/Testing/PrivateStaticAssetsConstructAssertions.cs b/src/LayeredCraft.Cdk.Constructs/Testing/PrivateStaticAssetsConstructAssertions.cs new file mode 100644 index 0000000..da14295 --- /dev/null +++ b/src/LayeredCraft.Cdk.Constructs/Testing/PrivateStaticAssetsConstructAssertions.cs @@ -0,0 +1,203 @@ +using Amazon.CDK.Assertions; + +namespace LayeredCraft.Cdk.Constructs.Testing; + +/// +/// Extension methods for asserting resources in CDK templates. These +/// helpers simplify the common security and deployment scenarios for consumers of the library. +/// +public static class PrivateStaticAssetsConstructAssertions +{ + /// + /// Asserts that the template contains a private, versioned, SSE-S3 bucket with Block Public Access fully on. + /// + /// The CDK template to assert against. + public static void ShouldHavePrivateBucket(this Template template) + { + template.HasResourceProperties("AWS::S3::Bucket", Match.ObjectLike(new Dictionary + { + ["BucketEncryption"] = Match.ObjectLike(new Dictionary + { + ["ServerSideEncryptionConfiguration"] = Match.ArrayWith(new object[] + { + Match.ObjectLike(new Dictionary + { + ["ServerSideEncryptionByDefault"] = Match.ObjectLike(new Dictionary + { + ["SSEAlgorithm"] = "AES256", + }), + }), + }), + }), + ["PublicAccessBlockConfiguration"] = Match.ObjectLike(new Dictionary + { + ["BlockPublicAcls"] = true, + ["BlockPublicPolicy"] = true, + ["IgnorePublicAcls"] = true, + ["RestrictPublicBuckets"] = true, + }), + ["VersioningConfiguration"] = Match.ObjectLike(new Dictionary + { + ["Status"] = "Enabled", + }), + })); + } + + /// Asserts that the template's bucket has no static website configuration. + /// The CDK template to assert against. + public static void ShouldNotHaveWebsiteEndpoint(this Template template) + { + template.HasResourceProperties("AWS::S3::Bucket", Match.Not(Match.ObjectLike(new Dictionary + { + ["WebsiteConfiguration"] = Match.AnyValue(), + }))); + } + + /// + /// Asserts that the distribution reaches the bucket through an origin access control and that an + /// AWS::CloudFront::OriginAccessControl of origin type s3 exists. + /// + /// The CDK template to assert against. + public static void ShouldHaveOacOnlyOrigin(this Template template) + { + template.HasResourceProperties("AWS::CloudFront::OriginAccessControl", Match.ObjectLike(new Dictionary + { + ["OriginAccessControlConfig"] = Match.ObjectLike(new Dictionary + { + ["OriginAccessControlOriginType"] = "s3", + }), + })); + + template.HasResourceProperties("AWS::CloudFront::Distribution", Match.ObjectLike(new Dictionary + { + ["DistributionConfig"] = Match.ObjectLike(new Dictionary + { + ["Origins"] = Match.ArrayWith(new object[] + { + Match.ObjectLike(new Dictionary + { + ["OriginAccessControlId"] = Match.AnyValue(), + }), + }), + }), + })); + } + + /// + /// Asserts that the bucket policy grants the CloudFront service s3:GetObject, conditioned on the + /// distribution's AWS:SourceArn. + /// + /// The CDK template to assert against. + public static void ShouldScopeBucketPolicyToDistribution(this Template template) + { + template.HasResourceProperties("AWS::S3::BucketPolicy", Match.ObjectLike(new Dictionary + { + ["PolicyDocument"] = Match.ObjectLike(new Dictionary + { + ["Statement"] = Match.ArrayWith(new object[] + { + Match.ObjectLike(new Dictionary + { + ["Effect"] = "Allow", + ["Action"] = "s3:GetObject", + ["Principal"] = Match.ObjectLike(new Dictionary + { + ["Service"] = "cloudfront.amazonaws.com", + }), + ["Condition"] = Match.ObjectLike(new Dictionary + { + ["StringEquals"] = Match.ObjectLike(new Dictionary + { + ["AWS:SourceArn"] = Match.AnyValue(), + }), + }), + }), + }), + }), + })); + } + + /// Asserts that the distribution's default behavior is HTTPS-only. + /// The CDK template to assert against. + public static void ShouldHaveHttpsOnlyViewerPolicy(this Template template) + { + template.HasResourceProperties("AWS::CloudFront::Distribution", Match.ObjectLike(new Dictionary + { + ["DistributionConfig"] = Match.ObjectLike(new Dictionary + { + ["DefaultCacheBehavior"] = Match.ObjectLike(new Dictionary + { + ["ViewerProtocolPolicy"] = "https-only", + }), + }), + })); + } + + /// + /// Asserts the bucket deployment's immutable settings: the destination key prefix (when supplied), the + /// prune and retain-on-delete flags, and the joined Cache-Control value (when supplied). + /// + /// The CDK template to assert against. + /// Expected destination key prefix, or null to skip the check. + /// Expected prune flag (default false). + /// Expected retain-on-delete flag (default true). + /// Expected joined cache-control value, or null to skip the check. + public static void ShouldHaveBucketDeployment(this Template template, string? destinationKeyPrefix = null, + bool prune = false, bool retainOnDelete = true, string? cacheControl = null) + { + var properties = new Dictionary + { + ["DestinationBucketName"] = Match.AnyValue(), + ["Prune"] = prune, + ["RetainOnDelete"] = retainOnDelete, + }; + + if (destinationKeyPrefix is not null) + { + properties["DestinationBucketKeyPrefix"] = destinationKeyPrefix; + } + + if (cacheControl is not null) + { + properties["SystemMetadata"] = Match.ObjectLike(new Dictionary + { + ["cache-control"] = cacheControl, + }); + } + + template.HasResourceProperties("Custom::CDKBucketDeployment", Match.ObjectLike(properties)); + } + + /// + /// Asserts that an A and an AAAA alias record exist for every supplied domain name. + /// + /// The CDK template to assert against. + /// The domain names that should have alias records. + public static void ShouldHaveDnsRecords(this Template template, params string[] domainNames) + { + foreach (var domainName in domainNames) + { + template.HasResourceProperties("AWS::Route53::RecordSet", Match.ObjectLike(new Dictionary + { + ["Name"] = $"{domainName}.", + ["Type"] = "A", + ["AliasTarget"] = Match.ObjectLike(new Dictionary + { + ["DNSName"] = Match.AnyValue(), + ["HostedZoneId"] = Match.AnyValue(), + }), + })); + + template.HasResourceProperties("AWS::Route53::RecordSet", Match.ObjectLike(new Dictionary + { + ["Name"] = $"{domainName}.", + ["Type"] = "AAAA", + ["AliasTarget"] = Match.ObjectLike(new Dictionary + { + ["DNSName"] = Match.AnyValue(), + ["HostedZoneId"] = Match.AnyValue(), + }), + })); + } + } +} diff --git a/src/LayeredCraft.Cdk.Constructs/Testing/PrivateStaticAssetsConstructPropsBuilder.cs b/src/LayeredCraft.Cdk.Constructs/Testing/PrivateStaticAssetsConstructPropsBuilder.cs new file mode 100644 index 0000000..2de5806 --- /dev/null +++ b/src/LayeredCraft.Cdk.Constructs/Testing/PrivateStaticAssetsConstructPropsBuilder.cs @@ -0,0 +1,147 @@ +using Amazon.CDK; +using Amazon.CDK.AWS.CloudFront; +using Amazon.CDK.AWS.S3.Deployment; +using LayeredCraft.Cdk.Constructs.Models; + +namespace LayeredCraft.Cdk.Constructs.Testing; + +/// +/// Fluent builder for used by tests. It mirrors the +/// repository's builder convention (see StaticSiteConstructPropsBuilder, +/// WebFunctionConstructPropsBuilder): private fields, With* methods that return this, and a +/// method that returns the record. +/// +public class PrivateStaticAssetsConstructPropsBuilder +{ + private string _assetPath = CdkTestHelper.GetTestAssetPath("TestAssets/static-site"); + private string? _destinationKeyPrefix; + private bool _prune; + private bool _retainOnDelete = true; + private readonly List _cacheControl = new(); + private string[]? _invalidationPaths; + private RemovalPolicy _removalPolicy = RemovalPolicy.RETAIN; + private ViewerProtocolPolicy _viewerProtocolPolicy = ViewerProtocolPolicy.HTTPS_ONLY; + private ICachePolicy _cachePolicy = CachePolicy.CACHING_OPTIMIZED; + private string? _comment; + private bool _spaRouting; + private readonly List _errorResponses = new(); + private string? _defaultRootObject; + private PrivateStaticAssetsDomainOptions? _domain; + + /// Sets the asset directory deployed to the bucket. + public PrivateStaticAssetsConstructPropsBuilder WithAssetPath(string assetPath) + { + _assetPath = assetPath; + return this; + } + + /// Sets the destination key prefix in the bucket. + public PrivateStaticAssetsConstructPropsBuilder WithDestinationKeyPrefix(string destinationKeyPrefix) + { + _destinationKeyPrefix = destinationKeyPrefix; + return this; + } + + /// Sets whether the deployment prunes objects that are not in the asset (default: true). + public PrivateStaticAssetsConstructPropsBuilder WithPrune(bool prune = true) + { + _prune = prune; + return this; + } + + /// Sets whether deployed objects are retained when the deployment resource is removed. + public PrivateStaticAssetsConstructPropsBuilder WithRetainOnDelete(bool retainOnDelete) + { + _retainOnDelete = retainOnDelete; + return this; + } + + /// Adds Cache-Control metadata applied to every deployed object. + public PrivateStaticAssetsConstructPropsBuilder WithCacheControl(params CacheControl[] cacheControl) + { + _cacheControl.AddRange(cacheControl); + return this; + } + + /// Sets the CloudFront invalidation paths applied after deployment. + public PrivateStaticAssetsConstructPropsBuilder WithInvalidationPaths(params string[] invalidationPaths) + { + _invalidationPaths = invalidationPaths; + return this; + } + + /// Sets the bucket removal policy (default: ). + public PrivateStaticAssetsConstructPropsBuilder WithRemovalPolicy(RemovalPolicy removalPolicy) + { + _removalPolicy = removalPolicy; + return this; + } + + /// Sets the default behavior's viewer protocol policy (default: HTTPS-only). + public PrivateStaticAssetsConstructPropsBuilder WithViewerProtocolPolicy(ViewerProtocolPolicy viewerProtocolPolicy) + { + _viewerProtocolPolicy = viewerProtocolPolicy; + return this; + } + + /// Sets the default behavior's cache policy (default: ). + public PrivateStaticAssetsConstructPropsBuilder WithCachePolicy(ICachePolicy cachePolicy) + { + _cachePolicy = cachePolicy; + return this; + } + + /// Sets the CloudFront distribution comment. + public PrivateStaticAssetsConstructPropsBuilder WithComment(string comment) + { + _comment = comment; + return this; + } + + /// Sets whether SPA route rewriting is enabled (default: true). + public PrivateStaticAssetsConstructPropsBuilder WithSpaRouting(bool spaRouting = true) + { + _spaRouting = spaRouting; + return this; + } + + /// Adds a custom error response to the distribution. + public PrivateStaticAssetsConstructPropsBuilder WithErrorResponse(IErrorResponse errorResponse) + { + _errorResponses.Add(errorResponse); + return this; + } + + /// Sets the distribution's default root object. + public PrivateStaticAssetsConstructPropsBuilder WithDefaultRootObject(string defaultRootObject) + { + _defaultRootObject = defaultRootObject; + return this; + } + + /// Sets the optional custom DNS configuration. + public PrivateStaticAssetsConstructPropsBuilder WithDomain(PrivateStaticAssetsDomainOptions domain) + { + _domain = domain; + return this; + } + + /// Builds the . + public PrivateStaticAssetsConstructProps Build() => new() + { + AssetPath = _assetPath, + DestinationKeyPrefix = _destinationKeyPrefix, + Prune = _prune, + RetainOnDelete = _retainOnDelete, + CacheControl = _cacheControl.ToArray(), + InvalidationPaths = _invalidationPaths, + RemovalPolicy = _removalPolicy, + ViewerProtocolPolicy = _viewerProtocolPolicy, + CachePolicy = _cachePolicy, + Comment = _comment, + SpaRouting = _spaRouting, + ErrorResponses = _errorResponses.ToArray(), + DefaultRootObject = _defaultRootObject, + Domain = _domain, + }; +} diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/Testing/PrivateStaticAssetsConstructTestingHelpersTests.cs b/test/LayeredCraft.Cdk.Constructs.Tests/Testing/PrivateStaticAssetsConstructTestingHelpersTests.cs new file mode 100644 index 0000000..04a1ed8 --- /dev/null +++ b/test/LayeredCraft.Cdk.Constructs.Tests/Testing/PrivateStaticAssetsConstructTestingHelpersTests.cs @@ -0,0 +1,278 @@ +using Amazon.CDK; +using Amazon.CDK.AWS.CertificateManager; +using Amazon.CDK.AWS.CloudFront; +using Amazon.CDK.AWS.Route53; +using Amazon.CDK.AWS.S3.Deployment; +using Amazon.CDK.Assertions; +using AwesomeAssertions; +using LayeredCraft.Cdk.Constructs; +using LayeredCraft.Cdk.Constructs.Models; +using LayeredCraft.Cdk.Constructs.Testing; + +namespace LayeredCraft.Cdk.Constructs.Tests.Testing; + +/// +/// Verifies the consumer-facing and +/// helpers, including negative cases that ensure a wrong +/// expectation is actually detected. +/// +[Collection("CDK Tests")] +public class PrivateStaticAssetsConstructTestingHelpersTests +{ + private const string AssetPath = "TestAssets/static-site"; + + private static PrivateStaticAssetsConstruct CreateConstruct( + Stack stack, + PrivateStaticAssetsConstructProps props, + string id = "assets") + => new(stack, id, props); + + private static PrivateStaticAssetsConstructProps DefaultProps() => new() + { + AssetPath = CdkTestHelper.GetTestAssetPath(AssetPath), + }; + + // ---- ShouldHavePrivateBucket ---- + + [Fact] + public void ShouldHavePrivateBucket_ShouldPassForTheConstructBucket() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + _ = CreateConstruct(stack, DefaultProps()); + + var act = () => Template.FromStack(stack).ShouldHavePrivateBucket(); + + act.Should().NotThrow(); + } + + [Fact] + public void ShouldHavePrivateBucket_ShouldThrowWhenNoBucketExists() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + var act = () => Template.FromStack(stack).ShouldHavePrivateBucket(); + + act.Should().Throw(); + } + + // ---- ShouldNotHaveWebsiteEndpoint ---- + + [Fact] + public void ShouldNotHaveWebsiteEndpoint_ShouldPassForTheConstructBucket() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + _ = CreateConstruct(stack, DefaultProps()); + + var act = () => Template.FromStack(stack).ShouldNotHaveWebsiteEndpoint(); + + act.Should().NotThrow(); + } + + // ---- ShouldHaveOacOnlyOrigin ---- + + [Fact] + public void ShouldHaveOacOnlyOrigin_ShouldPass() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + _ = CreateConstruct(stack, DefaultProps()); + + var act = () => Template.FromStack(stack).ShouldHaveOacOnlyOrigin(); + + act.Should().NotThrow(); + } + + [Fact] + public void ShouldHaveOacOnlyOrigin_ShouldThrowWhenNoOriginAccessControlExists() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + + var act = () => Template.FromStack(stack).ShouldHaveOacOnlyOrigin(); + + act.Should().Throw(); + } + + // ---- ShouldScopeBucketPolicyToDistribution ---- + + [Fact] + public void ShouldScopeBucketPolicyToDistribution_ShouldPass() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + _ = CreateConstruct(stack, DefaultProps()); + + var act = () => Template.FromStack(stack).ShouldScopeBucketPolicyToDistribution(); + + act.Should().NotThrow(); + } + + // ---- ShouldHaveHttpsOnlyViewerPolicy ---- + + [Fact] + public void ShouldHaveHttpsOnlyViewerPolicy_ShouldPassByDefault() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + _ = CreateConstruct(stack, DefaultProps()); + + var act = () => Template.FromStack(stack).ShouldHaveHttpsOnlyViewerPolicy(); + + act.Should().NotThrow(); + } + + [Fact] + public void ShouldHaveHttpsOnlyViewerPolicy_ShouldThrowForRedirectPolicy() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var props = DefaultProps(); + props.ViewerProtocolPolicy = ViewerProtocolPolicy.REDIRECT_TO_HTTPS; + _ = CreateConstruct(stack, props); + + var act = () => Template.FromStack(stack).ShouldHaveHttpsOnlyViewerPolicy(); + + act.Should().Throw(); + } + + // ---- ShouldHaveBucketDeployment ---- + + [Fact] + public void ShouldHaveBucketDeployment_ShouldMatchSettings() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var props = DefaultProps(); + props.DestinationKeyPrefix = "game/abc123/"; + props.CacheControl = [CacheControl.SetPublic(), CacheControl.MaxAge(Duration.Days(365)), CacheControl.Immutable()]; + _ = CreateConstruct(stack, props); + + var act = () => Template.FromStack(stack).ShouldHaveBucketDeployment( + "game/abc123/", prune: false, retainOnDelete: true, cacheControl: "public, max-age=31536000, immutable"); + + act.Should().NotThrow(); + } + + [Fact] + public void ShouldHaveBucketDeployment_ShouldThrowForWrongPruneFlag() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + _ = CreateConstruct(stack, DefaultProps()); + + var act = () => Template.FromStack(stack).ShouldHaveBucketDeployment(prune: true); + + act.Should().Throw(); + } + + // ---- ShouldHaveDnsRecords ---- + + [Fact] + public void ShouldHaveDnsRecords_ShouldMatchConfiguredDomains() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var zone = HostedZone.FromHostedZoneAttributes(stack, "HostedZone", new HostedZoneAttributes + { + HostedZoneId = "Z1234567890ABC", + ZoneName = "example.com", + }); + var certificate = Certificate.FromCertificateArn( + stack, + "Certificate", + "arn:aws:acm:us-east-1:123456789012:certificate/11111111-2222-3333-4444-555555555555"); + var props = DefaultProps(); + props.Domain = new PrivateStaticAssetsDomainOptions + { + DomainNames = ["assets.example.com", "cdn.example.com"], + Certificate = certificate, + HostedZone = zone, + }; + _ = CreateConstruct(stack, props); + + var act = () => Template.FromStack(stack).ShouldHaveDnsRecords("assets.example.com", "cdn.example.com"); + + act.Should().NotThrow(); + } + + [Fact] + public void ShouldHaveDnsRecords_ShouldThrowForUnknownDomain() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + _ = CreateConstruct(stack, DefaultProps()); + + var act = () => Template.FromStack(stack).ShouldHaveDnsRecords("missing.example.com"); + + act.Should().Throw(); + } + + // ---- PrivateStaticAssetsConstructPropsBuilder ---- + + [Fact] + public void PropsBuilder_ShouldApplyDocumentedDefaults() + { + var props = new PrivateStaticAssetsConstructPropsBuilder().Build(); + + props.AssetPath.Should().EndWith("TestAssets/static-site"); + Path.IsPathRooted(props.AssetPath).Should().BeTrue(); + props.DestinationKeyPrefix.Should().BeNull(); + props.Prune.Should().BeFalse(); + props.RetainOnDelete.Should().BeTrue(); + props.CacheControl.Should().BeEmpty(); + props.InvalidationPaths.Should().BeNull(); + props.RemovalPolicy.Should().Be(RemovalPolicy.RETAIN); + props.ViewerProtocolPolicy.Should().Be(ViewerProtocolPolicy.HTTPS_ONLY); + props.CachePolicy.CachePolicyId.Should().Be("658327ea-f89d-4fab-a63d-7e88639e58f6"); + props.Comment.Should().BeNull(); + props.SpaRouting.Should().BeFalse(); + props.ErrorResponses.Should().BeEmpty(); + props.DefaultRootObject.Should().BeNull(); + props.Domain.Should().BeNull(); + } + + [Fact] + public void PropsBuilder_ShouldFlowConfiguredValues() + { + var errorResponse = new ErrorResponse { HttpStatus = 404, ResponsePagePath = "/index.html" }; + + var props = new PrivateStaticAssetsConstructPropsBuilder() + .WithAssetPath(CdkTestHelper.GetTestAssetPath("TestAssets/static-site")) + .WithDestinationKeyPrefix("game/abc123/") + .WithPrune() + .WithRetainOnDelete(false) + .WithCacheControl(CacheControl.Immutable()) + .WithInvalidationPaths("/index.html") + .WithRemovalPolicy(RemovalPolicy.DESTROY) + .WithViewerProtocolPolicy(ViewerProtocolPolicy.REDIRECT_TO_HTTPS) + .WithCachePolicy(CachePolicy.CACHING_DISABLED) + .WithComment("assets") + .WithSpaRouting() + .WithErrorResponse(errorResponse) + .WithDefaultRootObject("index.html") + .Build(); + + props.DestinationKeyPrefix.Should().Be("game/abc123/"); + props.Prune.Should().BeTrue(); + props.RetainOnDelete.Should().BeFalse(); + props.CacheControl.Should().HaveCount(1); + props.InvalidationPaths.Should().Equal("/index.html"); + props.RemovalPolicy.Should().Be(RemovalPolicy.DESTROY); + props.ViewerProtocolPolicy.Should().Be(ViewerProtocolPolicy.REDIRECT_TO_HTTPS); + props.CachePolicy.CachePolicyId.Should().Be("4135ea2d-6df8-44a3-9df3-4b5a84be39ad"); + props.Comment.Should().Be("assets"); + props.SpaRouting.Should().BeTrue(); + props.ErrorResponses.Should().ContainSingle().Which.Should().BeSameAs(errorResponse); + props.DefaultRootObject.Should().Be("index.html"); + } + + [Fact] + public void PropsBuilder_ShouldCreateValidConstruct() + { + var (_, stack) = CdkTestHelper.CreateTestStack(); + var props = new PrivateStaticAssetsConstructPropsBuilder() + .WithDestinationKeyPrefix("game/abc123/") + .WithCacheControl(CacheControl.SetPublic(), CacheControl.MaxAge(Duration.Days(365)), CacheControl.Immutable()) + .Build(); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.ShouldHavePrivateBucket(); + template.ShouldHaveOacOnlyOrigin(); + template.ShouldHaveHttpsOnlyViewerPolicy(); + template.ShouldHaveBucketDeployment( + "game/abc123/", prune: false, retainOnDelete: true, cacheControl: "public, max-age=31536000, immutable"); + } +} From b9c98d996174b00c858e9c612b53e43f2b2fada4 Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Tue, 24 Nov 2026 07:25:53 -0500 Subject: [PATCH 3/6] test(static-assets): add default and custom-domain golden templates --- .../private-static-assets-custom-domain.json | 490 ++++++++++++++++++ .../private-static-assets-default.json | 367 +++++++++++++ .../PrivateStaticAssetsGoldenTemplateTests.cs | 63 +++ 3 files changed, 920 insertions(+) create mode 100644 test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/private-static-assets-custom-domain.json create mode 100644 test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/private-static-assets-default.json create mode 100644 test/LayeredCraft.Cdk.Constructs.Tests/PrivateStaticAssetsGoldenTemplateTests.cs diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/private-static-assets-custom-domain.json b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/private-static-assets-custom-domain.json new file mode 100644 index 0000000..4bc4499 --- /dev/null +++ b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/private-static-assets-custom-domain.json @@ -0,0 +1,490 @@ +{ + "Resources": { + "assetsassetsbucket39AC735D": { + "Type": "AWS::S3::Bucket", + "Properties": { + "BucketEncryption": { + "ServerSideEncryptionConfiguration": [ + { + "ServerSideEncryptionByDefault": { + "SSEAlgorithm": "AES256" + } + } + ] + }, + "PublicAccessBlockConfiguration": { + "BlockPublicAcls": true, + "BlockPublicPolicy": true, + "IgnorePublicAcls": true, + "RestrictPublicBuckets": true + }, + "Tags": [ + { + "Key": "aws-cdk:cr-owned:game/abc123/:51220c60", + "Value": "true" + } + ], + "VersioningConfiguration": { + "Status": "Enabled" + } + }, + "UpdateReplacePolicy": "Retain", + "DeletionPolicy": "Retain" + }, + "assetsassetsbucketPolicy368007AF": { + "Type": "AWS::S3::BucketPolicy", + "Properties": { + "Bucket": { + "Ref": "assetsassetsbucket39AC735D" + }, + "PolicyDocument": { + "Statement": [ + { + "Action": "s3:*", + "Condition": { + "Bool": { + "aws:SecureTransport": "false" + } + }, + "Effect": "Deny", + "Principal": { + "AWS": "*" + }, + "Resource": [ + { + "Fn::GetAtt": [ + "assetsassetsbucket39AC735D", + "Arn" + ] + }, + { + "Fn::Join": [ + "", + [ + { + "Fn::GetAtt": [ + "assetsassetsbucket39AC735D", + "Arn" + ] + }, + "/*" + ] + ] + } + ] + }, + { + "Action": "s3:GetObject", + "Condition": { + "StringEquals": { + "AWS:SourceArn": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":cloudfront::", + { + "Ref": "AWS::AccountId" + }, + ":distribution/", + { + "Ref": "assetsassetscdnDAA8EFCA" + } + ] + ] + } + } + }, + "Effect": "Allow", + "Principal": { + "Service": "cloudfront.amazonaws.com" + }, + "Resource": { + "Fn::Join": [ + "", + [ + { + "Fn::GetAtt": [ + "assetsassetsbucket39AC735D", + "Arn" + ] + }, + "/*" + ] + ] + } + } + ], + "Version": "2012-10-17" + } + } + }, + "assetsassetscdnOrigin1S3OriginAccessControlE24B5B69": { + "Type": "AWS::CloudFront::OriginAccessControl", + "Properties": { + "OriginAccessControlConfig": { + "Name": "goldenprivatestaticassetsassOrigin1S3OriginAccessControl03833EE2", + "OriginAccessControlOriginType": "s3", + "SigningBehavior": "always", + "SigningProtocol": "sigv4" + } + } + }, + "assetsassetscdnDAA8EFCA": { + "Type": "AWS::CloudFront::Distribution", + "Properties": { + "DistributionConfig": { + "Aliases": [ + "assets.example.com", + "cdn.example.com" + ], + "DefaultCacheBehavior": { + "AllowedMethods": [ + "GET", + "HEAD" + ], + "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6", + "Compress": true, + "TargetOriginId": "goldenprivatestaticassetsassetscdnOrigin16195BF22", + "ViewerProtocolPolicy": "https-only" + }, + "Enabled": true, + "HttpVersion": "http2", + "IPV6Enabled": true, + "Origins": [ + { + "DomainName": { + "Fn::GetAtt": [ + "assetsassetsbucket39AC735D", + "RegionalDomainName" + ] + }, + "Id": "goldenprivatestaticassetsassetscdnOrigin16195BF22", + "OriginAccessControlId": { + "Fn::GetAtt": [ + "assetsassetscdnOrigin1S3OriginAccessControlE24B5B69", + "Id" + ] + }, + "S3OriginConfig": { + "OriginAccessIdentity": "" + } + } + ], + "ViewerCertificate": { + "AcmCertificateArn": "arn:aws:acm:us-east-1:123456789012:certificate/11111111-2222-3333-4444-555555555555", + "MinimumProtocolVersion": "TLSv1.2_2021", + "SslSupportMethod": "sni-only" + } + } + } + }, + "assetsassetsarecord0C6BE2245": { + "Type": "AWS::Route53::RecordSet", + "Properties": { + "AliasTarget": { + "DNSName": { + "Fn::GetAtt": [ + "assetsassetscdnDAA8EFCA", + "DomainName" + ] + }, + "HostedZoneId": { + "Fn::FindInMap": [ + "AWSCloudFrontPartitionHostedZoneIdMap", + { + "Ref": "AWS::Partition" + }, + "zoneId" + ] + } + }, + "HostedZoneId": "Z1234567890ABC", + "Name": "assets.example.com.", + "Type": "A" + } + }, + "assetsassetsaaaarecord02F85D940": { + "Type": "AWS::Route53::RecordSet", + "Properties": { + "AliasTarget": { + "DNSName": { + "Fn::GetAtt": [ + "assetsassetscdnDAA8EFCA", + "DomainName" + ] + }, + "HostedZoneId": { + "Fn::FindInMap": [ + "AWSCloudFrontPartitionHostedZoneIdMap", + { + "Ref": "AWS::Partition" + }, + "zoneId" + ] + } + }, + "HostedZoneId": "Z1234567890ABC", + "Name": "assets.example.com.", + "Type": "AAAA" + } + }, + "assetsassetsarecord1BD1B3583": { + "Type": "AWS::Route53::RecordSet", + "Properties": { + "AliasTarget": { + "DNSName": { + "Fn::GetAtt": [ + "assetsassetscdnDAA8EFCA", + "DomainName" + ] + }, + "HostedZoneId": { + "Fn::FindInMap": [ + "AWSCloudFrontPartitionHostedZoneIdMap", + { + "Ref": "AWS::Partition" + }, + "zoneId" + ] + } + }, + "HostedZoneId": "Z1234567890ABC", + "Name": "cdn.example.com.", + "Type": "A" + } + }, + "assetsassetsaaaarecord13A9DB012": { + "Type": "AWS::Route53::RecordSet", + "Properties": { + "AliasTarget": { + "DNSName": { + "Fn::GetAtt": [ + "assetsassetscdnDAA8EFCA", + "DomainName" + ] + }, + "HostedZoneId": { + "Fn::FindInMap": [ + "AWSCloudFrontPartitionHostedZoneIdMap", + { + "Ref": "AWS::Partition" + }, + "zoneId" + ] + } + }, + "HostedZoneId": "Z1234567890ABC", + "Name": "cdn.example.com.", + "Type": "AAAA" + } + }, + "assetsassetsdeploymentAwsCliLayer5B2FAC00": { + "Type": "AWS::Lambda::LayerVersion", + "Properties": { + "Content": { + "S3Bucket": "cdk-hnb659fds-assets-123456789012-us-east-1", + "S3Key": ".zip" + }, + "Description": "/opt/awscli/aws" + } + }, + "assetsassetsdeploymentCustomResourceB45F3FEA": { + "Type": "Custom::CDKBucketDeployment", + "Properties": { + "ServiceToken": { + "Fn::GetAtt": [ + "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C81C01536", + "Arn" + ] + }, + "SourceBucketNames": [ + "cdk-hnb659fds-assets-123456789012-us-east-1" + ], + "SourceObjectKeys": [ + ".zip" + ], + "DestinationBucketName": { + "Ref": "assetsassetsbucket39AC735D" + }, + "DestinationBucketKeyPrefix": "game/abc123/", + "WaitForDistributionInvalidation": true, + "RetainOnDelete": true, + "Prune": false, + "SystemMetadata": { + "cache-control": "public, max-age=31536000, immutable" + }, + "OutputObjectKeys": true + }, + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete" + }, + "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRole89A01265": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": { + "Service": "lambda.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + }, + "ManagedPolicyArns": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" + ] + ] + } + ] + } + }, + "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRoleDefaultPolicy88902FDF": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": [ + "s3:GetObject*", + "s3:GetBucket*", + "s3:List*" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":s3:::cdk-hnb659fds-assets-123456789012-us-east-1" + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":s3:::cdk-hnb659fds-assets-123456789012-us-east-1/*" + ] + ] + } + ] + }, + { + "Action": [ + "s3:GetObject*", + "s3:GetBucket*", + "s3:List*", + "s3:DeleteObject*", + "s3:PutObject", + "s3:PutObjectLegalHold", + "s3:PutObjectRetention", + "s3:PutObjectTagging", + "s3:PutObjectVersionTagging", + "s3:Abort*" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::GetAtt": [ + "assetsassetsbucket39AC735D", + "Arn" + ] + }, + { + "Fn::Join": [ + "", + [ + { + "Fn::GetAtt": [ + "assetsassetsbucket39AC735D", + "Arn" + ] + }, + "/*" + ] + ] + } + ] + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRoleDefaultPolicy88902FDF", + "Roles": [ + { + "Ref": "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRole89A01265" + } + ] + } + }, + "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C81C01536": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Architectures": [ + "arm64" + ], + "Code": { + "S3Bucket": "cdk-hnb659fds-assets-123456789012-us-east-1", + "S3Key": ".zip" + }, + "Environment": { + "Variables": { + "AWS_CA_BUNDLE": "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem" + } + }, + "Handler": "index.handler", + "Layers": [ + { + "Ref": "assetsassetsdeploymentAwsCliLayer5B2FAC00" + } + ], + "MemorySize": 1024, + "Role": { + "Fn::GetAtt": [ + "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRole89A01265", + "Arn" + ] + }, + "Runtime": "python3.13", + "Timeout": 900 + }, + "DependsOn": [ + "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRoleDefaultPolicy88902FDF", + "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRole89A01265" + ] + } + }, + "Mappings": { + "AWSCloudFrontPartitionHostedZoneIdMap": { + "aws": { + "zoneId": "Z2FDTNDATAQYW2" + }, + "aws-cn": { + "zoneId": "Z3RFFRIM2A3IF5" + } + } + } +} \ No newline at end of file diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/private-static-assets-default.json b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/private-static-assets-default.json new file mode 100644 index 0000000..41ba451 --- /dev/null +++ b/test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/private-static-assets-default.json @@ -0,0 +1,367 @@ +{ + "Resources": { + "assetsassetsbucket39AC735D": { + "Type": "AWS::S3::Bucket", + "Properties": { + "BucketEncryption": { + "ServerSideEncryptionConfiguration": [ + { + "ServerSideEncryptionByDefault": { + "SSEAlgorithm": "AES256" + } + } + ] + }, + "PublicAccessBlockConfiguration": { + "BlockPublicAcls": true, + "BlockPublicPolicy": true, + "IgnorePublicAcls": true, + "RestrictPublicBuckets": true + }, + "Tags": [ + { + "Key": "aws-cdk:cr-owned:51220c60", + "Value": "true" + } + ], + "VersioningConfiguration": { + "Status": "Enabled" + } + }, + "UpdateReplacePolicy": "Retain", + "DeletionPolicy": "Retain" + }, + "assetsassetsbucketPolicy368007AF": { + "Type": "AWS::S3::BucketPolicy", + "Properties": { + "Bucket": { + "Ref": "assetsassetsbucket39AC735D" + }, + "PolicyDocument": { + "Statement": [ + { + "Action": "s3:*", + "Condition": { + "Bool": { + "aws:SecureTransport": "false" + } + }, + "Effect": "Deny", + "Principal": { + "AWS": "*" + }, + "Resource": [ + { + "Fn::GetAtt": [ + "assetsassetsbucket39AC735D", + "Arn" + ] + }, + { + "Fn::Join": [ + "", + [ + { + "Fn::GetAtt": [ + "assetsassetsbucket39AC735D", + "Arn" + ] + }, + "/*" + ] + ] + } + ] + }, + { + "Action": "s3:GetObject", + "Condition": { + "StringEquals": { + "AWS:SourceArn": { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":cloudfront::", + { + "Ref": "AWS::AccountId" + }, + ":distribution/", + { + "Ref": "assetsassetscdnDAA8EFCA" + } + ] + ] + } + } + }, + "Effect": "Allow", + "Principal": { + "Service": "cloudfront.amazonaws.com" + }, + "Resource": { + "Fn::Join": [ + "", + [ + { + "Fn::GetAtt": [ + "assetsassetsbucket39AC735D", + "Arn" + ] + }, + "/*" + ] + ] + } + } + ], + "Version": "2012-10-17" + } + } + }, + "assetsassetscdnOrigin1S3OriginAccessControlE24B5B69": { + "Type": "AWS::CloudFront::OriginAccessControl", + "Properties": { + "OriginAccessControlConfig": { + "Name": "goldenprivatestaticassetsassOrigin1S3OriginAccessControl03833EE2", + "OriginAccessControlOriginType": "s3", + "SigningBehavior": "always", + "SigningProtocol": "sigv4" + } + } + }, + "assetsassetscdnDAA8EFCA": { + "Type": "AWS::CloudFront::Distribution", + "Properties": { + "DistributionConfig": { + "DefaultCacheBehavior": { + "AllowedMethods": [ + "GET", + "HEAD" + ], + "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6", + "Compress": true, + "TargetOriginId": "goldenprivatestaticassetsassetscdnOrigin16195BF22", + "ViewerProtocolPolicy": "https-only" + }, + "Enabled": true, + "HttpVersion": "http2", + "IPV6Enabled": true, + "Origins": [ + { + "DomainName": { + "Fn::GetAtt": [ + "assetsassetsbucket39AC735D", + "RegionalDomainName" + ] + }, + "Id": "goldenprivatestaticassetsassetscdnOrigin16195BF22", + "OriginAccessControlId": { + "Fn::GetAtt": [ + "assetsassetscdnOrigin1S3OriginAccessControlE24B5B69", + "Id" + ] + }, + "S3OriginConfig": { + "OriginAccessIdentity": "" + } + } + ] + } + } + }, + "assetsassetsdeploymentAwsCliLayer5B2FAC00": { + "Type": "AWS::Lambda::LayerVersion", + "Properties": { + "Content": { + "S3Bucket": "cdk-hnb659fds-assets-123456789012-us-east-1", + "S3Key": ".zip" + }, + "Description": "/opt/awscli/aws" + } + }, + "assetsassetsdeploymentCustomResourceB45F3FEA": { + "Type": "Custom::CDKBucketDeployment", + "Properties": { + "ServiceToken": { + "Fn::GetAtt": [ + "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C81C01536", + "Arn" + ] + }, + "SourceBucketNames": [ + "cdk-hnb659fds-assets-123456789012-us-east-1" + ], + "SourceObjectKeys": [ + ".zip" + ], + "DestinationBucketName": { + "Ref": "assetsassetsbucket39AC735D" + }, + "WaitForDistributionInvalidation": true, + "RetainOnDelete": true, + "Prune": false, + "OutputObjectKeys": true + }, + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete" + }, + "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRole89A01265": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [ + { + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": { + "Service": "lambda.amazonaws.com" + } + } + ], + "Version": "2012-10-17" + }, + "ManagedPolicyArns": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" + ] + ] + } + ] + } + }, + "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRoleDefaultPolicy88902FDF": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": [ + "s3:GetObject*", + "s3:GetBucket*", + "s3:List*" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":s3:::cdk-hnb659fds-assets-123456789012-us-east-1" + ] + ] + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":s3:::cdk-hnb659fds-assets-123456789012-us-east-1/*" + ] + ] + } + ] + }, + { + "Action": [ + "s3:GetObject*", + "s3:GetBucket*", + "s3:List*", + "s3:DeleteObject*", + "s3:PutObject", + "s3:PutObjectLegalHold", + "s3:PutObjectRetention", + "s3:PutObjectTagging", + "s3:PutObjectVersionTagging", + "s3:Abort*" + ], + "Effect": "Allow", + "Resource": [ + { + "Fn::GetAtt": [ + "assetsassetsbucket39AC735D", + "Arn" + ] + }, + { + "Fn::Join": [ + "", + [ + { + "Fn::GetAtt": [ + "assetsassetsbucket39AC735D", + "Arn" + ] + }, + "/*" + ] + ] + } + ] + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRoleDefaultPolicy88902FDF", + "Roles": [ + { + "Ref": "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRole89A01265" + } + ] + } + }, + "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C81C01536": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Architectures": [ + "arm64" + ], + "Code": { + "S3Bucket": "cdk-hnb659fds-assets-123456789012-us-east-1", + "S3Key": ".zip" + }, + "Environment": { + "Variables": { + "AWS_CA_BUNDLE": "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem" + } + }, + "Handler": "index.handler", + "Layers": [ + { + "Ref": "assetsassetsdeploymentAwsCliLayer5B2FAC00" + } + ], + "MemorySize": 1024, + "Role": { + "Fn::GetAtt": [ + "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRole89A01265", + "Arn" + ] + }, + "Runtime": "python3.13", + "Timeout": 900 + }, + "DependsOn": [ + "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRoleDefaultPolicy88902FDF", + "CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRole89A01265" + ] + } + } +} \ No newline at end of file diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/PrivateStaticAssetsGoldenTemplateTests.cs b/test/LayeredCraft.Cdk.Constructs.Tests/PrivateStaticAssetsGoldenTemplateTests.cs new file mode 100644 index 0000000..673320b --- /dev/null +++ b/test/LayeredCraft.Cdk.Constructs.Tests/PrivateStaticAssetsGoldenTemplateTests.cs @@ -0,0 +1,63 @@ +using Amazon.CDK; +using Amazon.CDK.AWS.CertificateManager; +using Amazon.CDK.AWS.Route53; +using Amazon.CDK.AWS.S3.Deployment; +using LayeredCraft.Cdk.Constructs.Models; +using LayeredCraft.Cdk.Constructs.Testing; +using LayeredCraft.Cdk.Constructs.Tests.TestKit.Golden; + +namespace LayeredCraft.Cdk.Constructs.Tests; + +/// +/// Golden-template compatibility tests for . Each case pins the +/// complete synthesized CloudFormation template for a representative configuration: the default case and a +/// custom-domain case that also exercises the immutable deployment options. +/// +[Collection("CDK Tests")] +public class PrivateStaticAssetsGoldenTemplateTests +{ + [Fact] + public void PrivateStaticAssets_Defaults_ShouldMatchGoldenTemplate() + { + var (_, stack) = CdkTestHelper.CreateTestStack("golden-private-static-assets"); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", new PrivateStaticAssetsConstructProps + { + AssetPath = CdkTestHelper.GetTestAssetPath("TestAssets/static-site"), + }); + + GoldenTemplate.AssertMatches(stack, "private-static-assets-default.json"); + } + + [Fact] + public void PrivateStaticAssets_CustomDomain_ShouldMatchGoldenTemplate() + { + var (_, stack) = CdkTestHelper.CreateTestStack("golden-private-static-assets"); + + var zone = HostedZone.FromHostedZoneAttributes(stack, "HostedZone", new HostedZoneAttributes + { + HostedZoneId = "Z1234567890ABC", + ZoneName = "example.com", + }); + + var certificate = Certificate.FromCertificateArn( + stack, + "Certificate", + "arn:aws:acm:us-east-1:123456789012:certificate/11111111-2222-3333-4444-555555555555"); + + _ = new PrivateStaticAssetsConstruct(stack, "assets", new PrivateStaticAssetsConstructProps + { + AssetPath = CdkTestHelper.GetTestAssetPath("TestAssets/static-site"), + DestinationKeyPrefix = "game/abc123/", + CacheControl = [CacheControl.SetPublic(), CacheControl.MaxAge(Duration.Days(365)), CacheControl.Immutable()], + Domain = new PrivateStaticAssetsDomainOptions + { + DomainNames = ["assets.example.com", "cdn.example.com"], + Certificate = certificate, + HostedZone = zone, + }, + }); + + GoldenTemplate.AssertMatches(stack, "private-static-assets-custom-domain.json"); + } +} From f0c5191dc7bcaa599bdc2f7489448e2e83ea8367 Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Tue, 24 Nov 2026 07:25:56 -0500 Subject: [PATCH 4/6] docs(static-assets): document the private static assets construct --- docs/constructs/private-static-assets.md | 172 +++++++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 docs/constructs/private-static-assets.md diff --git a/docs/constructs/private-static-assets.md b/docs/constructs/private-static-assets.md new file mode 100644 index 0000000..df20dd5 --- /dev/null +++ b/docs/constructs/private-static-assets.md @@ -0,0 +1,172 @@ +# 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 (Jedi Duel example) + +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//...` 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 | +| `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. + +## 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** + +## 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. From 8833ffd7fab27ec87da2c9b399b854104d08b55d Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Tue, 24 Nov 2026 07:30:09 -0500 Subject: [PATCH 5/6] docs: wire PrivateStaticAssetsConstruct into the docs; remove stale AutoData docs - mkdocs nav, README, docs index, CLAUDE.md and the Testing guide (builder and assertions) for the new construct - construct page: CloudFront certificates must be in us-east-1; DESTROY cannot delete a non-empty versioned bucket; neutral example heading - Testing guide and Cognito page: replace the AutoFixture *AutoData attribute sections (removed with the test-project migration in #109) with a note on the library's Compono profiles Refs #111 Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 12 ++++ README.md | 2 + docs/constructs/cognito-user-pool.md | 18 ------ docs/constructs/private-static-assets.md | 7 ++- docs/index.md | 10 ++++ docs/testing/index.md | 72 ++++++++++++------------ mkdocs.yml | 1 + 7 files changed, 64 insertions(+), 58 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 5352a9f..e6a8619 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -69,6 +69,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 @@ -82,6 +89,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 - `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`) @@ -179,6 +187,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. diff --git a/README.md b/README.md index 077414c..962adb4 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 diff --git a/docs/constructs/cognito-user-pool.md b/docs/constructs/cognito-user-pool.md index 57d8931..cc42b7f 100644 --- a/docs/constructs/cognito-user-pool.md +++ b/docs/constructs/cognito-user-pool.md @@ -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. diff --git a/docs/constructs/private-static-assets.md b/docs/constructs/private-static-assets.md index df20dd5..d96a25c 100644 --- a/docs/constructs/private-static-assets.md +++ b/docs/constructs/private-static-assets.md @@ -44,7 +44,7 @@ public class MyStack : Stack } ``` -## Immutable, versioned deployment (Jedi Duel example) +## 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 @@ -129,7 +129,7 @@ var assets = new PrivateStaticAssetsConstruct(this, "GameAssets", new PrivateSta | Property | Type | Description | |----------|------|-------------| | `DomainNames` | `string[]` | The custom domain names (at least one) | -| `Certificate` | `ICertificate?` | Certificate for the domain names; created (DNS-validated) when omitted | +| `Certificate` | `ICertificate?` | Certificate for the domain names; created (DNS-validated) when omitted. CloudFront only accepts certificates in `us-east-1`, so a created certificate requires a `us-east-1` stack | | `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` | @@ -158,7 +158,8 @@ Validation at construction (`ArgumentException`): - **Versioning**: enabled - **No static website endpoint** - **Removal policy**: `RETAIN` by default -- **No auto-delete objects** +- **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 diff --git a/docs/index.md b/docs/index.md index be5a0a9..18be4ca 100644 --- a/docs/index.md +++ b/docs/index.md @@ -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 @@ -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: diff --git a/docs/testing/index.md b/docs/testing/index.md index f511594..e4b9370 100644 --- a/docs/testing/index.md +++ b/docs/testing/index.md @@ -15,7 +15,7 @@ The testing framework consists of: - **Test Helpers**: Utilities for creating test stacks and props - **Assertion Methods**: Fluent assertions for CDK resources - **Props Builders**: Fluent builders for construct properties -- **AutoFixture Integration**: Automatic test data generation with realistic values +- **Composed test data**: the library's own tests compose props with Compono profiles ## Getting Started @@ -194,6 +194,32 @@ template.ShouldHaveApiProxyBehavior("api.example.com"); template.ShouldNotHaveApiProxyBehavior(); ``` +## Private Static Assets Testing + +### Props Builder + +```csharp +var props = new PrivateStaticAssetsConstructPropsBuilder() + .WithAssetPath("./dist") + .WithDestinationKeyPrefix("game/1.2.3/") + .WithCacheControl(CacheControl.FromString("public, max-age=31536000, immutable")) + .Build(); +``` + +### Assertion Methods + +```csharp +var template = Template.FromStack(stack); + +template.ShouldHavePrivateBucket(); // Block Public Access, SSE-S3, SSL-only, versioned +template.ShouldNotHaveWebsiteEndpoint(); +template.ShouldHaveOacOnlyOrigin(); +template.ShouldScopeBucketPolicyToDistribution(); // AWS:SourceArn of this distribution +template.ShouldHaveHttpsOnlyViewerPolicy(); +template.ShouldHaveBucketDeployment(destinationKeyPrefix: "game/1.2.3/"); +template.ShouldHaveDnsRecords("assets.example.com"); // only with a custom domain +``` + ## DynamoDB Table Testing ### Props Builder @@ -337,23 +363,6 @@ template.ShouldHaveRevisionDependingOnLogGroups( The invocation assertions require `Effect = Allow`, the expected action (`lambda:InvokeWebFunctionEndpoint`), and the exact endpoint resource, so a `Deny` statement or an unrelated action never satisfies them. `ShouldHaveInvokeGrant` also matches a minimized policy whose `Resource` is an array of endpoint ARNs. The log-group assertions match by log-group **name** and exact `RetentionInDays`; tokenized names cannot be asserted this way. `ShouldHaveRevisionDependingOnLogGroups` resolves each name to its logical ID through the template, so it never hard-codes generated identifiers. Use `ShouldHaveWebFunctionLogGroup`, not `ShouldHaveLogGroup` (the latter is the Lambda Function construct's assertion). -### AutoData Support - -```csharp -[Theory] -[WebFunctionConstructAutoData] -public void Should_Synthesize_Generated_Props(WebFunctionConstructProps props) -{ - var (_, stack) = CdkTestHelper.CreateTestStack(); - - _ = new WebFunctionConstruct(stack, "web", props); - - Template.FromStack(stack).ShouldHaveWebFunction("test-web-function"); -} -``` - -`[WebFunctionConstructAutoData]` supplies deterministic props whose default code artifact is an imported, externally managed bucket, so the fixture synthesizes without credentials or a bucket resource. - ### Golden-Template Conventions Representative Web Function configurations are pinned as full synthesized templates under `test/LayeredCraft.Cdk.Constructs.Tests/GoldenTemplates/` (`web-function-default.json`, `web-function-cloudfront-oac.json`, and so on), alongside the golden templates for the four existing constructs. `GoldenTemplate.AssertMatches(stack, "web-function-default.json")` compares the complete, normalized template and fails with a readable diff. Regenerate intentionally with `UPDATE_GOLDEN_TEMPLATES=1`; the harness rewrites the checked-in file and then fails once so the change is reviewed. Existing-construct goldens must show **zero diff** on any dependency or CDK bump. @@ -363,33 +372,22 @@ Representative Web Function configurations are pinned as full synthesized templa - **Origin exceptions.** Validation that runs inside CDK's `IOrigin.Bind` path (and inside `HttpOrigin` construction) surfaces in .NET as a `System.Exception` carrying CDK's message, while factory-time checks in `WebFunctionOrigin` throw `InvalidOperationException`. Assert with the matching exception type, and prefer validating origin props at factory time. - **Principal materialization.** Identity-policy writes and principal classification depend partly on how jsii materializes types in `Amazon.CDK.Lib`: exported classes such as `Role`, `User`, `Group`, `LazyRole` and `PrincipalWithConditions` arrive as concrete .NET types, while CDK's private classes (`ImmutableRole`, the imported role) arrive as interface proxies. The real-CDK `CdkUpgradeGuard_*` tests in `WebFunctionSecurityTests.cs` pin this behavior; they must pass before any `Amazon.CDK.Lib` upgrade is accepted. -## AutoFixture Integration +## Composed Test Data (Compono) -### Custom Attributes +The library's own test suite composes construct props with [Compono](https://github.com/LayeredCraft/compono) +profiles (`test/LayeredCraft.Cdk.Constructs.Tests/TestKit/Profiles`), for example: ```csharp [Theory] -[LambdaFunctionConstructAutoData] -public void Should_Create_Lambda_With_Generated_Data(LambdaFunctionConstructProps props) +[Compose(LambdaFunctionConstructPropsOptions.Permissions)] +public void Should_Create_Lambda_With_Composed_Props(LambdaFunctionConstructProps props) { - // props is automatically generated with realistic test data -} - -[Theory] -[LambdaFunctionConstructAutoData(includeOtelLayer: false, includePermissions: true)] -public void Should_Create_Lambda_With_Custom_Settings(LambdaFunctionConstructProps props) -{ - // props generated with specific customizations + // props composed with deterministic, realistic values } ``` -### Available Attributes - -- `LambdaFunctionConstructAutoDataAttribute`: Generates Lambda props -- `StaticSiteConstructAutoDataAttribute`: Generates static site props -- `DynamoDbTableConstructAutoDataAttribute`: Generates DynamoDB props -- `CognitoUserPoolConstructAutoDataAttribute`: Generates Cognito user pool props (pass `includeBranding: true` to include Managed Login branding) -- `WebFunctionConstructAutoDataAttribute`: Generates Web Function props (imported, externally managed artifact bucket; IAM-auth endpoint) +These profiles are test-project infrastructure, not part of the package. In your own tests, use the shipped +`*ConstructPropsBuilder` classes, or your own composition, to create props. ## Testing Patterns diff --git a/mkdocs.yml b/mkdocs.yml index 8cd6117..03e748d 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -108,6 +108,7 @@ nav: - Constructs: - Lambda Function: constructs/lambda-function.md - Static Site: constructs/static-site.md + - Private Static Assets: constructs/private-static-assets.md - DynamoDB Table: constructs/dynamodb-table.md - Cognito User Pool: constructs/cognito-user-pool.md - Web Function: constructs/web-function.md From 134c34da55d8449d0f2ae4f97218908d51b9fcfc Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Tue, 24 Nov 2026 07:46:24 -0500 Subject: [PATCH 6/6] fix(static-assets): reject automatic certificate creation outside us-east-1 --- docs/constructs/private-static-assets.md | 7 +- .../PrivateStaticAssetsConstructProps.cs | 6 +- .../PrivateStaticAssetsConstruct.cs | 15 +++ .../PrivateStaticAssetsConstructTests.cs | 94 +++++++++++++++++++ 4 files changed, 119 insertions(+), 3 deletions(-) diff --git a/docs/constructs/private-static-assets.md b/docs/constructs/private-static-assets.md index d96a25c..7f60314 100644 --- a/docs/constructs/private-static-assets.md +++ b/docs/constructs/private-static-assets.md @@ -129,7 +129,7 @@ var assets = new PrivateStaticAssetsConstruct(this, "GameAssets", new PrivateSta | Property | Type | Description | |----------|------|-------------| | `DomainNames` | `string[]` | The custom domain names (at least one) | -| `Certificate` | `ICertificate?` | Certificate for the domain names; created (DNS-validated) when omitted. CloudFront only accepts certificates in `us-east-1`, so a created certificate requires a `us-east-1` stack | +| `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` | @@ -137,7 +137,10 @@ Validation at construction (`ArgumentException`): - no domain names; - both `HostedZone` and `HostedZoneName` set; -- neither a `Certificate` nor a hosted zone (or hosted-zone name) available. +- 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 diff --git a/src/LayeredCraft.Cdk.Constructs/Models/PrivateStaticAssetsConstructProps.cs b/src/LayeredCraft.Cdk.Constructs/Models/PrivateStaticAssetsConstructProps.cs index 174e8e6..b9348ee 100644 --- a/src/LayeredCraft.Cdk.Constructs/Models/PrivateStaticAssetsConstructProps.cs +++ b/src/LayeredCraft.Cdk.Constructs/Models/PrivateStaticAssetsConstructProps.cs @@ -151,7 +151,11 @@ public record PrivateStaticAssetsDomainOptions /// /// Optional certificate for the domain names. When omitted, a DNS-validated certificate is created using - /// the hosted zone. + /// the hosted zone. 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. + /// An environment-agnostic stack (an unresolved region) cannot be checked at synthesis and keeps creating + /// the certificate. /// public ICertificate? Certificate { get; set; } diff --git a/src/LayeredCraft.Cdk.Constructs/PrivateStaticAssetsConstruct.cs b/src/LayeredCraft.Cdk.Constructs/PrivateStaticAssetsConstruct.cs index 58ac75e..0d93cfc 100644 --- a/src/LayeredCraft.Cdk.Constructs/PrivateStaticAssetsConstruct.cs +++ b/src/LayeredCraft.Cdk.Constructs/PrivateStaticAssetsConstruct.cs @@ -187,6 +187,21 @@ private void ResolveDomain( nameof(domain)); } + if (domain.Certificate is null) + { + // CloudFront only accepts viewer certificates from us-east-1. The check is skipped when the stack + // region is a token (environment-agnostic stack), because it cannot be resolved at synthesis. + var region = Stack.Of(this).Region; + if (!Token.IsUnresolved(region) && region != "us-east-1") + { + throw new ArgumentException( + $"A CloudFront viewer certificate must be created in us-east-1, but the stack region is " + + $"'{region}'. Supply a Certificate created in us-east-1 (for example via " + + "Certificate.FromCertificateArn).", + nameof(domain)); + } + } + certificate = domain.Certificate ?? new Certificate(this, $"{id}-certificate", new CertificateProps { diff --git a/test/LayeredCraft.Cdk.Constructs.Tests/PrivateStaticAssetsConstructTests.cs b/test/LayeredCraft.Cdk.Constructs.Tests/PrivateStaticAssetsConstructTests.cs index 0e44c99..e7d0b69 100644 --- a/test/LayeredCraft.Cdk.Constructs.Tests/PrivateStaticAssetsConstructTests.cs +++ b/test/LayeredCraft.Cdk.Constructs.Tests/PrivateStaticAssetsConstructTests.cs @@ -856,6 +856,100 @@ public void Construct_ShouldThrowWhenNoCertificateAndNoZone() act.Should().Throw(); } + // ---- Certificate region (CloudFront viewer certificates must be in us-east-1) ---- + + [Fact] + public void Construct_ShouldThrowWhenCreatingCertificateOutsideUsEast1() + { + var (_, stack) = CdkTestHelper.CreateTestStack("test-stack", "eu-west-1", "123456789012"); + var zone = HostedZone.FromHostedZoneAttributes(stack, "HostedZone", new HostedZoneAttributes + { + HostedZoneId = "Z1234567890ABC", + ZoneName = "example.com", + }); + var props = CreateProps(); + props.Domain = new PrivateStaticAssetsDomainOptions + { + DomainNames = ["assets.example.com"], + HostedZone = zone, + }; + + var act = () => new PrivateStaticAssetsConstruct(stack, "assets", props); + + act.Should().Throw().WithMessage("*us-east-1*"); + } + + [Fact] + public void Construct_ShouldAcceptSuppliedCertificateOutsideUsEast1() + { + var (_, stack) = CdkTestHelper.CreateTestStack("test-stack", "eu-west-1", "123456789012"); + var zone = HostedZone.FromHostedZoneAttributes(stack, "HostedZone", new HostedZoneAttributes + { + HostedZoneId = "Z1234567890ABC", + ZoneName = "example.com", + }); + var certificate = Certificate.FromCertificateArn( + stack, + "Certificate", + "arn:aws:acm:us-east-1:123456789012:certificate/11111111-2222-3333-4444-555555555555"); + var props = CreateProps(); + props.Domain = new PrivateStaticAssetsDomainOptions + { + DomainNames = ["assets.example.com"], + Certificate = certificate, + HostedZone = zone, + }; + + var act = () => new PrivateStaticAssetsConstruct(stack, "assets", props); + + act.Should().NotThrow(); + } + + [Fact] + public void Construct_ShouldCreateCertificateWhenStackIsUsEast1() + { + var (_, stack) = CdkTestHelper.CreateTestStack("test-stack", "us-east-1", "123456789012"); + var zone = HostedZone.FromHostedZoneAttributes(stack, "HostedZone", new HostedZoneAttributes + { + HostedZoneId = "Z1234567890ABC", + ZoneName = "example.com", + }); + var props = CreateProps(); + props.Domain = new PrivateStaticAssetsDomainOptions + { + DomainNames = ["assets.example.com"], + HostedZone = zone, + }; + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.ResourceCountIs("AWS::CertificateManager::Certificate", 1); + } + + [Fact] + public void Construct_ShouldCreateCertificateWhenStackRegionIsUnresolved() + { + var app = new App(); + var stack = new Stack(app, "test-stack", new StackProps()); + var zone = HostedZone.FromHostedZoneAttributes(stack, "HostedZone", new HostedZoneAttributes + { + HostedZoneId = "Z1234567890ABC", + ZoneName = "example.com", + }); + var props = CreateProps(); + props.Domain = new PrivateStaticAssetsDomainOptions + { + DomainNames = ["assets.example.com"], + HostedZone = zone, + }; + + _ = new PrivateStaticAssetsConstruct(stack, "assets", props); + + var template = Template.FromStack(stack); + template.ResourceCountIs("AWS::CertificateManager::Certificate", 1); + } + // ---- Public properties and composed props ---- [Fact]