feat(cloudfront): apply response-headers policies when serving (#1833)

* feat(cloudfront): serve distribution requests from S3 and custom origins

* feat(cloudfront): add response headers policy support

* chore: re-run CI

The Build and Test failure on the previous head was RuntimeApiServerTest's
extension/stop race, a pre-existing flake unrelated to this change — it also failed
on #1820, #1823 and on #2131's own branch (the PR that tried to de-flake it).
Reproduced locally under `--cpus=1` and fixed separately.

* fix(cloudfront): wildcard aliases match exactly one subdomain level

wildcardAliasMatches did a plain suffix check, so "*.example.com" also matched
a.b.example.com. AWS is explicit that a wildcard alternate domain name replaces the
wildcard at that level only:

  "you can't add alternate domain names that are at levels higher or lower than the
   wildcard. For example, you can't add the alternate domain names example.com or
   marketing.product.example.com."

  https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html

Practical effect: a distribution owning "*.example.com" would answer for
a.b.example.com, which on AWS belongs to whoever owns "*.b.example.com" — or to
nobody. Require the label standing in for the wildcard to contain no dot.

wildcardAliasesMatchSubdomainsAndPreferMoreSpecificNames asserted the old behaviour
(a.b.example.test resolving to the *.example.test distribution); it now asserts no
match, plus the same for a deeper wildcard.

* test(dynamodb): retain Quarkus port for cleanup

* fix(cloudfront): isolate mocked storage backends

* fix: validate credentialed CloudFront CORS headers

* fix: log ignored CloudFront policy parse errors

* fix(ec2): wire managed prefix list storage in public IP test

* fix(cloudfront): preserve custom CORS-like headers
This commit is contained in:
Alex Banna authored and GitHub committed 2026-08-20 18:06:12 -04:00
1 parent f40d2e34f3
commit 520c0f4da2
21 files changed
+3141 -79

No files matched your search

@@ -347,6 +347,64 @@ public final class XmlParser {
return result;
}
/**
* Parses the first element with the requested local name into a small immutable element tree.
*
* <p>This supports structured AWS XML payloads where the same leaf name appears in multiple
* nested blocks and the flat extraction helpers would lose that context. Namespace prefixes are
* ignored, external entities and DTDs remain disabled by the shared factory, and malformed input
* returns {@code null} after a diagnostic log entry.
*/
public static XmlElement extractElementTree(String xml, String elementName) {
if (xml == null || xml.isEmpty()) {
return null;
}
try {
XMLStreamReader r = FACTORY.createXMLStreamReader(new StringReader(xml));
while (r.hasNext()) {
int event = r.next();
if (event == XMLStreamConstants.START_ELEMENT
&& elementName.equals(r.getLocalName())) {
XmlElement result = readElementTree(r);
r.close();
return result;
}
}
r.close();
} catch (Exception e) {
LOG.debugv("Ignoring malformed XML during structured parse: {0}", e.getMessage());
}
return null;
}
private static XmlElement readElementTree(XMLStreamReader r) throws XMLStreamException {
String name = r.getLocalName();
StringBuilder text = new StringBuilder();
List<XmlElement> children = new ArrayList<>();
while (r.hasNext()) {
int event = r.next();
if (event == XMLStreamConstants.START_ELEMENT) {
children.add(readElementTree(r));
} else if (event == XMLStreamConstants.CHARACTERS
|| event == XMLStreamConstants.CDATA) {
text.append(r.getText());
} else if (event == XMLStreamConstants.END_ELEMENT) {
return new XmlElement(name, text.toString().trim(), List.copyOf(children));
}
}
throw new XMLStreamException("Unexpected end of XML while reading " + name);
}
/** A namespace-agnostic XML element used by {@link #extractElementTree(String, String)}. */
public record XmlElement(String name, String text, List<XmlElement> children) {
public XmlElement child(String childName) {
return children.stream()
.filter(child -> childName.equals(child.name()))
.findFirst()
.orElse(null);
}
}
/**
* Extracts key/value pairs from a repeating {@code pairElement} nested at any depth
* inside each {@code parentElement} group, returning one map per group.
@@ -6450,6 +6450,7 @@ public class CloudFormationResourceProvisioner {
if (node != null && !node.isMissingNode() && !node.isNull()) {
dcb.setTargetOriginId(cfnText(node, "TargetOriginId", engine));
dcb.setViewerProtocolPolicy(cfnTextOrDefault(node, "ViewerProtocolPolicy", engine, "allow-all"));
dcb.setResponseHeadersPolicyId(cfnText(node, "ResponseHeadersPolicyId", engine));
List<String> trustedKeyGroups = cfnStringList(node.path("TrustedKeyGroups"), engine);
if (!trustedKeyGroups.isEmpty()) {
dcb.setTrustedKeyGroups(trustedKeyGroups);
@@ -6467,6 +6468,7 @@ public class CloudFormationResourceProvisioner {
cb.setPathPattern(cfnText(node, "PathPattern", engine));
cb.setTargetOriginId(cfnText(node, "TargetOriginId", engine));
cb.setViewerProtocolPolicy(cfnTextOrDefault(node, "ViewerProtocolPolicy", engine, "allow-all"));
cb.setResponseHeadersPolicyId(cfnText(node, "ResponseHeadersPolicyId", engine));
List<String> trustedKeyGroups = cfnStringList(node.path("TrustedKeyGroups"), engine);
if (!trustedKeyGroups.isEmpty()) {
cb.setTrustedKeyGroups(trustedKeyGroups);
@@ -510,12 +510,12 @@ public class CloudFrontController {
public Response getResponseHeadersPolicyConfig(@PathParam("Id") String id) {
try {
ResponseHeadersPolicy policy = service.getResponseHeadersPolicy(id);
String xml = new XmlBuilder()
XmlBuilder builder = new XmlBuilder()
.start("ResponseHeadersPolicyConfig", NS)
.elem("Name", policy.getName())
.elem("Comment", policy.getComment() != null ? policy.getComment() : "")
.end("ResponseHeadersPolicyConfig")
.build();
.elem("Comment", policy.getComment() != null ? policy.getComment() : "");
ResponseHeadersPolicyConfigCodec.serialize(builder, policy.getConfig());
String xml = builder.end("ResponseHeadersPolicyConfig").build();
return Response.ok(xml, XML).header("ETag", policy.getEtag()).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
@@ -563,23 +563,32 @@ public class CloudFrontController {
@QueryParam("MaxItems") @DefaultValue("100") int maxItems,
@QueryParam("Type") String type) {
try {
if (maxItems < 1 || maxItems > 100) {
throw new AwsException("InvalidArgument",
"MaxItems must be between 1 and 100.", 400);
}
Page<ResponseHeadersPolicy> page = page(
service.listResponseHeadersPolicies(marker, paginationFetchLimit(maxItems)),
service.listResponseHeadersPolicies(
marker, paginationFetchLimit(maxItems), type),
maxItems, ResponseHeadersPolicy::getId);
XmlBuilder xml = new XmlBuilder()
.start("ResponseHeadersPolicyList", NS)
.elem("NextMarker", page.nextMarker())
.elem("MaxItems", maxItems)
.elem("Quantity", page.items().size())
.start("Items");
for (ResponseHeadersPolicy p : page.items()) {
xml.start("ResponseHeadersPolicySummary")
.elem("Type", "custom")
.elem("Type", CloudFrontService.isManagedResponseHeadersPolicy(p.getId())
? "managed" : "custom")
.raw(xmlResponseHeadersPolicyResponse(p))
.end("ResponseHeadersPolicySummary");
}
xml.end("Items").end("ResponseHeadersPolicyList");
xml.end("Items")
.elem("MaxItems", maxItems);
if (page.nextMarker() != null) {
xml.elem("NextMarker", page.nextMarker());
}
xml.elem("Quantity", page.items().size())
.end("ResponseHeadersPolicyList");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
@@ -2060,15 +2069,16 @@ public class CloudFrontController {
}
private String xmlResponseHeadersPolicyResponse(ResponseHeadersPolicy policy) {
return new XmlBuilder()
XmlBuilder xml = new XmlBuilder()
.start("ResponseHeadersPolicy")
.elem("Id", policy.getId())
.elem("LastModifiedTime",
policy.getLastModifiedTime() != null ? policy.getLastModifiedTime().toString() : "")
.start("ResponseHeadersPolicyConfig")
.elem("Name", policy.getName())
.elem("Comment", policy.getComment() != null ? policy.getComment() : "")
.end("ResponseHeadersPolicyConfig")
.elem("Comment", policy.getComment() != null ? policy.getComment() : "");
ResponseHeadersPolicyConfigCodec.serialize(xml, policy.getConfig());
return xml.end("ResponseHeadersPolicyConfig")
.end("ResponseHeadersPolicy")
.build();
}
@@ -2883,6 +2893,7 @@ public class CloudFrontController {
ResponseHeadersPolicy policy = new ResponseHeadersPolicy();
policy.setName(XmlParser.extractFirst(body, "Name", null));
policy.setComment(XmlParser.extractFirst(body, "Comment", null));
policy.setConfig(ResponseHeadersPolicyConfigCodec.parse(body));
return policy;
}
@@ -104,6 +104,24 @@ public final class CloudFrontRequestRouter {
return dflt != null ? dflt.getTargetOriginId() : null;
}
/**
* Returns the {@code ResponseHeadersPolicyId} of the cache behavior that serves a normalized path,
* evaluating ordered behaviors first (first match wins) and the default behavior last, or
* {@code null} when the matched behavior references no response-headers policy.
*/
public static String matchResponseHeadersPolicyId(DistributionConfig config, String normalizedPath) {
List<CacheBehavior> behaviors = config.getCacheBehaviors();
if (behaviors != null) {
for (CacheBehavior behavior : behaviors) {
if (pathPatternMatches(behavior.getPathPattern(), normalizedPath)) {
return behavior.getResponseHeadersPolicyId();
}
}
}
DefaultCacheBehavior dflt = config.getDefaultCacheBehavior();
return dflt != null ? dflt.getResponseHeadersPolicyId() : null;
}
/**
* Returns the trusted key group IDs of the cache behavior that matches {@code normalizedPath} (the
* same ordered-first, default-last resolution as {@link #matchTargetOriginId}). An empty list means
@@ -130,6 +148,28 @@ public final class CloudFrontRequestRouter {
return List.of();
}
/**
* Returns the viewer HTTP methods accepted by the cache behavior that serves a normalized path.
* Legacy persisted configurations without an explicit list retain CloudFront's minimum
* GET/HEAD behavior.
*/
public static List<String> matchAllowedMethods(DistributionConfig config, String normalizedPath) {
List<CacheBehavior> behaviors = config.getCacheBehaviors();
if (behaviors != null) {
for (CacheBehavior behavior : behaviors) {
if (pathPatternMatches(behavior.getPathPattern(), normalizedPath)) {
return allowedMethodsOrDefault(behavior.getAllowedMethods());
}
}
}
DefaultCacheBehavior dflt = config.getDefaultCacheBehavior();
return allowedMethodsOrDefault(dflt != null ? dflt.getAllowedMethods() : null);
}
private static List<String> allowedMethodsOrDefault(List<String> methods) {
return methods == null || methods.isEmpty() ? List.of("GET", "HEAD") : methods;
}
/**
* Matches a CloudFront path pattern against a normalized path. A leading {@code /} on either side is
* ignored, {@code *} matches zero or more characters, {@code ?} matches exactly one, and matching is
@@ -45,11 +45,25 @@ import java.util.function.Function;
public class CloudFrontService {
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final int MAX_CUSTOM_RESPONSE_HEADERS_POLICIES = 20;
private static final int MAX_DISTRIBUTIONS_PER_RESPONSE_HEADERS_POLICY = 100;
private static final SecureRandom RANDOM = new SecureRandom();
private static final Set<String> OAC_ORIGIN_TYPES =
Set.of("s3", "mediastore", "mediapackagev2", "lambda");
private static final Set<String> OAC_SIGNING_BEHAVIORS =
Set.of("always", "never", "no-override");
static final String MANAGED_CORS_AND_SECURITY_POLICY_ID =
"e61eb60c-9c35-4d20-a928-2b84e02af89c";
static final String MANAGED_CORS_PREFLIGHT_POLICY_ID =
"5cc3b908-e619-4b99-88e5-2cf7f45965bd";
static final String MANAGED_CORS_PREFLIGHT_AND_SECURITY_POLICY_ID =
"eaab4381-ed33-4a86-88ca-d9558dc6cd63";
static final String MANAGED_SECURITY_POLICY_ID =
"67f7725c-6f97-4210-82d7-5512b31e9d03";
static final String MANAGED_SIMPLE_CORS_POLICY_ID =
"60669652-455b-4ae9-85a4-c4c02393f86c";
private static final Map<String, ResponseHeadersPolicy> MANAGED_RESPONSE_HEADERS_POLICIES =
managedResponseHeadersPolicies();
private final StorageBackend<String, Distribution> distStore;
private final StorageBackend<String, List<Invalidation>> invalidationStore;
@@ -115,6 +129,7 @@ public class CloudFrontService {
public synchronized Distribution createDistribution(Distribution dist, Map<String, String> tags) {
ensureAliasesAvailable(dist.getConfig(), null);
validateResponseHeadersPolicyReferences(dist.getConfig(), null);
validateTrustedKeyGroups(dist.getConfig());
String id = generateDistributionId();
dist.setId(id);
@@ -143,6 +158,7 @@ public class CloudFrontService {
"The If-Match version is missing or not valid for the resource.", 400);
}
ensureAliasesAvailable(updated.getConfig(), id);
validateResponseHeadersPolicyReferences(updated.getConfig(), id);
validateTrustedKeyGroups(updated.getConfig());
updated.setId(id);
updated.setArn(existing.getArn());
@@ -496,6 +512,12 @@ public class CloudFrontService {
// ── Response Headers Policies ─────────────────────────────────────────────
public synchronized ResponseHeadersPolicy createResponseHeadersPolicy(ResponseHeadersPolicy policy) {
ResponseHeadersPolicyValidator.validate(policy);
ensureResponseHeadersPolicyNameAvailable(policy.getName(), null);
if (rhpStore.scan(k -> true).size() >= MAX_CUSTOM_RESPONSE_HEADERS_POLICIES) {
throw new AwsException("TooManyResponseHeadersPolicies",
"The maximum number of response headers policies has been reached.", 400);
}
policy.setId(UUID.randomUUID().toString());
policy.setEtag(UUID.randomUUID().toString());
policy.setLastModifiedTime(Instant.now());
@@ -504,18 +526,22 @@ public class CloudFrontService {
}
public ResponseHeadersPolicy getResponseHeadersPolicy(String id) {
return rhpStore.get(id).orElseThrow(() ->
new AwsException("NoSuchResponseHeadersPolicy",
return rhpStore.get(id)
.or(() -> java.util.Optional.ofNullable(MANAGED_RESPONSE_HEADERS_POLICIES.get(id)))
.orElseThrow(() -> new AwsException("NoSuchResponseHeadersPolicy",
"The specified response headers policy does not exist.", 404));
}
public synchronized ResponseHeadersPolicy updateResponseHeadersPolicy(String id, String ifMatch,
ResponseHeadersPolicy updated) {
ResponseHeadersPolicy existing = getResponseHeadersPolicy(id);
rejectManagedResponseHeadersPolicyUpdate(id);
if (!existing.getEtag().equals(ifMatch)) {
throw new AwsException("InvalidIfMatchVersion",
"The If-Match version is missing or not valid for the resource.", 400);
throw new AwsException("PreconditionFailed",
"The precondition in one or more of the request-header fields evaluated to false.", 412);
}
ResponseHeadersPolicyValidator.validate(updated);
ensureResponseHeadersPolicyNameAvailable(updated.getName(), id);
updated.setId(id);
updated.setEtag(UUID.randomUUID().toString());
updated.setLastModifiedTime(Instant.now());
@@ -525,25 +551,52 @@ public class CloudFrontService {
public synchronized void deleteResponseHeadersPolicy(String id, String ifMatch) {
ResponseHeadersPolicy existing = getResponseHeadersPolicy(id);
rejectManagedResponseHeadersPolicyDelete(id);
if (!existing.getEtag().equals(ifMatch)) {
throw new AwsException("InvalidIfMatchVersion",
"The If-Match version is missing or not valid for the resource.", 400);
throw new AwsException("PreconditionFailed",
"The precondition in one or more of the request-header fields evaluated to false.", 412);
}
if (isResponseHeadersPolicyInUse(id)) {
throw new AwsException("ResponseHeadersPolicyInUse",
"The response headers policy is attached to one or more distributions.", 409);
}
rhpStore.delete(id);
}
public List<ResponseHeadersPolicy> listResponseHeadersPolicies(String marker, int maxItems) {
List<ResponseHeadersPolicy> all = new ArrayList<>(rhpStore.scan(k -> true));
return listResponseHeadersPolicies(marker, maxItems, null);
}
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()));
if (marker != null && !marker.isEmpty()) {
int idx = 0;
int idx = -1;
for (int i = 0; i < all.size(); i++) {
if (all.get(i).getId().equals(marker)) {
idx = i + 1;
break;
}
}
if (idx < 0) {
throw new AwsException("InvalidArgument",
"The specified marker is invalid.", 400);
}
all = all.subList(idx, all.size());
}
if (maxItems > 0 && all.size() > maxItems) {
@@ -552,6 +605,178 @@ public class CloudFrontService {
return all;
}
static boolean isManagedResponseHeadersPolicy(String id) {
return MANAGED_RESPONSE_HEADERS_POLICIES.containsKey(id);
}
private void ensureResponseHeadersPolicyNameAvailable(String name, String excludedId) {
boolean duplicateCustom = rhpStore.scan(k -> true).stream()
.anyMatch(existing -> !existing.getId().equals(excludedId)
&& name.equals(existing.getName()));
boolean duplicateManaged = MANAGED_RESPONSE_HEADERS_POLICIES.values().stream()
.anyMatch(existing -> name.equals(existing.getName()));
if (duplicateCustom || duplicateManaged) {
throw new AwsException("ResponseHeadersPolicyAlreadyExists",
"A response headers policy with this name already exists.", 409);
}
}
private static void rejectManagedResponseHeadersPolicyUpdate(String id) {
if (isManagedResponseHeadersPolicy(id)) {
throw new AwsException("IllegalUpdate",
"AWS managed response headers policies cannot be updated.", 400);
}
}
private static void rejectManagedResponseHeadersPolicyDelete(String id) {
if (isManagedResponseHeadersPolicy(id)) {
throw new AwsException("IllegalDelete",
"AWS managed response headers policies cannot be deleted.", 400);
}
}
private void validateResponseHeadersPolicyReferences(
DistributionConfig config, String excludedDistributionId) {
if (config == null) {
return;
}
Set<String> policyIds = new java.util.LinkedHashSet<>();
if (config.getDefaultCacheBehavior() != null) {
addResponseHeadersPolicyId(
policyIds,
config.getDefaultCacheBehavior().getResponseHeadersPolicyId());
}
if (config.getCacheBehaviors() != null) {
config.getCacheBehaviors().forEach(behavior ->
addResponseHeadersPolicyId(
policyIds, behavior.getResponseHeadersPolicyId()));
}
for (String policyId : policyIds) {
requireResponseHeadersPolicy(policyId);
long associatedDistributions = distStore.scan(k -> true).stream()
.filter(distribution -> excludedDistributionId == null
|| !excludedDistributionId.equals(distribution.getId()))
.filter(distribution -> usesResponseHeadersPolicy(
distribution.getConfig(), policyId))
.count();
if (associatedDistributions
>= MAX_DISTRIBUTIONS_PER_RESPONSE_HEADERS_POLICY) {
throw new AwsException(
"TooManyDistributionsAssociatedToResponseHeadersPolicy",
"The maximum number of distributions have been associated with the "
+ "specified response headers policy.",
400);
}
}
}
private static void addResponseHeadersPolicyId(
Set<String> policyIds, String policyId) {
if (policyId != null && !policyId.isBlank()) {
policyIds.add(policyId);
}
}
private void requireResponseHeadersPolicy(String policyId) {
if (policyId != null && !policyId.isBlank()) {
getResponseHeadersPolicy(policyId);
}
}
private boolean isResponseHeadersPolicyInUse(String id) {
return distStore.scan(k -> true).stream()
.map(Distribution::getConfig)
.anyMatch(config -> usesResponseHeadersPolicy(config, id));
}
private static boolean usesResponseHeadersPolicy(
DistributionConfig config, String id) {
if (config == null) {
return false;
}
boolean defaultUsesPolicy = config.getDefaultCacheBehavior() != null
&& id.equals(config.getDefaultCacheBehavior().getResponseHeadersPolicyId());
boolean orderedUsesPolicy = config.getCacheBehaviors() != null
&& config.getCacheBehaviors().stream().anyMatch(behavior ->
id.equals(behavior.getResponseHeadersPolicyId()));
return defaultUsesPolicy || orderedUsesPolicy;
}
private static Map<String, ResponseHeadersPolicy> managedResponseHeadersPolicies() {
Map<String, Object> simpleCors = corsConfig(
List.of("*"), List.of(), List.of(), List.of(), null);
Map<String, Object> preflightCors = corsConfig(
List.of("*"),
List.of("GET", "HEAD", "PUT", "POST", "PATCH", "DELETE", "OPTIONS"),
List.of(), List.of("*"), null);
Map<String, Object> security = securityHeadersConfig();
Map<String, ResponseHeadersPolicy> policies = new LinkedHashMap<>();
policies.put(MANAGED_CORS_AND_SECURITY_POLICY_ID, managedResponseHeadersPolicy(
MANAGED_CORS_AND_SECURITY_POLICY_ID, "Managed-CORS-and-SecurityHeadersPolicy",
"Allows all origins for simple CORS requests, and adds security headers",
Map.of("CorsConfig", simpleCors, "SecurityHeadersConfig", security)));
policies.put(MANAGED_CORS_PREFLIGHT_POLICY_ID, managedResponseHeadersPolicy(
MANAGED_CORS_PREFLIGHT_POLICY_ID, "Managed-CORS-With-Preflight",
"Allows all origins for CORS requests, including preflight requests",
Map.of("CorsConfig", preflightCors)));
policies.put(MANAGED_CORS_PREFLIGHT_AND_SECURITY_POLICY_ID, managedResponseHeadersPolicy(
MANAGED_CORS_PREFLIGHT_AND_SECURITY_POLICY_ID,
"Managed-CORS-with-preflight-and-SecurityHeadersPolicy",
"Allows all origins for CORS requests, including preflight requests, and adds security headers",
Map.of("CorsConfig", preflightCors, "SecurityHeadersConfig", security)));
policies.put(MANAGED_SECURITY_POLICY_ID, managedResponseHeadersPolicy(
MANAGED_SECURITY_POLICY_ID, "Managed-SecurityHeadersPolicy",
"Adds a set of security headers to every response",
Map.of("SecurityHeadersConfig", security)));
policies.put(MANAGED_SIMPLE_CORS_POLICY_ID, managedResponseHeadersPolicy(
MANAGED_SIMPLE_CORS_POLICY_ID, "Managed-SimpleCORS",
"Allows all origins for simple CORS requests",
Map.of("CorsConfig", simpleCors)));
return Map.copyOf(policies);
}
private static ResponseHeadersPolicy managedResponseHeadersPolicy(
String id, String name, String comment, Map<String, Object> config) {
ResponseHeadersPolicy policy = new ResponseHeadersPolicy();
policy.setId(id);
policy.setName(name);
policy.setComment(comment);
policy.setEtag("E23ZP02F085DFQ");
policy.setLastModifiedTime(Instant.EPOCH);
policy.setConfig(config);
return policy;
}
private static Map<String, Object> corsConfig(List<String> origins, List<String> methods,
List<String> headers, List<String> exposeHeaders,
Long maxAgeSeconds) {
Map<String, Object> cors = new LinkedHashMap<>();
cors.put("AccessControlAllowCredentials", "false");
cors.put("AccessControlAllowHeaders", headers);
cors.put("AccessControlAllowMethods", methods);
cors.put("AccessControlAllowOrigins", origins);
cors.put("AccessControlExposeHeaders", exposeHeaders);
if (maxAgeSeconds != null) {
cors.put("AccessControlMaxAgeSec", Long.toString(maxAgeSeconds));
}
cors.put("OriginOverride", "false");
return Map.copyOf(cors);
}
private static Map<String, Object> securityHeadersConfig() {
Map<String, Object> security = new LinkedHashMap<>();
security.put("ContentTypeOptions", Map.of("Override", "true"));
security.put("FrameOptions", Map.of("FrameOption", "SAMEORIGIN", "Override", "false"));
security.put("ReferrerPolicy", Map.of(
"ReferrerPolicy", "strict-origin-when-cross-origin", "Override", "false"));
security.put("StrictTransportSecurity", Map.of(
"AccessControlMaxAgeSec", "31536000", "Override", "false"));
security.put("XSSProtection", Map.of(
"Protection", "true", "ModeBlock", "true", "Override", "false"));
return Map.copyOf(security);
}
// ── Origin Access Control ─────────────────────────────────────────────────
public synchronized OriginAccessControl createOriginAccessControl(OriginAccessControl oac) {
@@ -13,6 +13,7 @@ import jakarta.annotation.PreDestroy;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HEAD;
import jakarta.ws.rs.OPTIONS;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.core.Context;
@@ -29,8 +30,10 @@ import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
@@ -56,8 +59,8 @@ import java.util.Set;
* If the configured error page is itself missing, the received status is returned (no loop).</li>
* </ul>
*
* <p>Viewer-protocol-policy and allowed-method enforcement are intentionally out of scope for this
* layer: the emulator is HTTP-first and serves GET/HEAD regardless of scheme.
* <p>Viewer-protocol-policy enforcement is intentionally out of scope for this layer: the emulator
* is HTTP-first. GET/HEAD are served, and OPTIONS is served only when the matched behavior allows it.
*/
@Path("/_cloudfront/{distId}")
public class CloudFrontServingController {
@@ -66,6 +69,10 @@ public class CloudFrontServingController {
private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";
private static final DateTimeFormatter HTTP_DATE = DateTimeFormatter.RFC_1123_DATE_TIME
.withZone(ZoneOffset.UTC);
private static final Set<String> FORBIDDEN_POLICY_RESPONSE_HEADERS = Set.of(
"connection", "content-length", "keep-alive", "proxy-authenticate",
"proxy-authorization", "proxy-connection", "te", "trailer",
"transfer-encoding", "upgrade", "via");
private static final Set<String> NON_FORWARDED_RESPONSE_HEADERS = Set.of(
"connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
"proxy-connection", "te", "trailer", "transfer-encoding", "upgrade", "via",
@@ -103,25 +110,57 @@ public class CloudFrontServingController {
@Path("/{proxy:.*}")
public Response get(@PathParam("distId") String distId, @PathParam("proxy") String proxy,
@Context HttpHeaders headers, @Context UriInfo uriInfo) {
String rawViewerPath = rawViewerPath(currentVertxRequest.getCurrent().request().uri());
var request = currentVertxRequest.getCurrent().request();
String rawViewerPath = rawViewerPath(request.uri());
return serve(distId, rawViewerPath, decodedViewerPath(rawViewerPath),
uriInfo.getRequestUri().getScheme(), headers.getHeaderString("Host"),
headers.getHeaderString(HttpHeaders.AUTHORIZATION), true);
uriInfo.getRequestUri().getScheme(),
headers.getHeaderString("Host"),
headers.getHeaderString(HttpHeaders.AUTHORIZATION),
request.getHeader("Origin"), "GET", null, null,
request.getHeader("Pragma"));
}
@HEAD
@Path("/{proxy:.*}")
public Response head(@PathParam("distId") String distId, @PathParam("proxy") String proxy,
@Context HttpHeaders headers, @Context UriInfo uriInfo) {
String rawViewerPath = rawViewerPath(currentVertxRequest.getCurrent().request().uri());
var request = currentVertxRequest.getCurrent().request();
String rawViewerPath = rawViewerPath(request.uri());
return serve(distId, rawViewerPath, decodedViewerPath(rawViewerPath),
uriInfo.getRequestUri().getScheme(), headers.getHeaderString("Host"),
headers.getHeaderString(HttpHeaders.AUTHORIZATION), false);
uriInfo.getRequestUri().getScheme(),
headers.getHeaderString("Host"),
headers.getHeaderString(HttpHeaders.AUTHORIZATION),
request.getHeader("Origin"), "HEAD", null, null,
request.getHeader("Pragma"));
}
@OPTIONS
@Path("/{proxy:.*}")
public Response options(@PathParam("distId") String distId, @PathParam("proxy") String proxy,
@Context HttpHeaders headers, @Context UriInfo uriInfo) {
var request = currentVertxRequest.getCurrent().request();
String rawViewerPath = rawViewerPath(request.uri());
return serve(distId, rawViewerPath, decodedViewerPath(rawViewerPath),
uriInfo.getRequestUri().getScheme(),
headers.getHeaderString("Host"),
headers.getHeaderString(HttpHeaders.AUTHORIZATION),
request.getHeader("Origin"), "OPTIONS",
request.getHeader("Access-Control-Request-Method"),
request.getHeader("Access-Control-Request-Headers"),
request.getHeader("Pragma"));
}
private Response serve(String distId, String rawViewerPath, String decodedViewerPath,
String viewerScheme, String viewerHost, String viewerAuthorization,
boolean includeBody) {
String viewerScheme, String viewerHost,
String viewerAuthorization,
String viewerOrigin, String method,
String accessControlRequestMethod,
String accessControlRequestHeaders,
String pragma) {
boolean includeBody = !"HEAD".equals(method);
boolean preflightRequest = "OPTIONS".equals(method)
&& viewerOrigin != null && !viewerOrigin.isBlank()
&& accessControlRequestMethod != null && !accessControlRequestMethod.isBlank();
Distribution dist = service.findByHost(viewerHost);
if (dist == null || !distId.equals(dist.getId())) {
return textError(404, "Distribution not found.");
@@ -136,6 +175,16 @@ public class CloudFrontServingController {
String normalized = CloudFrontRequestRouter.normalizePath(decodedViewerPath);
if (!CloudFrontRequestRouter.matchAllowedMethods(config, normalized).contains(method)) {
return textError(403, "Invalid method.");
}
// The response-headers policy of the behavior that matches the request applies to the final
// response CloudFront returns to the viewer, including any custom-error page substituted below.
String policyId = CloudFrontRequestRouter.matchResponseHeadersPolicyId(config, normalized);
ResponseHeadersPolicyConfigCodec.Directives directives = responseHeaderDirectives(
policyId, viewerOrigin, preflightRequest, pragma);
List<String> trustedKeyGroups =
CloudFrontRequestRouter.trustedKeyGroupsFor(config, normalized);
if (!trustedKeyGroups.isEmpty()) {
@@ -149,16 +198,40 @@ public class CloudFrontServingController {
}
OriginResponse origin = route(dist, normalized, rawViewerPath, decodedViewerPath,
viewerScheme, viewerAuthorization, includeBody);
viewerScheme, viewerAuthorization, method, viewerOrigin,
accessControlRequestMethod, accessControlRequestHeaders);
if (origin.status() >= 400) {
Response fallback = applyCustomError(
dist, origin, viewerScheme, viewerAuthorization, includeBody);
dist, origin, viewerScheme, viewerAuthorization, includeBody, directives);
if (fallback != null) {
return fallback;
}
}
return toResponse(origin, includeBody);
return toResponse(origin, includeBody, directives);
}
/** Resolves the response-headers policy for a behavior into the headers it contributes, if any. */
private ResponseHeadersPolicyConfigCodec.Directives responseHeaderDirectives(
String policyId, String viewerOrigin, boolean preflightRequest, String pragma) {
if (policyId == null || policyId.isBlank()) {
return null;
}
try {
return ResponseHeadersPolicyConfigCodec.directives(
service.getResponseHeadersPolicy(policyId).getConfig(), viewerOrigin,
preflightRequest, isManagedPreflightPolicy(policyId), pragma);
} catch (AwsException e) {
// New distribution writes reject dangling references. A persisted legacy record can still
// contain one, so keep serving it without policy headers but make the corruption visible.
LOG.warnv("Distribution references missing response headers policy {0}", policyId);
return null;
}
}
private static boolean isManagedPreflightPolicy(String policyId) {
return CloudFrontService.MANAGED_CORS_PREFLIGHT_POLICY_ID.equals(policyId)
|| CloudFrontService.MANAGED_CORS_PREFLIGHT_AND_SECURITY_POLICY_ID.equals(policyId);
}
/**
@@ -270,7 +343,9 @@ public class CloudFrontServingController {
private OriginResponse route(Distribution distribution, String normalized,
String rawViewerPath, String decodedViewerPath,
String viewerScheme, String viewerAuthorization,
boolean includeBody) {
String method, String viewerOrigin,
String accessControlRequestMethod,
String accessControlRequestHeaders) {
DistributionConfig config = distribution.getConfig();
String originId = CloudFrontRequestRouter.matchTargetOriginId(config, normalized);
Origin origin = CloudFrontRequestRouter.findOrigin(config, originId);
@@ -278,17 +353,22 @@ public class CloudFrontServingController {
return OriginResponse.error(502, "No origin matched the request.");
}
if (CloudFrontRequestRouter.isS3Origin(origin)) {
if ("OPTIONS".equals(method)) {
return fetchS3Preflight(origin, viewerOrigin, accessControlRequestMethod,
accessControlRequestHeaders);
}
String key = CloudFrontRequestRouter.resolveOriginKey(
origin.getOriginPath(), decodedViewerPath, config.getDefaultRootObject());
return fetchFromS3(
distribution, origin, key, viewerAuthorization, includeBody);
distribution, origin, key, viewerAuthorization, !"HEAD".equals(method));
}
String forwardUri = CloudFrontRequestRouter.resolveForwardUri(
origin.getOriginPath(), rawViewerPath, config.getDefaultRootObject());
// CloudFront forwards viewer query strings only when selected by a cache policy,
// origin request policy, or legacy ForwardedValues configuration. Those policy
// semantics are not modeled in the data plane yet, so the AWS default is to omit them.
return fetchFromCustomOrigin(origin, forwardUri, null, viewerScheme, includeBody);
return fetchFromCustomOrigin(origin, forwardUri, null, viewerScheme, method,
viewerOrigin, accessControlRequestMethod, accessControlRequestHeaders);
}
private OriginResponse fetchFromS3(
@@ -355,36 +435,58 @@ public class CloudFrontServingController {
s3Service.authorizeAnonymousGetObject(bucket, key);
}
private static String originAccessIdentityId(Origin origin) {
Map<String, String> config = origin.getS3OriginConfig();
String value = config != null ? config.get("OriginAccessIdentity") : null;
if (value == null || value.isBlank()) {
return null;
private OriginResponse fetchS3Preflight(Origin origin, String viewerOrigin,
String requestMethod, String requestHeaders) {
String bucket = CloudFrontRequestRouter.bucketFromS3Domain(origin.getDomainName());
if (bucket == null) {
return OriginResponse.error(502, "Could not determine S3 bucket for origin.");
}
String normalized = value.startsWith("/") ? value.substring(1) : value;
String prefix = "origin-access-identity/cloudfront/";
if (!normalized.startsWith(prefix)
|| normalized.length() == prefix.length()
|| normalized.substring(prefix.length()).contains("/")) {
throw new AwsException(
"InvalidArgument", "The S3 origin access identity is invalid.", 400);
if (viewerOrigin == null || viewerOrigin.isBlank()
|| requestMethod == null || requestMethod.isBlank()) {
return OriginResponse.error(403, "This CORS request is not allowed.");
}
return normalized.substring(prefix.length());
List<String> requestedHeaders = splitHeaderValues(requestHeaders);
return s3Service.evaluateCors(bucket, viewerOrigin, requestMethod, requestedHeaders)
.map(cors -> {
Map<String, List<String>> headers = new LinkedHashMap<>();
putHeader(headers, "Access-Control-Allow-Origin", cors.allowedOrigin());
putHeader(headers, "Access-Control-Allow-Methods",
String.join(", ", cors.allowedMethods()));
if (cors.maxAgeSeconds() > 0) {
putHeader(headers, "Access-Control-Max-Age",
Integer.toString(cors.maxAgeSeconds()));
}
if (!cors.allowedHeaders().isEmpty()) {
putHeader(headers, "Access-Control-Allow-Headers",
String.join(", ", cors.allowedHeaders()));
}
if (!cors.exposeHeaders().isEmpty()) {
putHeader(headers, "Access-Control-Expose-Headers",
String.join(", ", cors.exposeHeaders()));
}
return new OriginResponse(200, null, new byte[0], 0, headers);
})
.orElseGet(() -> OriginResponse.error(403,
"This CORS request is not allowed."));
}
/** Fetches from a custom (non-S3) origin. {@code forwardUri} already includes the origin path. */
private OriginResponse fetchFromCustomOrigin(Origin origin, String forwardUri, String rawQuery,
String viewerScheme, boolean includeBody) {
String viewerScheme, String method, String viewerOrigin,
String accessControlRequestMethod,
String accessControlRequestHeaders) {
boolean includeBody = !"HEAD".equals(method);
try {
URI target = buildCustomOriginUri(
origin, viewerScheme, forwardUri, rawQuery);
HttpRequest.Builder rb = HttpRequest.newBuilder()
.uri(target)
.timeout(Duration.ofSeconds(30));
if (includeBody) {
rb.GET();
} else {
rb.method("HEAD", HttpRequest.BodyPublishers.noBody());
rb.method(method, HttpRequest.BodyPublishers.noBody());
if ("OPTIONS".equals(method)) {
addRequestHeader(rb, "Origin", viewerOrigin);
addRequestHeader(rb, "Access-Control-Request-Method", accessControlRequestMethod);
addRequestHeader(rb, "Access-Control-Request-Headers", accessControlRequestHeaders);
}
HttpResponse<byte[]> resp = httpClient.send(rb.build(), HttpResponse.BodyHandlers.ofByteArray());
String ct = resp.headers().firstValue("content-type").orElse(DEFAULT_CONTENT_TYPE);
@@ -405,6 +507,23 @@ public class CloudFrontServingController {
}
}
private static String originAccessIdentityId(Origin origin) {
Map<String, String> config = origin.getS3OriginConfig();
String value = config != null ? config.get("OriginAccessIdentity") : null;
if (value == null || value.isBlank()) {
return null;
}
String normalized = value.startsWith("/") ? value.substring(1) : value;
String prefix = "origin-access-identity/cloudfront/";
if (!normalized.startsWith(prefix)
|| normalized.length() == prefix.length()
|| normalized.substring(prefix.length()).contains("/")) {
throw new AwsException(
"InvalidArgument", "The S3 origin access identity is invalid.", 400);
}
return normalized.substring(prefix.length());
}
static boolean isBlockedOriginAddress(InetAddress address) {
if (address.isAnyLocalAddress() || address.isLoopbackAddress()
|| address.isLinkLocalAddress() || address.isSiteLocalAddress()
@@ -576,7 +695,8 @@ public class CloudFrontServingController {
OriginResponse origin,
String viewerScheme,
String viewerAuthorization,
boolean includeBody) {
boolean includeBody,
ResponseHeadersPolicyConfigCodec.Directives directives) {
DistributionConfig config = distribution.getConfig();
Map<String, Object> cer = matchCustomError(config, origin.status());
if (cer == null) {
@@ -587,7 +707,7 @@ public class CloudFrontServingController {
if (pagePath.isBlank()) {
// ResponseCode override with no custom page: keep the origin body, change the status.
return toResponse(new OriginResponse(responseCode, origin.contentType(), origin.body(),
origin.contentLength(), origin.headers()), includeBody);
origin.contentLength(), origin.headers()), includeBody, directives);
}
String errNormalized = CloudFrontRequestRouter.normalizePath(pagePath);
@@ -605,15 +725,16 @@ public class CloudFrontServingController {
} else {
String forwardUri = CloudFrontRequestRouter.resolveForwardUri(errOrigin.getOriginPath(), errNormalized, null);
page = fetchFromCustomOrigin(
errOrigin, forwardUri, null, viewerScheme, includeBody);
errOrigin, forwardUri, null, viewerScheme,
includeBody ? "GET" : "HEAD", null, null, null);
}
if (page.status() >= 400) {
// Custom error page unavailable → return the status received from the error-page origin
// (AWS behavior), without recursively applying custom error handling.
return toResponse(page, includeBody);
return toResponse(page, includeBody, directives);
}
return toResponse(new OriginResponse(responseCode, page.contentType(), page.body(),
page.contentLength(), page.headers()), includeBody);
page.contentLength(), page.headers()), includeBody, directives);
}
private Map<String, Object> matchCustomError(DistributionConfig config, int status) {
@@ -629,32 +750,132 @@ public class CloudFrontServingController {
return null;
}
private Response toResponse(OriginResponse origin, boolean includeBody) {
private Response toResponse(OriginResponse origin, boolean includeBody,
ResponseHeadersPolicyConfigCodec.Directives directives) {
Response.ResponseBuilder rb = Response.status(origin.status());
Set<String> excludedHeaders = new HashSet<>(NON_FORWARDED_RESPONSE_HEADERS);
HeaderCollection collected = collectResponseHeaders(origin, includeBody);
applyResponseHeadersPolicy(collected.headers(), directives, collected.forbiddenPolicyHeaders());
for (HeaderValues header : collected.headers().values()) {
if ("date".equalsIgnoreCase(header.name())) {
currentVertxRequest.getCurrent().response()
.putHeader(header.name(), header.values());
} else {
header.values().forEach(value -> rb.header(header.name(), value));
}
}
if (includeBody && origin.body() != null) {
rb.entity(origin.body());
}
return rb.build();
}
/**
* Collects the origin's end-to-end response headers case-insensitively while preserving every
* value (notably multiple {@code Set-Cookie} fields). Hop-by-hop fields and every field named by
* the origin's {@code Connection} header stay out of the viewer response.
*/
private static HeaderCollection collectResponseHeaders(OriginResponse origin, boolean includeBody) {
Set<String> excludedOriginHeaders = new HashSet<>(NON_FORWARDED_RESPONSE_HEADERS);
Set<String> forbiddenPolicyHeaders = new HashSet<>(FORBIDDEN_POLICY_RESPONSE_HEADERS);
origin.headers().forEach((name, values) -> {
if ("connection".equalsIgnoreCase(name)) {
values.forEach(value -> {
for (String token : value.split(",")) {
excludedHeaders.add(token.trim().toLowerCase(Locale.ROOT));
String normalized = normalizeHeaderName(token);
if (!normalized.isEmpty()) {
excludedOriginHeaders.add(normalized);
}
}
});
}
});
Map<String, HeaderValues> headers = new LinkedHashMap<>();
origin.headers().forEach((name, values) -> {
if (!excludedHeaders.contains(name.toLowerCase(Locale.ROOT))) {
values.forEach(value -> rb.header(name, value));
String normalized = normalizeHeaderName(name);
if (!normalized.isEmpty() && !excludedOriginHeaders.contains(normalized)) {
HeaderValues existing = headers.computeIfAbsent(normalized,
ignored -> new HeaderValues(name, new ArrayList<>()));
existing.values().addAll(values);
}
});
if (origin.contentType() != null) {
rb.type(origin.contentType());
setHeader(headers, "Content-Type", origin.contentType());
}
if (includeBody && origin.body() != null) {
rb.entity(origin.body());
} else if (origin.contentLength() >= 0) {
rb.header("Content-Length", origin.contentLength());
if (!includeBody && origin.contentLength() >= 0) {
setHeader(headers, "Content-Length", Long.toString(origin.contentLength()));
}
return rb.build();
return new HeaderCollection(headers, forbiddenPolicyHeaders);
}
/** Applies removals first, then policy additions with their origin-override semantics. */
private static void applyResponseHeadersPolicy(
Map<String, HeaderValues> headers,
ResponseHeadersPolicyConfigCodec.Directives directives,
Set<String> forbiddenPolicyHeaders) {
if (directives == null) {
return;
}
boolean replaceServer = false;
boolean replaceDate = false;
for (String name : directives.remove()) {
String normalized = normalizeHeaderName(name);
if (ResponseHeadersPolicyValidator.isForbiddenRemoval(normalized)) {
continue;
}
headers.remove(normalized);
replaceServer |= "server".equals(normalized);
replaceDate |= "date".equals(normalized);
}
boolean hasOriginCorsHeader = headers.keySet().stream()
.anyMatch(CloudFrontServingController::isCorsHeader);
for (ResponseHeadersPolicyConfigCodec.PolicyHeader header : directives.add()) {
String normalized = normalizeHeaderName(header.name());
if (normalized.isEmpty() || forbiddenPolicyHeaders.contains(normalized)) {
continue;
}
// OriginOverride=false is group-wide for CORS: if the origin supplied any CORS header,
// CloudFront keeps the origin's CORS response and adds none of the policy's CORS fields.
if (header.cors() && !header.override() && hasOriginCorsHeader) {
continue;
}
if (header.override() || !headers.containsKey(normalized)) {
setHeader(headers, header.name(), header.value());
}
}
if (directives.serverTiming()) {
mergeServerTiming(headers);
}
if (replaceServer && !headers.containsKey("server")) {
setHeader(headers, "Server", "CloudFront");
}
if (replaceDate && !headers.containsKey("date")) {
setHeader(headers, "Date", HTTP_DATE.format(Instant.now()));
}
}
private static void mergeServerTiming(Map<String, HeaderValues> headers) {
String cloudFrontMetrics = "cdn-cache-miss,cdn-pop;desc=\"local\"";
HeaderValues origin = headers.get("server-timing");
if (origin == null || origin.values().isEmpty()) {
setHeader(headers, "Server-Timing", cloudFrontMetrics);
return;
}
setHeader(headers, "Server-Timing",
String.join(", ", origin.values()) + ", " + cloudFrontMetrics);
}
private static void setHeader(Map<String, HeaderValues> headers, String name, String value) {
headers.put(normalizeHeaderName(name),
new HeaderValues(name, new ArrayList<>(List.of(value == null ? "" : value))));
}
private static String normalizeHeaderName(String name) {
return name == null ? "" : name.trim().toLowerCase(Locale.ROOT);
}
private static boolean isCorsHeader(String name) {
return normalizeHeaderName(name).startsWith("access-control-");
}
private Response textError(int status, String message) {
@@ -692,6 +913,26 @@ public class CloudFrontServingController {
}
}
private static List<String> splitHeaderValues(String value) {
if (value == null || value.isBlank()) {
return List.of();
}
List<String> values = new ArrayList<>();
for (String item : value.split(",")) {
String trimmed = item.trim();
if (!trimmed.isEmpty()) {
values.add(trimmed);
}
}
return values;
}
private static void addRequestHeader(HttpRequest.Builder request, String name, String value) {
if (value != null && !value.isBlank()) {
request.header(name, value);
}
}
private static String str(Object value) {
return value != null ? value.toString() : "";
}
@@ -712,6 +953,13 @@ public class CloudFrontServingController {
}
}
private record HeaderValues(String name, List<String> values) {
}
private record HeaderCollection(Map<String, HeaderValues> headers,
Set<String> forbiddenPolicyHeaders) {
}
/** The result of fetching from an origin, including end-to-end response headers. */
private record OriginResponse(int status, String contentType, byte[] body, long contentLength,
Map<String, List<String>> headers) {
@@ -0,0 +1,565 @@
package io.github.hectorvent.floci.services.cloudfront;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.core.common.XmlParser.XmlElement;
import org.jboss.logging.Logger;
import java.net.URI;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;
/**
* Parses, re-serializes and applies a CloudFront {@code ResponseHeadersPolicyConfig}.
*
* <p>CloudFront lets a response-headers policy attach three kinds of headers to the responses it
* returns to viewers: a {@code SecurityHeadersConfig} (HSTS, {@code X-Content-Type-Options},
* {@code X-Frame-Options}, {@code Referrer-Policy}, {@code X-XSS-Protection},
* {@code Content-Security-Policy}), a {@code CorsConfig} (the {@code Access-Control-*} headers) and a
* free-form {@code CustomHeadersConfig}. It can also strip headers via {@code RemoveHeadersConfig}.
* Each header carries an {@code Override} flag deciding whether it replaces one an origin already set.
*
* <p>The parsed shape is kept in the policy's generic {@code config} map (nested maps/lists mirroring
* 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 {
private static final Logger LOG = Logger.getLogger(ResponseHeadersPolicyConfigCodec.class);
private ResponseHeadersPolicyConfigCodec() {
}
/** One header the policy contributes, including whether it came from the CORS group. */
record PolicyHeader(String name, String value, boolean override, boolean cors) {
}
/** Headers to add/remove plus whether CloudFront Server-Timing metrics should be synthesized. */
record Directives(List<PolicyHeader> add, List<String> remove, boolean serverTiming) {
}
// ── Parse ──────────────────────────────────────────────────────────────────
/** Parses a {@code ResponseHeadersPolicyConfig} body into the nested {@code config} shape. */
static Map<String, Object> parse(String body) {
Map<String, Object> config = new LinkedHashMap<>();
XmlElement root = configRoot(body);
if (root == null) {
throw new AwsException("InvalidArgument",
"The request body must contain a valid ResponseHeadersPolicyConfig element.", 400);
}
XmlElement security = child(root, "SecurityHeadersConfig");
if (security != null) {
Map<String, Object> sec = new LinkedHashMap<>();
for (String block : List.of("XSSProtection", "FrameOptions", "ReferrerPolicy",
"ContentSecurityPolicy", "ContentTypeOptions", "StrictTransportSecurity")) {
XmlElement el = child(security, block);
if (el != null) {
sec.put(block, scalarChildren(el));
}
}
config.put("SecurityHeadersConfig", sec);
}
XmlElement cors = child(root, "CorsConfig");
if (cors != null) {
config.put("CorsConfig", parseCors(cors));
}
XmlElement custom = child(root, "CustomHeadersConfig");
if (custom != null) {
List<Map<String, String>> items = itemsAsMaps(custom);
validateDeclaredQuantity(custom, items.size(), "CustomHeadersConfig");
config.put("CustomHeadersConfig", items);
}
XmlElement remove = child(root, "RemoveHeadersConfig");
if (remove != null) {
List<String> items = itemLeafValues(remove, "Header");
validateDeclaredQuantity(remove, items.size(), "RemoveHeadersConfig");
config.put("RemoveHeadersConfig", items);
}
XmlElement serverTiming = child(root, "ServerTimingHeadersConfig");
if (serverTiming != null) {
config.put("ServerTimingHeadersConfig", scalarChildren(serverTiming));
}
return config;
}
private static Map<String, Object> parseCors(XmlElement cors) {
Map<String, Object> map = new LinkedHashMap<>();
for (String list : List.of("AccessControlAllowOrigins", "AccessControlAllowHeaders",
"AccessControlAllowMethods", "AccessControlExposeHeaders")) {
XmlElement el = child(cors, list);
if (el != null) {
List<String> items = itemLeafValues(el, null);
validateDeclaredQuantity(el, items.size(), list);
map.put(list, items);
}
}
for (String scalar : List.of("AccessControlAllowCredentials", "AccessControlMaxAgeSec",
"OriginOverride")) {
String value = childText(cors, scalar);
if (value != null) {
map.put(scalar, value);
}
}
return map;
}
// ── Serialize ──────────────────────────────────────────────────────────────
/** Emits the parsed config back as the inner XML of {@code ResponseHeadersPolicyConfig}. */
@SuppressWarnings("unchecked")
static void serialize(XmlBuilder xml, Map<String, Object> config) {
if (config == null) {
return;
}
Map<String, Object> security = (Map<String, Object>) config.get("SecurityHeadersConfig");
if (security != null) {
xml.start("SecurityHeadersConfig");
for (Map.Entry<String, Object> block : security.entrySet()) {
xml.start(block.getKey());
for (Map.Entry<String, String> field : ((Map<String, String>) block.getValue()).entrySet()) {
xml.elem(field.getKey(), field.getValue());
}
xml.end(block.getKey());
}
xml.end("SecurityHeadersConfig");
}
Map<String, Object> cors = (Map<String, Object>) config.get("CorsConfig");
if (cors != null) {
xml.start("CorsConfig");
serializeCorsList(xml, cors, "AccessControlAllowOrigins", "Origin");
serializeCorsList(xml, cors, "AccessControlAllowHeaders", "Header");
serializeCorsList(xml, cors, "AccessControlAllowMethods", "Method");
serializeCorsList(xml, cors, "AccessControlExposeHeaders", "Header");
for (String scalar : List.of("AccessControlAllowCredentials", "AccessControlMaxAgeSec",
"OriginOverride")) {
if (cors.get(scalar) != null) {
xml.elem(scalar, cors.get(scalar).toString());
}
}
xml.end("CorsConfig");
}
List<Map<String, String>> custom = (List<Map<String, String>>) config.get("CustomHeadersConfig");
if (custom != null) {
xml.start("CustomHeadersConfig").elem("Quantity", custom.size()).start("Items");
for (Map<String, String> header : custom) {
xml.start("ResponseHeadersPolicyCustomHeader")
.elem("Header", header.getOrDefault("Header", ""))
.elem("Value", header.getOrDefault("Value", ""))
.elem("Override", header.getOrDefault("Override", "false"))
.end("ResponseHeadersPolicyCustomHeader");
}
xml.end("Items").end("CustomHeadersConfig");
}
List<String> remove = (List<String>) config.get("RemoveHeadersConfig");
if (remove != null) {
xml.start("RemoveHeadersConfig").elem("Quantity", remove.size()).start("Items");
for (String name : remove) {
xml.start("ResponseHeadersPolicyRemoveHeader").elem("Header", name)
.end("ResponseHeadersPolicyRemoveHeader");
}
xml.end("Items").end("RemoveHeadersConfig");
}
Map<String, Object> serverTiming = (Map<String, Object>) config.get("ServerTimingHeadersConfig");
if (serverTiming != null) {
xml.start("ServerTimingHeadersConfig");
for (Map.Entry<String, Object> e : serverTiming.entrySet()) {
xml.elem(e.getKey(), String.valueOf(e.getValue()));
}
xml.end("ServerTimingHeadersConfig");
}
}
@SuppressWarnings("unchecked")
private static void serializeCorsList(XmlBuilder xml, Map<String, Object> cors, String key, String itemName) {
List<String> values = (List<String>) cors.get(key);
if (values == null) {
return;
}
xml.start(key).elem("Quantity", values.size()).start("Items");
for (String v : values) {
xml.elem(itemName, v);
}
xml.end("Items").end(key);
}
// ── Apply ──────────────────────────────────────────────────────────────────
/** Computes the headers this policy contributes to a response and the headers it removes. */
static Directives directives(Map<String, Object> config) {
return directives(config, null);
}
/** Computes policy directives for a viewer request, including request-origin-aware CORS. */
static Directives directives(Map<String, Object> config, String viewerOrigin) {
return directives(config, viewerOrigin, false);
}
/** Computes policy directives, including the preflight-only CORS response fields when requested. */
static Directives directives(Map<String, Object> config, String viewerOrigin,
boolean preflightRequest) {
return directives(config, viewerOrigin, preflightRequest, false, null);
}
/**
* Computes request-aware policy directives. Managed preflight policies expose their configured
* headers only on preflight responses, and Pragma can force Server-Timing sampling.
*/
@SuppressWarnings("unchecked")
static Directives directives(Map<String, Object> config, String viewerOrigin,
boolean preflightRequest,
boolean exposeHeadersOnlyOnPreflight,
String pragma) {
List<PolicyHeader> add = new ArrayList<>();
List<String> remove = new ArrayList<>();
if (config == null) {
return new Directives(add, remove, false);
}
Map<String, Object> security = (Map<String, Object>) config.get("SecurityHeadersConfig");
if (security != null) {
securityHeaders(security, add);
}
List<Map<String, String>> custom = (List<Map<String, String>>) config.get("CustomHeadersConfig");
if (custom != null) {
for (Map<String, String> h : custom) {
String name = h.get("Header");
if (name != null) {
add.add(new PolicyHeader(name, h.getOrDefault("Value", ""),
Boolean.parseBoolean(h.getOrDefault("Override", "false")), false));
}
}
}
Map<String, Object> cors = (Map<String, Object>) config.get("CorsConfig");
if (cors != null) {
corsHeaders(cors, viewerOrigin, preflightRequest,
exposeHeadersOnlyOnPreflight, add);
}
List<String> removeCfg = (List<String>) config.get("RemoveHeadersConfig");
if (removeCfg != null) {
remove.addAll(removeCfg);
}
return new Directives(add, remove, serverTimingEnabled(config, pragma));
}
@SuppressWarnings("unchecked")
private static void securityHeaders(Map<String, Object> security, List<PolicyHeader> add) {
Map<String, String> hsts = (Map<String, String>) security.get("StrictTransportSecurity");
if (hsts != null) {
StringBuilder v = new StringBuilder("max-age=").append(hsts.getOrDefault("AccessControlMaxAgeSec", "0"));
if (Boolean.parseBoolean(hsts.get("IncludeSubdomains"))) {
v.append("; includeSubDomains");
}
if (Boolean.parseBoolean(hsts.get("Preload"))) {
v.append("; preload");
}
add.add(new PolicyHeader("Strict-Transport-Security", v.toString(), override(hsts), false));
}
Map<String, String> cto = (Map<String, String>) security.get("ContentTypeOptions");
if (cto != null) {
add.add(new PolicyHeader("X-Content-Type-Options", "nosniff", override(cto), false));
}
Map<String, String> frame = (Map<String, String>) security.get("FrameOptions");
if (frame != null && frame.get("FrameOption") != null) {
add.add(new PolicyHeader("X-Frame-Options", frame.get("FrameOption"), override(frame), false));
}
Map<String, String> referrer = (Map<String, String>) security.get("ReferrerPolicy");
if (referrer != null && referrer.get("ReferrerPolicy") != null) {
add.add(new PolicyHeader("Referrer-Policy", referrer.get("ReferrerPolicy"), override(referrer), false));
}
Map<String, String> xss = (Map<String, String>) security.get("XSSProtection");
if (xss != null) {
String value;
if (!Boolean.parseBoolean(xss.getOrDefault("Protection", "false"))) {
value = "0";
} else {
StringBuilder v = new StringBuilder("1");
if (Boolean.parseBoolean(xss.get("ModeBlock"))) {
v.append("; mode=block");
}
if (xss.get("ReportUri") != null && !xss.get("ReportUri").isBlank()) {
v.append("; report=").append(xss.get("ReportUri"));
}
value = v.toString();
}
add.add(new PolicyHeader("X-XSS-Protection", value, override(xss), false));
}
Map<String, String> csp = (Map<String, String>) security.get("ContentSecurityPolicy");
if (csp != null && csp.get("ContentSecurityPolicy") != null) {
add.add(new PolicyHeader("Content-Security-Policy", csp.get("ContentSecurityPolicy"), override(csp), false));
}
}
@SuppressWarnings("unchecked")
private static void corsHeaders(Map<String, Object> cors, String viewerOrigin,
boolean preflightRequest,
boolean exposeHeadersOnlyOnPreflight,
List<PolicyHeader> add) {
boolean override = Boolean.parseBoolean(String.valueOf(cors.get("OriginOverride")));
List<String> origins = (List<String>) cors.get("AccessControlAllowOrigins");
String allowOrigin = selectAllowOrigin(origins, viewerOrigin);
if (allowOrigin == null) {
// CloudFront emits CORS policy headers only for a request whose Origin matches the policy.
return;
}
add.add(new PolicyHeader("Access-Control-Allow-Origin", allowOrigin, override, true));
if (!exposeHeadersOnlyOnPreflight || preflightRequest) {
corsListHeader(cors, "AccessControlExposeHeaders",
"Access-Control-Expose-Headers", override, add);
}
if (Boolean.parseBoolean(String.valueOf(cors.get("AccessControlAllowCredentials")))) {
add.add(new PolicyHeader("Access-Control-Allow-Credentials", "true", override, true));
}
if (preflightRequest) {
corsListHeader(cors, "AccessControlAllowHeaders", "Access-Control-Allow-Headers", override, add);
corsMethodsHeader(cors, override, add);
Object maxAge = cors.get("AccessControlMaxAgeSec");
if (maxAge != null) {
add.add(new PolicyHeader("Access-Control-Max-Age", maxAge.toString(), override, true));
}
}
}
@SuppressWarnings("unchecked")
static boolean serverTimingEnabled(Map<String, Object> config, String pragma) {
if (config == null) {
return false;
}
Map<String, Object> serverTiming =
(Map<String, Object>) config.get("ServerTimingHeadersConfig");
if (serverTiming == null
|| !Boolean.parseBoolean(String.valueOf(serverTiming.get("Enabled")))) {
return false;
}
if (containsHeaderToken(pragma, "server-timing")) {
return true;
}
double samplingRate;
try {
samplingRate = Double.parseDouble(
String.valueOf(serverTiming.getOrDefault("SamplingRate", "0")));
} catch (NumberFormatException e) {
LOG.debugv("Ignoring invalid CloudFront Server-Timing sampling rate {0}: {1}",
serverTiming.get("SamplingRate"), e.getMessage());
return false;
}
if (samplingRate <= 0) {
return false;
}
if (samplingRate >= 100) {
return true;
}
return ThreadLocalRandom.current().nextDouble(100) < samplingRate;
}
private static boolean containsHeaderToken(String value, String expected) {
if (value == null || value.isBlank()) {
return false;
}
for (String token : value.split(",")) {
if (expected.equalsIgnoreCase(token.trim())) {
return true;
}
}
return false;
}
private static String selectAllowOrigin(List<String> allowedOrigins, String viewerOrigin) {
if (allowedOrigins == null || allowedOrigins.isEmpty()
|| viewerOrigin == null || viewerOrigin.isBlank()) {
return null;
}
String origin = viewerOrigin.trim();
for (String allowed : allowedOrigins) {
if ("*".equals(allowed)) {
return "*";
}
if (originMatches(allowed, origin)) {
return origin;
}
}
return null;
}
/** Implements CloudFront's documented scheme, subdomain, and port wildcard origin matching. */
static boolean originMatches(String allowedOrigin, String viewerOrigin) {
if (allowedOrigin == null || allowedOrigin.isBlank()
|| viewerOrigin == null || viewerOrigin.isBlank()) {
return false;
}
try {
URI viewer = URI.create(viewerOrigin.trim());
if (viewer.getScheme() == null || viewer.getHost() == null
|| viewer.getRawUserInfo() != null
|| (viewer.getRawPath() != null && !viewer.getRawPath().isEmpty())
|| viewer.getRawQuery() != null || viewer.getRawFragment() != null) {
return false;
}
String pattern = allowedOrigin.trim();
String allowedScheme = null;
int schemeEnd = pattern.indexOf("://");
if (schemeEnd >= 0) {
allowedScheme = pattern.substring(0, schemeEnd);
pattern = pattern.substring(schemeEnd + 3);
}
if (allowedScheme != null && !allowedScheme.equalsIgnoreCase(viewer.getScheme())) {
return false;
}
if (pattern.indexOf('/') >= 0 || pattern.indexOf('?') >= 0 || pattern.indexOf('#') >= 0) {
return false;
}
String hostPattern = pattern;
String portPattern = null;
int colon = pattern.lastIndexOf(':');
if (colon >= 0 && pattern.indexOf(':') == colon) {
hostPattern = pattern.substring(0, colon);
portPattern = pattern.substring(colon + 1);
}
String viewerHost = viewer.getHost().toLowerCase(Locale.ROOT);
String allowedHost = hostPattern.toLowerCase(Locale.ROOT);
boolean hostMatches;
if (allowedHost.startsWith("*.") && allowedHost.indexOf('*', 1) < 0) {
hostMatches = viewerHost.endsWith(allowedHost.substring(1));
} else {
hostMatches = allowedHost.indexOf('*') < 0 && viewerHost.equals(allowedHost);
}
if (!hostMatches) {
return false;
}
if (portPattern == null) {
return viewer.getPort() < 0;
}
if ("*".equals(portPattern)) {
return true;
}
if (viewer.getPort() < 0 || !portPattern.matches("[0-9*]+")) {
return false;
}
String portRegex = "\\Q" + portPattern.replace("*", "\\E.*\\Q") + "\\E";
return Pattern.matches(portRegex, Integer.toString(viewer.getPort()));
} catch (IllegalArgumentException e) {
LOG.debugv("CloudFront CORS origin match rejected pattern {0} for viewer origin {1}: {2}",
allowedOrigin, viewerOrigin, e.getMessage());
return false;
}
}
@SuppressWarnings("unchecked")
private static void corsListHeader(Map<String, Object> cors, String key, String header,
boolean override, List<PolicyHeader> add) {
List<String> values = (List<String>) cors.get(key);
if (values == null || values.isEmpty()) {
return;
}
add.add(new PolicyHeader(header, String.join(", ", values), override, true));
}
@SuppressWarnings("unchecked")
private static void corsMethodsHeader(Map<String, Object> cors, boolean override,
List<PolicyHeader> add) {
List<String> configured = (List<String>) cors.get("AccessControlAllowMethods");
if (configured == null || configured.isEmpty()) {
return;
}
List<String> methods = configured.stream().anyMatch("ALL"::equalsIgnoreCase)
? List.of("DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT")
: configured;
add.add(new PolicyHeader("Access-Control-Allow-Methods",
String.join(", ", methods), override, true));
}
private static boolean override(Map<String, String> block) {
return Boolean.parseBoolean(block.getOrDefault("Override", "false"));
}
// ── Structured XML helpers ───────────────────────────────────────────────────
private static XmlElement configRoot(String body) {
return XmlParser.extractElementTree(body, "ResponseHeadersPolicyConfig");
}
private static XmlElement child(XmlElement parent, String name) {
return parent.child(name);
}
private static String childText(XmlElement parent, String name) {
XmlElement element = child(parent, name);
return element == null ? null : element.text();
}
/** Every direct leaf child of {@code parent}, as an ordered {name -> text} map. */
private static Map<String, String> scalarChildren(XmlElement parent) {
Map<String, String> map = new LinkedHashMap<>();
for (XmlElement element : parent.children()) {
if (element.children().isEmpty()) {
map.put(element.name(), element.text());
}
}
return map;
}
/** Text of every leaf under a container's {@code Items}; {@code leafName} filters when non-null. */
private static List<String> itemLeafValues(XmlElement container, String leafName) {
List<String> values = new ArrayList<>();
XmlElement items = child(container, "Items");
if (items == null) {
return values;
}
for (XmlElement item : items.children()) {
if (leafName == null) {
values.add(item.text());
} else {
String text = childText(item, leafName);
values.add(text == null ? "" : text);
}
}
return values;
}
/** Each {@code Items} child element mapped to its own leaf children. */
private static List<Map<String, String>> itemsAsMaps(XmlElement container) {
List<Map<String, String>> list = new ArrayList<>();
XmlElement items = child(container, "Items");
if (items == null) {
return list;
}
for (XmlElement item : items.children()) {
list.add(scalarChildren(item));
}
return list;
}
private static void validateDeclaredQuantity(XmlElement container, int actual, String field) {
String rawQuantity = childText(container, "Quantity");
if (rawQuantity == null) {
throw new AwsException("InvalidArgument", field + " Quantity is required.", 400);
}
final int declared;
try {
declared = Integer.parseInt(rawQuantity);
} catch (NumberFormatException e) {
throw new AwsException("InvalidArgument",
field + " Quantity must be a non-negative integer.", 400);
}
if (declared < 0) {
throw new AwsException("InvalidArgument",
field + " Quantity must be a non-negative integer.", 400);
}
if (declared != actual) {
throw new AwsException("InconsistentQuantities",
field + " Quantity does not match the number of Items.", 400);
}
}
}
@@ -0,0 +1,427 @@
package io.github.hectorvent.floci.services.cloudfront;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudfront.model.ResponseHeadersPolicy;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/** AWS-compatible validation shared by response-headers policy create and update operations. */
final class ResponseHeadersPolicyValidator {
static final int MAX_CUSTOM_HEADERS = 10;
static final int MAX_REMOVE_HEADERS = 10;
static final int MAX_HEADER_NAME_LENGTH = 256;
static final int MAX_HEADER_VALUE_LENGTH = 1_783;
static final int MAX_CUSTOM_HEADER_BYTES = 10_240;
private static final Pattern POLICY_NAME = Pattern.compile("[A-Za-z0-9_-]{1,128}");
private static final Pattern HEADER_NAME = Pattern.compile("[!#$%&'*+.^_`|~0-9A-Za-z-]+");
private static final Set<String> CORS_METHODS = Set.of(
"GET", "DELETE", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "ALL");
private static final Set<String> FRAME_OPTIONS = Set.of("DENY", "SAMEORIGIN");
private static final Set<String> REFERRER_POLICIES = Set.of(
"no-referrer", "no-referrer-when-downgrade", "origin", "origin-when-cross-origin",
"same-origin", "strict-origin", "strict-origin-when-cross-origin", "unsafe-url");
private static final Set<String> FORBIDDEN_REMOVALS = Set.of(
"connection", "content-encoding", "content-length", "expect", "host", "keep-alive",
"proxy-authenticate", "proxy-authorization", "proxy-connection", "trailer",
"transfer-encoding", "upgrade", "via", "warning", "x-accel-buffering",
"x-accel-charset", "x-accel-limit-rate", "x-accel-redirect", "x-amzn-auth",
"x-amzn-cf-billing", "x-amzn-cf-id", "x-amzn-cf-xff", "x-amzn-errortype",
"x-amzn-fle-profile", "x-amzn-header-count", "x-amzn-header-order",
"x-amzn-lambda-integration-tag", "x-amzn-requestid", "x-cache",
"x-forwarded-proto", "x-real-ip");
private static final Set<String> FORBIDDEN_CUSTOM_HEADERS = Set.of(
"connection", "content-length", "keep-alive", "proxy-authenticate",
"proxy-authorization", "proxy-connection", "te", "trailer",
"transfer-encoding", "upgrade", "via");
private ResponseHeadersPolicyValidator() {
}
static void validate(ResponseHeadersPolicy policy) {
if (policy == null || policy.getName() == null
|| !POLICY_NAME.matcher(policy.getName()).matches()) {
throw invalid("Response headers policy Name must contain 1-128 letters, digits, hyphens, or underscores.");
}
if (policy.getComment() != null && policy.getComment().length() > 128) {
throw invalid("Response headers policy Comment cannot exceed 128 characters.");
}
Map<String, Object> config = policy.getConfig();
if (config == null) {
policy.setConfig(Map.of());
return;
}
validateCors(config.get("CorsConfig"));
validateCustomHeaders(config.get("CustomHeadersConfig"));
validateRemoveHeaders(config.get("RemoveHeadersConfig"));
validateSecurityHeaders(config.get("SecurityHeadersConfig"));
validateServerTiming(config.get("ServerTimingHeadersConfig"));
}
private static void validateCors(Object value) {
if (value == null) {
return;
}
Map<String, Object> cors = objectMap(value, "CorsConfig");
requireBoolean(cors, "AccessControlAllowCredentials");
requireBoolean(cors, "OriginOverride");
List<?> headers = requiredList(cors, "AccessControlAllowHeaders", false);
List<?> methods = requiredList(cors, "AccessControlAllowMethods", true);
List<?> origins = requiredList(cors, "AccessControlAllowOrigins", true);
validateCorsHeaderPatterns(headers, "AccessControlAllowHeaders entry", true);
if (Boolean.parseBoolean(cors.get("AccessControlAllowCredentials").toString())) {
for (Object header : headers) {
if (header.toString().contains("*")) {
throw invalid("AccessControlAllowHeaders cannot contain wildcards when "
+ "AccessControlAllowCredentials is true.");
}
}
}
Set<String> normalizedMethods = new HashSet<>();
for (Object method : methods) {
String configured = requireSafeText(method, "AccessControlAllowMethods entry", 16);
if (!CORS_METHODS.contains(configured)) {
throw invalid("Unsupported CORS method: " + configured);
}
if (!normalizedMethods.add(configured)) {
throw invalid("AccessControlAllowMethods entries must be unique.");
}
}
validateOrigins(origins);
Object expose = cors.get("AccessControlExposeHeaders");
if (expose != null) {
validateCorsHeaderPatterns(objectList(expose, "AccessControlExposeHeaders"),
"AccessControlExposeHeaders entry", false);
}
Object maxAge = cors.get("AccessControlMaxAgeSec");
if (maxAge != null) {
requireNonNegativeLong(maxAge, "AccessControlMaxAgeSec");
}
}
private static void validateCustomHeaders(Object value) {
if (value == null) {
return;
}
List<?> headers = objectList(value, "CustomHeadersConfig");
if (headers.size() > MAX_CUSTOM_HEADERS) {
throw new AwsException("TooManyCustomHeadersInResponseHeadersPolicy",
"A response headers policy can contain at most " + MAX_CUSTOM_HEADERS
+ " custom headers.", 400);
}
Set<String> seen = new HashSet<>();
int combinedLength = 0;
for (Object item : headers) {
Map<String, Object> header = objectMap(item, "CustomHeadersConfig item");
String name = requireHeaderName(header.get("Header"));
String normalized = name.toLowerCase(Locale.ROOT);
if (!seen.add(normalized)) {
throw invalid("Custom response header names must be unique.");
}
if (FORBIDDEN_CUSTOM_HEADERS.contains(normalized)) {
throw invalid("Custom response header is not allowed: " + name);
}
if (!header.containsKey("Value")) {
throw invalid("Custom response header Value is required.");
}
String headerValue = requireHeaderValue(header.get("Value"));
requireBoolean(header, "Override");
combinedLength += name.length() + headerValue.length();
}
if (combinedLength > MAX_CUSTOM_HEADER_BYTES) {
throw invalid("Combined custom response header names and values cannot exceed "
+ MAX_CUSTOM_HEADER_BYTES + " characters.");
}
}
private static void validateRemoveHeaders(Object value) {
if (value == null) {
return;
}
List<?> headers = objectList(value, "RemoveHeadersConfig");
if (headers.size() > MAX_REMOVE_HEADERS) {
throw new AwsException("TooManyRemoveHeadersInResponseHeadersPolicy",
"A response headers policy can remove at most " + MAX_REMOVE_HEADERS
+ " headers.", 400);
}
Set<String> seen = new HashSet<>();
for (Object valueItem : headers) {
String name = requireHeaderName(valueItem);
String normalized = name.toLowerCase(Locale.ROOT);
if (!seen.add(normalized)) {
throw invalid("Remove response header names must be unique.");
}
if (isForbiddenRemoval(normalized)) {
throw invalid("Response header cannot be removed: " + name);
}
}
}
private static void validateSecurityHeaders(Object value) {
if (value == null) {
return;
}
Map<String, Object> security = objectMap(value, "SecurityHeadersConfig");
Object hstsValue = security.get("StrictTransportSecurity");
if (hstsValue != null) {
Map<String, Object> hsts = objectMap(hstsValue, "StrictTransportSecurity");
requireNonNegativeLong(hsts.get("AccessControlMaxAgeSec"), "AccessControlMaxAgeSec");
if (hsts.get("IncludeSubdomains") != null) {
requireBoolean(hsts, "IncludeSubdomains");
}
if (hsts.get("Preload") != null) {
requireBoolean(hsts, "Preload");
}
requireBoolean(hsts, "Override");
}
Object contentTypeValue = security.get("ContentTypeOptions");
if (contentTypeValue != null) {
requireBoolean(objectMap(contentTypeValue, "ContentTypeOptions"), "Override");
}
Object frameValue = security.get("FrameOptions");
if (frameValue != null) {
Map<String, Object> frame = objectMap(frameValue, "FrameOptions");
String option = requireSafeText(frame.get("FrameOption"), "FrameOption", 16);
if (!FRAME_OPTIONS.contains(option)) {
throw invalid("FrameOption must be DENY or SAMEORIGIN.");
}
requireBoolean(frame, "Override");
}
Object referrerValue = security.get("ReferrerPolicy");
if (referrerValue != null) {
Map<String, Object> referrer = objectMap(referrerValue, "ReferrerPolicy");
String policy = requireSafeText(referrer.get("ReferrerPolicy"),
"ReferrerPolicy", 64);
if (!REFERRER_POLICIES.contains(policy)) {
throw invalid("Unsupported ReferrerPolicy: " + policy);
}
requireBoolean(referrer, "Override");
}
Object xssValue = security.get("XSSProtection");
if (xssValue != null) {
Map<String, Object> xss = objectMap(xssValue, "XSSProtection");
requireBoolean(xss, "Protection");
requireBoolean(xss, "Override");
if (xss.get("ModeBlock") != null) {
requireBoolean(xss, "ModeBlock");
}
if (xss.get("ReportUri") != null) {
requireSafeText(xss.get("ReportUri"), "ReportUri", MAX_HEADER_VALUE_LENGTH);
}
if (Boolean.parseBoolean(String.valueOf(xss.get("ModeBlock")))
&& xss.get("ReportUri") != null) {
throw invalid("XSSProtection cannot specify both ModeBlock and ReportUri.");
}
}
Object cspValue = security.get("ContentSecurityPolicy");
if (cspValue != null) {
Map<String, Object> csp = objectMap(cspValue, "ContentSecurityPolicy");
String policy = requireNonBlankText(csp.get("ContentSecurityPolicy"),
"ContentSecurityPolicy");
if (hasUnsafeControlCharacter(policy)) {
throw invalid("ContentSecurityPolicy contains an invalid control character.");
}
if (policy.length() > MAX_HEADER_VALUE_LENGTH) {
throw new AwsException("TooLongCSPInResponseHeadersPolicy",
"The Content-Security-Policy value exceeds the maximum length.", 400);
}
requireBoolean(csp, "Override");
}
}
private static void validateServerTiming(Object value) {
if (value == null) {
return;
}
Map<String, Object> serverTiming = objectMap(value, "ServerTimingHeadersConfig");
requireBoolean(serverTiming, "Enabled");
Object samplingRate = serverTiming.get("SamplingRate");
if (samplingRate == null) {
return;
}
try {
BigDecimal rate = new BigDecimal(samplingRate.toString());
if (rate.compareTo(BigDecimal.ZERO) < 0
|| rate.compareTo(BigDecimal.valueOf(100)) > 0) {
throw invalid("ServerTimingHeadersConfig SamplingRate must be between 0 and 100.");
}
if (rate.stripTrailingZeros().scale() > 4) {
throw invalid("ServerTimingHeadersConfig SamplingRate supports at most four decimal places.");
}
} catch (NumberFormatException e) {
throw invalid("ServerTimingHeadersConfig SamplingRate must be numeric.");
}
}
static boolean isForbiddenRemoval(String name) {
String normalized = name == null ? "" : name.trim().toLowerCase(Locale.ROOT);
return FORBIDDEN_REMOVALS.contains(normalized)
|| normalized.startsWith("x-amz-cf-")
|| normalized.startsWith("x-edge-");
}
private static List<?> requiredList(Map<String, Object> map, String key, boolean nonEmpty) {
Object value = map.get(key);
if (value == null) {
throw invalid("CorsConfig " + key + " is required.");
}
List<?> list = objectList(value, key);
if (nonEmpty && list.isEmpty()) {
throw invalid("CorsConfig " + key + " cannot be empty.");
}
return list;
}
private static void requireBoolean(Map<String, Object> map, String key) {
Object value = map.get(key);
if (value == null || !("true".equalsIgnoreCase(value.toString())
|| "false".equalsIgnoreCase(value.toString()))) {
throw invalid(key + " must be true or false.");
}
}
private static int requireNonNegativeLong(Object value, String field) {
if (value == null) {
throw invalid(field + " is required.");
}
try {
long number = Long.parseLong(value.toString());
if (number < 0 || number > Integer.MAX_VALUE) {
throw invalid(field + " must be between 0 and " + Integer.MAX_VALUE + ".");
}
return (int) number;
} catch (NumberFormatException e) {
throw invalid(field + " must be a non-negative integer.");
}
}
private static String requireHeaderName(Object value) {
String name = requireSafeText(value, "Header", MAX_HEADER_NAME_LENGTH);
if (!HEADER_NAME.matcher(name).matches()) {
throw invalid("Invalid HTTP response header name: " + name);
}
return name;
}
private static String requireHeaderValue(Object value) {
String text = value == null ? "" : value.toString();
if (text.length() > MAX_HEADER_VALUE_LENGTH || hasUnsafeControlCharacter(text)) {
throw invalid("Invalid HTTP response header value.");
}
return text;
}
private static String requireSafeText(Object value, String field, int maxLength) {
String text = requireNonBlankText(value, field);
if (text.length() > maxLength || hasUnsafeControlCharacter(text)) {
throw invalid(field + " is invalid or exceeds its maximum length.");
}
return text;
}
private static String requireNonBlankText(Object value, String field) {
if (value == null || value.toString().isBlank()) {
throw invalid(field + " is required.");
}
return value.toString();
}
private static void validateCorsHeaderPatterns(
List<?> values, String field, boolean allowEmbeddedWildcard) {
Set<String> seen = new HashSet<>();
for (Object value : values) {
String header = requireSafeText(value, field, MAX_HEADER_NAME_LENGTH);
long wildcardCount = header.chars().filter(character -> character == '*').count();
boolean valid = "*".equals(header)
|| (HEADER_NAME.matcher(header).matches()
&& (allowEmbeddedWildcard ? wildcardCount <= 1 : wildcardCount == 0));
if (!valid) {
throw invalid(field + " contains an invalid HTTP header pattern: " + header);
}
if (!seen.add(header.toLowerCase(Locale.ROOT))) {
throw invalid(field + " values must be unique.");
}
}
}
private static void validateOrigins(List<?> values) {
Set<String> seen = new HashSet<>();
for (Object value : values) {
String origin = requireSafeText(
value, "AccessControlAllowOrigins entry", MAX_HEADER_VALUE_LENGTH);
if (!isValidOriginPattern(origin)) {
throw invalid("Invalid AccessControlAllowOrigins entry: " + origin);
}
if (!seen.add(origin.toLowerCase(Locale.ROOT))) {
throw invalid("AccessControlAllowOrigins entries must be unique.");
}
}
}
private static boolean isValidOriginPattern(String origin) {
if ("*".equals(origin)) {
return true;
}
String authority = origin;
int schemeSeparator = authority.indexOf("://");
if (schemeSeparator >= 0) {
String scheme = authority.substring(0, schemeSeparator);
if (!scheme.matches("[A-Za-z][A-Za-z0-9+.-]*")) {
return false;
}
authority = authority.substring(schemeSeparator + 3);
}
if (authority.isEmpty() || authority.indexOf('/') >= 0 || authority.indexOf('?') >= 0
|| authority.indexOf('#') >= 0 || authority.indexOf('@') >= 0) {
return false;
}
String host = authority;
String port = null;
int colon = authority.lastIndexOf(':');
if (colon >= 0 && authority.indexOf(':') == colon) {
host = authority.substring(0, colon);
port = authority.substring(colon + 1);
}
if (host.isEmpty() || (host.contains("*")
&& !(host.startsWith("*.") && host.indexOf('*', 1) < 0))) {
return false;
}
if (!host.matches("(?:\\*\\.)?[A-Za-z0-9.-]+") || host.startsWith(".")
|| host.endsWith(".") || host.contains("..")) {
return false;
}
return port == null || (!port.isEmpty() && port.matches("[0-9*]+"));
}
private static boolean hasUnsafeControlCharacter(String value) {
return value.chars().anyMatch(character ->
(character < 0x20 && character != '\t') || character == 0x7f);
}
@SuppressWarnings("unchecked")
private static Map<String, Object> objectMap(Object value, String field) {
if (!(value instanceof Map<?, ?>)) {
throw invalid(field + " must be an object.");
}
return (Map<String, Object>) value;
}
private static List<?> objectList(Object value, String field) {
if (!(value instanceof List<?> list)) {
throw invalid(field + " must be a list.");
}
return list;
}
private static AwsException invalid(String message) {
return new AwsException("InvalidArgument", message, 400);
}
}