Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudfront): forward origin custom headers (#1832)
Alex Bannaf2ad05ce22e3
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFrontOriginCustomHeadersTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFrontOriginCustomHeadersTest.javanew file mode 100644index 0000000000..156cd085ea--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFrontOriginCustomHeadersTest.java@@ -0,0 +1,131 @@+package com.floci.test;++import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.cloudfront.CloudFrontClient;+import software.amazon.awssdk.services.cloudfront.model.CreateDistributionResponse;+import software.amazon.awssdk.services.cloudfront.model.CustomHeaders;+import software.amazon.awssdk.services.cloudfront.model.DistributionConfig;+import software.amazon.awssdk.services.cloudfront.model.GetDistributionConfigResponse;+import software.amazon.awssdk.services.cloudfront.model.Origin;+import software.amazon.awssdk.services.cloudfront.model.OriginCustomHeader;+import software.amazon.awssdk.services.cloudfront.model.S3OriginConfig;+import software.amazon.awssdk.services.cloudfront.model.ViewerProtocolPolicy;++import java.util.List;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assumptions.assumeFalse;++class CloudFrontOriginCustomHeadersTest {++ @Test+ void roundTripsOriginCustomHeadersWithTheAwsSdk() {+ assumeFalse(+ TestFixtures.isRealAws(),+ "The immediate distribution lifecycle in this test is emulator-specific");++ String suffix = TestFixtures.uniqueName("cloudfront-origin-headers");+ String distributionId = null;++ try (CloudFrontClient cloudFront = TestFixtures.cloudFrontClient()) {+ Origin configuredOrigin = Origin.builder()+ .id("configured-origin")+ .domainName("configured-content.s3.amazonaws.com")+ .customHeaders(CustomHeaders.builder()+ .quantity(1)+ .items(OriginCustomHeader.builder()+ .headerName("X-Origin-Verify")+ .headerValue("configured-value")+ .build())+ .build())+ .s3OriginConfig(S3OriginConfig.builder()+ .originAccessIdentity("")+ .build())+ .build();+ Origin emptyOrigin = Origin.builder()+ .id("empty-origin")+ .domainName("empty-content.s3.amazonaws.com")+ .s3OriginConfig(S3OriginConfig.builder()+ .originAccessIdentity("")+ .build())+ .build();+ DistributionConfig configuration = DistributionConfig.builder()+ .callerReference("distribution-reference-" + suffix)+ .enabled(true)+ .origins(origins -> origins+ .quantity(2)+ .items(configuredOrigin, emptyOrigin))+ .defaultCacheBehavior(behavior -> behavior+ .targetOriginId(configuredOrigin.id())+ .viewerProtocolPolicy(ViewerProtocolPolicy.ALLOW_ALL))+ .build();++ CreateDistributionResponse created = cloudFront.createDistribution(+ request -> request.distributionConfig(configuration));+ distributionId = created.distribution().id();+ assertOriginShapes(created.distribution()+ .distributionConfig()+ .origins()+ .items());++ GetDistributionConfigResponse fetched = cloudFront.getDistributionConfig(+ request -> request.id(created.distribution().id()));+ assertOriginShapes(fetched.distributionConfig().origins().items());++ var listed = cloudFront.listDistributions(request -> request.maxItems("100"))+ .distributionList()+ .items()+ .stream()+ .filter(summary -> created.distribution().id().equals(summary.id()))+ .findFirst()+ .orElseThrow();+ assertOriginShapes(listed.origins().items());+ } finally {+ if (distributionId != null) {+ try (CloudFrontClient cloudFront = TestFixtures.cloudFrontClient()) {+ String id = distributionId;+ GetDistributionConfigResponse current = cloudFront.getDistributionConfig(+ request -> request.id(id));+ var disabled = current.distributionConfig()+ .toBuilder()+ .enabled(false)+ .build();+ var updated = cloudFront.updateDistribution(request -> request+ .id(id)+ .ifMatch(current.eTag())+ .distributionConfig(disabled));+ cloudFront.deleteDistribution(request -> request+ .id(id)+ .ifMatch(updated.eTag()));+ }+ }+ }+ }++ private static void assertOriginShapes(List<Origin> origins) {+ Origin configured = originById(origins, "configured-origin");+ assertNotNull(configured.customHeaders());+ assertEquals(1, configured.customHeaders().quantity());+ assertEquals(1, configured.customHeaders().items().size());+ assertEquals(+ "X-Origin-Verify",+ configured.customHeaders().items().get(0).headerName());+ assertEquals(+ "configured-value",+ configured.customHeaders().items().get(0).headerValue());++ Origin empty = originById(origins, "empty-origin");+ assertNotNull(empty.customHeaders());+ assertEquals(0, empty.customHeaders().quantity());+ assertFalse(empty.customHeaders().hasItems());+ }++ private static Origin originById(List<Origin> origins, String id) {+ return origins.stream()+ .filter(origin -> id.equals(origin.id()))+ .findFirst()+ .orElseThrow();+ }+}diff --git a/docs/services/cloudfront.md b/docs/services/cloudfront.mdindex e2bbb18780..3801e0e329 100644--- a/docs/services/cloudfront.md+++ b/docs/services/cloudfront.md@@ -148,6 +148,11 @@ GET/HEAD/OPTIONS delivery from S3 or custom origins.- Viewer GET/HEAD requests, and OPTIONS requests allowed by the matched cache behavior, addressed toan enabled distribution's generated domain or alias are routed to the matching S3 or customorigin. Origin forwarding preserves the raw path; custom-origin redirects are not followed.+- Origin custom headers are persisted through the CloudFront API and CloudFormation. They replace+ same-named viewer headers on custom-origin GET/HEAD/OPTIONS requests. For in-process S3 origins, a+ configured `Origin` header is used for S3 CORS evaluation. AWS-prohibited names, malformed+ values, inconsistent quantities, duplicates, and quota violations are rejected with modeled+ CloudFront errors when the distribution is created or updated.- Cache behaviors with enabled `TrustedKeyGroups` require a valid CloudFront signed URL or signedcookie before the origin is contacted. Signed URL parameters take precedence over signed cookies.Canned and custom policies support SHA-1 or SHA-256 signatures with RSA-2048 or ECDSA P-256 publicdiff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.javaindex b30e79a3be..a4d06edcb4 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java@@ -6423,6 +6423,17 @@ public class CloudFormationResourceProvisioner {if (!originAccessControlId.isEmpty()) {origin.setOriginAccessControlId(originAccessControlId);}+ JsonNode originCustomHeaders = node.path("OriginCustomHeaders");+ if (originCustomHeaders.isArray()) {+ List<Map<String, String>> customHeaders = new ArrayList<>();+ for (JsonNode customHeader : originCustomHeaders) {+ Map<String, String> mapped = new LinkedHashMap<>();+ mapped.put("HeaderName", cfnText(customHeader, "HeaderName", engine));+ mapped.put("HeaderValue", cfnText(customHeader, "HeaderValue", engine));+ customHeaders.add(mapped);+ }+ origin.setCustomHeaders(customHeaders);+ }JsonNode s3 = node.path("S3OriginConfig");JsonNode custom = node.path("CustomOriginConfig");if (!custom.isMissingNode() && !custom.isNull()) {diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.javaindex 13b6c3ba87..3115f411e6 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java@@ -1851,6 +1851,22 @@ public class CloudFrontController {.end("CustomOriginConfig");}+ List<Map<String, String>> customHeaders = o.getCustomHeaders();+ int customHeaderCount = customHeaders == null ? 0 : customHeaders.size();+ xml.start("CustomHeaders")+ .elem("Quantity", customHeaderCount);+ if (customHeaderCount > 0) {+ xml.start("Items");+ for (Map<String, String> header : customHeaders) {+ xml.start("OriginCustomHeader")+ .elem("HeaderName", header.getOrDefault("HeaderName", ""))+ .elem("HeaderValue", header.getOrDefault("HeaderValue", ""))+ .end("OriginCustomHeader");+ }+ xml.end("Items");+ }+ xml.end("CustomHeaders");+xml.end("Origin");return xml.build();}@@ -1995,9 +2011,7 @@ public class CloudFrontController {List<Origin> origins = cfg != null ? cfg.getOrigins() : null;xml.raw(xmlQuantityItems("Origins", "Origin",origins != null ? origins.size() : 0,- origins != null ? origins.stream().map(o ->- "<Origin><Id>" + XmlBuilder.escape(o.getId()) + "</Id><DomainName>"- + XmlBuilder.escape(o.getDomainName()) + "</DomainName></Origin>").toList()+ origins != null ? origins.stream().map(this::xmlOrigin).toList(): List.of()));List<String> aliases = cfg != null ? cfg.getAliases() : null;@@ -2378,11 +2392,37 @@ public class CloudFrontController {Origin current = null;Map<String, String> s3Config = null;Map<String, Object> customConfig = null;+ boolean inCustomHeaders = false;+ boolean inCustomHeaderItems = false;+ boolean customHeaderItemsSeen = false;+ List<Map<String, String>> customHeaders = null;+ Map<String, String> currentHeader = null;+ Integer customHeadersQuantity = null;while (r.hasNext()) {int event = r.next();if (event == XMLStreamConstants.START_ELEMENT) {String local = r.getLocalName();+ if (inCustomHeaders) {+ boolean validElement = switch (local) {+ case "Quantity" -> !inCustomHeaderItems+ && currentHeader == null+ && customHeadersQuantity == null;+ case "Items" -> !inCustomHeaderItems+ && currentHeader == null+ && !customHeaderItemsSeen;+ case "OriginCustomHeader" ->+ inCustomHeaderItems && currentHeader == null;+ case "HeaderName" -> currentHeader != null+ && !currentHeader.containsKey("HeaderName");+ case "HeaderValue" -> currentHeader != null+ && !currentHeader.containsKey("HeaderValue");+ default -> false;+ };+ if (!validElement) {+ throw invalidOriginCustomHeadersStructure();+ }+ }switch (local) {case "Origins" -> inOrigins = true;case "Origin" -> {@@ -2427,7 +2467,8 @@ public class CloudFrontController {if (inOrigin && !inS3OriginConfig && !inCustomOriginConfig && current != null) {try {current.setConnectionAttempts(Integer.parseInt(r.getElementText()));- } catch (NumberFormatException ignored) {+ } catch (NumberFormatException e) {+ LOG.debugv("Ignoring malformed ConnectionAttempts during parse: {0}", e.getMessage());}}}@@ -2435,7 +2476,8 @@ public class CloudFrontController {if (inOrigin && !inS3OriginConfig && !inCustomOriginConfig && current != null) {try {current.setConnectionTimeout(Integer.parseInt(r.getElementText()));- } catch (NumberFormatException ignored) {+ } catch (NumberFormatException e) {+ LOG.debugv("Ignoring malformed ConnectionTimeout during parse: {0}", e.getMessage());}}}@@ -2459,6 +2501,45 @@ public class CloudFrontController {customConfig.put("OriginProtocolPolicy", r.getElementText());}}+ case "CustomHeaders" -> {+ if (inOrigin) {+ inCustomHeaders = true;+ inCustomHeaderItems = false;+ customHeaderItemsSeen = false;+ customHeaders = new ArrayList<>();+ customHeadersQuantity = null;+ }+ }+ case "Quantity" -> {+ if (inCustomHeaders && currentHeader == null) {+ try {+ customHeadersQuantity = Integer.parseInt(r.getElementText());+ } catch (NumberFormatException e) {+ throw inconsistentQuantities();+ }+ }+ }+ case "Items" -> {+ if (inCustomHeaders) {+ inCustomHeaderItems = true;+ customHeaderItemsSeen = true;+ }+ }+ case "OriginCustomHeader" -> {+ if (inCustomHeaders) {+ currentHeader = new LinkedHashMap<>();+ }+ }+ case "HeaderName" -> {+ if (inCustomHeaders && currentHeader != null) {+ currentHeader.put("HeaderName", r.getElementText());+ }+ }+ case "HeaderValue" -> {+ if (inCustomHeaders && currentHeader != null) {+ currentHeader.put("HeaderValue", r.getElementText());+ }+ }default -> {}}@@ -2478,6 +2559,37 @@ public class CloudFrontController {inCustomOriginConfig = false;customConfig = null;}+ case "OriginCustomHeader" -> {+ if (inCustomHeaders && currentHeader != null && customHeaders != null) {+ customHeaders.add(currentHeader);+ }+ currentHeader = null;+ }+ case "Items" -> {+ if (inCustomHeaders) {+ if (currentHeader != null) {+ throw invalidOriginCustomHeadersStructure();+ }+ inCustomHeaderItems = false;+ }+ }+ case "CustomHeaders" -> {+ if (inCustomHeaders && current != null) {+ int itemCount = customHeaders == null ? 0 : customHeaders.size();+ if (customHeadersQuantity == null || customHeadersQuantity != itemCount) {+ throw inconsistentQuantities();+ }+ if (itemCount > 0 && !customHeaderItemsSeen) {+ throw invalidOriginCustomHeadersStructure();+ }+ current.setCustomHeaders(customHeaders);+ }+ inCustomHeaders = false;+ inCustomHeaderItems = false;+ customHeaderItemsSeen = false;+ customHeaders = null;+ customHeadersQuantity = null;+ }case "Origin" -> {if (inOrigin && current != null) {result.add(current);@@ -2492,9 +2604,30 @@ public class CloudFrontController {}}r.close();- } catch (Exception ignored) {+ return result;+ } catch (AwsException e) {+ throw e;+ } catch (Exception e) {+ LOG.debugv("Rejecting malformed Origins during parse: {0}", e.getMessage());+ throw new AwsException(+ "InvalidArgument",+ "The origin configuration is invalid.",+ 400);}- return result;+ }++ private static AwsException inconsistentQuantities() {+ return new AwsException(+ "InconsistentQuantities",+ "The value of Quantity and the size of Items do not match.",+ 400);+ }++ private static AwsException invalidOriginCustomHeadersStructure() {+ return new AwsException(+ "InvalidArgument",+ "The origin custom headers structure is invalid.",+ 400);}private DefaultCacheBehavior parseDefaultCacheBehavior(String body) {diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClient.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClient.javaindex aed4e47b89..018b5fb264 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClient.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClient.java@@ -112,6 +112,12 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {HttpResponse<byte[]> send(HttpRequest request, HttpResponse.BodyHandler<byte[]> bodyHandler)throws IOException, InterruptedException {+ return send(request, Map.of(), bodyHandler);+ }++ HttpResponse<byte[]> send(HttpRequest request, Map<String, String> originHeaders,+ HttpResponse.BodyHandler<byte[]> bodyHandler)+ throws IOException, InterruptedException {if (Thread.currentThread().isInterrupted()) {throw new InterruptedException("CloudFront origin request interrupted");}@@ -124,6 +130,7 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {.setVersion(HttpVersion.HTTP_1_1);request.headers().map().forEach((name, values) ->values.forEach(value -> builder.addHeader(name, value)));+ originHeaders.forEach(builder::setHeader);HttpClientContext context = HttpClientContext.create();Duration responseTimeout = request.timeout().orElse(RESPONSE_TIMEOUT);diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.javaindex 94446d550f..9c3825d529 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java@@ -32,14 +32,17 @@ import jakarta.inject.Inject;import java.security.SecureRandom;import java.time.Instant;import java.util.ArrayList;+import java.util.HashSet;import java.util.LinkedHashMap;import java.util.LinkedHashSet;import java.util.List;+import java.util.Locale;import java.util.Map;import java.util.Objects;import java.util.Set;import java.util.UUID;import java.util.function.Function;+import java.util.regex.Pattern;@ApplicationScopedpublic class CloudFrontService {@@ -52,6 +55,18 @@ public class CloudFrontService {Set.of("s3", "mediastore", "mediapackagev2", "lambda");private static final Set<String> OAC_SIGNING_BEHAVIORS =Set.of("always", "never", "no-override");+ private static final int MAX_ORIGIN_CUSTOM_HEADERS = 30;+ private static final int MAX_CUSTOM_HEADER_NAME_LENGTH = 256;+ private static final int MAX_CUSTOM_HEADER_VALUE_LENGTH = 1_783;+ private static final int MAX_CUSTOM_HEADERS_LENGTH = 10_240;+ private static final Pattern HTTP_HEADER_NAME =+ Pattern.compile("[!#$%&'*+.^_`|~0-9A-Za-z-]+");+ private static final Set<String> PROHIBITED_ORIGIN_CUSTOM_HEADERS = Set.of(+ "cache-control", "connection", "content-length", "cookie", "host", "if-match",+ "if-modified-since", "if-none-match", "if-range", "if-unmodified-since",+ "max-forwards", "pragma", "proxy-authenticate", "proxy-authorization",+ "proxy-connection", "range", "request-range", "te", "trailer", "transfer-encoding",+ "upgrade", "via", "x-real-ip");static final String MANAGED_CORS_AND_SECURITY_POLICY_ID ="e61eb60c-9c35-4d20-a928-2b84e02af89c";static final String MANAGED_CORS_PREFLIGHT_POLICY_ID =@@ -129,6 +144,7 @@ public class CloudFrontService {public synchronized Distribution createDistribution(Distribution dist, Map<String, String> tags) {ensureAliasesAvailable(dist.getConfig(), null);+ validateOriginCustomHeaders(dist.getConfig());validateResponseHeadersPolicyReferences(dist.getConfig(), null);validateTrustedKeyGroups(dist.getConfig());String id = generateDistributionId();@@ -158,6 +174,7 @@ public class CloudFrontService {"The If-Match version is missing or not valid for the resource.", 400);}ensureAliasesAvailable(updated.getConfig(), id);+ validateOriginCustomHeaders(updated.getConfig());validateResponseHeadersPolicyReferences(updated.getConfig(), id);validateTrustedKeyGroups(updated.getConfig());updated.setId(id);@@ -171,6 +188,53 @@ public class CloudFrontService {return updated;}+ private static void validateOriginCustomHeaders(DistributionConfig config) {+ if (config == null || config.getOrigins() == null) {+ return;+ }+ for (Origin origin : config.getOrigins()) {+ List<Map<String, String>> headers = origin.getCustomHeaders();+ if (headers == null) {+ continue;+ }+ if (headers.size() > MAX_ORIGIN_CUSTOM_HEADERS) {+ throw new AwsException(+ "TooManyOriginCustomHeaders",+ "Your request contains too many origin custom headers.",+ 400);+ }+ int combinedLength = 0;+ Set<String> names = new HashSet<>();+ for (Map<String, String> header : headers) {+ String name = header == null ? null : header.get("HeaderName");+ String value = header == null ? null : header.get("HeaderValue");+ if (name == null || name.isBlank() || value == null+ || name.length() > MAX_CUSTOM_HEADER_NAME_LENGTH+ || value.length() > MAX_CUSTOM_HEADER_VALUE_LENGTH+ || !HTTP_HEADER_NAME.matcher(name).matches()+ || value.indexOf('\r') >= 0 || value.indexOf('\n') >= 0) {+ throw invalidOriginCustomHeader("Invalid origin custom header name or value");+ }+ String normalized = name.toLowerCase(Locale.ROOT);+ if (PROHIBITED_ORIGIN_CUSTOM_HEADERS.contains(normalized)+ || normalized.startsWith("x-amz-") || normalized.startsWith("x-edge-")) {+ throw invalidOriginCustomHeader("Prohibited origin custom header: " + name);+ }+ if (!names.add(normalized)) {+ throw invalidOriginCustomHeader("Duplicate origin custom header: " + name);+ }+ combinedLength += name.length() + value.length();+ if (combinedLength > MAX_CUSTOM_HEADERS_LENGTH) {+ throw invalidOriginCustomHeader("Origin custom headers exceed the size quota");+ }+ }+ }+ }++ private static AwsException invalidOriginCustomHeader(String message) {+ return new AwsException("InvalidArgument", message, 400);+ }+public synchronized void deleteDistribution(String id, String ifMatch) {Distribution existing = getDistribution(id);if (!existing.getEtag().equals(ifMatch)) {diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.javaindex 8115a07bb4..d6bf7f2b7a 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java@@ -381,21 +381,25 @@ public class CloudFrontServingController {if (bucket == null) {return OriginResponse.error(502, "Could not determine S3 bucket for origin.");}+ OriginResponse response;try {authorizeS3OriginRead(distribution, origin, bucket, key, viewerAuthorization);if (includeBody) {S3Object obj = s3Service.getObject(bucket, key);byte[] data = obj.getData() != null ? obj.getData() : new byte[0];- return new OriginResponse(+ response = new OriginResponse(200, contentType(obj), data, data.length, s3ObjectHeaders(obj));+ } else {+ S3Object meta = s3Service.headObject(bucket, key);+ response = new OriginResponse(+ 200, contentType(meta), null, meta.getSize(), s3ObjectHeaders(meta));}- S3Object meta = s3Service.headObject(bucket, key);- return new OriginResponse(- 200, contentType(meta), null, meta.getSize(), s3ObjectHeaders(meta));} catch (AwsException e) {- return OriginResponse.error(e.getHttpStatus(), e.getMessage());+ response = OriginResponse.error(e.getHttpStatus(), e.getMessage());}+ return withS3CorsHeaders(+ bucket, origin, includeBody ? "GET" : "HEAD", response);}private void authorizeS3OriginRead(@@ -441,17 +445,25 @@ public class CloudFrontServingController {if (bucket == null) {return OriginResponse.error(502, "Could not determine S3 bucket for origin.");}- if (viewerOrigin == null || viewerOrigin.isBlank()+ String configuredOrigin = originCustomHeader(origin, "Origin");+ String originHeader = configuredOrigin == null || configuredOrigin.isBlank()+ ? viewerOrigin+ : configuredOrigin;+ if (originHeader == null || originHeader.isBlank()|| requestMethod == null || requestMethod.isBlank()) {return OriginResponse.error(403, "This CORS request is not allowed.");}List<String> requestedHeaders = splitHeaderValues(requestHeaders);- return s3Service.evaluateCors(bucket, viewerOrigin, requestMethod, requestedHeaders)+ return s3Service.evaluateCors(bucket, originHeader, requestMethod, requestedHeaders).map(cors -> {Map<String, List<String>> headers = new LinkedHashMap<>();+ boolean wildcardOrigin = "*".equals(cors.allowedOrigin());putHeader(headers, "Access-Control-Allow-Origin", cors.allowedOrigin());putHeader(headers, "Access-Control-Allow-Methods",String.join(", ", cors.allowedMethods()));+ if (!wildcardOrigin) {+ putHeader(headers, "Access-Control-Allow-Credentials", "true");+ }if (cors.maxAgeSeconds() > 0) {putHeader(headers, "Access-Control-Max-Age",Integer.toString(cors.maxAgeSeconds()));@@ -464,6 +476,14 @@ public class CloudFrontServingController {putHeader(headers, "Access-Control-Expose-Headers",String.join(", ", cors.exposeHeaders()));}+ if (!wildcardOrigin) {+ mergeVary(+ headers,+ List.of(+ "Origin",+ "Access-Control-Request-Headers",+ "Access-Control-Request-Method"));+ }return new OriginResponse(200, null, new byte[0], 0, headers);}).orElseGet(() -> OriginResponse.error(403,@@ -482,13 +502,28 @@ public class CloudFrontServingController {HttpRequest.Builder rb = HttpRequest.newBuilder().uri(target).timeout(Duration.ofSeconds(30));+ // Origin custom headers: CloudFront adds these to every request it forwards to the origin+ // (overriding any same-named viewer header), which is how a distribution restricts an origin+ // to CloudFront-only traffic via a shared secret header.+ Map<String, String> originHeaders = new LinkedHashMap<>();+ List<Map<String, String>> customHeaders = origin.getCustomHeaders();+ if (customHeaders != null) {+ for (Map<String, String> header : customHeaders) {+ String name = header.get("HeaderName");+ String value = header.get("HeaderValue");+ if (name != null && value != null) {+ originHeaders.put(name, value);+ }+ }+ }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());+ HttpResponse<byte[]> resp = httpClient.send(+ rb.build(), originHeaders, HttpResponse.BodyHandlers.ofByteArray());String ct = resp.headers().firstValue("content-type").orElse(DEFAULT_CONTENT_TYPE);byte[] body = resp.body() != null ? resp.body() : new byte[0];long contentLength = includeBody ? body.length : responseContentLength(resp);@@ -907,6 +942,103 @@ public class CloudFrontServingController {return headers;}+ private OriginResponse withS3CorsHeaders(+ String bucket, Origin origin, String method, OriginResponse response) {+ String configuredOrigin = originCustomHeader(origin, "Origin");+ if (configuredOrigin == null || configuredOrigin.isBlank()) {+ return response;+ }++ Map<String, List<String>> headers = new LinkedHashMap<>(response.headers());+ s3Service.evaluateCors(bucket, configuredOrigin, method, List.of()).ifPresent(cors -> {+ // A rule whose AllowedOrigin is "*" echoes "*" rather than the request origin, and the+ // CORS spec forbids pairing that with Access-Control-Allow-Credentials: true — browsers+ // reject the combination outright for credentialed requests. Verified against real S3:+ // with AllowedOrigins ["*"] it returns only Allow-Origin/Allow-Methods/Max-Age, while a+ // concrete AllowedOrigin additionally returns Allow-Credentials: true and Vary.+ boolean wildcardOrigin = "*".equals(cors.allowedOrigin());+ putHeaderReplacing(headers, "Access-Control-Allow-Origin", cors.allowedOrigin());+ putHeaderReplacing(+ headers,+ "Access-Control-Allow-Methods",+ String.join(", ", cors.allowedMethods()));+ if (!wildcardOrigin) {+ putHeaderReplacing(headers, "Access-Control-Allow-Credentials", "true");+ }+ if (cors.maxAgeSeconds() > 0) {+ putHeaderReplacing(+ headers,+ "Access-Control-Max-Age",+ Integer.toString(cors.maxAgeSeconds()));+ }+ if (!cors.exposeHeaders().isEmpty()) {+ putHeaderReplacing(+ headers,+ "Access-Control-Expose-Headers",+ String.join(", ", cors.exposeHeaders()));+ }+ // Vary is likewise omitted for a wildcard rule: the response is byte-identical for every+ // origin, so there is nothing to vary on. Real S3 returns Vary only in the concrete case.+ if (!wildcardOrigin) {+ mergeVary(+ headers,+ List.of(+ "Origin",+ "Access-Control-Request-Headers",+ "Access-Control-Request-Method"));+ }+ });+ return new OriginResponse(+ response.status(),+ response.contentType(),+ response.body(),+ response.contentLength(),+ headers);+ }++ private static String originCustomHeader(Origin origin, String requestedName) {+ if (origin.getCustomHeaders() == null) {+ return null;+ }+ for (Map<String, String> header : origin.getCustomHeaders()) {+ String name = header.get("HeaderName");+ if (name != null && name.equalsIgnoreCase(requestedName)) {+ return header.get("HeaderValue");+ }+ }+ return null;+ }++ private static void putHeaderReplacing(+ Map<String, List<String>> headers, String name, String value) {+ headers.keySet().removeIf(existing -> existing.equalsIgnoreCase(name));+ putHeader(headers, name, value);+ }++ private static void mergeVary(+ Map<String, List<String>> headers, List<String> requiredTokens) {+ String varyKey = headers.keySet().stream()+ .filter(name -> "Vary".equalsIgnoreCase(name))+ .findFirst()+ .orElse("Vary");+ List<String> tokens = new ArrayList<>();+ headers.getOrDefault(varyKey, List.of()).stream()+ .flatMap(value -> java.util.Arrays.stream(value.split(",")))+ .map(String::trim)+ .filter(token -> !token.isEmpty())+ .forEach(token -> addCaseInsensitive(tokens, token));+ for (String requiredToken : requiredTokens) {+ addCaseInsensitive(tokens, requiredToken);+ }+ headers.put(varyKey, List.of(String.join(", ", tokens)));+ }++ private static void addCaseInsensitive(List<String> values, String candidate) {+ if (values.stream().noneMatch(candidate::equalsIgnoreCase)) {+ values.add(candidate);+ }+ }+private static void putHeader(Map<String, List<String>> headers, String name, String value) {if (value != null) {headers.put(name, List.of(value));diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontDistributionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontDistributionIntegrationTest.javaindex 8d3793e2b0..d1358d5f7f 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontDistributionIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontDistributionIntegrationTest.java@@ -73,6 +73,9 @@ class CloudFormationCloudFrontDistributionIntegrationTest {"Id": "s3-origin","DomainName": "%s.s3.us-east-1.amazonaws.com","OriginAccessControlId": "%s",+ "OriginCustomHeaders": [+ {"HeaderName": "X-Origin-Verify", "HeaderValue": "cfn-secret"}+ ],"S3OriginConfig": { "OriginAccessIdentity": "" }}],@@ -128,6 +131,8 @@ class CloudFormationCloudFrontDistributionIntegrationTest {assertEquals(oac.getId(),provisioned.getConfig().getOrigins().getFirst().getOriginAccessControlId());+ assertEquals(List.of(Map.of("HeaderName", "X-Origin-Verify", "HeaderValue", "cfn-secret")),+ provisioned.getConfig().getOrigins().getFirst().getCustomHeaders());assertEquals("60669652-455b-4ae9-85a4-c4c02393f86c",provisioned.getConfig().getDefaultCacheBehavior().getResponseHeadersPolicyId());assertEquals(List.of("67f7725c-6f97-4210-82d7-5512b31e9d03"),diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontCustomOriginServingTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontCustomOriginServingTest.javaindex 88b7fad868..97dd780aac 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontCustomOriginServingTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontCustomOriginServingTest.java@@ -50,8 +50,11 @@ class CloudFrontCustomOriginServingTest {void omitsQueryByDefaultAndForwardsResponseHeadersAndHeadMetadata() throws Exception {AtomicReference<String> receivedQuery = new AtomicReference<>();AtomicReference<String> receivedPath = new AtomicReference<>();+ AtomicReference<String> receivedCustomHeader = new AtomicReference<>();+ AtomicReference<String> receivedExpectHeader = new AtomicReference<>();originServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);- originServer.createContext("/", exchange -> respond(exchange, receivedQuery, receivedPath));+ originServer.createContext("/", exchange ->+ respond(exchange, receivedQuery, receivedPath, receivedCustomHeader, receivedExpectHeader));originServer.start();Origin customOrigin = new Origin();@@ -59,6 +62,11 @@ class CloudFrontCustomOriginServingTest {// The embedded port is deliberately wrong. CustomOriginConfig.HTTPPort is authoritative.customOrigin.setDomainName("127.0.0.1:1");customOrigin.setCustomOriginConfig(customOriginConfig(originServer.getAddress().getPort()));+ customOrigin.setCustomHeaders(List.of(+ new LinkedHashMap<>(Map.of(+ "HeaderName", "X-Origin-Verify", "HeaderValue", "shared-secret-42")),+ new LinkedHashMap<>(Map.of(+ "HeaderName", "Expect", "HeaderValue", "100-continue"))));DistributionConfig config = new DistributionConfig();config.setEnabled(true);@@ -84,6 +92,8 @@ class CloudFrontCustomOriginServingTest {.header("X-Origin-Header", equalTo("preserved"));assertNull(receivedQuery.get());+ assertEquals("shared-secret-42", receivedCustomHeader.get());+ assertEquals("100-continue", receivedExpectHeader.get());given().urlEncodingEnabled(false)@@ -211,9 +221,13 @@ class CloudFrontCustomOriginServingTest {}private static void respond(HttpExchange exchange, AtomicReference<String> receivedQuery,- AtomicReference<String> receivedPath) throws IOException {+ AtomicReference<String> receivedPath,+ AtomicReference<String> receivedCustomHeader,+ AtomicReference<String> receivedExpectHeader) throws IOException {receivedQuery.set(exchange.getRequestURI().getRawQuery());receivedPath.set(exchange.getRequestURI().getRawPath());+ receivedCustomHeader.set(exchange.getRequestHeaders().getFirst("X-Origin-Verify"));+ receivedExpectHeader.set(exchange.getRequestHeaders().getFirst("Expect"));exchange.getResponseHeaders().add("Content-Type", "text/plain");exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "https://viewer.example");exchange.getResponseHeaders().add("Cache-Control", "public, max-age=60");diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontDistributionServingTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontDistributionServingTest.javaindex 95cce39a80..2b59ef2c9a 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontDistributionServingTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontDistributionServingTest.java@@ -781,6 +781,390 @@ class CloudFrontDistributionServingTest {assertDistributionWasNotCreated(callerReference);}+ @Test+ void roundTripsOriginCustomHeadersThroughTheApi() {+ // The distribution parser must capture and re-serialize origin CustomHeaders so a read-back+ // (get-distribution) matches what was configured, rather than dropping them.+ String body = """+ <?xml version="1.0" encoding="UTF-8"?>+ <DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">+ <CallerReference>cf-custom-headers-roundtrip</CallerReference>+ <Origins>+ <Quantity>1</Quantity>+ <Items>+ <Origin>+ <Id>secured</Id>+ <DomainName>api.internal.example</DomainName>+ <OriginPath></OriginPath>+ <CustomHeaders>+ <Quantity>1</Quantity>+ <Items>+ <OriginCustomHeader>+ <HeaderName>X-Origin-Verify</HeaderName>+ <HeaderValue>shared-secret-42</HeaderValue>+ </OriginCustomHeader>+ </Items>+ </CustomHeaders>+ <CustomOriginConfig>+ <HTTPPort>80</HTTPPort>+ <HTTPSPort>443</HTTPSPort>+ <OriginProtocolPolicy>https-only</OriginProtocolPolicy>+ </CustomOriginConfig>+ </Origin>+ </Items>+ </Origins>+ <DefaultCacheBehavior>+ <TargetOriginId>secured</TargetOriginId>+ <ViewerProtocolPolicy>https-only</ViewerProtocolPolicy>+ </DefaultCacheBehavior>+ <Comment>custom-headers round-trip</Comment>+ <Enabled>true</Enabled>+ </DistributionConfig>+ """;++ given()+ .contentType("application/xml")+ .body(body)+ .when()+ .post("/2020-05-31/distribution")+ .then()+ .statusCode(201)+ .body(containsString("<OriginCustomHeader>"))+ .body(containsString("<HeaderName>X-Origin-Verify</HeaderName>"))+ .body(containsString("<HeaderValue>shared-secret-42</HeaderValue>"));+ }++ @Test+ void rejectsProhibitedOriginCustomHeaders() {+ String body = """+ <DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">+ <CallerReference>cf-prohibited-custom-header</CallerReference>+ <Origins><Quantity>1</Quantity><Items><Origin>+ <Id>secured</Id><DomainName>example.com</DomainName>+ <CustomHeaders><Quantity>1</Quantity><Items><OriginCustomHeader>+ <HeaderName>Host</HeaderName><HeaderValue>internal.example</HeaderValue>+ </OriginCustomHeader></Items></CustomHeaders>+ <CustomOriginConfig><HTTPPort>80</HTTPPort><HTTPSPort>443</HTTPSPort>+ <OriginProtocolPolicy>https-only</OriginProtocolPolicy></CustomOriginConfig>+ </Origin></Items></Origins>+ <DefaultCacheBehavior><TargetOriginId>secured</TargetOriginId>+ <ViewerProtocolPolicy>https-only</ViewerProtocolPolicy></DefaultCacheBehavior>+ <Enabled>true</Enabled>+ </DistributionConfig>+ """;++ given()+ .contentType("application/xml")+ .body(body)+ .when()+ .post("/2020-05-31/distribution")+ .then()+ .statusCode(400)+ .body(containsString("<Code>InvalidArgument</Code>"));+ }++ @Test+ void acceptsAuthorizationOriginCustomHeaders() {+ String body = distributionWithOriginCustomHeaders(1, """+ <OriginCustomHeader>+ <HeaderName>Authorization</HeaderName>+ <HeaderValue>Bearer secret</HeaderValue>+ </OriginCustomHeader>+ """).replace("cf-custom-header-validation", "cf-authorization-custom-header");++ given()+ .contentType("application/xml")+ .body(body)+ .when()+ .post("/2020-05-31/distribution")+ .then()+ .statusCode(201)+ .body(containsString("<HeaderName>Authorization</HeaderName>"))+ .body(containsString("<HeaderValue>Bearer secret</HeaderValue>"));+ }++ @Test+ void rejectsInconsistentOriginCustomHeaderQuantity() {+ String body = distributionWithOriginCustomHeaders(2, """+ <OriginCustomHeader>+ <HeaderName>X-Origin-Verify</HeaderName>+ <HeaderValue>shared-secret</HeaderValue>+ </OriginCustomHeader>+ """);++ given()+ .contentType("application/xml")+ .body(body)+ .when()+ .post("/2020-05-31/distribution")+ .then()+ .statusCode(400)+ .body(containsString("<Code>InconsistentQuantities</Code>"));+ }++ @Test+ void serializesEmptyOriginCustomHeadersWithZeroQuantity() {+ given()+ .contentType("application/xml")+ .body(distributionWithOriginCustomHeaders(0, "", false))+ .when()+ .post("/2020-05-31/distribution")+ .then()+ .statusCode(201)+ .body(containsString("<CustomHeaders><Quantity>0</Quantity></CustomHeaders>"));+ }++ @Test+ void rejectsMalformedOriginCustomHeaderStructure() {+ String item = """+ <OriginCustomHeader>+ <HeaderName>X-Origin-Verify</HeaderName>+ <HeaderValue>shared-secret</HeaderValue>+ </OriginCustomHeader>+ """;+ List<String> malformedBodies = List.of(+ distributionWithOriginCustomHeaders(1, item, false),+ distributionWithOriginCustomHeaders(1, """+ <Header>+ <HeaderName>X-Origin-Verify</HeaderName>+ <HeaderValue>shared-secret</HeaderValue>+ </Header>+ """),+ distributionWithOriginCustomHeaders(1, """+ <OriginCustomHeader>+ <HeaderName><Value>X-Origin-Verify</Value></HeaderName>+ <HeaderValue>shared-secret</HeaderValue>+ </OriginCustomHeader>+ """));++ for (String body : malformedBodies) {+ given()+ .contentType("application/xml")+ .body(body)+ .when()+ .post("/2020-05-31/distribution")+ .then()+ .statusCode(400)+ .body(containsString("<Code>InvalidArgument</Code>"));+ }+ }++ @Test+ void rejectsTooManyOriginCustomHeadersWithAwsErrorCode() {+ StringBuilder items = new StringBuilder();+ for (int i = 0; i < 31; i++) {+ items.append("""+ <OriginCustomHeader>+ <HeaderName>X-Origin-%d</HeaderName>+ <HeaderValue>value</HeaderValue>+ </OriginCustomHeader>+ """.formatted(i));+ }+ String body = distributionWithOriginCustomHeaders(31, items.toString());++ given()+ .contentType("application/xml")+ .body(body)+ .when()+ .post("/2020-05-31/distribution")+ .then()+ .statusCode(400)+ .body(containsString("<Code>TooManyOriginCustomHeaders</Code>"));+ }++ /**+ * A rule whose {@code AllowedOrigin} is {@code *} echoes {@code *}, and the CORS specification+ * forbids pairing that with {@code Access-Control-Allow-Credentials: true} — browsers reject the+ * combination for credentialed requests, so emitting it would break in the browser while passing+ * here. Verified against real S3: a wildcard rule returns only Allow-Origin, Allow-Methods and+ * Max-Age, with no Allow-Credentials and no Vary; a concrete origin returns both (covered by+ * {@link #appliesConfiguredOriginHeaderToS3CorsResponses()}).+ */+ @Test+ void wildcardCorsOriginOmitsCredentialsAndVary() {+ String suffix = suffix();+ String bucket = "cf-origin-header-cors-wild-" + suffix;+ createBucket(bucket);+ putObject(bucket, "asset.txt", "cors-body", "text/plain");+ s3Service.putBucketCors(bucket, """+ <CORSConfiguration>+ <CORSRule>+ <AllowedOrigin>*</AllowedOrigin>+ <AllowedMethod>GET</AllowedMethod>+ <AllowedMethod>HEAD</AllowedMethod>+ <MaxAgeSeconds>600</MaxAgeSeconds>+ </CORSRule>+ </CORSConfiguration>+ """);++ Origin origin = s3Origin("s3-origin", bucket);+ origin.setCustomHeaders(List.of(new LinkedHashMap<>(Map.of(+ "HeaderName", "Origin",+ "HeaderValue", "https://configured.example"))));+ DistributionConfig cfg = new DistributionConfig();+ cfg.setEnabled(true);+ cfg.setOrigins(List.of(origin));+ DefaultCacheBehavior behavior = defaultBehavior(origin.getId());+ behavior.setAllowedMethods(List.of("GET", "HEAD", "OPTIONS"));+ cfg.setDefaultCacheBehavior(behavior);+ Distribution dist = cloudFrontService.createDistribution(distribution(cfg), Map.of());++ given()+ .header("Host", dist.getDomainName())+ .header("Origin", "https://viewer.example")+ .when()+ .get("/asset.txt")+ .then()+ .statusCode(200)+ .header("Access-Control-Allow-Origin", equalTo("*"))+ .header("Access-Control-Allow-Methods", equalTo("GET, HEAD"))+ .header("Access-Control-Max-Age", equalTo("600"))+ .header("Access-Control-Allow-Credentials", nullValue())+ .header("Vary", nullValue());++ given()+ .header("Host", dist.getDomainName())+ .header("Origin", "https://viewer.example")+ .header("Access-Control-Request-Method", "GET")+ .when()+ .options("/asset.txt")+ .then()+ .statusCode(200)+ .header("Access-Control-Allow-Origin", equalTo("*"))+ .header("Access-Control-Allow-Methods", equalTo("GET, HEAD"))+ .header("Access-Control-Max-Age", equalTo("600"))+ .header("Access-Control-Allow-Credentials", nullValue())+ .header("Vary", nullValue());+ }++ @Test+ void appliesConfiguredOriginHeaderToS3CorsResponses() {+ String suffix = suffix();+ String bucket = "cf-origin-header-cors-" + suffix;+ createBucket(bucket);+ putObject(bucket, "asset.txt", "cors-body", "text/plain");+ s3Service.putBucketCors(bucket, """+ <CORSConfiguration>+ <CORSRule>+ <AllowedOrigin>https://configured.example</AllowedOrigin>+ <AllowedMethod>GET</AllowedMethod>+ <AllowedMethod>HEAD</AllowedMethod>+ <ExposeHeader>ETag</ExposeHeader>+ <MaxAgeSeconds>600</MaxAgeSeconds>+ </CORSRule>+ </CORSConfiguration>+ """);++ Origin origin = s3Origin("s3-origin", bucket);+ origin.setCustomHeaders(List.of(new LinkedHashMap<>(Map.of(+ "HeaderName", "Origin",+ "HeaderValue", "https://configured.example"))));+ DistributionConfig cfg = new DistributionConfig();+ cfg.setEnabled(true);+ cfg.setOrigins(List.of(origin));+ cfg.setDefaultCacheBehavior(defaultBehavior(origin.getId()));+ Distribution dist = cloudFrontService.createDistribution(distribution(cfg), Map.of());++ given()+ .header("Host", dist.getDomainName())+ .header("Origin", "https://viewer.example")+ .when()+ .get("/asset.txt")+ .then()+ .statusCode(200)+ .header("Access-Control-Allow-Origin", equalTo("https://configured.example"))+ .header("Access-Control-Allow-Methods", equalTo("GET, HEAD"))+ .header("Access-Control-Allow-Credentials", equalTo("true"))+ .header("Access-Control-Max-Age", equalTo("600"))+ .header("Access-Control-Expose-Headers", equalTo("ETag"))+ .header("Vary", containsString("Origin"))+ .header("Vary", containsString("Access-Control-Request-Headers"))+ .header("Vary", containsString("Access-Control-Request-Method"));++ given()+ .header("Host", dist.getDomainName())+ .header("Origin", "https://viewer.example")+ .when()+ .head("/asset.txt")+ .then()+ .statusCode(200)+ .header("Access-Control-Allow-Origin", equalTo("https://configured.example"))+ .header("Access-Control-Allow-Methods", equalTo("GET, HEAD"))+ .header("Access-Control-Allow-Credentials", equalTo("true"))+ .header("Access-Control-Max-Age", equalTo("600"))+ .header("Access-Control-Expose-Headers", equalTo("ETag"))+ .header("Vary", containsString("Origin"))+ .header("Vary", containsString("Access-Control-Request-Headers"))+ .header("Vary", containsString("Access-Control-Request-Method"));+ }++ @Test+ void appliesConfiguredOriginHeaderToS3CorsPreflight() {+ String suffix = suffix();+ String bucket = "cf-origin-header-preflight-" + suffix;+ createBucket(bucket);+ s3Service.putBucketCors(bucket, """+ <CORSConfiguration>+ <CORSRule>+ <AllowedOrigin>https://configured.example</AllowedOrigin>+ <AllowedMethod>GET</AllowedMethod>+ <AllowedHeader>Authorization</AllowedHeader>+ </CORSRule>+ </CORSConfiguration>+ """);++ Origin origin = s3Origin("s3-origin", bucket);+ origin.setCustomHeaders(List.of(new LinkedHashMap<>(Map.of(+ "HeaderName", "Origin",+ "HeaderValue", "https://configured.example"))));+ DefaultCacheBehavior behavior = defaultBehavior(origin.getId());+ behavior.setAllowedMethods(List.of("GET", "HEAD", "OPTIONS"));+ DistributionConfig config = new DistributionConfig();+ config.setEnabled(true);+ config.setOrigins(List.of(origin));+ config.setDefaultCacheBehavior(behavior);+ Distribution distribution =+ cloudFrontService.createDistribution(distribution(config), Map.of());++ given()+ .header("Host", distribution.getDomainName())+ .header("Origin", "https://viewer.example")+ .header("Access-Control-Request-Method", "GET")+ .header("Access-Control-Request-Headers", "Authorization")+ .when().options("/asset.txt")+ .then().statusCode(200)+ .header("Access-Control-Allow-Origin", equalTo("https://configured.example"))+ .header("Access-Control-Allow-Methods", equalTo("GET"))+ .header("Access-Control-Allow-Headers", equalTo("Authorization"))+ .header("Access-Control-Allow-Credentials", equalTo("true"))+ .header("Vary", containsString("Origin"))+ .header("Vary", containsString("Access-Control-Request-Headers"))+ .header("Vary", containsString("Access-Control-Request-Method"));+ }++ private static String distributionWithOriginCustomHeaders(int quantity, String items) {+ return distributionWithOriginCustomHeaders(quantity, items, true);+ }++ private static String distributionWithOriginCustomHeaders(+ int quantity, String items, boolean includeItems) {+ String itemList = includeItems ? "<Items>" + items + "</Items>" : items;+ return """+ <DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">+ <CallerReference>cf-custom-header-validation</CallerReference>+ <Origins><Quantity>1</Quantity><Items><Origin>+ <Id>secured</Id><DomainName>example.com</DomainName>+ <CustomHeaders><Quantity>%d</Quantity>%s</CustomHeaders>+ <CustomOriginConfig><HTTPPort>80</HTTPPort><HTTPSPort>443</HTTPSPort>+ <OriginProtocolPolicy>https-only</OriginProtocolPolicy></CustomOriginConfig>+ </Origin></Items></Origins>+ <DefaultCacheBehavior><TargetOriginId>secured</TargetOriginId>+ <ViewerProtocolPolicy>https-only</ViewerProtocolPolicy></DefaultCacheBehavior>+ <Enabled>true</Enabled>+ </DistributionConfig>+ """.formatted(quantity, itemList);+ }+@Testvoid appliesResponseHeadersPolicyToServedResponses() {String suffix = suffix();diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClientTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClientTest.javaindex 0c6f7d0df9..9412c7f087 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClientTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClientTest.java@@ -28,6 +28,7 @@ import java.security.Security;import java.security.cert.X509Certificate;import java.time.Duration;import java.util.List;+import java.util.Map;import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.atomic.AtomicReference;@@ -141,6 +142,37 @@ class CloudFrontOriginHttpClientTest {}}+ @Test+ void originHeadersReplaceSameNamedRequestHeaders() throws Exception {+ AtomicReference<List<String>> receivedValues = new AtomicReference<>();+ HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);+ server.createContext("/", exchange -> {+ receivedValues.set(exchange.getRequestHeaders().get("X-Origin-Verify"));+ exchange.sendResponseHeaders(200, -1);+ exchange.close();+ });+ server.start();++ try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(+ resolver(InetAddress.getByName("127.0.0.1")), List.of("origin.invalid"))) {+ HttpRequest request = HttpRequest.newBuilder(java.net.URI.create(+ "http://origin.invalid:" + server.getAddress().getPort() + "/"))+ .timeout(Duration.ofSeconds(5))+ .header("X-Origin-Verify", "viewer-value")+ .GET()+ .build();++ client.send(+ request,+ Map.of("X-Origin-Verify", "configured-value"),+ HttpResponse.BodyHandlers.ofByteArray());++ assertEquals(List.of("configured-value"), receivedValues.get());+ } finally {+ server.stop(0);+ }+ }+@Testvoid httpsPinningPreservesSniAndHostnameVerification() throws Exception {if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.javaindex 96347aea85..5476e9ba25 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java@@ -531,6 +531,49 @@ class CloudFrontServiceTest {assertEquals(409, keyGroupError.getHttpStatus());}+ @Test+ void rejectsInvalidOriginCustomHeaderNamesAndValues() {+ CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");+ List<List<Map<String, String>>> invalidHeaders = List.of(+ List.of(header("X-Duplicate", "one"), header("x-duplicate", "two")),+ List.of(header("X-Amz-Reserved", "value")),+ List.of(header("X-Edge-Reserved", "value")),+ List.of(header("Bad Header", "value")),+ List.of(header("", "value")),+ List.of(header("X-Missing-Value", null)),+ List.of(header("X-Injected", "value\r\nInjected: true")),+ List.of(header("X".repeat(257), "value")),+ List.of(header("X-Too-Long", "v".repeat(1_784))),+ List.of(+ header("X-Quota-1", "v".repeat(1_783)),+ header("X-Quota-2", "v".repeat(1_783)),+ header("X-Quota-3", "v".repeat(1_783)),+ header("X-Quota-4", "v".repeat(1_783)),+ header("X-Quota-5", "v".repeat(1_783)),+ header("X-Quota-6", "v".repeat(1_783))));++ for (int i = 0; i < invalidHeaders.size(); i++) {+ Distribution candidate = distribution(false, List.of());+ Origin origin = new Origin();+ origin.setCustomHeaders(invalidHeaders.get(i));+ candidate.getConfig().setOrigins(List.of(origin));++ AwsException error = assertThrows(+ AwsException.class,+ () -> service.createDistribution(candidate, Map.of()),+ "validation case " + i);+ assertEquals("InvalidArgument", error.getErrorCode(), "validation case " + i);+ assertEquals(400, error.getHttpStatus(), "validation case " + i);+ }+ }++ private static Map<String, String> header(String name, String value) {+ Map<String, String> header = new LinkedHashMap<>();+ header.put("HeaderName", name);+ header.put("HeaderValue", value);+ return header;+ }+@Testvoid exposesCanonicalManagedResponseHeadersPolicies() {CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");@@ -704,6 +747,7 @@ class CloudFrontServiceTest {assertEquals(code, error.getErrorCode());return error;}+private static Distribution distribution(boolean enabled, List<String> aliases) {DistributionConfig config = new DistributionConfig();config.setEnabled(enabled);