From 04a6ad6cbbd9ab9c101bfd02e0c902368e27f246 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Mon, 14 Sep 2026 22:08:33 -0500 Subject: [PATCH] refactor(cloudformation): move AWS::CloudFront::Distribution into CloudFrontCfnProvisioner (#3587) Moves the last CloudFront type out of the monolith switch and into the provisioner that already owns the four configuration types a distribution references by id. Monolith 4,702 to 4,521 lines, legacy types 29 to 28. No new class: the type joins an existing provisioner that already injects CloudFrontService and is already wired into CfnProvisionerFixture. Nine private helpers move with it, every one exclusive to the distribution: cfnOrigins, cfnDefaultCacheBehavior, cfnCacheBehaviors, cfnCustomErrorResponses, putIfPresent, cfnStringList, cfnText, cfnTextOrDefault and cfnBool. cfnText shows 21 references in the monolith and looks shared until each is resolved to its enclosing method: they are all CloudFront. All nine are carried over byte for byte. The provision method itself changes in exactly two places. It takes a ProvisionContext rather than a bare engine, and it decides create versus update from ctx.isUpdate() and ctx.priorPhysicalId() rather than reading the physical id off the resource, which is what AGENTS.md asks for because provision assigns the new id as it runs. The two are the same value on the same call: the engine sets resource.setPhysicalId(existingPhysicalId) and passes that same variable into the context. Delete keeps the monolith's behaviour. removeDistribution is the stack-level delete, with no disable or If-Match guard, and it tolerates an id that is already gone, so unlike the policy arms beside it there is no not-found code to list. Also deletes blankToNull, which #3582 left behind with no caller. It had 9 references before that PR and 1 after, its own definition. Tests: three cases added to the existing CloudFrontCfnProvisionerTest covering create with the exact Fn::GetAtt keys, an in-place update under the prior id, and the stack-level delete. servesTheFourConfigTypes pinned the served set at four types and is renamed and widened to five, which is the assertion doing its job rather than an inconvenience. Registration is proved rather than assumed: removing the type from resourceTypes(), which is what a missed registration looks like, fails both CfnResourceInventoryTest and the provisioner test. Without that, the dispatcher's stub arm reports CREATE_COMPLETE with a synthetic ARN and the suite stays green. --- .../CloudFormationResourceProvisioner.java | 181 ----------------- .../CloudFrontCfnProvisioner.java | 183 +++++++++++++++++- .../cloudformation/CfnProvisionerFixture.java | 1 - .../CloudFrontCfnProvisionerTest.java | 95 ++++++++- .../supported-resource-types.tsv | 2 +- 5 files changed, 275 insertions(+), 187 deletions(-) diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java index 1e4659b23a..1ab643a61d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java @@ -3,12 +3,6 @@ package io.github.hectorvent.floci.services.cloudformation; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsNamespaces; import io.github.hectorvent.floci.core.common.XmlBuilder; -import io.github.hectorvent.floci.services.cloudfront.CloudFrontService; -import io.github.hectorvent.floci.services.cloudfront.model.CacheBehavior; -import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior; -import io.github.hectorvent.floci.services.cloudfront.model.Distribution; -import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig; -import io.github.hectorvent.floci.services.cloudfront.model.Origin; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import io.github.hectorvent.floci.services.cloudformation.provisioners.ReplacementCleanup; import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback; @@ -174,7 +168,6 @@ public class CloudFormationResourceProvisioner { "AWS::ApiGatewayV2::Route", "AWS::ApiGatewayV2::Stage", "AWS::CloudFormation::CustomResource", - "AWS::CloudFront::Distribution", "AWS::DynamoDB::GlobalTable", "AWS::DynamoDB::Table", "AWS::EC2::Instance", @@ -214,7 +207,6 @@ public class CloudFormationResourceProvisioner { private final StepFunctionsService stepFunctionsService; private final Ec2Service ec2Service; private final EksService eksService; - private final CloudFrontService cloudFrontService; // Item 15 decomposition: extracted per-service provisioners are consulted before the switch // below. As types migrate, their switch cases and provisionXxx methods are removed here; the // now-dead service deps above are cleared in the final cleanup once the switch is empty. @@ -242,7 +234,6 @@ public class CloudFormationResourceProvisioner { KinesisService kinesisService, CloudWatchMetricsService cloudWatchMetricsService, FirehoseService firehoseService, - CloudFrontService cloudFrontService, CloudFormationResourceRegistry resourceRegistry, CfnDynamicReferences dynamicReferences, EmulatorConfig config) { @@ -260,7 +251,6 @@ public class CloudFormationResourceProvisioner { this.stepFunctionsService = stepFunctionsService; this.ec2Service = ec2Service; this.eksService = eksService; - this.cloudFrontService = cloudFrontService; this.resourceRegistry = resourceRegistry; this.dynamicReferences = dynamicReferences; } @@ -347,8 +337,6 @@ public class CloudFormationResourceProvisioner { case "AWS::EC2::Instance" -> provisionEc2Instance(resource, properties, engine, region); case "AWS::EKS::Cluster" -> provisionEksCluster(resource, properties, engine, stackName); case "AWS::EKS::Nodegroup" -> provisionEksNodegroup(resource, properties, engine, stackName); - case "AWS::CloudFront::Distribution" -> - provisionCloudFrontDistribution(resource, properties, engine); default -> { if (resourceType != null && resourceType.startsWith("Custom::")) { provisionCustomResource(resource, properties, engine, region, accountId, stackName); @@ -573,7 +561,6 @@ public class CloudFormationResourceProvisioner { case "AWS::EC2::SecurityGroup" -> ec2Service.deleteSecurityGroup(region, physicalId); case "AWS::EC2::Instance" -> ec2Service.terminateInstances(region, List.of(physicalId)); case "AWS::EKS::Cluster" -> eksService.deleteCluster(physicalId); - case "AWS::CloudFront::Distribution" -> cloudFrontService.removeDistribution(physicalId); // Warn for the same reason the create path does: the delete reports success over a // type nothing here removes, and at debug that is invisible at the default log level. // The line names the physical id without claiming a resource survives it: this arm @@ -718,9 +705,6 @@ public class CloudFormationResourceProvisioner { return new ArrayList<>(engine.resolveStringList(props.get(field))); } - private String blankToNull(String value) { - return (value == null || value.isBlank()) ? null : value; - } private void provisionEc2Instance(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, String region) { @@ -4279,179 +4263,14 @@ public class CloudFormationResourceProvisioner { // ── CloudFront ──────────────────────────────────────────────────────────── - /** - * Provisions an {@code AWS::CloudFront::Distribution} by translating its {@code DistributionConfig} - * property tree into a {@link DistributionConfig} and creating or updating the distribution. - * {@code Ref} returns the distribution id; {@code Fn::GetAtt} exposes {@code Id} and - * {@code DomainName} (closes #1147, where {@code Fn::GetAtt DomainName} previously returned an - * unresolved token). - */ - private void provisionCloudFrontDistribution(StackResource r, JsonNode props, - CloudFormationTemplateEngine engine) { - JsonNode dc = props != null ? props.path("DistributionConfig") : null; - DistributionConfig config = new DistributionConfig(); - if (dc != null && !dc.isMissingNode() && !dc.isNull()) { - config.setEnabled(cfnBool(dc, "Enabled", engine, true)); - config.setComment(cfnText(dc, "Comment", engine)); - config.setDefaultRootObject(cfnText(dc, "DefaultRootObject", engine)); - config.setHttpVersion(cfnTextOrDefault(dc, "HttpVersion", engine, "http2")); - config.setPriceClass(cfnTextOrDefault(dc, "PriceClass", engine, "PriceClass_All")); - config.setAliases(cfnStringList(dc.path("Aliases"), engine)); - config.setOrigins(cfnOrigins(dc, engine)); - config.setDefaultCacheBehavior(cfnDefaultCacheBehavior(dc.path("DefaultCacheBehavior"), engine)); - config.setCacheBehaviors(cfnCacheBehaviors(dc, engine)); - config.setCustomErrorResponses(cfnCustomErrorResponses(dc, engine)); - } - Distribution dist = new Distribution(); - dist.setConfig(config); - if (r.getPhysicalId() == null || r.getPhysicalId().isBlank()) { - dist = cloudFrontService.createDistribution(dist, Map.of()); - } else { - Distribution existing = cloudFrontService.getDistribution(r.getPhysicalId()); - dist = cloudFrontService.updateDistribution( - existing.getId(), existing.getEtag(), dist); - } - r.setPhysicalId(dist.getId()); - r.getAttributes().put("Id", dist.getId()); - r.getAttributes().put("DomainName", dist.getDomainName()); - r.getAttributes().put("Arn", dist.getArn()); - } - private List cfnOrigins(JsonNode dc, CloudFormationTemplateEngine engine) { - List origins = new ArrayList<>(); - JsonNode items = dc.path("Origins"); - if (items.isArray()) { - for (JsonNode node : items) { - Origin origin = new Origin(); - origin.setId(cfnText(node, "Id", engine)); - origin.setDomainName(cfnText(node, "DomainName", engine)); - String originPath = cfnText(node, "OriginPath", engine); - if (!originPath.isEmpty()) { - origin.setOriginPath(originPath); - } - String originAccessControlId = - cfnText(node, "OriginAccessControlId", engine); - if (!originAccessControlId.isEmpty()) { - origin.setOriginAccessControlId(originAccessControlId); - } - JsonNode originCustomHeaders = node.path("OriginCustomHeaders"); - if (originCustomHeaders.isArray()) { - List> customHeaders = new ArrayList<>(); - for (JsonNode customHeader : originCustomHeaders) { - Map mapped = new LinkedHashMap<>(); - mapped.put("HeaderName", cfnText(customHeader, "HeaderName", engine)); - mapped.put("HeaderValue", cfnText(customHeader, "HeaderValue", engine)); - customHeaders.add(mapped); - } - origin.setCustomHeaders(customHeaders); - } - JsonNode s3 = node.path("S3OriginConfig"); - JsonNode custom = node.path("CustomOriginConfig"); - if (!custom.isMissingNode() && !custom.isNull()) { - Map coc = new LinkedHashMap<>(); - coc.put("HTTPPort", cfnTextOrDefault(custom, "HTTPPort", engine, "80")); - coc.put("HTTPSPort", cfnTextOrDefault(custom, "HTTPSPort", engine, "443")); - coc.put("OriginProtocolPolicy", - cfnTextOrDefault(custom, "OriginProtocolPolicy", engine, "https-only")); - origin.setCustomOriginConfig(coc); - } else { - // No CustomOriginConfig => S3 origin (S3OriginConfig may be present or defaulted). - Map s3c = new LinkedHashMap<>(); - s3c.put("OriginAccessIdentity", - s3.isMissingNode() || s3.isNull() ? "" : cfnText(s3, "OriginAccessIdentity", engine)); - origin.setS3OriginConfig(s3c); - } - origins.add(origin); - } - } - return origins; - } - private DefaultCacheBehavior cfnDefaultCacheBehavior(JsonNode node, CloudFormationTemplateEngine engine) { - DefaultCacheBehavior dcb = new DefaultCacheBehavior(); - if (node != null && !node.isMissingNode() && !node.isNull()) { - dcb.setTargetOriginId(cfnText(node, "TargetOriginId", engine)); - dcb.setViewerProtocolPolicy(cfnTextOrDefault(node, "ViewerProtocolPolicy", engine, "allow-all")); - dcb.setResponseHeadersPolicyId(cfnText(node, "ResponseHeadersPolicyId", engine)); - List trustedKeyGroups = cfnStringList(node.path("TrustedKeyGroups"), engine); - if (!trustedKeyGroups.isEmpty()) { - dcb.setTrustedKeyGroups(trustedKeyGroups); - } - } - return dcb; - } - private List cfnCacheBehaviors(JsonNode dc, CloudFormationTemplateEngine engine) { - List behaviors = new ArrayList<>(); - JsonNode items = dc.path("CacheBehaviors"); - if (items.isArray()) { - for (JsonNode node : items) { - CacheBehavior cb = new CacheBehavior(); - cb.setPathPattern(cfnText(node, "PathPattern", engine)); - cb.setTargetOriginId(cfnText(node, "TargetOriginId", engine)); - cb.setViewerProtocolPolicy(cfnTextOrDefault(node, "ViewerProtocolPolicy", engine, "allow-all")); - cb.setResponseHeadersPolicyId(cfnText(node, "ResponseHeadersPolicyId", engine)); - List trustedKeyGroups = cfnStringList(node.path("TrustedKeyGroups"), engine); - if (!trustedKeyGroups.isEmpty()) { - cb.setTrustedKeyGroups(trustedKeyGroups); - } - behaviors.add(cb); - } - } - return behaviors; - } - private List> cfnCustomErrorResponses(JsonNode dc, CloudFormationTemplateEngine engine) { - List> result = new ArrayList<>(); - JsonNode items = dc.path("CustomErrorResponses"); - if (items.isArray()) { - for (JsonNode node : items) { - Map cer = new LinkedHashMap<>(); - cer.put("ErrorCode", cfnText(node, "ErrorCode", engine)); - putIfPresent(cer, "ResponseCode", cfnText(node, "ResponseCode", engine)); - putIfPresent(cer, "ResponsePagePath", cfnText(node, "ResponsePagePath", engine)); - putIfPresent(cer, "ErrorCachingMinTTL", cfnText(node, "ErrorCachingMinTTL", engine)); - result.add(cer); - } - } - return result; - } - private static void putIfPresent(Map map, String key, String value) { - if (value != null && !value.isEmpty()) { - map.put(key, value); - } - } - private List cfnStringList(JsonNode arrayNode, CloudFormationTemplateEngine engine) { - List result = new ArrayList<>(); - if (arrayNode != null && arrayNode.isArray()) { - for (JsonNode item : arrayNode) { - String value = engine.resolve(item); - if (value != null && !value.isEmpty()) { - result.add(value); - } - } - } - return result; - } - - private String cfnText(JsonNode parent, String field, CloudFormationTemplateEngine engine) { - return parent == null ? "" : engine.resolve(parent.path(field)); - } - - private String cfnTextOrDefault(JsonNode parent, String field, CloudFormationTemplateEngine engine, - String dflt) { - String value = cfnText(parent, field, engine); - return value.isEmpty() ? dflt : value; - } - - private boolean cfnBool(JsonNode parent, String field, CloudFormationTemplateEngine engine, boolean dflt) { - String value = cfnText(parent, field, engine); - return value.isEmpty() ? dflt : "true".equalsIgnoreCase(value); - } private String resolveOptional(JsonNode props, String name, CloudFormationTemplateEngine engine) { if (props == null || !props.has(name) || props.get(name).isNull()) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java index 0fe481a185..ad7c280156 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java @@ -2,10 +2,16 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners; import com.fasterxml.jackson.databind.JsonNode; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import io.github.hectorvent.floci.services.cloudfront.CloudFrontService; import io.github.hectorvent.floci.services.cloudfront.ResponseHeadersPolicyConfigCodec; +import io.github.hectorvent.floci.services.cloudfront.model.CacheBehavior; import io.github.hectorvent.floci.services.cloudfront.model.CachePolicy; +import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior; +import io.github.hectorvent.floci.services.cloudfront.model.Distribution; +import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig; +import io.github.hectorvent.floci.services.cloudfront.model.Origin; import io.github.hectorvent.floci.services.cloudfront.model.OriginAccessControl; import io.github.hectorvent.floci.services.cloudfront.model.OriginRequestPolicy; import io.github.hectorvent.floci.services.cloudfront.model.ResponseHeadersPolicy; @@ -47,6 +53,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner { private static final Logger LOG = Logger.getLogger(CloudFrontCfnProvisioner.class); + static final String DISTRIBUTION = "AWS::CloudFront::Distribution"; static final String RESPONSE_HEADERS_POLICY = "AWS::CloudFront::ResponseHeadersPolicy"; static final String CACHE_POLICY = "AWS::CloudFront::CachePolicy"; static final String ORIGIN_REQUEST_POLICY = "AWS::CloudFront::OriginRequestPolicy"; @@ -67,13 +74,15 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner { @Override public Set resourceTypes() { - return Set.of(RESPONSE_HEADERS_POLICY, CACHE_POLICY, ORIGIN_REQUEST_POLICY, ORIGIN_ACCESS_CONTROL); + return Set.of(DISTRIBUTION, RESPONSE_HEADERS_POLICY, CACHE_POLICY, ORIGIN_REQUEST_POLICY, + ORIGIN_ACCESS_CONTROL); } @Override public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { Map attributesBefore = Map.copyOf(r.getAttributes()); switch (r.getResourceType()) { + case DISTRIBUTION -> provisionDistribution(r, props, ctx); case RESPONSE_HEADERS_POLICY -> provisionResponseHeadersPolicy(r, props, ctx); case CACHE_POLICY -> provisionCachePolicy(r, props, ctx); case ORIGIN_REQUEST_POLICY -> provisionOriginRequestPolicy(r, props, ctx); @@ -136,6 +145,9 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner { // is refused with InUse, which must fail the stack delete as it does on AWS; in a stack // the distribution depends on the policy, so it is deleted first. switch (resourceType) { + // removeDistribution is the stack-level delete: no disable or If-Match guard, and it + // tolerates an id that is already gone, so no not-found code needs listing here. + case DISTRIBUTION -> cloudFrontService.removeDistribution(physicalId); case RESPONSE_HEADERS_POLICY -> deleteWithEtag("response headers policy", physicalId, id -> cloudFrontService.getResponseHeadersPolicy(id).getEtag(), cloudFrontService::deleteResponseHeadersPolicy, NO_SUCH_RESPONSE_HEADERS_POLICY); @@ -302,4 +314,173 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner { } return node.asText(); } + + // The distribution itself, moved out of CloudFormationResourceProvisioner. It reads the + // policy ids the types above hand it, which is why the two live in one provisioner. + + + /** + * Provisions an {@code AWS::CloudFront::Distribution} by translating its {@code DistributionConfig} + * property tree into a {@link DistributionConfig} and creating or updating the distribution. + * {@code Ref} returns the distribution id; {@code Fn::GetAtt} exposes {@code Id} and + * {@code DomainName} (closes #1147, where {@code Fn::GetAtt DomainName} previously returned an + * unresolved token). + */ + private void provisionDistribution(StackResource r, JsonNode props, ProvisionContext ctx) { + CloudFormationTemplateEngine engine = ctx.engine(); + JsonNode dc = props != null ? props.path("DistributionConfig") : null; + DistributionConfig config = new DistributionConfig(); + if (dc != null && !dc.isMissingNode() && !dc.isNull()) { + config.setEnabled(cfnBool(dc, "Enabled", engine, true)); + config.setComment(cfnText(dc, "Comment", engine)); + config.setDefaultRootObject(cfnText(dc, "DefaultRootObject", engine)); + config.setHttpVersion(cfnTextOrDefault(dc, "HttpVersion", engine, "http2")); + config.setPriceClass(cfnTextOrDefault(dc, "PriceClass", engine, "PriceClass_All")); + config.setAliases(cfnStringList(dc.path("Aliases"), engine)); + config.setOrigins(cfnOrigins(dc, engine)); + config.setDefaultCacheBehavior(cfnDefaultCacheBehavior(dc.path("DefaultCacheBehavior"), engine)); + config.setCacheBehaviors(cfnCacheBehaviors(dc, engine)); + config.setCustomErrorResponses(cfnCustomErrorResponses(dc, engine)); + } + + Distribution dist = new Distribution(); + dist.setConfig(config); + if (!ctx.isUpdate()) { + dist = cloudFrontService.createDistribution(dist, Map.of()); + } else { + Distribution existing = cloudFrontService.getDistribution(ctx.priorPhysicalId()); + dist = cloudFrontService.updateDistribution( + existing.getId(), existing.getEtag(), dist); + } + + r.setPhysicalId(dist.getId()); + r.getAttributes().put("Id", dist.getId()); + r.getAttributes().put("DomainName", dist.getDomainName()); + r.getAttributes().put("Arn", dist.getArn()); + } + private List cfnOrigins(JsonNode dc, CloudFormationTemplateEngine engine) { + List origins = new ArrayList<>(); + JsonNode items = dc.path("Origins"); + if (items.isArray()) { + for (JsonNode node : items) { + Origin origin = new Origin(); + origin.setId(cfnText(node, "Id", engine)); + origin.setDomainName(cfnText(node, "DomainName", engine)); + String originPath = cfnText(node, "OriginPath", engine); + if (!originPath.isEmpty()) { + origin.setOriginPath(originPath); + } + String originAccessControlId = + cfnText(node, "OriginAccessControlId", engine); + if (!originAccessControlId.isEmpty()) { + origin.setOriginAccessControlId(originAccessControlId); + } + JsonNode originCustomHeaders = node.path("OriginCustomHeaders"); + if (originCustomHeaders.isArray()) { + List> customHeaders = new ArrayList<>(); + for (JsonNode customHeader : originCustomHeaders) { + Map mapped = new LinkedHashMap<>(); + mapped.put("HeaderName", cfnText(customHeader, "HeaderName", engine)); + mapped.put("HeaderValue", cfnText(customHeader, "HeaderValue", engine)); + customHeaders.add(mapped); + } + origin.setCustomHeaders(customHeaders); + } + JsonNode s3 = node.path("S3OriginConfig"); + JsonNode custom = node.path("CustomOriginConfig"); + if (!custom.isMissingNode() && !custom.isNull()) { + Map coc = new LinkedHashMap<>(); + coc.put("HTTPPort", cfnTextOrDefault(custom, "HTTPPort", engine, "80")); + coc.put("HTTPSPort", cfnTextOrDefault(custom, "HTTPSPort", engine, "443")); + coc.put("OriginProtocolPolicy", + cfnTextOrDefault(custom, "OriginProtocolPolicy", engine, "https-only")); + origin.setCustomOriginConfig(coc); + } else { + // No CustomOriginConfig => S3 origin (S3OriginConfig may be present or defaulted). + Map s3c = new LinkedHashMap<>(); + s3c.put("OriginAccessIdentity", + s3.isMissingNode() || s3.isNull() ? "" : cfnText(s3, "OriginAccessIdentity", engine)); + origin.setS3OriginConfig(s3c); + } + origins.add(origin); + } + } + return origins; + } + private DefaultCacheBehavior cfnDefaultCacheBehavior(JsonNode node, CloudFormationTemplateEngine engine) { + DefaultCacheBehavior dcb = new DefaultCacheBehavior(); + if (node != null && !node.isMissingNode() && !node.isNull()) { + dcb.setTargetOriginId(cfnText(node, "TargetOriginId", engine)); + dcb.setViewerProtocolPolicy(cfnTextOrDefault(node, "ViewerProtocolPolicy", engine, "allow-all")); + dcb.setResponseHeadersPolicyId(cfnText(node, "ResponseHeadersPolicyId", engine)); + List trustedKeyGroups = cfnStringList(node.path("TrustedKeyGroups"), engine); + if (!trustedKeyGroups.isEmpty()) { + dcb.setTrustedKeyGroups(trustedKeyGroups); + } + } + return dcb; + } + private List cfnCacheBehaviors(JsonNode dc, CloudFormationTemplateEngine engine) { + List behaviors = new ArrayList<>(); + JsonNode items = dc.path("CacheBehaviors"); + if (items.isArray()) { + for (JsonNode node : items) { + CacheBehavior cb = new CacheBehavior(); + cb.setPathPattern(cfnText(node, "PathPattern", engine)); + cb.setTargetOriginId(cfnText(node, "TargetOriginId", engine)); + cb.setViewerProtocolPolicy(cfnTextOrDefault(node, "ViewerProtocolPolicy", engine, "allow-all")); + cb.setResponseHeadersPolicyId(cfnText(node, "ResponseHeadersPolicyId", engine)); + List trustedKeyGroups = cfnStringList(node.path("TrustedKeyGroups"), engine); + if (!trustedKeyGroups.isEmpty()) { + cb.setTrustedKeyGroups(trustedKeyGroups); + } + behaviors.add(cb); + } + } + return behaviors; + } + private List> cfnCustomErrorResponses(JsonNode dc, CloudFormationTemplateEngine engine) { + List> result = new ArrayList<>(); + JsonNode items = dc.path("CustomErrorResponses"); + if (items.isArray()) { + for (JsonNode node : items) { + Map cer = new LinkedHashMap<>(); + cer.put("ErrorCode", cfnText(node, "ErrorCode", engine)); + putIfPresent(cer, "ResponseCode", cfnText(node, "ResponseCode", engine)); + putIfPresent(cer, "ResponsePagePath", cfnText(node, "ResponsePagePath", engine)); + putIfPresent(cer, "ErrorCachingMinTTL", cfnText(node, "ErrorCachingMinTTL", engine)); + result.add(cer); + } + } + return result; + } + private static void putIfPresent(Map map, String key, String value) { + if (value != null && !value.isEmpty()) { + map.put(key, value); + } + } + private List cfnStringList(JsonNode arrayNode, CloudFormationTemplateEngine engine) { + List result = new ArrayList<>(); + if (arrayNode != null && arrayNode.isArray()) { + for (JsonNode item : arrayNode) { + String value = engine.resolve(item); + if (value != null && !value.isEmpty()) { + result.add(value); + } + } + } + return result; + } + private String cfnText(JsonNode parent, String field, CloudFormationTemplateEngine engine) { + return parent == null ? "" : engine.resolve(parent.path(field)); + } + private String cfnTextOrDefault(JsonNode parent, String field, CloudFormationTemplateEngine engine, + String dflt) { + String value = cfnText(parent, field, engine); + return value.isEmpty() ? dflt : value; + } + private boolean cfnBool(JsonNode parent, String field, CloudFormationTemplateEngine engine, boolean dflt) { + String value = cfnText(parent, field, engine); + return value.isEmpty() ? dflt : "true".equalsIgnoreCase(value); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index 98e677042b..95e9be9a01 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -676,7 +676,6 @@ final class CfnProvisionerFixture { kinesisService, cloudWatchMetricsService, firehoseService, - cloudFrontService, resourceRegistry, dynamicReferences, config); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java index c152ba0d16..696e05edcc 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java @@ -7,6 +7,9 @@ import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplate import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import io.github.hectorvent.floci.services.cloudfront.CloudFrontService; import io.github.hectorvent.floci.services.cloudfront.model.CachePolicy; +import io.github.hectorvent.floci.services.cloudfront.model.Distribution; +import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig; +import io.github.hectorvent.floci.services.cloudfront.model.Origin; import io.github.hectorvent.floci.services.cloudfront.model.OriginAccessControl; import io.github.hectorvent.floci.services.cloudfront.model.OriginRequestPolicy; import io.github.hectorvent.floci.services.cloudfront.model.ResponseHeadersPolicy; @@ -43,6 +46,7 @@ class CloudFrontCfnProvisionerTest { private static final String CACHE_POLICY = "AWS::CloudFront::CachePolicy"; private static final String ORIGIN_REQUEST_POLICY = "AWS::CloudFront::OriginRequestPolicy"; private static final String ORIGIN_ACCESS_CONTROL = "AWS::CloudFront::OriginAccessControl"; + private static final String DISTRIBUTION = "AWS::CloudFront::Distribution"; private static final String REGION = "us-east-1"; private static final String ID = "5cc3b908-e619-4b99-88e5-2cf7f45965bd"; private static final String ETAG = "E2QWRUHAPOMQZL"; @@ -96,9 +100,94 @@ class CloudFrontCfnProvisionerTest { } @Test - void servesTheFourConfigTypes() { - assertEquals(Set.of(RESPONSE_HEADERS_POLICY, CACHE_POLICY, ORIGIN_REQUEST_POLICY, ORIGIN_ACCESS_CONTROL), - provisioner.resourceTypes()); + void servesTheDistributionAndItsFourConfigTypes() { + assertEquals(Set.of(DISTRIBUTION, RESPONSE_HEADERS_POLICY, CACHE_POLICY, ORIGIN_REQUEST_POLICY, + ORIGIN_ACCESS_CONTROL), provisioner.resourceTypes()); + } + + /** + * The distribution helpers read every scalar through {@code engine.resolve}, which the shared + * {@link #ctx()} leaves unstubbed because the config types only need {@code resolveNode}. + */ + private ProvisionContext distributionCtx(String priorPhysicalId) { + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0)); + when(engine.resolve(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return node == null || node.isMissingNode() || node.isNull() ? "" : node.asText(); + }); + return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId); + } + + private static Distribution distribution(String id, String domainName) { + Distribution d = new Distribution(); + d.setId(id); + d.setDomainName(domainName); + d.setArn("arn:aws:cloudfront::000000000000:distribution/" + id); + d.setEtag(ETAG); + return d; + } + + @Test + void createsDistributionAndExposesTheSchemaAttributes() throws Exception { + when(cloudFront.createDistribution(any(), any())).thenReturn(distribution("E1DIST", "d111.cloudfront.net")); + StackResource r = resource(DISTRIBUTION); + + provisioner.provision(r, json(""" + {"DistributionConfig": { + "Enabled": true, + "Comment": "site", + "Origins": [{"Id": "o1", "DomainName": "b.s3.amazonaws.com"}], + "DefaultCacheBehavior": {"TargetOriginId": "o1", "ViewerProtocolPolicy": "redirect-to-https"} + }} + """), distributionCtx(null)); + + // Ref is the distribution id; Id and DomainName are the schema's read-only properties. + assertEquals("E1DIST", r.getPhysicalId()); + assertEquals("E1DIST", r.getAttributes().get("Id")); + assertEquals("d111.cloudfront.net", r.getAttributes().get("DomainName")); + assertEquals("arn:aws:cloudfront::000000000000:distribution/E1DIST", r.getAttributes().get("Arn")); + + ArgumentCaptor sent = ArgumentCaptor.forClass(Distribution.class); + verify(cloudFront).createDistribution(sent.capture(), any()); + DistributionConfig config = sent.getValue().getConfig(); + assertTrue(config.isEnabled()); + assertEquals("site", config.getComment()); + // Defaults the monolith applied and that must survive the move. + assertEquals("http2", config.getHttpVersion()); + assertEquals("PriceClass_All", config.getPriceClass()); + Origin origin = config.getOrigins().getFirst(); + assertEquals("o1", origin.getId()); + assertEquals("b.s3.amazonaws.com", origin.getDomainName()); + // No CustomOriginConfig means an S3 origin. + assertNull(origin.getCustomOriginConfig()); + assertEquals("redirect-to-https", config.getDefaultCacheBehavior().getViewerProtocolPolicy()); + } + + @Test + void updatesTheDistributionInPlaceUnderThePriorId() throws Exception { + // provision() re-runs on every UpdateStack. The prior id comes from the context, not from + // the resource, because provision assigns the new id as it runs. + when(cloudFront.getDistribution("E1DIST")).thenReturn(distribution("E1DIST", "d111.cloudfront.net")); + when(cloudFront.updateDistribution(eq("E1DIST"), eq(ETAG), any())) + .thenReturn(distribution("E1DIST", "d111.cloudfront.net")); + StackResource r = resource(DISTRIBUTION, "E1DIST", Map.of()); + + provisioner.provision(r, json(""" + {"DistributionConfig": {"Enabled": false, "Comment": "paused"}} + """), distributionCtx("E1DIST")); + + verify(cloudFront).updateDistribution(eq("E1DIST"), eq(ETAG), any()); + verify(cloudFront, never()).createDistribution(any(), any()); + assertEquals("E1DIST", r.getPhysicalId()); + } + + @Test + void deletesTheDistributionThroughTheStackLevelRemove() { + provisioner.delete(DISTRIBUTION, "E1DIST", REGION); + // removeDistribution skips the disable and If-Match guards deleteDistribution enforces, + // because the stack owns the lifecycle. + verify(cloudFront).removeDistribution("E1DIST"); } @Test diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 9b0c6f1ed7..d0e70a068c 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -34,7 +34,7 @@ AWS::CDK::Metadata CdkMetadataCfnProvisioner AWS::CertificateManager::Certificate AcmCfnProvisioner AWS::CloudFormation::CustomResource LEGACY_SWITCH AWS::CloudFront::CachePolicy CloudFrontCfnProvisioner -AWS::CloudFront::Distribution LEGACY_SWITCH +AWS::CloudFront::Distribution CloudFrontCfnProvisioner AWS::CloudFront::OriginAccessControl CloudFrontCfnProvisioner AWS::CloudFront::OriginRequestPolicy CloudFrontCfnProvisioner AWS::CloudFront::ResponseHeadersPolicy CloudFrontCfnProvisioner