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

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

AWS::CloudFront::ResponseHeadersPolicy, CachePolicy, OriginRequestPolicy
and OriginAccessControl had no provisioner, so the dispatcher's stub arm
reported CREATE_COMPLETE with a synthetic id and a distribution that
referenced it failed with "The specified response headers policy does not
exist."

A new CloudFrontCfnProvisioner creates each type through CloudFrontService:
the physical id is the service id, Fn::GetAtt exposes Id and LastModifiedTime
(Id only for the origin access control, per the registry schemas), updates go
through the service's etag-guarded update, and deletes tolerate only the
type's own not-found code so an in-use policy fails the stack delete as on
AWS. The response headers configuration is reshaped into the flattened form
the service's codec stores through the new
ResponseHeadersPolicyConfigCodec.fromItemsTree.

Closes #2441

* fix(cloudfront): reject deleting a cache or origin request policy in use

DeleteCachePolicy declares CachePolicyInUse and DeleteOriginRequestPolicy
declares OriginRequestPolicyInUse, both 409 sender faults, and both are
documented as refusing the delete while the policy is attached to a cache
behavior. Floci checked only two of the four policy-shaped types:
deleteResponseHeadersPolicy and deleteOriginAccessControl raised their in-use
errors, while these two deleted unconditionally once the etag matched. A policy
still referenced by a distribution could be removed, leaving that distribution
pointing at something that no longer existed.

Both now raise the modeled error after the etag check, matching the ordering the
other two deletes already use. Cache, origin request and response headers
policies all hang off the same two places, a distribution's default cache
behavior and its ordered ones, so the three near-identical scans collapse into
one helper that differs only in which id it reads. The per-distribution
association count keeps its own entry point, since it asks about one config at a
time and can be handed a distribution with none.

Found while reviewing the CloudFormation provisioner in this PR, which was
already written for this: its delete tolerates only NoSuch<Type>, so it fails
the stack correctly now that the service raises the in-use error. The
CloudFormation integration test covers that end to end: it attaches both
policies to a distribution and still deletes the stack cleanly, because
CloudFormation removes the distribution before the policies it references.

Four tests: a cache policy attached to a default behavior and to an ordered one,
an origin request policy in use, and an unattached policy still deleting.

* test(cloudformation): parse stack outputs with XmlParser

The CloudFront policies integration test pulled Outputs out of the DescribeStacks
response with two regular expressions over <member> and <OutputValue> blocks.
XmlParser.extractPairs already does exactly this, and seventeen sibling
CloudFormation integration tests define the same one-line helper over it, so the
twelve-line version was reinventing a shared utility. It also matches the repo's
rule against parsing XML with regex.

Behaviour is unchanged, including the failure message that names the missing key.

* fix(cloudformation): roll back a recreated CloudFront policy on a failed update

When an update finds the prior policy or origin access control already deleted
out of band, the provisioner recreates it under a new physical id. If a later
resource then failed the stack update, the rollback left that new object behind:
the engine only deletes resources the update ADDED, inside the previous == null
branch of rollbackUpdatedResources, so an existing resource that merely acquired
a new physical id fell through to the "Rollback is not implemented" arm, which
deletes nothing.

ReplacementCleanup already models exactly this, and CognitoCfnProvisioner wires
it for the same situation, so the provisioner records the displaced entity after
each provision and delegates the cleanup hooks and rollbackUpdate to it. A
rollback now names the prior id again with the attributes it carried and deletes
the object the failed update created.

The physical id changes here only when the prior object was already gone, since
prior() returns the entity whenever the service still knows it, so the recorded
displaced entity is always one that no longer exists and its cleanup delete is a
no-op tolerated by the type's not-found code. The hooks are still needed, or a
recorded entity would stay owed a delete forever.

An in-place update keeps its physical id, so nothing is recorded and
rollbackUpdate answers false: putting a committed in-place change back needs a
configuration snapshot this provisioner does not keep, the same limitation
AWS::Cognito::UserPool has. A test pins that so it stays a decision.

Raised by the review on this PR. My first reply argued the finding did not hold,
generalising from the create path; that was wrong for this one, and the
correction is on the thread.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-09 09:32:52 -04:00
1 parent 3218d2404e
commit 895adce214
10 files changed
+1363 -13

No files matched your search

@@ -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));
}
@@ -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);
}
}
@@ -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());
}
}
@@ -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);
@@ -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"));
}
}