Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(cloudformation): provision CloudFront policies and origin access controls (#3228)

Hector Ventura895adce214b6
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index f17fc4663f..3caf02508e 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -99,7 +99,7 @@ cross-resource references.
| Kinesis | `Stream` |
| Kinesis Data Firehose | `DeliveryStream` |
| IoT Core | `DomainConfiguration` (`ServerCertificates` resolves to a JSON string), `Policy` (deleted after detaching it from its principals; on AWS the delete fails with `DeleteConflictException` while the policy is attached), `Thing`, `TopicRule` |
-| CloudFront | `Distribution` |
+| CloudFront | `CachePolicy`, `Distribution`, `OriginAccessControl`, `OriginRequestPolicy`, `ResponseHeadersPolicy` |
| CloudWatch | `Alarm` |
| CloudWatch Logs | `LogGroup` |
| WAFv2 | `WebACL` |
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
new file mode 100644
index 0000000000..0fe481a185
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java
@@ -0,0 +1,305 @@
+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.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.CachePolicy;
+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;
+import jakarta.enterprise.context.ApplicationScoped;
+import org.jboss.logging.Logger;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+
+/**
+ * Provisions the CloudFront configuration types a distribution references by id: response headers
+ * policies, cache policies, origin request policies and origin access controls.
+ *
+ * <p>Each type has a single required {@code <Type>Config} property and no create-only property, so
+ * the physical id is the id the service assigns and every update is applied in place through the
+ * service's etag-guarded update, reading the current etag first as a client would. {@code Fn::GetAtt}
+ * exposes {@code Id} and {@code LastModifiedTime} (origin access controls only {@code Id}), the
+ * registry schema's read-only properties. Before this provisioner these types fell through to the
+ * dispatcher's stub arm, whose synthetic id a distribution then refused (issue #2441).
+ *
+ * <p>A policy configuration is handed to the service as nested maps and lists with every scalar as
+ * text, since the service's validator and codec read the blocks as string maps; the response headers
+ * config is additionally reshaped by {@link ResponseHeadersPolicyConfigCodec#fromItemsTree} into the
+ * flattened form that codec stores. {@code Name} and {@code Comment} are model fields, not part of
+ * the map.
+ *
+ * <p>A committed in-place update is not reverted when a later resource fails the update; the stack
+ * keeps the new policy configuration, the same limit the Cognito user pool has.
+ */
+@ApplicationScoped
+public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final Logger LOG = Logger.getLogger(CloudFrontCfnProvisioner.class);
+
+ 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";
+ static final String ORIGIN_ACCESS_CONTROL = "AWS::CloudFront::OriginAccessControl";
+
+ static final String NO_SUCH_RESPONSE_HEADERS_POLICY = "NoSuchResponseHeadersPolicy";
+ static final String NO_SUCH_CACHE_POLICY = "NoSuchCachePolicy";
+ static final String NO_SUCH_ORIGIN_REQUEST_POLICY = "NoSuchOriginRequestPolicy";
+ static final String NO_SUCH_ORIGIN_ACCESS_CONTROL = "NoSuchOriginAccessControl";
+
+ private static final Set<String> MODEL_FIELDS = Set.of("Name", "Comment");
+
+ private final CloudFrontService cloudFrontService;
+
+ public CloudFrontCfnProvisioner(CloudFrontService cloudFrontService) {
+ this.cloudFrontService = cloudFrontService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of(RESPONSE_HEADERS_POLICY, CACHE_POLICY, ORIGIN_REQUEST_POLICY, ORIGIN_ACCESS_CONTROL);
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
+ switch (r.getResourceType()) {
+ case RESPONSE_HEADERS_POLICY -> provisionResponseHeadersPolicy(r, props, ctx);
+ case CACHE_POLICY -> provisionCachePolicy(r, props, ctx);
+ case ORIGIN_REQUEST_POLICY -> provisionOriginRequestPolicy(r, props, ctx);
+ case ORIGIN_ACCESS_CONTROL -> provisionOriginAccessControl(r, props, ctx);
+ default -> throw new IllegalArgumentException("Unsupported resource type: " + r.getResourceType());
+ }
+ ReplacementCleanup.record(r, ctx, attributesBefore);
+ }
+
+ /**
+ * The physical id only changes here when the prior object was already gone: {@code prior}
+ * returns the entity whenever the service still knows it, so an update either mutates that
+ * entity in place under the same id or recreates a missing one under a new id. The entity
+ * {@link ReplacementCleanup} records as displaced is therefore always one that no longer
+ * exists, and the delete these hooks run for it is a no-op tolerated by its not-found code.
+ * They are still needed: without them a recorded entity would never leave the cleanup list.
+ */
+ @Override
+ public boolean hasReplacementUpdate(StackResource resource) {
+ return ReplacementCleanup.hasReplacement(resource);
+ }
+
+ @Override
+ public String updateCleanupPhysicalId(StackResource resource) {
+ return ReplacementCleanup.cleanupPhysicalId(resource);
+ }
+
+ @Override
+ public UpdateCleanupResult completeUpdate(StackResource resource) {
+ return ReplacementCleanup.complete(resource, this::delete);
+ }
+
+ @Override
+ public void clearUpdate(StackResource resource) {
+ ReplacementCleanup.clear(resource);
+ }
+
+ /**
+ * Undoes a recreation when a later resource fails the stack update: the resource names the
+ * prior id again with the attributes it carried, and the object this update created is
+ * deleted. Without this the engine reached its "Rollback is not implemented" arm, which never
+ * deletes, so the replacement stayed behind.
+ *
+ * <p>An in-place update leaves the physical id unchanged, so no rollback fields are recorded
+ * and this answers false. Putting a committed in-place change back needs a configuration
+ * snapshot this provisioner does not keep, so that case still reports as not rolled back, as
+ * it does for {@code AWS::Cognito::UserPool}.
+ */
+ @Override
+ public boolean rollbackUpdate(StackResource resource) {
+ return ReplacementCleanup.rollback(resource, this::delete);
+ }
+
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ if (physicalId == null || physicalId.isBlank()) {
+ return;
+ }
+ // Only the type's own not-found code is tolerated. A policy still attached to a distribution
+ // is refused with <Type>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) {
+ case RESPONSE_HEADERS_POLICY -> deleteWithEtag("response headers policy", physicalId,
+ id -> cloudFrontService.getResponseHeadersPolicy(id).getEtag(),
+ cloudFrontService::deleteResponseHeadersPolicy, NO_SUCH_RESPONSE_HEADERS_POLICY);
+ case CACHE_POLICY -> deleteWithEtag("cache policy", physicalId,
+ id -> cloudFrontService.getCachePolicy(id).getEtag(),
+ cloudFrontService::deleteCachePolicy, NO_SUCH_CACHE_POLICY);
+ case ORIGIN_REQUEST_POLICY -> deleteWithEtag("origin request policy", physicalId,
+ id -> cloudFrontService.getOriginRequestPolicy(id).getEtag(),
+ cloudFrontService::deleteOriginRequestPolicy, NO_SUCH_ORIGIN_REQUEST_POLICY);
+ case ORIGIN_ACCESS_CONTROL -> deleteWithEtag("origin access control", physicalId,
+ id -> cloudFrontService.getOriginAccessControl(id).getEtag(),
+ cloudFrontService::deleteOriginAccessControl, NO_SUCH_ORIGIN_ACCESS_CONTROL);
+ default -> { }
+ }
+ }
+
+ private void provisionResponseHeadersPolicy(StackResource r, JsonNode props, ProvisionContext ctx) {
+ JsonNode config = requireConfig(RESPONSE_HEADERS_POLICY, "ResponseHeadersPolicyConfig", props, ctx);
+ ResponseHeadersPolicy policy = new ResponseHeadersPolicy();
+ policy.setName(text(config, "Name"));
+ policy.setComment(text(config, "Comment"));
+ policy.setConfig(ResponseHeadersPolicyConfigCodec.fromItemsTree(toConfigMap(config)));
+ ResponseHeadersPolicy prior = prior(ctx, "response headers policy",
+ cloudFrontService::getResponseHeadersPolicy, NO_SUCH_RESPONSE_HEADERS_POLICY);
+ ResponseHeadersPolicy provisioned = prior == null
+ ? cloudFrontService.createResponseHeadersPolicy(policy)
+ : cloudFrontService.updateResponseHeadersPolicy(prior.getId(), prior.getEtag(), policy);
+ expose(r, provisioned.getId(), provisioned.getLastModifiedTime());
+ }
+
+ private void provisionCachePolicy(StackResource r, JsonNode props, ProvisionContext ctx) {
+ JsonNode config = requireConfig(CACHE_POLICY, "CachePolicyConfig", props, ctx);
+ CachePolicy policy = new CachePolicy();
+ policy.setName(text(config, "Name"));
+ policy.setComment(text(config, "Comment"));
+ policy.setConfig(toConfigMap(config));
+ CachePolicy prior = prior(ctx, "cache policy", cloudFrontService::getCachePolicy, NO_SUCH_CACHE_POLICY);
+ CachePolicy provisioned = prior == null
+ ? cloudFrontService.createCachePolicy(policy)
+ : cloudFrontService.updateCachePolicy(prior.getId(), prior.getEtag(), policy);
+ expose(r, provisioned.getId(), provisioned.getLastModifiedTime());
+ }
+
+ private void provisionOriginRequestPolicy(StackResource r, JsonNode props, ProvisionContext ctx) {
+ JsonNode config = requireConfig(ORIGIN_REQUEST_POLICY, "OriginRequestPolicyConfig", props, ctx);
+ OriginRequestPolicy policy = new OriginRequestPolicy();
+ policy.setName(text(config, "Name"));
+ policy.setComment(text(config, "Comment"));
+ policy.setConfig(toConfigMap(config));
+ OriginRequestPolicy prior = prior(ctx, "origin request policy",
+ cloudFrontService::getOriginRequestPolicy, NO_SUCH_ORIGIN_REQUEST_POLICY);
+ OriginRequestPolicy provisioned = prior == null
+ ? cloudFrontService.createOriginRequestPolicy(policy)
+ : cloudFrontService.updateOriginRequestPolicy(prior.getId(), prior.getEtag(), policy);
+ expose(r, provisioned.getId(), provisioned.getLastModifiedTime());
+ }
+
+ private void provisionOriginAccessControl(StackResource r, JsonNode props, ProvisionContext ctx) {
+ JsonNode config = requireConfig(ORIGIN_ACCESS_CONTROL, "OriginAccessControlConfig", props, ctx);
+ OriginAccessControl oac = new OriginAccessControl();
+ oac.setName(text(config, "Name"));
+ oac.setDescription(text(config, "Description"));
+ oac.setSigningBehavior(text(config, "SigningBehavior"));
+ oac.setSigningProtocol(text(config, "SigningProtocol"));
+ oac.setOriginAccessControlOriginType(text(config, "OriginAccessControlOriginType"));
+ OriginAccessControl prior = prior(ctx, "origin access control",
+ cloudFrontService::getOriginAccessControl, NO_SUCH_ORIGIN_ACCESS_CONTROL);
+ OriginAccessControl provisioned = prior == null
+ ? cloudFrontService.createOriginAccessControl(oac)
+ : cloudFrontService.updateOriginAccessControl(prior.getId(), prior.getEtag(), oac);
+ r.setPhysicalId(provisioned.getId());
+ r.getAttributes().put("Id", provisioned.getId());
+ }
+
+ private static void expose(StackResource r, String id, Instant lastModifiedTime) {
+ r.setPhysicalId(id);
+ r.getAttributes().put("Id", id);
+ r.getAttributes().put("LastModifiedTime", lastModifiedTime == null ? "" : lastModifiedTime.toString());
+ }
+
+ /**
+ * The prior entity on an update, or null on a create or when the record is stale: a prior id the
+ * service no longer knows (the emulator restarted without persistence) is recreated rather than
+ * failing the update on a policy nobody can see.
+ */
+ private <T> T prior(ProvisionContext ctx, String description, Function<String, T> get, String notFound) {
+ if (!ctx.isUpdate() || ctx.priorPhysicalId() == null || ctx.priorPhysicalId().isBlank()) {
+ return null;
+ }
+ try {
+ return get.apply(ctx.priorPhysicalId());
+ } catch (AwsException e) {
+ if (!notFound.equals(e.getErrorCode())) {
+ throw e;
+ }
+ LOG.debugv("Prior {0} {1} is gone; creating a new one", description, ctx.priorPhysicalId());
+ return null;
+ }
+ }
+
+ private static void deleteWithEtag(String description, String physicalId, Function<String, String> etagOf,
+ BiConsumer<String, String> delete, String notFound) {
+ CfnDeletes.safeDelete(description, physicalId,
+ () -> delete.accept(physicalId, etagOf.apply(physicalId)), notFound);
+ }
+
+ private static JsonNode requireConfig(String type, String name, JsonNode props, ProvisionContext ctx) {
+ JsonNode raw = props == null ? null : props.get(name);
+ JsonNode resolved = raw == null || raw.isNull() ? null : ctx.engine().resolveNode(raw);
+ if (resolved == null || !resolved.isObject()) {
+ throw new AwsException("ValidationError", type + " requires " + name, 400);
+ }
+ return resolved;
+ }
+
+ private static String text(JsonNode node, String name) {
+ JsonNode value = node.get(name);
+ return value == null || value.isNull() ? null : value.asText();
+ }
+
+ /**
+ * The configuration blocks as the service's codec shapes them: objects to maps, arrays to lists,
+ * every scalar as its text (a JSON {@code true} arrives as {@code "true"}), nulls dropped.
+ */
+ static Map<String, Object> toConfigMap(JsonNode config) {
+ Map<String, Object> map = new LinkedHashMap<>();
+ for (Iterator<Map.Entry<String, JsonNode>> it = config.fields(); it.hasNext(); ) {
+ Map.Entry<String, JsonNode> field = it.next();
+ if (MODEL_FIELDS.contains(field.getKey())) {
+ continue;
+ }
+ Object value = toConfigValue(field.getValue());
+ if (value != null) {
+ map.put(field.getKey(), value);
+ }
+ }
+ return map;
+ }
+
+ private static Object toConfigValue(JsonNode node) {
+ if (node == null || node.isNull() || node.isMissingNode()) {
+ return null;
+ }
+ if (node.isObject()) {
+ Map<String, Object> map = new LinkedHashMap<>();
+ for (Iterator<Map.Entry<String, JsonNode>> it = node.fields(); it.hasNext(); ) {
+ Map.Entry<String, JsonNode> field = it.next();
+ Object value = toConfigValue(field.getValue());
+ if (value != null) {
+ map.put(field.getKey(), value);
+ }
+ }
+ return map;
+ }
+ if (node.isArray()) {
+ List<Object> list = new ArrayList<>();
+ for (JsonNode element : node) {
+ Object value = toConfigValue(element);
+ if (value != null) {
+ list.add(value);
+ }
+ }
+ return list;
+ }
+ return node.asText();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java
index 9cc945a557..93db2d7d4c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java
@@ -493,6 +493,11 @@ public class CloudFrontService {
throw new AwsException("InvalidIfMatchVersion",
"The If-Match version is missing or not valid for the resource.", 400);
}
+ if (isCachePolicyInUse(id)) {
+ throw new AwsException("CachePolicyInUse",
+ "Cannot delete the cache policy because it is attached to one or more cache behaviors.",
+ 409);
+ }
cachePolicyStore.delete(id);
}
@@ -552,6 +557,11 @@ public class CloudFrontService {
throw new AwsException("InvalidIfMatchVersion",
"The If-Match version is missing or not valid for the resource.", 400);
}
+ if (isOriginRequestPolicyInUse(id)) {
+ throw new AwsException("OriginRequestPolicyInUse",
+ "Cannot delete the origin request policy because it is attached to one or more cache behaviors.",
+ 409);
+ }
orpStore.delete(id);
}
@@ -750,21 +760,51 @@ public class CloudFrontService {
}
private boolean isResponseHeadersPolicyInUse(String id) {
+ return isAttachedToACacheBehavior(id,
+ DefaultCacheBehavior::getResponseHeadersPolicyId, CacheBehavior::getResponseHeadersPolicyId);
+ }
+
+ /**
+ * Kept as its own entry point for the per-distribution association count, which asks the
+ * question of one config at a time and can be handed a distribution with none.
+ */
+ private static boolean usesResponseHeadersPolicy(DistributionConfig config, String id) {
+ return config != null && usesPolicy(config, id,
+ DefaultCacheBehavior::getResponseHeadersPolicyId, CacheBehavior::getResponseHeadersPolicyId);
+ }
+
+ private boolean isCachePolicyInUse(String id) {
+ return isAttachedToACacheBehavior(id,
+ DefaultCacheBehavior::getCachePolicyId, CacheBehavior::getCachePolicyId);
+ }
+
+ private boolean isOriginRequestPolicyInUse(String id) {
+ return isAttachedToACacheBehavior(id,
+ DefaultCacheBehavior::getOriginRequestPolicyId, CacheBehavior::getOriginRequestPolicyId);
+ }
+
+ /**
+ * Whether any distribution attaches {@code id} to its default or one of its ordered cache
+ * behaviors. Cache, origin request and response headers policies each hang off the same two
+ * places, so the three in-use checks differ only in which id they read.
+ */
+ private boolean isAttachedToACacheBehavior(String id,
+ Function<DefaultCacheBehavior, String> onDefault,
+ Function<CacheBehavior, String> onOrdered) {
return distStore.scan(k -> true).stream()
.map(Distribution::getConfig)
- .anyMatch(config -> usesResponseHeadersPolicy(config, id));
+ .filter(Objects::nonNull)
+ .anyMatch(config -> usesPolicy(config, id, onDefault, onOrdered));
}
- private static boolean usesResponseHeadersPolicy(
- DistributionConfig config, String id) {
- if (config == null) {
- return false;
- }
+ private static boolean usesPolicy(DistributionConfig config, String id,
+ Function<DefaultCacheBehavior, String> onDefault,
+ Function<CacheBehavior, String> onOrdered) {
boolean defaultUsesPolicy = config.getDefaultCacheBehavior() != null
- && id.equals(config.getDefaultCacheBehavior().getResponseHeadersPolicyId());
+ && id.equals(onDefault.apply(config.getDefaultCacheBehavior()));
boolean orderedUsesPolicy = config.getCacheBehaviors() != null
- && config.getCacheBehaviors().stream().anyMatch(behavior ->
- id.equals(behavior.getResponseHeadersPolicyId()));
+ && config.getCacheBehaviors().stream()
+ .anyMatch(behavior -> behavior != null && id.equals(onOrdered.apply(behavior)));
return defaultUsesPolicy || orderedUsesPolicy;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/ResponseHeadersPolicyConfigCodec.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/ResponseHeadersPolicyConfigCodec.java
index 0c07befc78..b370a17375 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/ResponseHeadersPolicyConfigCodec.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/ResponseHeadersPolicyConfigCodec.java
@@ -29,9 +29,11 @@ import java.util.regex.Pattern;
* the wire), so it round-trips through describe without a bespoke model, and the serving path reads
* the same shape to compute the headers to apply.
*/
-final class ResponseHeadersPolicyConfigCodec {
+public final class ResponseHeadersPolicyConfigCodec {
private static final Logger LOG = Logger.getLogger(ResponseHeadersPolicyConfigCodec.class);
+ private static final List<String> CORS_LISTS = List.of("AccessControlAllowOrigins",
+ "AccessControlAllowHeaders", "AccessControlAllowMethods", "AccessControlExposeHeaders");
private ResponseHeadersPolicyConfigCodec() {
}
@@ -89,6 +91,57 @@ final class ResponseHeadersPolicyConfigCodec {
return config;
}
+ /**
+ * Converts a config in the structured shape CloudFormation and the JSON SDKs use, where every
+ * list block is wrapped as {@code {Items: [...]}} and {@code RemoveHeadersConfig} items are
+ * {@code {Header: name}} objects, into the nested shape {@link #parse(String)} produces: the
+ * lists unwrapped, remove-header items reduced to their names, scalars already text. Blocks
+ * this codec does not know are passed through for the validator to refuse.
+ */
+ public static Map<String, Object> fromItemsTree(Map<String, Object> tree) {
+ Map<String, Object> config = new LinkedHashMap<>();
+ for (Map.Entry<String, Object> block : tree.entrySet()) {
+ Object value = switch (block.getKey()) {
+ case "CorsConfig" -> unwrapCorsLists(block.getValue());
+ case "CustomHeadersConfig" -> unwrapItems(block.getValue());
+ case "RemoveHeadersConfig" -> removeHeaderNames(unwrapItems(block.getValue()));
+ default -> block.getValue();
+ };
+ config.put(block.getKey(), value);
+ }
+ return config;
+ }
+
+ private static Object unwrapCorsLists(Object cors) {
+ if (!(cors instanceof Map<?, ?> blocks)) {
+ return cors;
+ }
+ Map<String, Object> map = new LinkedHashMap<>();
+ for (Map.Entry<?, ?> e : blocks.entrySet()) {
+ String key = String.valueOf(e.getKey());
+ map.put(key, CORS_LISTS.contains(key) ? unwrapItems(e.getValue()) : e.getValue());
+ }
+ return map;
+ }
+
+ private static Object unwrapItems(Object block) {
+ if (block instanceof Map<?, ?> map && map.containsKey("Items")) {
+ return map.get("Items");
+ }
+ return block;
+ }
+
+ private static Object removeHeaderNames(Object items) {
+ if (!(items instanceof List<?> list)) {
+ return items;
+ }
+ List<Object> names = new ArrayList<>();
+ for (Object item : list) {
+ names.add(item instanceof Map<?, ?> map && map.containsKey("Header") ? map.get("Header") : item);
+ }
+ return names;
+ }
+
private static Map<String, Object> parseCors(XmlElement cors) {
Map<String, Object> map = new LinkedHashMap<>();
for (String list : List.of("AccessControlAllowOrigins", "AccessControlAllowHeaders",
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 c82b53520f..c1bb65ef44 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
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
import io.github.hectorvent.floci.services.batch.BatchService;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences;
+import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFrontCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ConfigCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2FlowLogCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaMicrovmsCfnProvisioner;
@@ -233,6 +234,9 @@ final class CfnProvisionerFixture {
if (cognitoService != null) {
discovered.add(new CognitoCfnProvisioner(cognitoService));
}
+ if (cloudFrontService != null) {
+ discovered.add(new CloudFrontCfnProvisioner(cloudFrontService));
+ }
if (firehoseService != null) {
discovered.add(new FirehoseCfnProvisioner(firehoseService));
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontPoliciesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontPoliciesIntegrationTest.java
new file mode 100644
index 0000000000..5917473127
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontPoliciesIntegrationTest.java
@@ -0,0 +1,299 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.core.common.XmlParser;
+import io.github.hectorvent.floci.core.common.AwsException;
+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.OriginAccessControl;
+import io.github.hectorvent.floci.services.cloudfront.model.OriginRequestPolicy;
+import io.github.hectorvent.floci.services.cloudfront.model.ResponseHeadersPolicy;
+import io.quarkus.test.junit.QuarkusTest;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Map;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * The CloudFront configuration types through the stack lifecycle: the reproduction from issue #2441
+ * (a response headers policy referenced by a distribution in the same stack), then cache policy,
+ * origin request policy and origin access control with their exact {@code Fn::GetAtt} keys.
+ */
+@QuarkusTest
+class CloudFormationCloudFrontPoliciesIntegrationTest {
+
+ private static final String CFN_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
+
+ @Inject
+ CloudFrontService cloudFrontService;
+
+ @Test
+ void distributionRefToAResponseHeadersPolicyInTheSameStackResolves() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "floci-response-policy-ref-repro-" + suffix;
+ String policyName = "floci-response-policy-ref-repro-" + suffix;
+
+ createStack(stackName, issueTemplate(policyName, "Minimal response headers policy reference reproduction"));
+
+ String describe = describeStacks(stackName);
+ assertTrue(describe.contains("<StackStatus>CREATE_COMPLETE</StackStatus>"), describe);
+ String policyId = output(describe, "PolicyRef");
+ assertEquals(policyId, output(describe, "PolicyId"));
+ assertFalse(policyId.startsWith("ResponseHeadersPolicy"), "Ref must be the real id, not a stub: " + policyId);
+ ResponseHeadersPolicy policy = cloudFrontService.getResponseHeadersPolicy(policyId);
+ assertEquals(policyName, policy.getName());
+ assertEquals(policy.getLastModifiedTime().toString(), output(describe, "PolicyModified"));
+ assertEquals(List.of(Map.of("Header", "X-Floci-Repro", "Value", "enabled", "Override", "true")),
+ policy.getConfig().get("CustomHeadersConfig"));
+
+ String distributionId = output(describe, "DistributionId");
+ Distribution distribution = cloudFrontService.getDistribution(distributionId);
+ assertEquals(policyId, distribution.getConfig().getDefaultCacheBehavior().getResponseHeadersPolicyId());
+
+ String firstEtag = policy.getEtag();
+ updateStack(stackName, issueTemplate(policyName, "second revision"));
+ String updated = describeStacks(stackName);
+ assertTrue(updated.contains("<StackStatus>UPDATE_COMPLETE</StackStatus>"), updated);
+ assertEquals(policyId, output(updated, "PolicyRef"));
+ ResponseHeadersPolicy revised = cloudFrontService.getResponseHeadersPolicy(policyId);
+ assertEquals("second revision", revised.getComment());
+ assertNotEquals(firstEtag, revised.getEtag());
+
+ deleteStack(stackName);
+ assertThrows(AwsException.class, () -> cloudFrontService.getDistribution(distributionId));
+ AwsException gone = assertThrows(AwsException.class, () -> cloudFrontService.getResponseHeadersPolicy(policyId));
+ assertEquals("NoSuchResponseHeadersPolicy", gone.getErrorCode());
+ }
+
+ @Test
+ void cachePolicyOriginRequestPolicyAndOriginAccessControlExposeTheirAttributes() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-cloudfront-policies-" + suffix;
+
+ createStack(stackName, """
+ {
+ "Resources": {
+ "Cache": {
+ "Type": "AWS::CloudFront::CachePolicy",
+ "Properties": {
+ "CachePolicyConfig": {
+ "Name": "cfn-cache-%1$s",
+ "DefaultTTL": 86400, "MaxTTL": 31536000, "MinTTL": 1,
+ "ParametersInCacheKeyAndForwardedToOrigin": {
+ "EnableAcceptEncodingGzip": true,
+ "CookiesConfig": {"CookieBehavior": "none"},
+ "HeadersConfig": {"HeaderBehavior": "none"},
+ "QueryStringsConfig": {"QueryStringBehavior": "none"}
+ }
+ }
+ }
+ },
+ "OriginRequest": {
+ "Type": "AWS::CloudFront::OriginRequestPolicy",
+ "Properties": {
+ "OriginRequestPolicyConfig": {
+ "Name": "cfn-origin-request-%1$s",
+ "CookiesConfig": {"CookieBehavior": "all"},
+ "HeadersConfig": {"HeaderBehavior": "allViewer"},
+ "QueryStringsConfig": {"QueryStringBehavior": "all"}
+ }
+ }
+ },
+ "Oac": {
+ "Type": "AWS::CloudFront::OriginAccessControl",
+ "Properties": {
+ "OriginAccessControlConfig": {
+ "Name": "cfn-oac-%1$s",
+ "Description": "bucket access",
+ "SigningBehavior": "always",
+ "SigningProtocol": "sigv4",
+ "OriginAccessControlOriginType": "s3"
+ }
+ }
+ },
+ "Dist": {
+ "Type": "AWS::CloudFront::Distribution",
+ "Properties": {
+ "DistributionConfig": {
+ "Enabled": true,
+ "Origins": [{
+ "Id": "s3-origin",
+ "DomainName": "cfn-%1$s.s3.us-east-1.amazonaws.com",
+ "OriginAccessControlId": {"Ref": "Oac"},
+ "S3OriginConfig": {"OriginAccessIdentity": ""}
+ }],
+ "DefaultCacheBehavior": {
+ "TargetOriginId": "s3-origin",
+ "ViewerProtocolPolicy": "redirect-to-https",
+ "CachePolicyId": {"Ref": "Cache"},
+ "OriginRequestPolicyId": {"Ref": "OriginRequest"}
+ }
+ }
+ }
+ }
+ },
+ "Outputs": {
+ "CacheRef": {"Value": {"Ref": "Cache"}},
+ "CacheId": {"Value": {"Fn::GetAtt": ["Cache", "Id"]}},
+ "CacheModified": {"Value": {"Fn::GetAtt": ["Cache", "LastModifiedTime"]}},
+ "OriginRequestRef": {"Value": {"Ref": "OriginRequest"}},
+ "OriginRequestId": {"Value": {"Fn::GetAtt": ["OriginRequest", "Id"]}},
+ "OriginRequestModified": {"Value": {"Fn::GetAtt": ["OriginRequest", "LastModifiedTime"]}},
+ "OacRef": {"Value": {"Ref": "Oac"}},
+ "OacId": {"Value": {"Fn::GetAtt": ["Oac", "Id"]}},
+ "DistributionId": {"Value": {"Ref": "Dist"}}
+ }
+ }
+ """.formatted(suffix));
+
+ String describe = describeStacks(stackName);
+ assertTrue(describe.contains("<StackStatus>CREATE_COMPLETE</StackStatus>"), describe);
+
+ String cacheId = output(describe, "CacheRef");
+ assertEquals(cacheId, output(describe, "CacheId"));
+ CachePolicy cache = cloudFrontService.getCachePolicy(cacheId);
+ assertEquals("cfn-cache-" + suffix, cache.getName());
+ assertEquals(cache.getLastModifiedTime().toString(), output(describe, "CacheModified"));
+ assertEquals("86400", cache.getConfig().get("DefaultTTL"));
+
+ String originRequestId = output(describe, "OriginRequestRef");
+ assertEquals(originRequestId, output(describe, "OriginRequestId"));
+ OriginRequestPolicy originRequest = cloudFrontService.getOriginRequestPolicy(originRequestId);
+ assertEquals("cfn-origin-request-" + suffix, originRequest.getName());
+ assertEquals(originRequest.getLastModifiedTime().toString(), output(describe, "OriginRequestModified"));
+
+ String oacId = output(describe, "OacRef");
+ assertEquals(oacId, output(describe, "OacId"));
+ OriginAccessControl oac = cloudFrontService.getOriginAccessControl(oacId);
+ assertEquals("cfn-oac-" + suffix, oac.getName());
+ assertEquals("always", oac.getSigningBehavior());
+ assertEquals("s3", oac.getOriginAccessControlOriginType());
+
+ Distribution distribution = cloudFrontService.getDistribution(output(describe, "DistributionId"));
+ assertEquals(oacId, distribution.getConfig().getOrigins().getFirst().getOriginAccessControlId());
+
+ deleteStack(stackName);
+ assertEquals("NoSuchCachePolicy",
+ assertThrows(AwsException.class, () -> cloudFrontService.getCachePolicy(cacheId)).getErrorCode());
+ assertEquals("NoSuchOriginRequestPolicy",
+ assertThrows(AwsException.class, () -> cloudFrontService.getOriginRequestPolicy(originRequestId)).getErrorCode());
+ assertEquals("NoSuchOriginAccessControl",
+ assertThrows(AwsException.class, () -> cloudFrontService.getOriginAccessControl(oacId)).getErrorCode());
+ }
+
+ /** The template from issue #2441, with a unique policy name and the outputs the assertions read. */
+ private static String issueTemplate(String policyName, String comment) {
+ return """
+ AWSTemplateFormatVersion: "2010-09-09"
+ Resources:
+ ResponseHeadersPolicy:
+ Type: AWS::CloudFront::ResponseHeadersPolicy
+ Properties:
+ ResponseHeadersPolicyConfig:
+ Name: %s
+ Comment: %s
+ CustomHeadersConfig:
+ Items:
+ - Header: X-Floci-Repro
+ Value: enabled
+ Override: true
+
+ Distribution:
+ Type: AWS::CloudFront::Distribution
+ Properties:
+ DistributionConfig:
+ Enabled: true
+ Origins:
+ - Id: origin
+ DomainName: example-bucket.s3.amazonaws.com
+ S3OriginConfig: {}
+ DefaultCacheBehavior:
+ TargetOriginId: origin
+ ViewerProtocolPolicy: redirect-to-https
+ ForwardedValues:
+ QueryString: false
+ ResponseHeadersPolicyId: !Ref ResponseHeadersPolicy
+ Outputs:
+ PolicyRef:
+ Value: !Ref ResponseHeadersPolicy
+ PolicyId:
+ Value: !GetAtt ResponseHeadersPolicy.Id
+ PolicyModified:
+ Value: !GetAtt ResponseHeadersPolicy.LastModifiedTime
+ DistributionId:
+ Value: !Ref Distribution
+ """.formatted(policyName, comment);
+ }
+
+ private static void createStack(String stackName, String template) {
+ stackCall("CreateStack", stackName, template);
+ }
+
+ private static void updateStack(String stackName, String template) {
+ stackCall("UpdateStack", stackName, template);
+ }
+
+ private static void stackCall(String action, String stackName, String template) {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", action)
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ }
+
+ private static void deleteStack(String stackName) {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DeleteStack")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body(containsString("Stack with id " + stackName + " does not exist"));
+ }
+
+ private static String describeStacks(String stackName) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().asString();
+ }
+
+ private static String output(String describeStacks, String key) {
+ String value = XmlParser.extractPairs(describeStacks, "Outputs", "OutputKey", "OutputValue").get(key);
+ return value != null ? value : fail("Output " + key + " missing from: " + describeStacks);
+ }
+}
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
new file mode 100644
index 0000000000..c152ba0d16
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java
@@ -0,0 +1,504 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+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.model.CachePolicy;
+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;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.time.Instant;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * The CloudFront CFN provisioner in isolation: one mocked service. Every case asserts the exact
+ * physical id and the exact {@code Fn::GetAtt} attribute keys, since an unmapped type still
+ * reports CREATE_COMPLETE through the dispatcher's stub arm (issue #2441).
+ */
+class CloudFrontCfnProvisionerTest {
+
+ private static final String RESPONSE_HEADERS_POLICY = "AWS::CloudFront::ResponseHeadersPolicy";
+ 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 REGION = "us-east-1";
+ private static final String ID = "5cc3b908-e619-4b99-88e5-2cf7f45965bd";
+ private static final String ETAG = "E2QWRUHAPOMQZL";
+ private static final String NEW_ETAG = "E3ZQ1XZ4M2ZTKH";
+ private static final Instant MODIFIED = Instant.parse("2026-09-07T10:15:30Z");
+
+ private final CloudFrontService cloudFront = mock(CloudFrontService.class);
+ private final CloudFrontCfnProvisioner provisioner = new CloudFrontCfnProvisioner(cloudFront);
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ private ProvisionContext ctx() {
+ return ctx(null);
+ }
+
+ private ProvisionContext ctx(String priorPhysicalId) {
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
+ return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
+ }
+
+ private static StackResource resource(String type) {
+ StackResource r = new StackResource();
+ r.setLogicalId("Policy");
+ r.setResourceType(type);
+ r.setAttributes(new HashMap<>());
+ return r;
+ }
+
+ private static StackResource resource(String type, String physicalId, Map<String, String> attributes) {
+ StackResource r = resource(type);
+ r.setPhysicalId(physicalId);
+ r.setAttributes(new HashMap<>(attributes));
+ return r;
+ }
+
+ private JsonNode json(String json) throws Exception {
+ return mapper.readTree(json);
+ }
+
+ private static ResponseHeadersPolicy responseHeadersPolicy(String id, String etag) {
+ ResponseHeadersPolicy p = new ResponseHeadersPolicy();
+ p.setId(id);
+ p.setEtag(etag);
+ p.setLastModifiedTime(MODIFIED);
+ return p;
+ }
+
+ private static <T> T withIdentity(T model, java.util.function.Consumer<T> set) {
+ set.accept(model);
+ return model;
+ }
+
+ @Test
+ void servesTheFourConfigTypes() {
+ assertEquals(Set.of(RESPONSE_HEADERS_POLICY, CACHE_POLICY, ORIGIN_REQUEST_POLICY, ORIGIN_ACCESS_CONTROL),
+ provisioner.resourceTypes());
+ }
+
+ @Test
+ void createsResponseHeadersPolicyFromTheConfigInTheCodecShape() throws Exception {
+ when(cloudFront.createResponseHeadersPolicy(any()))
+ .thenAnswer(inv -> withIdentity(inv.<ResponseHeadersPolicy>getArgument(0), p -> {
+ p.setId(ID);
+ p.setEtag(ETAG);
+ p.setLastModifiedTime(MODIFIED);
+ }));
+ StackResource r = resource(RESPONSE_HEADERS_POLICY);
+
+ provisioner.provision(r, json("""
+ {"ResponseHeadersPolicyConfig": {
+ "Name": "floci-response-policy-ref-repro",
+ "Comment": "Minimal response headers policy reference reproduction",
+ "CustomHeadersConfig": {"Items": [{"Header": "X-Floci-Repro", "Value": "enabled", "Override": true}]},
+ "SecurityHeadersConfig": {"FrameOptions": {"FrameOption": "DENY", "Override": false}},
+ "CorsConfig": {
+ "AccessControlAllowOrigins": {"Items": ["https://app.example.test"]},
+ "AccessControlMaxAgeSec": 600,
+ "OriginOverride": true
+ },
+ "RemoveHeadersConfig": {"Items": [{"Header": "Server"}]}
+ }}
+ """), ctx());
+
+ ArgumentCaptor<ResponseHeadersPolicy> captor = ArgumentCaptor.forClass(ResponseHeadersPolicy.class);
+ verify(cloudFront).createResponseHeadersPolicy(captor.capture());
+ ResponseHeadersPolicy sent = captor.getValue();
+ assertEquals("floci-response-policy-ref-repro", sent.getName());
+ assertEquals("Minimal response headers policy reference reproduction", sent.getComment());
+ assertEquals(Map.of(
+ "CustomHeadersConfig", List.of(
+ Map.of("Header", "X-Floci-Repro", "Value", "enabled", "Override", "true")),
+ "SecurityHeadersConfig", Map.of("FrameOptions", Map.of("FrameOption", "DENY", "Override", "false")),
+ "CorsConfig", Map.of(
+ "AccessControlAllowOrigins", List.of("https://app.example.test"),
+ "AccessControlMaxAgeSec", "600",
+ "OriginOverride", "true"),
+ "RemoveHeadersConfig", List.of("Server")),
+ sent.getConfig());
+ assertEquals(ID, r.getPhysicalId());
+ assertEquals(Map.of("Id", ID, "LastModifiedTime", "2026-09-07T10:15:30Z"), r.getAttributes());
+ }
+
+ @Test
+ void updatesResponseHeadersPolicyInPlaceWithTheCurrentEtag() throws Exception {
+ when(cloudFront.getResponseHeadersPolicy(ID)).thenReturn(responseHeadersPolicy(ID, ETAG));
+ when(cloudFront.updateResponseHeadersPolicy(eq(ID), eq(ETAG), any()))
+ .thenAnswer(inv -> withIdentity(inv.<ResponseHeadersPolicy>getArgument(2), p -> {
+ p.setId(ID);
+ p.setEtag(NEW_ETAG);
+ p.setLastModifiedTime(MODIFIED.plusSeconds(60));
+ }));
+ StackResource r = resource(RESPONSE_HEADERS_POLICY, ID,
+ Map.of("Id", ID, "LastModifiedTime", MODIFIED.toString()));
+
+ provisioner.provision(r, json("""
+ {"ResponseHeadersPolicyConfig": {"Name": "renamed", "Comment": "second revision"}}
+ """), ctx(ID));
+
+ ArgumentCaptor<ResponseHeadersPolicy> captor = ArgumentCaptor.forClass(ResponseHeadersPolicy.class);
+ verify(cloudFront).updateResponseHeadersPolicy(eq(ID), eq(ETAG), captor.capture());
+ assertEquals("renamed", captor.getValue().getName());
+ assertEquals(Map.of(), captor.getValue().getConfig());
+ verify(cloudFront, never()).createResponseHeadersPolicy(any());
+ assertEquals(ID, r.getPhysicalId());
+ assertEquals(Map.of("Id", ID, "LastModifiedTime", "2026-09-07T10:16:30Z"), r.getAttributes());
+ }
+
+ @Test
+ void recreatesResponseHeadersPolicyWhenThePriorRecordIsGone() throws Exception {
+ when(cloudFront.getResponseHeadersPolicy(ID)).thenThrow(
+ new AwsException("NoSuchResponseHeadersPolicy", "The specified response headers policy does not exist.", 404));
+ when(cloudFront.createResponseHeadersPolicy(any()))
+ .thenAnswer(inv -> withIdentity(inv.<ResponseHeadersPolicy>getArgument(0), p -> {
+ p.setId("new-id");
+ p.setEtag(ETAG);
+ p.setLastModifiedTime(MODIFIED);
+ }));
+ StackResource r = resource(RESPONSE_HEADERS_POLICY, ID, Map.of("Id", ID));
+
+ provisioner.provision(r, json("""
+ {"ResponseHeadersPolicyConfig": {"Name": "policy"}}
+ """), ctx(ID));
+
+ verify(cloudFront, never()).updateResponseHeadersPolicy(any(), any(), any());
+ assertEquals("new-id", r.getPhysicalId());
+ assertEquals("new-id", r.getAttributes().get("Id"));
+ }
+
+ @Test
+ void rollingBackARecreationDeletesTheReplacementAndRestoresThePriorId() throws Exception {
+ // The engine's update rollback only deletes resources the update ADDED; a resource that
+ // already existed and merely acquired a new physical id reached the "Rollback is not
+ // implemented" arm, which deletes nothing, so the recreated policy stayed behind.
+ when(cloudFront.getResponseHeadersPolicy(ID)).thenThrow(new AwsException(
+ "NoSuchResponseHeadersPolicy", "The specified response headers policy does not exist.", 404));
+ when(cloudFront.createResponseHeadersPolicy(any()))
+ .thenAnswer(inv -> withIdentity(inv.<ResponseHeadersPolicy>getArgument(0), p -> {
+ p.setId("new-id");
+ p.setEtag(ETAG);
+ p.setLastModifiedTime(MODIFIED);
+ }));
+ StackResource r = resource(RESPONSE_HEADERS_POLICY, ID, Map.of("Id", ID, "LastModifiedTime", "old-time"));
+ provisioner.provision(r, json("""
+ {"ResponseHeadersPolicyConfig": {"Name": "policy"}}
+ """), ctx(ID));
+ assertEquals("new-id", r.getPhysicalId());
+ when(cloudFront.getResponseHeadersPolicy("new-id")).thenReturn(responseHeadersPolicy("new-id", ETAG));
+
+ assertTrue(provisioner.rollbackUpdate(r));
+
+ verify(cloudFront).deleteResponseHeadersPolicy("new-id", ETAG);
+ assertEquals(ID, r.getPhysicalId(), "the prior id is named again");
+ assertEquals(ID, r.getAttributes().get("Id"));
+ assertEquals("old-time", r.getAttributes().get("LastModifiedTime"));
+ }
+
+ @Test
+ void rollingBackAnInPlaceUpdateReportsNotRolledBack() {
+ // Deliberate and unchanged: an in-place update keeps the physical id, so nothing is
+ // recorded to undo, and putting the committed change back would need a configuration
+ // snapshot this provisioner does not keep. Same limitation as AWS::Cognito::UserPool.
+ StackResource r = resource(CACHE_POLICY, ID, Map.of("Id", ID));
+
+ assertFalse(provisioner.rollbackUpdate(r));
+
+ verify(cloudFront, never()).deleteCachePolicy(any(), any());
+ }
+
+ @Test
+ void aRecreationOwesCleanupForThePriorEntityAndToleratesItBeingGone() throws Exception {
+ // The recorded displaced entity is always one the service already forgot, since prior()
+ // returns the object whenever it exists. The cleanup still has to run so the record is
+ // cleared rather than left owed forever.
+ when(cloudFront.getCachePolicy(ID)).thenThrow(
+ new AwsException("NoSuchCachePolicy", "The specified cache policy does not exist.", 404));
+ when(cloudFront.createCachePolicy(any()))
+ .thenAnswer(inv -> withIdentity(inv.<CachePolicy>getArgument(0), p -> {
+ p.setId("new-id");
+ p.setEtag(ETAG);
+ p.setLastModifiedTime(MODIFIED);
+ }));
+ StackResource r = resource(CACHE_POLICY, ID, Map.of("Id", ID));
+
+ provisioner.provision(r, json("""
+ {"CachePolicyConfig": {"Name": "policy"}}
+ """), ctx(ID));
+
+ assertTrue(provisioner.hasReplacementUpdate(r), "the prior entity is owed a cleanup");
+ assertEquals(ID, provisioner.updateCleanupPhysicalId(r));
+ provisioner.completeUpdate(r);
+ assertFalse(provisioner.hasReplacementUpdate(r), "the record is cleared once the cleanup ran");
+ }
+
+ @Test
+ void otherLookupFailuresOnUpdatePropagate() throws Exception {
+ when(cloudFront.getResponseHeadersPolicy(ID)).thenThrow(new AwsException("AccessDenied", "denied", 403));
+ StackResource r = resource(RESPONSE_HEADERS_POLICY, ID, Map.of("Id", ID));
+
+ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, json("""
+ {"ResponseHeadersPolicyConfig": {"Name": "policy"}}
+ """), ctx(ID)));
+
+ assertEquals("AccessDenied", e.getErrorCode());
+ verify(cloudFront, never()).createResponseHeadersPolicy(any());
+ }
+
+ @Test
+ void missingConfigIsAValidationError() throws Exception {
+ for (String[] type : new String[][] {
+ {RESPONSE_HEADERS_POLICY, "ResponseHeadersPolicyConfig"},
+ {CACHE_POLICY, "CachePolicyConfig"},
+ {ORIGIN_REQUEST_POLICY, "OriginRequestPolicyConfig"},
+ {ORIGIN_ACCESS_CONTROL, "OriginAccessControlConfig"}}) {
+ StackResource r = resource(type[0]);
+ AwsException e = assertThrows(AwsException.class,
+ () -> provisioner.provision(r, json("{\"Tags\": []}"), ctx()));
+ assertEquals("ValidationError", e.getErrorCode());
+ assertEquals(type[0] + " requires " + type[1], e.getMessage());
+ assertNull(r.getPhysicalId());
+ }
+ verify(cloudFront, never()).createResponseHeadersPolicy(any());
+ verify(cloudFront, never()).createCachePolicy(any());
+ verify(cloudFront, never()).createOriginRequestPolicy(any());
+ verify(cloudFront, never()).createOriginAccessControl(any());
+ }
+
+ @Test
+ void deletesResponseHeadersPolicyWithItsCurrentEtag() {
+ when(cloudFront.getResponseHeadersPolicy(ID)).thenReturn(responseHeadersPolicy(ID, ETAG));
+
+ provisioner.delete(RESPONSE_HEADERS_POLICY, ID, REGION);
+
+ verify(cloudFront).deleteResponseHeadersPolicy(ID, ETAG);
+ }
+
+ @Test
+ void deleteToleratesAPolicyAlreadyGone() {
+ when(cloudFront.getResponseHeadersPolicy(ID)).thenThrow(
+ new AwsException("NoSuchResponseHeadersPolicy", "The specified response headers policy does not exist.", 404));
+
+ provisioner.delete(RESPONSE_HEADERS_POLICY, ID, REGION);
+ provisioner.delete(RESPONSE_HEADERS_POLICY, "", REGION);
+ provisioner.delete(RESPONSE_HEADERS_POLICY, null, REGION);
+
+ verify(cloudFront, never()).deleteResponseHeadersPolicy(any(), any());
+ }
+
+ @Test
+ void deleteOfAPolicyStillInUseFailsTheStack() {
+ when(cloudFront.getResponseHeadersPolicy(ID)).thenReturn(responseHeadersPolicy(ID, ETAG));
+ AwsException inUse = new AwsException("ResponseHeadersPolicyInUse",
+ "The response headers policy is attached to one or more distributions.", 409);
+ org.mockito.Mockito.doThrow(inUse).when(cloudFront).deleteResponseHeadersPolicy(ID, ETAG);
+
+ AwsException e = assertThrows(AwsException.class,
+ () -> provisioner.delete(RESPONSE_HEADERS_POLICY, ID, REGION));
+
+ assertSame(inUse, e);
+ }
+
+ @Test
+ void createsCachePolicyWithTtlsAsText() throws Exception {
+ when(cloudFront.createCachePolicy(any()))
+ .thenAnswer(inv -> withIdentity(inv.<CachePolicy>getArgument(0), p -> {
+ p.setId(ID);
+ p.setEtag(ETAG);
+ p.setLastModifiedTime(MODIFIED);
+ }));
+ StackResource r = resource(CACHE_POLICY);
+
+ provisioner.provision(r, json("""
+ {"CachePolicyConfig": {
+ "Name": "cfn-cache",
+ "DefaultTTL": 86400, "MaxTTL": 31536000, "MinTTL": 1,
+ "ParametersInCacheKeyAndForwardedToOrigin": {
+ "EnableAcceptEncodingGzip": true,
+ "CookiesConfig": {"CookieBehavior": "none"},
+ "HeadersConfig": {"HeaderBehavior": "whitelist", "Headers": ["Origin"]},
+ "QueryStringsConfig": {"QueryStringBehavior": "all"}
+ }
+ }}
+ """), ctx());
+
+ ArgumentCaptor<CachePolicy> captor = ArgumentCaptor.forClass(CachePolicy.class);
+ verify(cloudFront).createCachePolicy(captor.capture());
+ assertEquals("cfn-cache", captor.getValue().getName());
+ assertNull(captor.getValue().getComment());
+ assertEquals(Map.of(
+ "DefaultTTL", "86400", "MaxTTL", "31536000", "MinTTL", "1",
+ "ParametersInCacheKeyAndForwardedToOrigin", Map.of(
+ "EnableAcceptEncodingGzip", "true",
+ "CookiesConfig", Map.of("CookieBehavior", "none"),
+ "HeadersConfig", Map.of("HeaderBehavior", "whitelist", "Headers", List.of("Origin")),
+ "QueryStringsConfig", Map.of("QueryStringBehavior", "all"))),
+ captor.getValue().getConfig());
+ assertEquals(ID, r.getPhysicalId());
+ assertEquals(Map.of("Id", ID, "LastModifiedTime", "2026-09-07T10:15:30Z"), r.getAttributes());
+ }
+
+ @Test
+ void updatesAndDeletesCachePolicyThroughTheEtag() throws Exception {
+ CachePolicy existing = new CachePolicy();
+ existing.setId(ID);
+ existing.setEtag(ETAG);
+ when(cloudFront.getCachePolicy(ID)).thenReturn(existing);
+ when(cloudFront.updateCachePolicy(eq(ID), eq(ETAG), any()))
+ .thenAnswer(inv -> withIdentity(inv.<CachePolicy>getArgument(2), p -> {
+ p.setId(ID);
+ p.setLastModifiedTime(MODIFIED);
+ }));
+ StackResource r = resource(CACHE_POLICY, ID, Map.of("Id", ID, "LastModifiedTime", ""));
+
+ provisioner.provision(r, json("{\"CachePolicyConfig\": {\"Name\": \"cfn-cache-2\"}}"), ctx(ID));
+ provisioner.delete(CACHE_POLICY, ID, REGION);
+
+ verify(cloudFront, never()).createCachePolicy(any());
+ verify(cloudFront).deleteCachePolicy(ID, ETAG);
+ assertEquals(ID, r.getPhysicalId());
+ assertEquals(Map.of("Id", ID, "LastModifiedTime", "2026-09-07T10:15:30Z"), r.getAttributes());
+ }
+
+ @Test
+ void createsAndDeletesOriginRequestPolicy() throws Exception {
+ when(cloudFront.createOriginRequestPolicy(any()))
+ .thenAnswer(inv -> withIdentity(inv.<OriginRequestPolicy>getArgument(0), p -> {
+ p.setId(ID);
+ p.setEtag(ETAG);
+ p.setLastModifiedTime(MODIFIED);
+ }));
+ OriginRequestPolicy existing = new OriginRequestPolicy();
+ existing.setId(ID);
+ existing.setEtag(ETAG);
+ when(cloudFront.getOriginRequestPolicy(ID)).thenReturn(existing);
+ StackResource r = resource(ORIGIN_REQUEST_POLICY);
+
+ provisioner.provision(r, json("""
+ {"OriginRequestPolicyConfig": {
+ "Name": "cfn-origin-request", "Comment": "forward all",
+ "CookiesConfig": {"CookieBehavior": "all"},
+ "HeadersConfig": {"HeaderBehavior": "allViewer"},
+ "QueryStringsConfig": {"QueryStringBehavior": "all"}
+ }}
+ """), ctx());
+ provisioner.delete(ORIGIN_REQUEST_POLICY, ID, REGION);
+
+ ArgumentCaptor<OriginRequestPolicy> captor = ArgumentCaptor.forClass(OriginRequestPolicy.class);
+ verify(cloudFront).createOriginRequestPolicy(captor.capture());
+ assertEquals("cfn-origin-request", captor.getValue().getName());
+ assertEquals("forward all", captor.getValue().getComment());
+ assertEquals(Map.of(
+ "CookiesConfig", Map.of("CookieBehavior", "all"),
+ "HeadersConfig", Map.of("HeaderBehavior", "allViewer"),
+ "QueryStringsConfig", Map.of("QueryStringBehavior", "all")),
+ captor.getValue().getConfig());
+ verify(cloudFront).deleteOriginRequestPolicy(ID, ETAG);
+ assertEquals(ID, r.getPhysicalId());
+ assertEquals(Map.of("Id", ID, "LastModifiedTime", "2026-09-07T10:15:30Z"), r.getAttributes());
+ }
+
+ @Test
+ void createsOriginAccessControlWithAllFiveFieldsAndOnlyIdAsAttribute() throws Exception {
+ when(cloudFront.createOriginAccessControl(any()))
+ .thenAnswer(inv -> withIdentity(inv.<OriginAccessControl>getArgument(0), o -> {
+ o.setId("E2ABCDEFGHIJKL");
+ o.setEtag(ETAG);
+ o.setLastModifiedTime(MODIFIED);
+ }));
+ StackResource r = resource(ORIGIN_ACCESS_CONTROL);
+
+ provisioner.provision(r, json("""
+ {"OriginAccessControlConfig": {
+ "Name": "cfn-oac", "Description": "bucket access",
+ "SigningBehavior": "always", "SigningProtocol": "sigv4",
+ "OriginAccessControlOriginType": "s3"
+ }}
+ """), ctx());
+
+ ArgumentCaptor<OriginAccessControl> captor = ArgumentCaptor.forClass(OriginAccessControl.class);
+ verify(cloudFront).createOriginAccessControl(captor.capture());
+ OriginAccessControl sent = captor.getValue();
+ assertEquals("cfn-oac", sent.getName());
+ assertEquals("bucket access", sent.getDescription());
+ assertEquals("always", sent.getSigningBehavior());
+ assertEquals("sigv4", sent.getSigningProtocol());
+ assertEquals("s3", sent.getOriginAccessControlOriginType());
+ assertEquals("E2ABCDEFGHIJKL", r.getPhysicalId());
+ assertEquals(Map.of("Id", "E2ABCDEFGHIJKL"), r.getAttributes());
+ assertFalse(r.getAttributes().containsKey("LastModifiedTime"));
+ }
+
+ @Test
+ void updatesAndDeletesOriginAccessControlThroughTheEtag() throws Exception {
+ OriginAccessControl existing = new OriginAccessControl();
+ existing.setId("E2ABCDEFGHIJKL");
+ existing.setEtag(ETAG);
+ when(cloudFront.getOriginAccessControl("E2ABCDEFGHIJKL")).thenReturn(existing);
+ when(cloudFront.updateOriginAccessControl(eq("E2ABCDEFGHIJKL"), eq(ETAG), any()))
+ .thenAnswer(inv -> withIdentity(inv.<OriginAccessControl>getArgument(2),
+ o -> o.setId("E2ABCDEFGHIJKL")));
+ StackResource r = resource(ORIGIN_ACCESS_CONTROL, "E2ABCDEFGHIJKL", Map.of("Id", "E2ABCDEFGHIJKL"));
+
+ provisioner.provision(r, json("""
+ {"OriginAccessControlConfig": {"Name": "cfn-oac", "SigningBehavior": "never",
+ "SigningProtocol": "sigv4", "OriginAccessControlOriginType": "s3"}}
+ """), ctx("E2ABCDEFGHIJKL"));
+ provisioner.delete(ORIGIN_ACCESS_CONTROL, "E2ABCDEFGHIJKL", REGION);
+
+ ArgumentCaptor<OriginAccessControl> captor = ArgumentCaptor.forClass(OriginAccessControl.class);
+ verify(cloudFront).updateOriginAccessControl(eq("E2ABCDEFGHIJKL"), eq(ETAG), captor.capture());
+ assertEquals("never", captor.getValue().getSigningBehavior());
+ verify(cloudFront, never()).createOriginAccessControl(any());
+ verify(cloudFront).deleteOriginAccessControl("E2ABCDEFGHIJKL", ETAG);
+ assertEquals(Map.of("Id", "E2ABCDEFGHIJKL"), r.getAttributes());
+ }
+
+ @Test
+ void configIntrinsicsAreResolvedThroughTheEngine() throws Exception {
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolveNode(any())).thenAnswer(inv -> json("""
+ {"Name": "resolved-name", "CustomHeadersConfig": {"Items": [{"Header": "X-A", "Value": "1", "Override": false}]}}
+ """));
+ ProvisionContext ctx = new ProvisionContext(engine, REGION, "000000000000", "my-stack", null);
+ when(cloudFront.createResponseHeadersPolicy(any()))
+ .thenAnswer(inv -> withIdentity(inv.<ResponseHeadersPolicy>getArgument(0), p -> p.setId(ID)));
+ StackResource r = resource(RESPONSE_HEADERS_POLICY);
+
+ provisioner.provision(r, json("""
+ {"ResponseHeadersPolicyConfig": {"Name": {"Fn::Sub": "${AWS::StackName}-policy"}}}
+ """), ctx);
+
+ ArgumentCaptor<ResponseHeadersPolicy> captor = ArgumentCaptor.forClass(ResponseHeadersPolicy.class);
+ verify(cloudFront).createResponseHeadersPolicy(captor.capture());
+ assertEquals("resolved-name", captor.getValue().getName());
+ assertEquals(Map.of("CustomHeadersConfig",
+ List.of(Map.of("Header", "X-A", "Value", "1", "Override", "false"))),
+ captor.getValue().getConfig());
+ assertEquals(Map.of("Id", ID, "LastModifiedTime", ""), r.getAttributes());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java
index 6905947367..478d075599 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java
@@ -6,6 +6,8 @@ import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
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.OriginRequestPolicy;
import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontFunction;
import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontOriginAccessIdentity;
import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;
@@ -876,6 +878,99 @@ class CloudFrontServiceTest {
distributionWithPolicy(policy.getId())));
}
+ @Test
+ void preventsDeletingACachePolicyAttachedToTheDefaultCacheBehavior() {
+ // DeleteCachePolicy declares CachePolicyInUse and documents "You cannot delete a cache
+ // policy if it's attached to a cache behavior"; without the check the distribution was
+ // left pointing at a policy that no longer existed.
+ CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
+ CachePolicy policy = service.createCachePolicy(namedCachePolicy("in-use-cache-policy"));
+ Distribution distribution = service.createDistribution(
+ distributionWithCachePolicy(policy.getId(), null), Map.of());
+
+ assertAws("CachePolicyInUse", () -> service.deleteCachePolicy(policy.getId(), policy.getEtag()));
+
+ Distribution detached = distributionWithCachePolicy(null, null);
+ service.updateDistribution(distribution.getId(), distribution.getEtag(), detached);
+ service.deleteCachePolicy(policy.getId(), policy.getEtag());
+ assertAws("NoSuchCachePolicy", () -> service.getCachePolicy(policy.getId()));
+ }
+
+ @Test
+ void preventsDeletingACachePolicyAttachedToAnOrderedCacheBehavior() {
+ CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
+ CachePolicy policy = service.createCachePolicy(namedCachePolicy("ordered-cache-policy"));
+ service.createDistribution(distributionWithCachePolicy(null, policy.getId()), Map.of());
+
+ assertAws("CachePolicyInUse", () -> service.deleteCachePolicy(policy.getId(), policy.getEtag()));
+ }
+
+ @Test
+ void preventsDeletingAnOriginRequestPolicyInUse() {
+ CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
+ OriginRequestPolicy policy =
+ service.createOriginRequestPolicy(namedOriginRequestPolicy("in-use-orp"));
+ Distribution distribution = service.createDistribution(
+ distributionWithOriginRequestPolicy(policy.getId()), Map.of());
+
+ assertAws("OriginRequestPolicyInUse",
+ () -> service.deleteOriginRequestPolicy(policy.getId(), policy.getEtag()));
+
+ Distribution detached = distributionWithOriginRequestPolicy(null);
+ service.updateDistribution(distribution.getId(), distribution.getEtag(), detached);
+ service.deleteOriginRequestPolicy(policy.getId(), policy.getEtag());
+ assertAws("NoSuchOriginRequestPolicy", () -> service.getOriginRequestPolicy(policy.getId()));
+ }
+
+ @Test
+ void deletesAnUnattachedCachePolicy() {
+ CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
+ CachePolicy policy = service.createCachePolicy(namedCachePolicy("free-cache-policy"));
+
+ service.deleteCachePolicy(policy.getId(), policy.getEtag());
+
+ assertAws("NoSuchCachePolicy", () -> service.getCachePolicy(policy.getId()));
+ }
+
+ private static CachePolicy namedCachePolicy(String name) {
+ CachePolicy policy = new CachePolicy();
+ policy.setName(name);
+ policy.setConfig(Map.of());
+ return policy;
+ }
+
+ private static OriginRequestPolicy namedOriginRequestPolicy(String name) {
+ OriginRequestPolicy policy = new OriginRequestPolicy();
+ policy.setName(name);
+ policy.setConfig(Map.of());
+ return policy;
+ }
+
+ private static Distribution distributionWithCachePolicy(String defaultPolicyId, String orderedPolicyId) {
+ DefaultCacheBehavior behavior = new DefaultCacheBehavior();
+ behavior.setCachePolicyId(defaultPolicyId);
+ DistributionConfig config = new DistributionConfig();
+ config.setDefaultCacheBehavior(behavior);
+ if (orderedPolicyId != null) {
+ CacheBehavior ordered = new CacheBehavior();
+ ordered.setCachePolicyId(orderedPolicyId);
+ config.setCacheBehaviors(List.of(ordered));
+ }
+ Distribution distribution = new Distribution();
+ distribution.setConfig(config);
+ return distribution;
+ }
+
+ private static Distribution distributionWithOriginRequestPolicy(String policyId) {
+ DefaultCacheBehavior behavior = new DefaultCacheBehavior();
+ behavior.setOriginRequestPolicyId(policyId);
+ DistributionConfig config = new DistributionConfig();
+ config.setDefaultCacheBehavior(behavior);
+ Distribution distribution = new Distribution();
+ distribution.setConfig(config);
+ return distribution;
+ }
+
private static Distribution distributionWithPolicy(String policyId) {
DefaultCacheBehavior behavior = new DefaultCacheBehavior();
behavior.setResponseHeadersPolicyId(policyId);
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/ResponseHeadersPolicyConfigCodecTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/ResponseHeadersPolicyConfigCodecTest.java
index 7f85049596..9a3036d7ae 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/ResponseHeadersPolicyConfigCodecTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/ResponseHeadersPolicyConfigCodecTest.java
@@ -287,4 +287,50 @@ class ResponseHeadersPolicyConfigCodecTest {
}
return map;
}
+
+ @Test
+ void fromItemsTreeStoresTheShapeParseProducesAndSurvivesTheRoundTrip() {
+ Map<String, Object> tree = new LinkedHashMap<>();
+ tree.put("SecurityHeadersConfig", Map.of("FrameOptions", Map.of("Override", "true", "FrameOption", "DENY")));
+ Map<String, Object> cors = new LinkedHashMap<>();
+ cors.put("AccessControlAllowOrigins", Map.of("Items", List.of("https://app.example.test")));
+ cors.put("AccessControlAllowMethods", Map.of("Items", List.of("GET", "HEAD")));
+ cors.put("AccessControlAllowCredentials", "false");
+ cors.put("OriginOverride", "true");
+ tree.put("CorsConfig", cors);
+ tree.put("CustomHeadersConfig", Map.of("Items", List.of(
+ Map.of("Header", "X-Floci-Repro", "Value", "enabled", "Override", "true"))));
+ tree.put("RemoveHeadersConfig", Map.of("Items", List.of(Map.of("Header", "Server"))));
+ tree.put("ServerTimingHeadersConfig", Map.of("Enabled", "true", "SamplingRate", "50"));
+
+ Map<String, Object> config = ResponseHeadersPolicyConfigCodec.fromItemsTree(tree);
+
+ assertEquals(List.of("https://app.example.test"),
+ ((Map<?, ?>) config.get("CorsConfig")).get("AccessControlAllowOrigins"));
+ assertEquals(List.of("GET", "HEAD"), ((Map<?, ?>) config.get("CorsConfig")).get("AccessControlAllowMethods"));
+ assertEquals("true", ((Map<?, ?>) config.get("CorsConfig")).get("OriginOverride"));
+ assertEquals(List.of(Map.of("Header", "X-Floci-Repro", "Value", "enabled", "Override", "true")),
+ config.get("CustomHeadersConfig"));
+ assertEquals(List.of("Server"), config.get("RemoveHeadersConfig"));
+ assertEquals(Map.of("Enabled", "true", "SamplingRate", "50"), config.get("ServerTimingHeadersConfig"));
+
+ XmlBuilder xml = new XmlBuilder().start("ResponseHeadersPolicyConfig");
+ ResponseHeadersPolicyConfigCodec.serialize(xml, config);
+ Map<String, Object> reparsed = ResponseHeadersPolicyConfigCodec.parse(xml.end("ResponseHeadersPolicyConfig").build());
+ assertEquals(config, reparsed);
+ }
+
+ @Test
+ void fromItemsTreePassesUnknownBlocksAndBareListsThrough() {
+ Map<String, Object> tree = new LinkedHashMap<>();
+ tree.put("CustomHeadersConfig", List.of(Map.of("Header", "X-A", "Value", "1", "Override", "false")));
+ tree.put("RemoveHeadersConfig", Map.of("Items", List.of("Server")));
+ tree.put("Unknown", Map.of("Items", List.of("x")));
+
+ Map<String, Object> config = ResponseHeadersPolicyConfigCodec.fromItemsTree(tree);
+
+ assertEquals(List.of(Map.of("Header", "X-A", "Value", "1", "Override", "false")), config.get("CustomHeadersConfig"));
+ assertEquals(List.of("Server"), config.get("RemoveHeadersConfig"));
+ assertEquals(Map.of("Items", List.of("x")), config.get("Unknown"));
+ }
}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index 60308dcd7c..2488ba5907 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -27,7 +27,11 @@ AWS::Batch::JobQueue LEGACY_SWITCH
AWS::CDK::Metadata CdkMetadataCfnProvisioner
AWS::CertificateManager::Certificate AcmCfnProvisioner
AWS::CloudFormation::CustomResource LEGACY_SWITCH
+AWS::CloudFront::CachePolicy CloudFrontCfnProvisioner
AWS::CloudFront::Distribution LEGACY_SWITCH
+AWS::CloudFront::OriginAccessControl CloudFrontCfnProvisioner
+AWS::CloudFront::OriginRequestPolicy CloudFrontCfnProvisioner
+AWS::CloudFront::ResponseHeadersPolicy CloudFrontCfnProvisioner
AWS::CloudTrail::Trail CloudTrailCfnProvisioner
AWS::CloudWatch::Alarm CloudWatchCfnProvisioner
AWS::CodeBuild::Project CodeBuildCfnProvisioner