mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(cloudfront): forward origin custom headers (#1832)
* feat(cloudfront): serve distribution requests from S3 and custom origins * feat(cloudfront): forward origin custom headers * fix(cloudfront): omit Allow-Credentials and Vary for wildcard S3 CORS rules withS3CorsHeaders emitted Access-Control-Allow-Credentials: true for every matched rule, including one whose AllowedOrigin is "*" (where evaluateCors echoes "*"). The CORS specification forbids that pairing and browsers reject it for credentialed requests, so the emulator produced a response that fails in a browser while passing against Floci. Verified against real S3 rather than inferred. Bucket with AllowedOrigins ["*"]: Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET Access-Control-Max-Age: 3000 and with a concrete AllowedOrigin it additionally returns Access-Control-Allow-Credentials: true Vary: Origin, Access-Control-Request-Headers, Access-Control-Request-Method Both preflight and actual GET behave identically. Vary is now also conditional: the wildcard response is byte-identical for every origin, so there is nothing to vary on, and real S3 omits it there too. * 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(ec2): wire managed prefix list storage in public IP test * fix(cloudfront): allow authorization origin custom headers * fix(cloudfront): preserve S3 preflight CORS headers
This commit is contained in:
1 parent
520c0f4da2
commit
f2ad05ce22
12 files changed
+979
-17
No files matched your search
+11
@@ -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()) {
|
||||
|
||||
+140
-7
@@ -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) {
|
||||
|
||||
+7
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@ApplicationScoped
|
||||
public 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)) {
|
||||
|
||||
+140
-8
@@ -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));
|
||||
|
||||
Reference in new issue
Block a user