feat(cloudfront): model AWS managed cache policies (#6698)

* feat(cloudfront): model AWS managed cache policies

Serve the 7 AWS managed cache policies that AWS documents with full
settings through GetCachePolicy, GetCachePolicyConfig and
ListCachePolicies, by their AWS IDs. ListCachePolicies honors
Type=managed|custom. UpdateCachePolicy and DeleteCachePolicy refuse a
managed policy with IllegalUpdate and IllegalDelete, as for managed
origin request policies. A cache behavior that references a managed
policy now forwards what that policy selects.

The 4 Amplify-only policies are not modeled: AWS publishes their IDs
but not their settings.

Closes #6691

* refactor(cloudfront): share the policy list merge and the managed ETag

listCachePolicies, listOriginRequestPolicies and listResponseHeadersPolicies
now call one helper for the Type check, the merge of custom and managed
policies, and the sort by name. Each method keeps its own paging, so the
response headers list still rejects an unknown marker.

The managed policy ETag is one constant beside the managed policy maps.

---------

Co-authored-by: liRONCO11 <7966063+liRONCO11@users.noreply.github.com>
This commit is contained in:
Liron CohenandliRONCO11 authored and GitHub committed 2026-10-27 11:34:06 -04:00
1 parent 3890378728
commit c538fb5520
7 files changed
+371 -44

No files matched your search

@@ -76,6 +76,9 @@ class CloudFrontCustomOriginServingTest {
/** The AWS managed CachingDisabled cache policy, which forwards no viewer values. */
private static final String CACHING_DISABLED = "4135ea2d-6df8-44a3-9df3-4b5a84be39ad";
/** The AWS managed CachingOptimized cache policy: Accept-Encoding only, no cookies or query. */
private static final String CACHING_OPTIMIZED = "658327ea-f89d-4fab-a63d-7e88639e58f6";
@Inject
CloudFrontService cloudFrontService;
@@ -595,6 +598,28 @@ class CloudFrontCustomOriginServingTest {
assertEquals("\"v1\"", received.get().header("If-Range"));
}
@Test
void cachingOptimizedForwardsOnlyNormalizedAcceptEncoding() throws Exception {
AtomicReference<ReceivedRequest> received = new AtomicReference<>();
startRecordingOrigin(received, new AtomicInteger());
Distribution created = createDistribution(
customOriginDistribution(policyBehavior(CACHING_OPTIMIZED, null)));
given()
.header("Host", created.getDomainName())
.header("Accept-Encoding", "gzip, deflate, br")
.header("Cookie", "session=abc")
.queryParam("color", "blue")
.when()
.get("/asset.js")
.then()
.statusCode(200);
assertEquals("br,gzip", received.get().header("Accept-Encoding"));
assertNull(received.get().header("Cookie"));
assertNull(received.get().query());
}
@Test
void forwardsTheViewerAuthorizationOnWriteMethodsOnly() throws Exception {
AtomicReference<ReceivedRequest> received = new AtomicReference<>();
@@ -485,6 +485,84 @@ class CloudFrontManagementProtocolTest {
.body(hasXPath("//*[local-name()='Code']/text()", equalTo("IllegalDelete")));
}
@Test
void managedCachePolicyIsReadableAsPolicyAndConfig() {
String optimized = "658327ea-f89d-4fab-a63d-7e88639e58f6";
given()
.when()
.get(API + "cache-policy/" + optimized)
.then()
.statusCode(200)
.body(hasXPath("//*[local-name()='Name']/text()", equalTo("Managed-CachingOptimized")))
.body(hasXPath("//*[local-name()='MinTTL']/text()", equalTo("1")))
.body(hasXPath("//*[local-name()='DefaultTTL']/text()", equalTo("86400")))
.body(hasXPath("//*[local-name()='MaxTTL']/text()", equalTo("31536000")))
.body(hasXPath("//*[local-name()='EnableAcceptEncodingGzip']/text()", equalTo("true")))
.body(hasXPath("//*[local-name()='EnableAcceptEncodingBrotli']/text()", equalTo("true")))
.body(hasXPath("//*[local-name()='HeaderBehavior']/text()", equalTo("none")));
given()
.when()
.get(API + "cache-policy/" + optimized + "/config")
.then()
.statusCode(200)
.body(hasXPath("local-name(/*)", equalTo("CachePolicyConfig")))
.body(hasXPath("//*[local-name()='Name']/text()", equalTo("Managed-CachingOptimized")));
}
@Test
void managedCachePoliciesAreListedWithTheirType() {
String disabled = "4135ea2d-6df8-44a3-9df3-4b5a84be39ad";
given()
.queryParam("Type", "managed")
.when()
.get(API + "cache-policy")
.then()
.statusCode(200)
.body(hasXPath("/*/*[local-name()='Quantity']/text()", equalTo("7")))
.body(hasXPath("//*[local-name()='CachePolicySummary']"
+ "[.//*[local-name()='Id' and text()='" + disabled + "']]"
+ "/*[local-name()='Type']/text()", equalTo("managed")));
given()
.queryParam("Type", "custom")
.when()
.get(API + "cache-policy")
.then()
.statusCode(200)
.body(hasXPath("count(//*[local-name()='Id' and text()='" + disabled + "'])",
equalTo("0")));
}
@Test
void managedCachePolicyCannotBeUpdatedOrDeleted() {
String optimized = "658327ea-f89d-4fab-a63d-7e88639e58f6";
given()
.header("If-Match", "E23ZP02F085DFQ")
.contentType("application/xml")
.body(cachePolicyBody("replacement", "c", "100", "session"))
.when()
.put(API + "cache-policy/" + optimized)
.then()
.statusCode(400)
.body(hasXPath("//*[local-name()='Code']/text()", equalTo("IllegalUpdate")));
given()
.header("If-Match", "E23ZP02F085DFQ")
.when()
.delete(API + "cache-policy/" + optimized)
.then()
.statusCode(400)
.body(hasXPath("//*[local-name()='Code']/text()", equalTo("IllegalDelete")));
given()
.when()
.get(API + "cache-policy/" + optimized)
.then()
.statusCode(200)
.body(hasXPath("//*[local-name()='Name']/text()", equalTo("Managed-CachingOptimized")));
}
private static String cachePolicyBody(String name, String comment, String defaultTtl, String cookie) {
return """
<CachePolicyConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
@@ -1537,6 +1537,131 @@ class CloudFrontServiceTest {
() -> service.deleteOriginRequestPolicy(exceptHost.getId(), exceptHost.getEtag()));
}
@Test
void exposesTheSevenAwsManagedCachePolicies() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
List<String> originOverrideHeaders = List.of(
"Host", "Origin", "X-HTTP-Method-Override", "X-HTTP-Method", "X-Method-Override");
Map<String, Object> noHeaders = Map.of("HeaderBehavior", "none");
Map<String, Object> noCookies = Map.of("CookieBehavior", "none");
Map<String, Object> allCookies = Map.of("CookieBehavior", "all");
Map<String, Object> noQueryStrings = Map.of("QueryStringBehavior", "none");
Map<String, Object> allQueryStrings = Map.of("QueryStringBehavior", "all");
Map<String, Object> originOverrideHeaderSelection =
Map.of("HeaderBehavior", "whitelist", "Headers", originOverrideHeaders);
assertManagedCachePolicy(service, "2e54312d-136d-493c-8eb9-b001f22f67d2", "Managed-Amplify",
"2", "2", "600", "true", "true",
Map.of("HeaderBehavior", "whitelist", "Headers",
List.of("Authorization", "CloudFront-Viewer-Country", "Host")),
allCookies, allQueryStrings);
assertManagedCachePolicy(service, "4135ea2d-6df8-44a3-9df3-4b5a84be39ad",
"Managed-CachingDisabled", "0", "0", "0", "false", "false",
noHeaders, noCookies, noQueryStrings);
assertManagedCachePolicy(service, "658327ea-f89d-4fab-a63d-7e88639e58f6",
"Managed-CachingOptimized", "1", "86400", "31536000", "true", "true",
noHeaders, noCookies, noQueryStrings);
assertManagedCachePolicy(service, "b2884449-e4de-46a7-ac36-70bc7f1ddd6d",
"Managed-CachingOptimizedForUncompressedObjects", "1", "86400", "31536000",
"false", "false", noHeaders, noCookies, noQueryStrings);
assertManagedCachePolicy(service, "08627262-05a9-4f76-9ded-b50ca2e3a84f",
"Managed-Elemental-MediaPackage", "0", "86400", "31536000", "true", "false",
Map.of("HeaderBehavior", "whitelist", "Headers", List.of("Origin")), noCookies,
Map.of("QueryStringBehavior", "whitelist", "QueryStrings",
List.of("aws.manifestfilter", "start", "end", "m")));
assertManagedCachePolicy(service, "83da9c7e-98b4-4e11-a168-04f0df8e2c65",
"Managed-UseOriginCacheControlHeaders", "0", "0", "31536000", "true", "true",
originOverrideHeaderSelection, allCookies, noQueryStrings);
assertManagedCachePolicy(service, "4cc15a8a-d715-48a4-82b8-cc0b614638fe",
"Managed-UseOriginCacheControlHeaders-QueryStrings", "0", "0", "31536000",
"true", "true", originOverrideHeaderSelection, allCookies, allQueryStrings);
assertAws("NoSuchCachePolicy",
() -> service.getCachePolicy("4d1d2f1d-3a71-49ad-9e08-7ea5d843a556"));
}
@Test
void listsManagedAndCustomCachePoliciesByType() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
CachePolicy custom = service.createCachePolicy(namedCachePolicy("custom-cache-policy"));
assertEquals(7, service.listCachePolicies(null, 100, "managed").size());
assertTrue(service.listCachePolicies(null, 100, "managed").stream()
.allMatch(policy -> CloudFrontService.isManagedCachePolicy(policy.getId())));
assertEquals(List.of(custom.getId()), service.listCachePolicies(null, 100, "custom")
.stream().map(CachePolicy::getId).toList());
assertEquals(8, service.listCachePolicies(null, 100, null).size());
assertEquals(8, service.listCachePolicies(null, 100).size());
assertAws("InvalidArgument", () -> service.listCachePolicies(null, 100, "MANAGED"));
}
@Test
void listCachePolicies_badType_rejectsWithCachePolicyMessage() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
AwsException error = assertAws("InvalidArgument",
() -> service.listCachePolicies(null, 100, "unsupported"));
assertEquals("Cache policy Type must be managed or custom.", error.getMessage());
}
@Test
void listOriginRequestPolicies_badType_rejectsWithOriginRequestPolicyMessage() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
AwsException error = assertAws("InvalidArgument",
() -> service.listOriginRequestPolicies(null, 100, "unsupported"));
assertEquals("Origin request policy Type must be managed or custom.", error.getMessage());
}
@Test
void listResponseHeadersPolicies_badTypeAndUnknownMarker_rejectWithOwnMessages() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
AwsException badType = assertAws("InvalidArgument",
() -> service.listResponseHeadersPolicies(null, 100, "unsupported"));
AwsException badMarker = assertAws("InvalidArgument",
() -> service.listResponseHeadersPolicies("missing-marker", 100, null));
assertEquals("Response headers policy Type must be managed or custom.", badType.getMessage());
assertEquals("The specified marker is invalid.", badMarker.getMessage());
}
@Test
void refusesToUpdateOrDeleteAManagedCachePolicy() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
CachePolicy managed = service.getCachePolicy("658327ea-f89d-4fab-a63d-7e88639e58f6");
assertAws("IllegalUpdate", () -> service.updateCachePolicy(managed.getId(),
managed.getEtag(), namedCachePolicy("replacement")));
assertAws("IllegalDelete",
() -> service.deleteCachePolicy(managed.getId(), managed.getEtag()));
CachePolicy after = service.getCachePolicy(managed.getId());
assertEquals("Managed-CachingOptimized", after.getName());
assertEquals(managed.getEtag(), after.getEtag());
}
private static void assertManagedCachePolicy(
CloudFrontService service, String id, String name, String minTtl, String defaultTtl,
String maxTtl, String gzip, String brotli, Map<String, Object> headers,
Map<String, Object> cookies, Map<String, Object> queryStrings) {
CachePolicy policy = service.getCachePolicy(id);
assertEquals(id, policy.getId());
assertEquals(name, policy.getName());
Map<String, Object> config = policy.getConfig();
assertEquals(minTtl, config.get("MinTTL"), name + " MinTTL");
assertEquals(defaultTtl, config.get("DefaultTTL"), name + " DefaultTTL");
assertEquals(maxTtl, config.get("MaxTTL"), name + " MaxTTL");
Map<?, ?> parameters = (Map<?, ?>) config.get("ParametersInCacheKeyAndForwardedToOrigin");
assertEquals(gzip, parameters.get("EnableAcceptEncodingGzip"), name + " Gzip");
assertEquals(brotli, parameters.get("EnableAcceptEncodingBrotli"), name + " Brotli");
assertEquals(headers, parameters.get("HeadersConfig"), name + " headers");
assertEquals(cookies, parameters.get("CookiesConfig"), name + " cookies");
assertEquals(queryStrings, parameters.get("QueryStringsConfig"), name + " query strings");
}
@Test
void deletesAnUnattachedCachePolicy() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");