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

+9 -4
View File
@@ -223,10 +223,15 @@ PUT, PATCH and DELETE).
them). Device-type, geolocation, TLS, JA3/JA4 and header-order headers are not generated.
- The eight AWS managed origin request policies are available by their AWS IDs through
`GetOriginRequestPolicy` and `ListOriginRequestPolicies` (`Type` is `managed` or `custom`), and
cannot be updated or deleted. AWS managed cache policies are not modeled: a behavior that
references one forwards nothing on its account, which matches `CachingDisabled`,
`CachingOptimized` and `CachingOptimizedForUncompressedObjects` but not `Amplify`,
`Elemental-MediaPackage` or the `UseOriginCacheControlHeaders` policies.
cannot be updated or deleted. The seven AWS managed cache policies with published settings
(`Managed-Amplify`, `Managed-CachingDisabled`, `Managed-CachingOptimized`,
`Managed-CachingOptimizedForUncompressedObjects`, `Managed-Elemental-MediaPackage`,
`Managed-UseOriginCacheControlHeaders` and `Managed-UseOriginCacheControlHeaders-QueryStrings`)
are available by their AWS IDs through `GetCachePolicy`, `GetCachePolicyConfig` and
`ListCachePolicies` (`Type` is `managed` or `custom`), and cannot be updated or deleted. A
behavior that references one forwards what its settings select. The four Amplify-only managed
cache policies (`Amplify-Default`, `Amplify-DefaultNoCookies`, `Amplify-ImageOptimization` and
`Amplify-StaticContent`) are not modeled: a behavior that references one forwards nothing.
- In-process S3 origins do not apply forwarding settings: viewer query strings, cookies and headers
do not change the S3 read, apart from the viewer's `Range` and `If-Range` on a GET or HEAD.
- Origin responses are streamed to the viewer, from in-process S3 origins and custom origins alike,
@@ -351,7 +351,7 @@ public class CloudFrontController {
@QueryParam("Type") String type) {
try {
Page<CachePolicy> page = page(
service.listCachePolicies(marker, paginationFetchLimit(maxItems)),
service.listCachePolicies(marker, paginationFetchLimit(maxItems), type),
maxItems, CachePolicy::getId);
XmlBuilder xml = new XmlBuilder()
@@ -362,7 +362,8 @@ public class CloudFrontController {
.start("Items");
for (CachePolicy p : page.items()) {
xml.start("CachePolicySummary")
.elem("Type", "custom")
.elem("Type", CloudFrontService.isManagedCachePolicy(p.getId())
? "managed" : "custom")
.raw(xmlCachePolicyResponse(p))
.end("CachePolicySummary");
}
@@ -39,6 +39,7 @@ import java.net.URI;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
@@ -112,6 +113,8 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
"acba4595-bd28-49b8-b9fe-13317c0390fa";
private static final Map<String, OriginRequestPolicy> MANAGED_ORIGIN_REQUEST_POLICIES =
managedOriginRequestPolicies();
private static final Map<String, CachePolicy> MANAGED_CACHE_POLICIES = managedCachePolicies();
private static final String MANAGED_POLICY_ETAG = "E23ZP02F085DFQ";
private final StorageBackend<String, Distribution> distStore;
private final StorageBackend<String, List<Invalidation>> invalidationStore;
@@ -674,12 +677,18 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
}
public CachePolicy getCachePolicy(String id) {
return cachePolicyStore.get(id).orElseThrow(() ->
new AwsException("NoSuchCachePolicy", "The specified cache policy does not exist.", 404));
return cachePolicyStore.get(id)
.or(() -> Optional.ofNullable(MANAGED_CACHE_POLICIES.get(id)))
.orElseThrow(() -> new AwsException("NoSuchCachePolicy",
"The specified cache policy does not exist.", 404));
}
public synchronized CachePolicy updateCachePolicy(String id, String ifMatch, CachePolicy updated) {
CachePolicy existing = getCachePolicy(id);
if (isManagedCachePolicy(id)) {
throw new AwsException("IllegalUpdate",
"AWS managed cache policies cannot be updated.", 400);
}
if (!existing.getEtag().equals(ifMatch)) {
throw new AwsException("InvalidIfMatchVersion",
"The If-Match version is missing or not valid for the resource.", 400);
@@ -693,6 +702,10 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
public synchronized void deleteCachePolicy(String id, String ifMatch) {
CachePolicy existing = getCachePolicy(id);
if (isManagedCachePolicy(id)) {
throw new AwsException("IllegalDelete",
"AWS managed cache policies cannot be deleted.", 400);
}
if (!existing.getEtag().equals(ifMatch)) {
throw new AwsException("InvalidIfMatchVersion",
"The If-Match version is missing or not valid for the resource.", 400);
@@ -706,12 +719,24 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
}
public List<CachePolicy> listCachePolicies(String marker, int maxItems) {
List<CachePolicy> all = new ArrayList<>(cachePolicyStore.scan(k -> true));
all.sort((a, b) -> a.getName() != null && b.getName() != null
? a.getName().compareTo(b.getName()) : a.getId().compareTo(b.getId()));
return listCachePolicies(marker, maxItems, null);
}
/**
* Lists custom and AWS managed cache policies; {@code type} narrows the list to the AWS
* lowercase {@code managed} or {@code custom} value.
*/
public List<CachePolicy> listCachePolicies(String marker, int maxItems, String type) {
List<CachePolicy> all = mergeCustomAndManaged(type, "Cache policy",
cachePolicyStore.scan(k -> true), MANAGED_CACHE_POLICIES.values(),
CachePolicy::getName, CachePolicy::getId);
return paginate(all, marker, maxItems, CachePolicy::getId);
}
static boolean isManagedCachePolicy(String id) {
return MANAGED_CACHE_POLICIES.containsKey(id);
}
// ── Origin Request Policies ───────────────────────────────────────────────
public synchronized OriginRequestPolicy createOriginRequestPolicy(OriginRequestPolicy policy) {
@@ -774,19 +799,9 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
* AWS lowercase {@code managed} or {@code custom} value.
*/
public List<OriginRequestPolicy> listOriginRequestPolicies(String marker, int maxItems, String type) {
if (type != null && !"custom".equals(type) && !"managed".equals(type)) {
throw new AwsException("InvalidArgument",
"Origin request policy Type must be managed or custom.", 400);
}
List<OriginRequestPolicy> all = new ArrayList<>();
if (!"managed".equals(type)) {
all.addAll(orpStore.scan(k -> true));
}
if (!"custom".equals(type)) {
all.addAll(MANAGED_ORIGIN_REQUEST_POLICIES.values());
}
all.sort((a, b) -> a.getName() != null && b.getName() != null
? a.getName().compareTo(b.getName()) : a.getId().compareTo(b.getId()));
List<OriginRequestPolicy> all = mergeCustomAndManaged(type, "Origin request policy",
orpStore.scan(k -> true), MANAGED_ORIGIN_REQUEST_POLICIES.values(),
OriginRequestPolicy::getName, OriginRequestPolicy::getId);
return paginate(all, marker, maxItems, OriginRequestPolicy::getId);
}
@@ -854,22 +869,9 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
public List<ResponseHeadersPolicy> listResponseHeadersPolicies(
String marker, int maxItems, String type) {
String normalizedType = type;
if (normalizedType != null
&& !"custom".equals(normalizedType)
&& !"managed".equals(normalizedType)) {
throw new AwsException("InvalidArgument",
"Response headers policy Type must be managed or custom.", 400);
}
List<ResponseHeadersPolicy> all = new ArrayList<>();
if (!"managed".equals(normalizedType)) {
all.addAll(rhpStore.scan(k -> true));
}
if (!"custom".equals(normalizedType)) {
all.addAll(MANAGED_RESPONSE_HEADERS_POLICIES.values());
}
all.sort((a, b) -> a.getName() != null && b.getName() != null
? a.getName().compareTo(b.getName()) : a.getId().compareTo(b.getId()));
List<ResponseHeadersPolicy> all = mergeCustomAndManaged(type, "Response headers policy",
rhpStore.scan(k -> true), MANAGED_RESPONSE_HEADERS_POLICIES.values(),
ResponseHeadersPolicy::getName, ResponseHeadersPolicy::getId);
if (marker != null && !marker.isEmpty()) {
int idx = -1;
for (int i = 0; i < all.size(); i++) {
@@ -1129,6 +1131,77 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
return Map.copyOf(policies);
}
/**
* The AWS managed cache policies whose settings the CloudFront Developer Guide lists under
* "Use managed cache policies". The four Amplify-only policies have no published settings and
* are not modeled.
*/
private static Map<String, CachePolicy> managedCachePolicies() {
List<String> noHeaders = List.of();
List<String> originOverrideHeaders = List.of(
"Host", "Origin", "X-HTTP-Method-Override", "X-HTTP-Method", "X-Method-Override");
Map<String, Object> noCookies = selection("CookieBehavior", "none", "Cookies", List.of());
Map<String, Object> allCookies = selection("CookieBehavior", "all", "Cookies", List.of());
Map<String, Object> noQueryStrings =
selection("QueryStringBehavior", "none", "QueryStrings", List.of());
Map<String, Object> allQueryStrings =
selection("QueryStringBehavior", "all", "QueryStrings", List.of());
Map<String, CachePolicy> policies = new LinkedHashMap<>();
addManagedCachePolicy(policies, "2e54312d-136d-493c-8eb9-b001f22f67d2", "Managed-Amplify",
2, 600, 2, true, true,
headerSelection(List.of("Authorization", "CloudFront-Viewer-Country", "Host")),
allCookies, allQueryStrings);
addManagedCachePolicy(policies, "4135ea2d-6df8-44a3-9df3-4b5a84be39ad",
"Managed-CachingDisabled", 0, 0, 0, false, false,
headerSelection(noHeaders), noCookies, noQueryStrings);
addManagedCachePolicy(policies, "658327ea-f89d-4fab-a63d-7e88639e58f6",
"Managed-CachingOptimized", 1, 31536000, 86400, true, true,
headerSelection(noHeaders), noCookies, noQueryStrings);
addManagedCachePolicy(policies, "b2884449-e4de-46a7-ac36-70bc7f1ddd6d",
"Managed-CachingOptimizedForUncompressedObjects", 1, 31536000, 86400, false, false,
headerSelection(noHeaders), noCookies, noQueryStrings);
addManagedCachePolicy(policies, "08627262-05a9-4f76-9ded-b50ca2e3a84f",
"Managed-Elemental-MediaPackage", 0, 31536000, 86400, true, false,
headerSelection(List.of("Origin")), noCookies,
selection("QueryStringBehavior", "whitelist", "QueryStrings",
List.of("aws.manifestfilter", "start", "end", "m")));
addManagedCachePolicy(policies, "83da9c7e-98b4-4e11-a168-04f0df8e2c65",
"Managed-UseOriginCacheControlHeaders", 0, 31536000, 0, true, true,
headerSelection(originOverrideHeaders), allCookies, noQueryStrings);
addManagedCachePolicy(policies, "4cc15a8a-d715-48a4-82b8-cc0b614638fe",
"Managed-UseOriginCacheControlHeaders-QueryStrings", 0, 31536000, 0, true, true,
headerSelection(originOverrideHeaders), allCookies, allQueryStrings);
return Map.copyOf(policies);
}
private static Map<String, Object> headerSelection(List<String> names) {
return selection("HeaderBehavior", names.isEmpty() ? "none" : "whitelist", "Headers", names);
}
private static void addManagedCachePolicy(
Map<String, CachePolicy> policies, String id, String name, long minTtl, long maxTtl,
long defaultTtl, boolean gzip, boolean brotli, Map<String, Object> headers,
Map<String, Object> cookies, Map<String, Object> queryStrings) {
Map<String, Object> parameters = new LinkedHashMap<>();
parameters.put("EnableAcceptEncodingGzip", Boolean.toString(gzip));
parameters.put("EnableAcceptEncodingBrotli", Boolean.toString(brotli));
parameters.put("HeadersConfig", headers);
parameters.put("CookiesConfig", cookies);
parameters.put("QueryStringsConfig", queryStrings);
Map<String, Object> config = new LinkedHashMap<>();
config.put("MinTTL", Long.toString(minTtl));
config.put("DefaultTTL", Long.toString(defaultTtl));
config.put("MaxTTL", Long.toString(maxTtl));
config.put("ParametersInCacheKeyAndForwardedToOrigin", Map.copyOf(parameters));
CachePolicy policy = new CachePolicy();
policy.setId(id);
policy.setName(name);
policy.setEtag(MANAGED_POLICY_ETAG);
policy.setLastModifiedTime(Instant.EPOCH);
policy.setConfig(Map.copyOf(config));
policies.put(id, policy);
}
private static OriginRequestPolicy managedOriginRequestPolicy(
String id, String name, String comment, Map<String, Object> headers,
Map<String, Object> cookies, Map<String, Object> queryStrings) {
@@ -1140,7 +1213,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
policy.setId(id);
policy.setName(name);
policy.setComment(comment);
policy.setEtag("E23ZP02F085DFQ");
policy.setEtag(MANAGED_POLICY_ETAG);
policy.setLastModifiedTime(Instant.EPOCH);
policy.setConfig(Map.copyOf(config));
return policy;
@@ -1163,7 +1236,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
policy.setId(id);
policy.setName(name);
policy.setComment(comment);
policy.setEtag("E23ZP02F085DFQ");
policy.setEtag(MANAGED_POLICY_ETAG);
policy.setLastModifiedTime(Instant.EPOCH);
policy.setConfig(config);
return policy;
@@ -2307,6 +2380,27 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
return sb.toString();
}
private static <T> List<T> mergeCustomAndManaged(String type, String policyLabel,
Collection<T> custom, Collection<T> managed,
Function<T, String> nameFn,
Function<T, String> idFn) {
if (type != null && !"custom".equals(type) && !"managed".equals(type)) {
throw new AwsException("InvalidArgument",
policyLabel + " Type must be managed or custom.", 400);
}
List<T> all = new ArrayList<>();
if (!"managed".equals(type)) {
all.addAll(custom);
}
if (!"custom".equals(type)) {
all.addAll(managed);
}
all.sort((a, b) -> nameFn.apply(a) != null && nameFn.apply(b) != null
? nameFn.apply(a).compareTo(nameFn.apply(b))
: idFn.apply(a).compareTo(idFn.apply(b)));
return all;
}
private <T> List<T> paginate(List<T> all, String marker, int maxItems,
Function<T, String> keyFn) {
if (marker != null && !marker.isEmpty()) {
@@ -558,8 +558,7 @@ public class CloudFrontServingController {
&& config.get("ParametersInCacheKeyAndForwardedToOrigin") instanceof Map<?, ?> parameters
? parameters : null;
} catch (AwsException e) {
// AWS managed cache policies are not modeled. The common ones (CachingDisabled,
// CachingOptimized) forward no viewer values, which is what an unknown id contributes.
// Amplify-only managed policies and unknown ids forward no viewer values.
LOG.debugv("Cache policy {0} is not defined; it forwards no viewer values", cachePolicyId);
return null;
}
@@ -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");