mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
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:
1 parent
f40d2e34f3
commit
520c0f4da2
21 files changed
+3141
-79
No files matched your search
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env bats
|
||||
# CloudFront AWS CLI compatibility tests
|
||||
|
||||
setup() {
|
||||
load 'test_helper/common-setup'
|
||||
}
|
||||
|
||||
@test "CloudFront: list response headers policies decodes the modeled payload" {
|
||||
run aws_cmd cloudfront list-response-headers-policies \
|
||||
--type managed \
|
||||
--max-items 1 \
|
||||
--no-paginate
|
||||
assert_success
|
||||
|
||||
[ "$(json_get "$output" '.ResponseHeadersPolicyList.Quantity')" = "1" ]
|
||||
[ "$(json_get "$output" '.ResponseHeadersPolicyList.MaxItems')" = "1" ]
|
||||
[ "$(json_get "$output" '.ResponseHeadersPolicyList.Items | length')" = "1" ]
|
||||
[ "$(json_get "$output" '.ResponseHeadersPolicyList.Items[0].Type')" = "managed" ]
|
||||
[ -n "$(json_get "$output" \
|
||||
'.ResponseHeadersPolicyList.Items[0].ResponseHeadersPolicy.Id // empty')" ]
|
||||
[ -n "$(json_get "$output" \
|
||||
'.ResponseHeadersPolicyList.NextMarker // empty')" ]
|
||||
|
||||
first_id="$(json_get "$output" \
|
||||
'.ResponseHeadersPolicyList.Items[0].ResponseHeadersPolicy.Id')"
|
||||
next_marker="$(json_get "$output" \
|
||||
'.ResponseHeadersPolicyList.NextMarker')"
|
||||
|
||||
run aws_cmd cloudfront list-response-headers-policies \
|
||||
--type managed \
|
||||
--marker "$next_marker" \
|
||||
--max-items 1 \
|
||||
--no-paginate
|
||||
assert_success
|
||||
|
||||
[ "$(json_get "$output" '.ResponseHeadersPolicyList.Quantity')" = "1" ]
|
||||
[ "$(json_get "$output" \
|
||||
'.ResponseHeadersPolicyList.Items[0].ResponseHeadersPolicy.Id')" != "$first_id" ]
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;
|
||||
import software.amazon.awssdk.services.cloudfront.model.CreateResponseHeadersPolicyResponse;
|
||||
import software.amazon.awssdk.services.cloudfront.model.NoSuchResponseHeadersPolicyException;
|
||||
import software.amazon.awssdk.services.cloudfront.model.PreconditionFailedException;
|
||||
import software.amazon.awssdk.services.cloudfront.model.ResponseHeadersPolicyConfig;
|
||||
import software.amazon.awssdk.services.cloudfront.model.ResponseHeadersPolicyType;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeFalse;
|
||||
|
||||
class CloudFrontResponseHeadersPolicyTest {
|
||||
|
||||
@Test
|
||||
void roundTripsResponseHeadersPolicyWithTheAwsSdk() {
|
||||
assumeFalse(
|
||||
TestFixtures.isRealAws(),
|
||||
"The immediate policy lifecycle in this test is emulator-specific");
|
||||
|
||||
String suffix = TestFixtures.uniqueName("cloudfront-response-headers");
|
||||
String policyId = null;
|
||||
String etag = null;
|
||||
|
||||
try (CloudFrontClient cloudFront = TestFixtures.cloudFrontClient()) {
|
||||
CreateResponseHeadersPolicyResponse created =
|
||||
cloudFront.createResponseHeadersPolicy(request -> request
|
||||
.responseHeadersPolicyConfig(policyConfig(
|
||||
suffix, "created", "created-value")));
|
||||
policyId = created.responseHeadersPolicy().id();
|
||||
etag = created.eTag();
|
||||
assertNotNull(policyId);
|
||||
assertNotNull(etag);
|
||||
assertTrue(created.location().endsWith("/" + policyId));
|
||||
assertNotNull(created.responseHeadersPolicy().lastModifiedTime());
|
||||
assertEquals("policy-" + suffix,
|
||||
created.responseHeadersPolicy()
|
||||
.responseHeadersPolicyConfig()
|
||||
.name());
|
||||
|
||||
String id = policyId;
|
||||
var fetched = cloudFront.getResponseHeadersPolicy(
|
||||
request -> request.id(id));
|
||||
assertEquals(etag, fetched.eTag());
|
||||
assertEquals("created",
|
||||
fetched.responseHeadersPolicy()
|
||||
.responseHeadersPolicyConfig()
|
||||
.comment());
|
||||
assertEquals("created-value",
|
||||
fetched.responseHeadersPolicy()
|
||||
.responseHeadersPolicyConfig()
|
||||
.customHeadersConfig()
|
||||
.items()
|
||||
.get(0)
|
||||
.value());
|
||||
assertEquals(1,
|
||||
fetched.responseHeadersPolicy()
|
||||
.responseHeadersPolicyConfig()
|
||||
.customHeadersConfig()
|
||||
.quantity());
|
||||
assertEquals("X-Floci-Policy",
|
||||
fetched.responseHeadersPolicy()
|
||||
.responseHeadersPolicyConfig()
|
||||
.customHeadersConfig()
|
||||
.items()
|
||||
.get(0)
|
||||
.header());
|
||||
assertTrue(fetched.responseHeadersPolicy()
|
||||
.responseHeadersPolicyConfig()
|
||||
.customHeadersConfig()
|
||||
.items()
|
||||
.get(0)
|
||||
.override());
|
||||
|
||||
var fetchedConfig = cloudFront.getResponseHeadersPolicyConfig(
|
||||
request -> request.id(id));
|
||||
assertEquals(etag, fetchedConfig.eTag());
|
||||
assertEquals("created-value",
|
||||
fetchedConfig.responseHeadersPolicyConfig()
|
||||
.customHeadersConfig()
|
||||
.items()
|
||||
.get(0)
|
||||
.value());
|
||||
assertEquals(0.0,
|
||||
fetchedConfig.responseHeadersPolicyConfig()
|
||||
.serverTimingHeadersConfig()
|
||||
.samplingRate());
|
||||
assertTrue(fetchedConfig.responseHeadersPolicyConfig()
|
||||
.serverTimingHeadersConfig()
|
||||
.enabled());
|
||||
|
||||
var listed = cloudFront.listResponseHeadersPolicies(request -> request
|
||||
.type(ResponseHeadersPolicyType.CUSTOM)
|
||||
.maxItems("100"))
|
||||
.responseHeadersPolicyList();
|
||||
assertTrue(listed.items().stream().anyMatch(summary ->
|
||||
id.equals(summary.responseHeadersPolicy().id())
|
||||
&& summary.type() == ResponseHeadersPolicyType.CUSTOM));
|
||||
assertTrue(listed.quantity() >= 1);
|
||||
|
||||
assertThrows(PreconditionFailedException.class,
|
||||
() -> cloudFront.updateResponseHeadersPolicy(request -> request
|
||||
.id(id)
|
||||
.ifMatch("stale-etag")
|
||||
.responseHeadersPolicyConfig(policyConfig(
|
||||
suffix, "stale", "stale-value"))));
|
||||
|
||||
var updated = cloudFront.updateResponseHeadersPolicy(request -> request
|
||||
.id(id)
|
||||
.ifMatch(created.eTag())
|
||||
.responseHeadersPolicyConfig(policyConfig(
|
||||
suffix, "updated", "updated-value")));
|
||||
etag = updated.eTag();
|
||||
assertNotNull(etag);
|
||||
assertNotEquals(created.eTag(), etag);
|
||||
assertEquals("updated",
|
||||
updated.responseHeadersPolicy()
|
||||
.responseHeadersPolicyConfig()
|
||||
.comment());
|
||||
assertEquals("updated-value",
|
||||
updated.responseHeadersPolicy()
|
||||
.responseHeadersPolicyConfig()
|
||||
.customHeadersConfig()
|
||||
.items()
|
||||
.get(0)
|
||||
.value());
|
||||
|
||||
String currentEtag = etag;
|
||||
cloudFront.deleteResponseHeadersPolicy(request -> request
|
||||
.id(id)
|
||||
.ifMatch(currentEtag));
|
||||
policyId = null;
|
||||
assertThrows(NoSuchResponseHeadersPolicyException.class,
|
||||
() -> cloudFront.getResponseHeadersPolicy(
|
||||
request -> request.id(id)));
|
||||
} finally {
|
||||
if (policyId != null && etag != null) {
|
||||
try (CloudFrontClient cloudFront =
|
||||
TestFixtures.cloudFrontClient()) {
|
||||
String id = policyId;
|
||||
String currentEtag = cloudFront
|
||||
.getResponseHeadersPolicyConfig(
|
||||
request -> request.id(id))
|
||||
.eTag();
|
||||
cloudFront.deleteResponseHeadersPolicy(request -> request
|
||||
.id(id)
|
||||
.ifMatch(currentEtag));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static ResponseHeadersPolicyConfig policyConfig(
|
||||
String suffix, String comment, String headerValue) {
|
||||
return ResponseHeadersPolicyConfig.builder()
|
||||
.name("policy-" + suffix)
|
||||
.comment(comment)
|
||||
.customHeadersConfig(custom -> custom
|
||||
.quantity(1)
|
||||
.items(header -> header
|
||||
.header("X-Floci-Policy")
|
||||
.value(headerValue)
|
||||
.override(true)))
|
||||
.serverTimingHeadersConfig(serverTiming -> serverTiming
|
||||
.enabled(true)
|
||||
.samplingRate(0.0))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
# CloudFront
|
||||
|
||||
CloudFront management-plane and local content-delivery emulation. Supports distribution lifecycle, cache policies, origin request policies, response headers policies, origin access controls, origin access identities, public keys, trusted key groups, CloudFront Functions, invalidations, tagging, and GET/HEAD delivery from S3 or custom origins.
|
||||
CloudFront management-plane and local content-delivery emulation. Supports distribution lifecycle,
|
||||
cache policies, origin request policies, response headers policies, origin access controls, origin
|
||||
access identities, public keys, trusted key groups, CloudFront Functions, invalidations, tagging, and
|
||||
GET/HEAD/OPTIONS delivery from S3 or custom origins.
|
||||
|
||||
**Protocol:** REST XML
|
||||
**API version:** `2020-05-31`
|
||||
@@ -131,7 +134,7 @@ CloudFront management-plane and local content-delivery emulation. Supports distr
|
||||
- Invalidations are immediately marked `Completed`.
|
||||
- `DeleteDistribution` returns `DistributionNotDisabled` (409) if `Enabled` is `true` in the config.
|
||||
- All mutating operations (`PUT`, `DELETE`) require an `If-Match` header containing the current
|
||||
`ETag`. Public key and key group updates and deletions distinguish a missing header
|
||||
`ETag`. Response headers policies, public keys, and key groups distinguish a missing header
|
||||
(`InvalidIfMatchVersion`, 400) from a stale `ETag` (`PreconditionFailed`, 412). Other CloudFront
|
||||
resources currently return `InvalidIfMatchVersion` (400) for either case.
|
||||
- All `GET` and `POST` (create) responses include an `ETag` response header.
|
||||
@@ -142,9 +145,9 @@ CloudFront management-plane and local content-delivery emulation. Supports distr
|
||||
- CNAME aliases are globally unique. `AssociateAlias` atomically transfers an alias from its current
|
||||
owner to the target distribution. Exact aliases take precedence over the most-specific matching
|
||||
wildcard alias.
|
||||
- Viewer GET/HEAD requests addressed to an enabled distribution's generated domain or alias are
|
||||
routed to the matching S3 or custom origin. Origin forwarding preserves the raw path;
|
||||
custom-origin redirects are not followed.
|
||||
- Viewer GET/HEAD requests, and OPTIONS requests allowed by the matched cache behavior, addressed to
|
||||
an enabled distribution's generated domain or alias are routed to the matching S3 or custom
|
||||
origin. Origin forwarding preserves the raw path; custom-origin redirects are not followed.
|
||||
- Cache behaviors with enabled `TrustedKeyGroups` require a valid CloudFront signed URL or signed
|
||||
cookie 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 public
|
||||
@@ -166,6 +169,16 @@ CloudFront management-plane and local content-delivery emulation. Supports distr
|
||||
implemented yet. Viewer query strings therefore follow CloudFront's default behavior and are not
|
||||
forwarded to origins.
|
||||
- Custom origins that resolve to loopback, private, link-local, carrier-grade NAT, or other non-routable addresses are rejected by default. Development-only private origins must be explicitly allowlisted by exact hostname.
|
||||
- Response headers policies validate the AWS configuration shape and are applied after the origin
|
||||
response, including CORS preflight fields, origin override behavior, custom headers, security
|
||||
headers, allowed header removals, and sampled `Server-Timing` metrics. `Pragma: server-timing`
|
||||
forces those metrics for enabled policies. Distribution writes reject unknown policy IDs, and
|
||||
policies attached to a cache behavior cannot be deleted.
|
||||
- Up to 20 custom response headers policies can be created, and one policy can be associated with
|
||||
up to 100 distributions.
|
||||
- The five AWS managed response headers policy IDs are available and can be selected with
|
||||
`ListResponseHeadersPolicies?Type=managed`; `Type` uses the AWS lowercase `managed` or `custom`
|
||||
values.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -270,4 +283,6 @@ aws cloudfront delete-distribution --id E1Z2X3C4V5B6N7 --if-match "$ETAG"
|
||||
- Streaming distributions (RTMP — deprecated by AWS)
|
||||
- VPC origins, Anycast IP lists, key value stores
|
||||
- Monitoring subscriptions
|
||||
- CloudFormation provisioning of custom `AWS::CloudFront::ResponseHeadersPolicy` resources
|
||||
(literal custom or managed policy IDs are supported on distributions)
|
||||
- Persistent edge caching and global CDN propagation
|
||||
@@ -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.
|
||||
|
||||
+2
@@ -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);
|
||||
|
||||
+24
-13
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
+40
@@ -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
|
||||
|
||||
+233
-8
@@ -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) {
|
||||
|
||||
+298
-50
@@ -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) {
|
||||
|
||||
+565
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+427
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -95,6 +95,32 @@ class XmlParserTest {
|
||||
assertNull(groups.get(0).get("Nested"));
|
||||
}
|
||||
|
||||
// --- extractElementTree: scoped structured parsing ---
|
||||
|
||||
@Test
|
||||
void extractElementTreePreservesNestedNamespaceQualifiedBlocks() {
|
||||
var root = XmlParser.extractElementTree("""
|
||||
<Envelope xmlns:cf="https://cloudfront.amazonaws.com/doc/2020-05-31/">
|
||||
<cf:Config>
|
||||
<cf:First><cf:Value>one</cf:Value></cf:First>
|
||||
<cf:Second><cf:Value><![CDATA[two]]></cf:Value></cf:Second>
|
||||
</cf:Config>
|
||||
</Envelope>
|
||||
""", "Config");
|
||||
|
||||
assertNotNull(root);
|
||||
assertEquals("Config", root.name());
|
||||
assertEquals("one", root.child("First").child("Value").text());
|
||||
assertEquals("two", root.child("Second").child("Value").text());
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractElementTreeReturnsNullForMalformedOrMissingElements() {
|
||||
assertNull(XmlParser.extractElementTree("<Root><Target></Root>", "Target"));
|
||||
assertNull(XmlParser.extractElementTree("<Root/>", "Target"));
|
||||
assertNull(XmlParser.extractElementTree(null, "Target"));
|
||||
}
|
||||
|
||||
// --- extractPairsPerGroup ---
|
||||
|
||||
@Test
|
||||
|
||||
+18
-2
@@ -17,6 +17,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -77,8 +78,15 @@ class CloudFormationCloudFrontDistributionIntegrationTest {
|
||||
],
|
||||
"DefaultCacheBehavior": {
|
||||
"TargetOriginId": "s3-origin",
|
||||
"ViewerProtocolPolicy": "allow-all"
|
||||
}
|
||||
"ViewerProtocolPolicy": "allow-all",
|
||||
"ResponseHeadersPolicyId": "60669652-455b-4ae9-85a4-c4c02393f86c"
|
||||
},
|
||||
"CacheBehaviors": [{
|
||||
"PathPattern": "/api/*",
|
||||
"TargetOriginId": "s3-origin",
|
||||
"ViewerProtocolPolicy": "allow-all",
|
||||
"ResponseHeadersPolicyId": "67f7725c-6f97-4210-82d7-5512b31e9d03"
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,15 +128,23 @@ class CloudFormationCloudFrontDistributionIntegrationTest {
|
||||
assertEquals(
|
||||
oac.getId(),
|
||||
provisioned.getConfig().getOrigins().getFirst().getOriginAccessControlId());
|
||||
assertEquals("60669652-455b-4ae9-85a4-c4c02393f86c",
|
||||
provisioned.getConfig().getDefaultCacheBehavior().getResponseHeadersPolicyId());
|
||||
assertEquals(List.of("67f7725c-6f97-4210-82d7-5512b31e9d03"),
|
||||
provisioned.getConfig().getCacheBehaviors().stream()
|
||||
.map(behavior -> behavior.getResponseHeadersPolicyId())
|
||||
.toList());
|
||||
|
||||
// The provisioned distribution is browsable: a request to its alias serves the S3 origin's
|
||||
// default root object.
|
||||
given()
|
||||
.header("Host", alias)
|
||||
.header("Origin", "https://viewer.example")
|
||||
.when()
|
||||
.get("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.header("Access-Control-Allow-Origin", equalTo("*"))
|
||||
.body(containsString("CFN-INDEX-" + suffix));
|
||||
}
|
||||
|
||||
|
||||
+140
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.ResponseHeadersPolicy;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
@@ -24,7 +25,10 @@ import java.util.concurrent.atomic.AtomicReference;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(CloudFrontCustomOriginServingTest.PrivateOriginProfile.class)
|
||||
@@ -68,6 +72,7 @@ class CloudFrontCustomOriginServingTest {
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.header("Host", created.getDomainName())
|
||||
.header("Origin", "https://viewer.example")
|
||||
.when()
|
||||
.get("/resource?x=1&x=2&encoded=a%2Fb")
|
||||
.then()
|
||||
@@ -100,6 +105,111 @@ class CloudFrontCustomOriginServingTest {
|
||||
.body(equalTo(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void responseHeadersPolicyRemovesOverridesAndPreservesOriginHeaderValues() throws Exception {
|
||||
originServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
originServer.createContext("/", CloudFrontCustomOriginServingTest::respondWithPolicyHeaders);
|
||||
originServer.start();
|
||||
|
||||
Map<String, Object> policyConfig = new LinkedHashMap<>();
|
||||
policyConfig.put("RemoveHeadersConfig", List.of("X-Remove", "X-Readd", "Server", "Date"));
|
||||
policyConfig.put("CustomHeadersConfig", List.of(
|
||||
policyHeader("X-Readd", "policy-readded", false),
|
||||
policyHeader("X-Override", "policy-override", true),
|
||||
policyHeader("X-Preserve", "policy-ignored", false),
|
||||
policyHeader("X-New", "policy-new", false),
|
||||
policyHeader("X-Hop", "policy-hop", true),
|
||||
policyHeader("sErVeR", "policy-server", false),
|
||||
policyHeader("dAtE", "Thu, 02 Jan 2020 00:00:00 GMT", false)));
|
||||
policyConfig.put("SecurityHeadersConfig", Map.of(
|
||||
"StrictTransportSecurity", Map.of(
|
||||
"AccessControlMaxAgeSec", "31536000",
|
||||
"IncludeSubdomains", "true",
|
||||
"Preload", "false",
|
||||
"Override", "true")));
|
||||
policyConfig.put("ServerTimingHeadersConfig", Map.of(
|
||||
"Enabled", "true", "SamplingRate", "100"));
|
||||
policyConfig.put("CorsConfig", new LinkedHashMap<>(Map.of(
|
||||
"AccessControlAllowCredentials", "false",
|
||||
"AccessControlAllowHeaders", List.of(),
|
||||
"AccessControlAllowOrigins", List.of("https://viewer.example"),
|
||||
"AccessControlAllowMethods", List.of("GET"),
|
||||
"OriginOverride", "false")));
|
||||
ResponseHeadersPolicy policy = new ResponseHeadersPolicy();
|
||||
policy.setName("custom-origin-policy-" + System.nanoTime());
|
||||
policy.setConfig(policyConfig);
|
||||
ResponseHeadersPolicy createdPolicy = cloudFrontService.createResponseHeadersPolicy(policy);
|
||||
|
||||
Origin customOrigin = new Origin();
|
||||
customOrigin.setId("custom-origin");
|
||||
customOrigin.setDomainName("127.0.0.1");
|
||||
customOrigin.setCustomOriginConfig(customOriginConfig(originServer.getAddress().getPort()));
|
||||
|
||||
DefaultCacheBehavior behavior = defaultBehavior("custom-origin");
|
||||
behavior.setResponseHeadersPolicyId(createdPolicy.getId());
|
||||
DistributionConfig config = new DistributionConfig();
|
||||
config.setEnabled(true);
|
||||
config.setOrigins(List.of(customOrigin));
|
||||
config.setDefaultCacheBehavior(behavior);
|
||||
Distribution distribution = new Distribution();
|
||||
distribution.setConfig(config);
|
||||
Distribution created = cloudFrontService.createDistribution(distribution, Map.of());
|
||||
|
||||
var response = given()
|
||||
.header("Host", created.getDomainName())
|
||||
.header("Origin", "https://viewer.example")
|
||||
.when().get("/resource")
|
||||
.then().statusCode(200)
|
||||
.extract().response();
|
||||
|
||||
assertEquals("policy-readded", response.getHeader("X-Readd"));
|
||||
assertEquals("policy-override", response.getHeader("X-Override"));
|
||||
assertEquals("origin-preserve", response.getHeader("X-Preserve"));
|
||||
assertEquals("policy-new", response.getHeader("X-New"));
|
||||
assertEquals("https://origin.example", response.getHeader("Access-Control-Allow-Origin"));
|
||||
assertNull(response.getHeader("X-Remove"));
|
||||
assertEquals("policy-hop", response.getHeader("X-Hop"));
|
||||
assertNull(response.getHeader("Connection"));
|
||||
assertEquals("max-age=31536000; includeSubDomains",
|
||||
response.getHeader("Strict-Transport-Security"));
|
||||
assertEquals("policy-server", response.getHeader("Server"));
|
||||
List<String> dateValues = response.getHeaders().getValues("Date");
|
||||
assertTrue(dateValues.contains("Thu, 02 Jan 2020 00:00:00 GMT"),
|
||||
dateValues.toString());
|
||||
assertFalse(dateValues.contains("Wed, 01 Jan 2020 00:00:00 GMT"),
|
||||
dateValues.toString());
|
||||
assertTrue(response.getHeader("Server-Timing").contains("origin;dur=5"));
|
||||
assertTrue(response.getHeader("Server-Timing").contains("cdn-cache-miss"));
|
||||
List<String> cookies = response.getHeaders().getValues("Set-Cookie");
|
||||
assertEquals(2, cookies.size());
|
||||
assertTrue(cookies.contains("session=a"), cookies.toString());
|
||||
assertTrue(cookies.contains("preference=b"), cookies.toString());
|
||||
|
||||
ResponseHeadersPolicy removeOnly = new ResponseHeadersPolicy();
|
||||
removeOnly.setName("remove-server-date-" + System.nanoTime());
|
||||
removeOnly.setConfig(Map.of("RemoveHeadersConfig", List.of("Server", "Date")));
|
||||
removeOnly = cloudFrontService.createResponseHeadersPolicy(removeOnly);
|
||||
DefaultCacheBehavior removeOnlyBehavior = defaultBehavior("custom-origin");
|
||||
removeOnlyBehavior.setResponseHeadersPolicyId(removeOnly.getId());
|
||||
DistributionConfig removeOnlyConfig = new DistributionConfig();
|
||||
removeOnlyConfig.setEnabled(true);
|
||||
removeOnlyConfig.setOrigins(List.of(customOrigin));
|
||||
removeOnlyConfig.setDefaultCacheBehavior(removeOnlyBehavior);
|
||||
Distribution removeOnlyDistribution = new Distribution();
|
||||
removeOnlyDistribution.setConfig(removeOnlyConfig);
|
||||
Distribution removeOnlyCreated =
|
||||
cloudFrontService.createDistribution(removeOnlyDistribution, Map.of());
|
||||
|
||||
var removeOnlyResponse = given()
|
||||
.header("Host", removeOnlyCreated.getDomainName())
|
||||
.when().get("/resource")
|
||||
.then().statusCode(200)
|
||||
.extract().response();
|
||||
assertEquals("CloudFront", removeOnlyResponse.getHeader("Server"));
|
||||
assertNotEquals("Wed, 01 Jan 2020 00:00:00 GMT",
|
||||
removeOnlyResponse.getHeader("Date"));
|
||||
}
|
||||
|
||||
private static void respond(HttpExchange exchange, AtomicReference<String> receivedQuery,
|
||||
AtomicReference<String> receivedPath) throws IOException {
|
||||
receivedQuery.set(exchange.getRequestURI().getRawQuery());
|
||||
@@ -120,6 +230,36 @@ class CloudFrontCustomOriginServingTest {
|
||||
exchange.close();
|
||||
}
|
||||
|
||||
private static void respondWithPolicyHeaders(HttpExchange exchange) throws IOException {
|
||||
exchange.getResponseHeaders().add("Content-Type", "text/plain");
|
||||
exchange.getResponseHeaders().add(
|
||||
"Connection", "X-Hop, Strict-Transport-Security");
|
||||
exchange.getResponseHeaders().add("X-Hop", "origin-hop-value");
|
||||
exchange.getResponseHeaders().add(
|
||||
"Strict-Transport-Security", "max-age=1");
|
||||
exchange.getResponseHeaders().add("X-Remove", "remove-me");
|
||||
exchange.getResponseHeaders().add("X-Readd", "origin-readd");
|
||||
exchange.getResponseHeaders().add("X-Override", "origin-override");
|
||||
exchange.getResponseHeaders().add("X-Preserve", "origin-preserve");
|
||||
exchange.getResponseHeaders().add("Server", "origin-server");
|
||||
exchange.getResponseHeaders().add("Date", "Wed, 01 Jan 2020 00:00:00 GMT");
|
||||
exchange.getResponseHeaders().add("Server-Timing", "origin;dur=5");
|
||||
exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "https://origin.example");
|
||||
exchange.getResponseHeaders().add("Set-Cookie", "session=a");
|
||||
exchange.getResponseHeaders().add("Set-Cookie", "preference=b");
|
||||
byte[] body = "origin-policy-body".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(200, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
exchange.close();
|
||||
}
|
||||
|
||||
private static Map<String, String> policyHeader(String name, String value, boolean override) {
|
||||
return new LinkedHashMap<>(Map.of(
|
||||
"Header", name,
|
||||
"Value", value,
|
||||
"Override", Boolean.toString(override)));
|
||||
}
|
||||
|
||||
private static Map<String, Object> customOriginConfig(int port) {
|
||||
Map<String, Object> config = new LinkedHashMap<>();
|
||||
config.put("HTTPPort", String.valueOf(port));
|
||||
|
||||
+364
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.KeyGroup;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.PublicKey;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.ResponseHeadersPolicy;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.PutObjectOptions;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
@@ -30,6 +31,7 @@ import java.util.concurrent.atomic.AtomicInteger;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -779,6 +781,361 @@ class CloudFrontDistributionServingTest {
|
||||
assertDistributionWasNotCreated(callerReference);
|
||||
}
|
||||
|
||||
@Test
|
||||
void appliesResponseHeadersPolicyToServedResponses() {
|
||||
String suffix = suffix();
|
||||
String bucket = "cf-rhp-" + suffix;
|
||||
createBucket(bucket);
|
||||
putObject(bucket, "index.html", "RHP-INDEX-" + suffix, "text/html");
|
||||
|
||||
Map<String, Object> security = new LinkedHashMap<>();
|
||||
security.put("StrictTransportSecurity", new LinkedHashMap<>(Map.of(
|
||||
"Override", "true", "AccessControlMaxAgeSec", "31536000",
|
||||
"IncludeSubdomains", "true", "Preload", "false")));
|
||||
security.put("ContentTypeOptions", new LinkedHashMap<>(Map.of("Override", "true")));
|
||||
security.put("FrameOptions", new LinkedHashMap<>(Map.of("Override", "true", "FrameOption", "DENY")));
|
||||
Map<String, Object> config = new LinkedHashMap<>();
|
||||
config.put("SecurityHeadersConfig", security);
|
||||
config.put("CustomHeadersConfig", List.of(new LinkedHashMap<>(Map.of(
|
||||
"Header", "X-App", "Value", "floci", "Override", "true"))));
|
||||
config.put("CorsConfig", new LinkedHashMap<>(Map.of(
|
||||
"AccessControlAllowCredentials", "false",
|
||||
"AccessControlAllowHeaders", List.of(),
|
||||
"AccessControlAllowMethods", List.of("GET", "HEAD"),
|
||||
"AccessControlAllowOrigins", List.of("*"),
|
||||
"OriginOverride", "true")));
|
||||
|
||||
ResponseHeadersPolicy policy = new ResponseHeadersPolicy();
|
||||
policy.setName("sec-" + suffix);
|
||||
policy.setConfig(config);
|
||||
ResponseHeadersPolicy created = cloudFrontService.createResponseHeadersPolicy(policy);
|
||||
|
||||
DefaultCacheBehavior dcb = defaultBehavior("only-origin");
|
||||
dcb.setResponseHeadersPolicyId(created.getId());
|
||||
|
||||
DistributionConfig cfg = new DistributionConfig();
|
||||
cfg.setEnabled(true);
|
||||
cfg.setDefaultRootObject("index.html");
|
||||
cfg.setOrigins(List.of(s3Origin("only-origin", bucket)));
|
||||
cfg.setDefaultCacheBehavior(dcb);
|
||||
|
||||
Distribution dist = cloudFrontService.createDistribution(distribution(cfg), Map.of());
|
||||
|
||||
given()
|
||||
.header("Host", dist.getDomainName())
|
||||
.header("Origin", "https://viewer.example")
|
||||
.when().get("/")
|
||||
.then().statusCode(200)
|
||||
.header("Strict-Transport-Security", containsString("max-age=31536000"))
|
||||
.header("X-Content-Type-Options", "nosniff")
|
||||
.header("X-Frame-Options", "DENY")
|
||||
.header("X-App", "floci")
|
||||
.header("Access-Control-Allow-Origin", "*")
|
||||
.body(containsString("RHP-INDEX-" + suffix));
|
||||
}
|
||||
|
||||
@Test
|
||||
void preservesOverridesAndRemovesS3OriginHeaders() {
|
||||
String suffix = suffix();
|
||||
String bucket = "cf-s3-headers-" + suffix;
|
||||
createBucket(bucket);
|
||||
s3Service.putObject(bucket, "index.html",
|
||||
("S3-HEADERS-" + suffix).getBytes(StandardCharsets.UTF_8),
|
||||
"text/html",
|
||||
Map.of("keep", "origin-keep", "override", "origin-override", "remove", "remove-me"),
|
||||
new PutObjectOptions()
|
||||
.withCacheControl("public, max-age=60")
|
||||
.withContentDisposition("inline"));
|
||||
|
||||
Map<String, Object> policyConfig = new LinkedHashMap<>();
|
||||
policyConfig.put("RemoveHeadersConfig", List.of("X-Amz-Meta-Remove"));
|
||||
policyConfig.put("CustomHeadersConfig", List.of(
|
||||
policyHeader("Cache-Control", "policy-cache", false),
|
||||
policyHeader("X-Amz-Meta-Override", "policy-override", true),
|
||||
policyHeader("X-New", "policy-new", false)));
|
||||
ResponseHeadersPolicy policy = new ResponseHeadersPolicy();
|
||||
policy.setName("s3-origin-headers-" + suffix);
|
||||
policy.setConfig(policyConfig);
|
||||
policy = cloudFrontService.createResponseHeadersPolicy(policy);
|
||||
|
||||
DefaultCacheBehavior behavior = defaultBehavior("only-origin");
|
||||
behavior.setResponseHeadersPolicyId(policy.getId());
|
||||
DistributionConfig config = new DistributionConfig();
|
||||
config.setEnabled(true);
|
||||
config.setDefaultRootObject("index.html");
|
||||
config.setOrigins(List.of(s3Origin("only-origin", bucket)));
|
||||
config.setDefaultCacheBehavior(behavior);
|
||||
Distribution distribution = cloudFrontService.createDistribution(distribution(config), Map.of());
|
||||
|
||||
given().header("Host", distribution.getDomainName())
|
||||
.when().get("/")
|
||||
.then().statusCode(200)
|
||||
.header("Cache-Control", equalTo("public, max-age=60"))
|
||||
.header("Content-Disposition", equalTo("inline"))
|
||||
.header("ETag", notNullValue())
|
||||
.header("Last-Modified", notNullValue())
|
||||
.header("X-Amz-Meta-Keep", equalTo("origin-keep"))
|
||||
.header("X-Amz-Meta-Override", equalTo("policy-override"))
|
||||
.header("X-Amz-Meta-Remove", nullValue())
|
||||
.header("X-New", equalTo("policy-new"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void servesCorsPreflightThroughS3AndAppliesPreflightPolicyFields() {
|
||||
String suffix = suffix();
|
||||
String bucket = "cf-preflight-" + suffix;
|
||||
createBucket(bucket);
|
||||
s3Service.putBucketCors(bucket, """
|
||||
<CORSConfiguration>
|
||||
<CORSRule>
|
||||
<AllowedOrigin>*</AllowedOrigin>
|
||||
<AllowedMethod>GET</AllowedMethod>
|
||||
<AllowedHeader>*</AllowedHeader>
|
||||
</CORSRule>
|
||||
</CORSConfiguration>
|
||||
""");
|
||||
|
||||
Map<String, Object> cors = new LinkedHashMap<>();
|
||||
cors.put("AccessControlAllowCredentials", "false");
|
||||
cors.put("AccessControlAllowHeaders", List.of("*", "Authorization"));
|
||||
cors.put("AccessControlAllowMethods", List.of("ALL"));
|
||||
cors.put("AccessControlAllowOrigins", List.of("*"));
|
||||
cors.put("AccessControlExposeHeaders", List.of("ETag"));
|
||||
cors.put("AccessControlMaxAgeSec", "600");
|
||||
cors.put("OriginOverride", "true");
|
||||
ResponseHeadersPolicy policy = new ResponseHeadersPolicy();
|
||||
policy.setName("preflight-policy-" + suffix);
|
||||
policy.setConfig(Map.of("CorsConfig", cors));
|
||||
policy = cloudFrontService.createResponseHeadersPolicy(policy);
|
||||
|
||||
DefaultCacheBehavior behavior = defaultBehavior("only-origin");
|
||||
behavior.setAllowedMethods(List.of("GET", "HEAD", "OPTIONS"));
|
||||
behavior.setResponseHeadersPolicyId(policy.getId());
|
||||
DistributionConfig config = new DistributionConfig();
|
||||
config.setEnabled(true);
|
||||
config.setOrigins(List.of(s3Origin("only-origin", bucket)));
|
||||
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("/resource")
|
||||
.then().statusCode(200)
|
||||
.header("Access-Control-Allow-Origin", equalTo("*"))
|
||||
.header("Access-Control-Allow-Methods",
|
||||
equalTo("DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT"))
|
||||
.header("Access-Control-Allow-Headers", equalTo("*, Authorization"))
|
||||
.header("Access-Control-Expose-Headers", equalTo("ETag"))
|
||||
.header("Access-Control-Max-Age", equalTo("600"));
|
||||
|
||||
given()
|
||||
.header("Host", distribution.getDomainName())
|
||||
.header("Access-Control-Request-Method", "GET")
|
||||
.when().options("/resource")
|
||||
.then().statusCode(403);
|
||||
|
||||
given()
|
||||
.header("Host", distribution.getDomainName())
|
||||
.header("Origin", "https://viewer.example")
|
||||
.when().options("/resource")
|
||||
.then().statusCode(403);
|
||||
|
||||
given()
|
||||
.header("Host", distribution.getDomainName())
|
||||
.header("Origin", "https://viewer.example")
|
||||
.header("Access-Control-Request-Method", "POST")
|
||||
.when().options("/resource")
|
||||
.then().statusCode(403);
|
||||
}
|
||||
|
||||
@Test
|
||||
void corsOriginOverrideIsGroupWideButDoesNotSuppressCustomHeaders() {
|
||||
String suffix = suffix();
|
||||
String bucket = "cf-cors-origin-override-" + suffix;
|
||||
createBucket(bucket);
|
||||
s3Service.putBucketCors(bucket, """
|
||||
<CORSConfiguration><CORSRule>
|
||||
<AllowedOrigin>*</AllowedOrigin>
|
||||
<AllowedMethod>GET</AllowedMethod>
|
||||
</CORSRule></CORSConfiguration>
|
||||
""");
|
||||
|
||||
Map<String, Object> cors = new LinkedHashMap<>();
|
||||
cors.put("AccessControlAllowCredentials", "false");
|
||||
cors.put("AccessControlAllowHeaders", List.of());
|
||||
cors.put("AccessControlAllowMethods", List.of("GET"));
|
||||
cors.put("AccessControlAllowOrigins", List.of("*"));
|
||||
cors.put("AccessControlExposeHeaders", List.of());
|
||||
cors.put("AccessControlMaxAgeSec", "600");
|
||||
cors.put("OriginOverride", "false");
|
||||
|
||||
Map<String, Object> policyConfig = new LinkedHashMap<>();
|
||||
policyConfig.put("CorsConfig", cors);
|
||||
policyConfig.put("CustomHeadersConfig", List.of(
|
||||
policyHeader("Access-Control-X-Floci", "custom", false)));
|
||||
ResponseHeadersPolicy policy = new ResponseHeadersPolicy();
|
||||
policy.setName("cors-origin-override-" + suffix);
|
||||
policy.setConfig(policyConfig);
|
||||
policy = cloudFrontService.createResponseHeadersPolicy(policy);
|
||||
|
||||
DefaultCacheBehavior behavior = defaultBehavior("only-origin");
|
||||
behavior.setAllowedMethods(List.of("GET", "HEAD", "OPTIONS"));
|
||||
behavior.setResponseHeadersPolicyId(policy.getId());
|
||||
DistributionConfig config = new DistributionConfig();
|
||||
config.setEnabled(true);
|
||||
config.setOrigins(List.of(s3Origin("only-origin", bucket)));
|
||||
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")
|
||||
.when().options("/resource")
|
||||
.then().statusCode(200)
|
||||
.header("Access-Control-Allow-Origin", equalTo("*"))
|
||||
.header("Access-Control-Max-Age", nullValue())
|
||||
.header("Access-Control-X-Floci", equalTo("custom"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsOptionsWhenTheMatchedBehaviorDoesNotAllowIt() {
|
||||
String suffix = suffix();
|
||||
String bucket = "cf-options-" + suffix;
|
||||
createBucket(bucket);
|
||||
s3Service.putBucketCors(bucket, """
|
||||
<CORSConfiguration><CORSRule>
|
||||
<AllowedOrigin>*</AllowedOrigin>
|
||||
<AllowedMethod>GET</AllowedMethod>
|
||||
</CORSRule></CORSConfiguration>
|
||||
""");
|
||||
|
||||
DefaultCacheBehavior dflt = defaultBehavior("only-origin");
|
||||
dflt.setAllowedMethods(List.of("GET", "HEAD", "OPTIONS"));
|
||||
CacheBehavior api = behavior("api/*", "only-origin");
|
||||
api.setAllowedMethods(List.of("GET", "HEAD"));
|
||||
DistributionConfig config = new DistributionConfig();
|
||||
config.setEnabled(true);
|
||||
config.setOrigins(List.of(s3Origin("only-origin", bucket)));
|
||||
config.setDefaultCacheBehavior(dflt);
|
||||
config.setCacheBehaviors(List.of(api));
|
||||
Distribution distribution = cloudFrontService.createDistribution(distribution(config), Map.of());
|
||||
|
||||
given()
|
||||
.header("Host", distribution.getDomainName())
|
||||
.header("Origin", "https://viewer.example")
|
||||
.header("Access-Control-Request-Method", "GET")
|
||||
.when().options("/api/resource")
|
||||
.then().statusCode(403)
|
||||
.body(equalTo("Invalid method."));
|
||||
|
||||
given()
|
||||
.header("Host", distribution.getDomainName())
|
||||
.header("Origin", "https://viewer.example")
|
||||
.header("Access-Control-Request-Method", "GET")
|
||||
.when().options("/resource")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void managedPreflightPoliciesEmitOnlyAllowOriginForSimpleRequests() {
|
||||
String suffix = suffix();
|
||||
String bucket = "cf-managed-cors-" + suffix;
|
||||
createBucket(bucket);
|
||||
putObject(bucket, "index.html", "MANAGED-CORS-" + suffix, "text/html");
|
||||
|
||||
for (String policyId : List.of(
|
||||
CloudFrontService.MANAGED_CORS_PREFLIGHT_POLICY_ID,
|
||||
CloudFrontService.MANAGED_CORS_PREFLIGHT_AND_SECURITY_POLICY_ID)) {
|
||||
DefaultCacheBehavior behavior = defaultBehavior("only-origin");
|
||||
behavior.setResponseHeadersPolicyId(policyId);
|
||||
DistributionConfig config = new DistributionConfig();
|
||||
config.setEnabled(true);
|
||||
config.setDefaultRootObject("index.html");
|
||||
config.setOrigins(List.of(s3Origin("only-origin", bucket)));
|
||||
config.setDefaultCacheBehavior(behavior);
|
||||
Distribution distribution =
|
||||
cloudFrontService.createDistribution(distribution(config), Map.of());
|
||||
|
||||
given()
|
||||
.header("Host", distribution.getDomainName())
|
||||
.header("Origin", "https://viewer.example")
|
||||
.when().get("/")
|
||||
.then().statusCode(200)
|
||||
.header("Access-Control-Allow-Origin", equalTo("*"))
|
||||
.header("Access-Control-Expose-Headers", nullValue())
|
||||
.header("Access-Control-Allow-Methods", nullValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void pragmaForcesServerTimingWhenSamplingRateIsZero() {
|
||||
String suffix = suffix();
|
||||
String bucket = "cf-timing-" + suffix;
|
||||
createBucket(bucket);
|
||||
putObject(bucket, "index.html", "TIMING-" + suffix, "text/html");
|
||||
|
||||
ResponseHeadersPolicy policy = new ResponseHeadersPolicy();
|
||||
policy.setName("timing-" + suffix);
|
||||
policy.setConfig(Map.of("ServerTimingHeadersConfig",
|
||||
Map.of("Enabled", "true", "SamplingRate", "0")));
|
||||
policy = cloudFrontService.createResponseHeadersPolicy(policy);
|
||||
DefaultCacheBehavior behavior = defaultBehavior("only-origin");
|
||||
behavior.setResponseHeadersPolicyId(policy.getId());
|
||||
DistributionConfig config = new DistributionConfig();
|
||||
config.setEnabled(true);
|
||||
config.setDefaultRootObject("index.html");
|
||||
config.setOrigins(List.of(s3Origin("only-origin", bucket)));
|
||||
config.setDefaultCacheBehavior(behavior);
|
||||
Distribution distribution = cloudFrontService.createDistribution(distribution(config), Map.of());
|
||||
|
||||
given()
|
||||
.header("Host", distribution.getDomainName())
|
||||
.when().get("/")
|
||||
.then().statusCode(200)
|
||||
.header("Server-Timing", nullValue());
|
||||
|
||||
given()
|
||||
.header("Host", distribution.getDomainName())
|
||||
.header("Pragma", "server-timing")
|
||||
.when().get("/")
|
||||
.then().statusCode(200)
|
||||
.header("Server-Timing", containsString("cdn-cache-miss"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listsManagedResponseHeadersPoliciesWithAwsModeledPayloadRoot() {
|
||||
String body = given()
|
||||
.queryParam("Type", "managed")
|
||||
.when().get("/2020-05-31/response-headers-policy")
|
||||
.then().statusCode(200)
|
||||
.extract().asString();
|
||||
|
||||
assertTrue(body.startsWith("<ResponseHeadersPolicyList xmlns=\""
|
||||
+ "http://cloudfront.amazonaws.com/doc/2020-05-31/\">"), body);
|
||||
assertFalse(body.contains("<ListResponseHeadersPoliciesResult"), body);
|
||||
assertTrue(body.contains("<Quantity>5</Quantity>"), body);
|
||||
assertFalse(body.contains("<NextMarker>"), body);
|
||||
assertFalse(body.contains("<Marker>"), body);
|
||||
assertFalse(body.contains("<IsTruncated>"), body);
|
||||
assertTrue(body.contains("<Type>managed</Type>"), body);
|
||||
assertTrue(body.contains("Managed-SimpleCORS"), body);
|
||||
assertFalse(body.contains("<Type>custom</Type>"), body);
|
||||
|
||||
String firstPage = given()
|
||||
.queryParam("Type", "managed")
|
||||
.queryParam("MaxItems", 1)
|
||||
.when().get("/2020-05-31/response-headers-policy")
|
||||
.then().statusCode(200)
|
||||
.extract().asString();
|
||||
assertTrue(firstPage.contains("<Quantity>1</Quantity>"), firstPage);
|
||||
assertTrue(firstPage.contains("<NextMarker>"), firstPage);
|
||||
assertFalse(firstPage.contains("<IsTruncated>"), firstPage);
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
private static String trustedKeyGroupsXml(String keyGroup) {
|
||||
@@ -879,6 +1236,13 @@ class CloudFrontDistributionServingTest {
|
||||
return cer;
|
||||
}
|
||||
|
||||
private static Map<String, String> policyHeader(String name, String value, boolean override) {
|
||||
return new LinkedHashMap<>(Map.of(
|
||||
"Header", name,
|
||||
"Value", value,
|
||||
"Override", Boolean.toString(override)));
|
||||
}
|
||||
|
||||
private static String suffix() {
|
||||
return Long.toString(System.nanoTime(), 36);
|
||||
}
|
||||
|
||||
+26
@@ -79,6 +79,32 @@ class CloudFrontManagementProtocolTest {
|
||||
.body(hasXPath("/*/*[local-name()='IsTruncated']"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void responseHeadersPolicyListRejectsNonModeledTypeCasing() {
|
||||
given()
|
||||
.queryParam("Type", "MANAGED")
|
||||
.when()
|
||||
.get(API + "response-headers-policy")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(hasXPath(
|
||||
"//*[local-name()='Code']/text()",
|
||||
equalTo("InvalidArgument")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void responseHeadersPolicyListRejectsUnknownMarker() {
|
||||
given()
|
||||
.queryParam("Marker", "missing-marker")
|
||||
.when()
|
||||
.get(API + "response-headers-policy")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(hasXPath(
|
||||
"//*[local-name()='Code']/text()",
|
||||
equalTo("InvalidArgument")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createOriginAccessControlDoesNotDefaultRequiredConfiguration() {
|
||||
String body = """
|
||||
|
||||
+36
@@ -101,6 +101,42 @@ class CloudFrontRequestRouterTest {
|
||||
assertEquals("directory-origin", CloudFrontRequestRouter.matchTargetOriginId(cfg, normalized));
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchResponseHeadersPolicyIdFollowsTheSameBehaviorOrder() {
|
||||
CacheBehavior api = behavior("api/*", "api-origin");
|
||||
api.setResponseHeadersPolicyId("api-policy");
|
||||
DefaultCacheBehavior dflt = defaultBehavior("default-origin");
|
||||
dflt.setResponseHeadersPolicyId("default-policy");
|
||||
|
||||
DistributionConfig cfg = new DistributionConfig();
|
||||
cfg.setCacheBehaviors(List.of(api));
|
||||
cfg.setDefaultCacheBehavior(dflt);
|
||||
|
||||
// A matching ordered behavior wins; otherwise the default behavior's policy applies.
|
||||
assertEquals("api-policy", CloudFrontRequestRouter.matchResponseHeadersPolicyId(cfg, "/api/data"));
|
||||
assertEquals("default-policy", CloudFrontRequestRouter.matchResponseHeadersPolicyId(cfg, "/index.html"));
|
||||
|
||||
// A behavior with no policy resolves to null (no headers applied).
|
||||
dflt.setResponseHeadersPolicyId(null);
|
||||
assertNull(CloudFrontRequestRouter.matchResponseHeadersPolicyId(cfg, "/index.html"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchAllowedMethodsUsesTheSelectedBehaviorAndDefaultsToGetHead() {
|
||||
CacheBehavior api = behavior("api/*", "api-origin");
|
||||
api.setAllowedMethods(List.of("GET", "HEAD", "OPTIONS"));
|
||||
DefaultCacheBehavior dflt = defaultBehavior("default-origin");
|
||||
|
||||
DistributionConfig cfg = new DistributionConfig();
|
||||
cfg.setCacheBehaviors(List.of(api));
|
||||
cfg.setDefaultCacheBehavior(dflt);
|
||||
|
||||
assertEquals(List.of("GET", "HEAD", "OPTIONS"),
|
||||
CloudFrontRequestRouter.matchAllowedMethods(cfg, "/api/data"));
|
||||
assertEquals(List.of("GET", "HEAD"),
|
||||
CloudFrontRequestRouter.matchAllowedMethods(cfg, "/index.html"));
|
||||
}
|
||||
|
||||
// ── Default root object: ROOT ONLY (never appended to subdirectories) ─────────
|
||||
|
||||
@Test
|
||||
|
||||
+180
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.CacheBehavior;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontOriginAccessIdentity;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
|
||||
@@ -12,17 +13,23 @@ import io.github.hectorvent.floci.services.cloudfront.model.KeyGroup;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.OriginAccessControl;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.PublicKey;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.ResponseHeadersPolicy;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.StreamingDistribution;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.spec.ECGenParameterSpec;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -524,6 +531,179 @@ class CloudFrontServiceTest {
|
||||
assertEquals(409, keyGroupError.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void exposesCanonicalManagedResponseHeadersPolicies() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
|
||||
ResponseHeadersPolicy simple = service.getResponseHeadersPolicy(
|
||||
CloudFrontService.MANAGED_SIMPLE_CORS_POLICY_ID);
|
||||
assertEquals("Managed-SimpleCORS", simple.getName());
|
||||
assertEquals("Allows all origins for simple CORS requests", simple.getComment());
|
||||
assertEquals(Instant.EPOCH, simple.getLastModifiedTime());
|
||||
assertEquals("E23ZP02F085DFQ", simple.getEtag());
|
||||
Map<String, String> simpleHeaders = policyHeaders(simple, false);
|
||||
assertEquals(Map.of("Access-Control-Allow-Origin", "*"), simpleHeaders);
|
||||
|
||||
ResponseHeadersPolicy preflight = service.getResponseHeadersPolicy(
|
||||
CloudFrontService.MANAGED_CORS_PREFLIGHT_POLICY_ID);
|
||||
Map<String, String> preflightHeaders = policyHeaders(preflight, true);
|
||||
assertEquals("GET, HEAD, PUT, POST, PATCH, DELETE, OPTIONS",
|
||||
preflightHeaders.get("Access-Control-Allow-Methods"));
|
||||
assertEquals("*", preflightHeaders.get("Access-Control-Expose-Headers"));
|
||||
assertFalse(preflightHeaders.containsKey("Access-Control-Allow-Headers"));
|
||||
assertFalse(preflightHeaders.containsKey("Access-Control-Max-Age"));
|
||||
|
||||
assertEquals(5, service.listResponseHeadersPolicies(null, 100, "managed").size());
|
||||
assertTrue(service.listResponseHeadersPolicies(null, 100, "custom").isEmpty());
|
||||
assertAws("InvalidArgument",
|
||||
() -> service.listResponseHeadersPolicies(null, 100, "unsupported"));
|
||||
assertAws("InvalidArgument",
|
||||
() -> service.listResponseHeadersPolicies(null, 100, "MANAGED"));
|
||||
assertAws("InvalidArgument",
|
||||
() -> service.listResponseHeadersPolicies("missing-marker", 100, "managed"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatesResponseHeadersPolicyReferencesBeforeDistributionMutation() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
Distribution invalidDefault = distributionWithPolicy("missing-default-policy");
|
||||
|
||||
assertAws("NoSuchResponseHeadersPolicy",
|
||||
() -> service.createDistribution(invalidDefault, Map.of()));
|
||||
assertNull(invalidDefault.getId());
|
||||
assertTrue(service.listDistributions(null, 100).isEmpty());
|
||||
|
||||
Distribution valid = distributionWithPolicy(CloudFrontService.MANAGED_SIMPLE_CORS_POLICY_ID);
|
||||
valid = service.createDistribution(valid, Map.of());
|
||||
Distribution invalidUpdate = distributionWithPolicy(null);
|
||||
CacheBehavior ordered = new CacheBehavior();
|
||||
ordered.setResponseHeadersPolicyId("missing-ordered-policy");
|
||||
invalidUpdate.getConfig().setCacheBehaviors(List.of(ordered));
|
||||
Distribution stored = valid;
|
||||
|
||||
assertAws("NoSuchResponseHeadersPolicy",
|
||||
() -> service.updateDistribution(stored.getId(), stored.getEtag(), invalidUpdate));
|
||||
assertEquals(CloudFrontService.MANAGED_SIMPLE_CORS_POLICY_ID,
|
||||
service.getDistribution(stored.getId()).getConfig()
|
||||
.getDefaultCacheBehavior().getResponseHeadersPolicyId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enforcesPolicyNameUniquenessAndManagedPolicyImmutability() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
ResponseHeadersPolicy first = service.createResponseHeadersPolicy(customPolicy("unique-name"));
|
||||
|
||||
assertAws("ResponseHeadersPolicyAlreadyExists",
|
||||
() -> service.createResponseHeadersPolicy(customPolicy("unique-name")));
|
||||
assertAws("ResponseHeadersPolicyAlreadyExists",
|
||||
() -> service.createResponseHeadersPolicy(customPolicy("Managed-SimpleCORS")));
|
||||
|
||||
ResponseHeadersPolicy managed = service.getResponseHeadersPolicy(
|
||||
CloudFrontService.MANAGED_SIMPLE_CORS_POLICY_ID);
|
||||
assertAws("IllegalUpdate", () -> service.updateResponseHeadersPolicy(
|
||||
managed.getId(), managed.getEtag(), customPolicy("replacement")));
|
||||
assertAws("IllegalDelete", () -> service.deleteResponseHeadersPolicy(
|
||||
managed.getId(), managed.getEtag()));
|
||||
|
||||
ResponseHeadersPolicy second = service.createResponseHeadersPolicy(customPolicy("second-name"));
|
||||
assertAws("ResponseHeadersPolicyAlreadyExists", () -> service.updateResponseHeadersPolicy(
|
||||
second.getId(), second.getEtag(), customPolicy(first.getName())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void preventsDeletingAReferencedResponseHeadersPolicy() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
ResponseHeadersPolicy policy = service.createResponseHeadersPolicy(customPolicy("in-use-policy"));
|
||||
Distribution distribution = service.createDistribution(
|
||||
distributionWithPolicy(policy.getId()), Map.of());
|
||||
|
||||
assertAws("ResponseHeadersPolicyInUse",
|
||||
() -> service.deleteResponseHeadersPolicy(policy.getId(), policy.getEtag()));
|
||||
|
||||
Distribution detached = distributionWithPolicy(null);
|
||||
service.updateDistribution(distribution.getId(), distribution.getEtag(), detached);
|
||||
service.deleteResponseHeadersPolicy(policy.getId(), policy.getEtag());
|
||||
assertAws("NoSuchResponseHeadersPolicy",
|
||||
() -> service.getResponseHeadersPolicy(policy.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void enforcesCustomPolicyQuotaAndStaleEtagPreconditions() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
for (int index = 0; index < 20; index++) {
|
||||
service.createResponseHeadersPolicy(customPolicy("quota-policy-" + index));
|
||||
}
|
||||
assertAws("TooManyResponseHeadersPolicies",
|
||||
() -> service.createResponseHeadersPolicy(customPolicy("quota-policy-overflow")));
|
||||
|
||||
CloudFrontService etagService = serviceWithDomainSuffix("cloudfront.net");
|
||||
ResponseHeadersPolicy policy = etagService.createResponseHeadersPolicy(
|
||||
customPolicy("etag-policy"));
|
||||
AwsException update = assertAws("PreconditionFailed",
|
||||
() -> etagService.updateResponseHeadersPolicy(
|
||||
policy.getId(), "stale-etag", customPolicy("etag-policy")));
|
||||
assertEquals(412, update.getHttpStatus());
|
||||
AwsException delete = assertAws("PreconditionFailed",
|
||||
() -> etagService.deleteResponseHeadersPolicy(policy.getId(), "stale-etag"));
|
||||
assertEquals(412, delete.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void limitsResponseHeadersPolicyToOneHundredDistributions() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
ResponseHeadersPolicy policy = service.createResponseHeadersPolicy(
|
||||
customPolicy("association-quota"));
|
||||
for (int index = 0; index < 100; index++) {
|
||||
service.createDistribution(
|
||||
distributionWithPolicy(policy.getId()), Map.of());
|
||||
}
|
||||
|
||||
AwsException overflow = assertAws(
|
||||
"TooManyDistributionsAssociatedToResponseHeadersPolicy",
|
||||
() -> service.createDistribution(
|
||||
distributionWithPolicy(policy.getId()), Map.of()));
|
||||
assertEquals(400, overflow.getHttpStatus());
|
||||
|
||||
Distribution existing = service.listDistributions(null, 100).get(0);
|
||||
assertDoesNotThrow(() -> service.updateDistribution(
|
||||
existing.getId(), existing.getEtag(),
|
||||
distributionWithPolicy(policy.getId())));
|
||||
}
|
||||
|
||||
private static Distribution distributionWithPolicy(String policyId) {
|
||||
DefaultCacheBehavior behavior = new DefaultCacheBehavior();
|
||||
behavior.setResponseHeadersPolicyId(policyId);
|
||||
DistributionConfig config = new DistributionConfig();
|
||||
config.setDefaultCacheBehavior(behavior);
|
||||
Distribution distribution = new Distribution();
|
||||
distribution.setConfig(config);
|
||||
return distribution;
|
||||
}
|
||||
|
||||
private static ResponseHeadersPolicy customPolicy(String name) {
|
||||
ResponseHeadersPolicy policy = new ResponseHeadersPolicy();
|
||||
policy.setName(name);
|
||||
policy.setConfig(Map.of());
|
||||
return policy;
|
||||
}
|
||||
|
||||
private static Map<String, String> policyHeaders(
|
||||
ResponseHeadersPolicy policy, boolean preflight) {
|
||||
return ResponseHeadersPolicyConfigCodec.directives(
|
||||
policy.getConfig(), "https://viewer.example", preflight).add().stream()
|
||||
.collect(Collectors.toMap(
|
||||
ResponseHeadersPolicyConfigCodec.PolicyHeader::name,
|
||||
ResponseHeadersPolicyConfigCodec.PolicyHeader::value,
|
||||
(left, right) -> right,
|
||||
LinkedHashMap::new));
|
||||
}
|
||||
|
||||
private static AwsException assertAws(
|
||||
String code, org.junit.jupiter.api.function.Executable action) {
|
||||
AwsException error = assertThrows(AwsException.class, action);
|
||||
assertEquals(code, error.getErrorCode());
|
||||
return error;
|
||||
}
|
||||
private static Distribution distribution(boolean enabled, List<String> aliases) {
|
||||
DistributionConfig config = new DistributionConfig();
|
||||
config.setEnabled(enabled);
|
||||
|
||||
+290
@@ -0,0 +1,290 @@
|
||||
package io.github.hectorvent.floci.services.cloudfront;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.XmlBuilder;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Unit tests for the {@link ResponseHeadersPolicyConfigCodec}: a full response-headers policy config
|
||||
* (security headers, CORS, custom headers, header removal) is parsed into the header directives the
|
||||
* serving path applies, and survives a serialize round-trip.
|
||||
*/
|
||||
class ResponseHeadersPolicyConfigCodecTest {
|
||||
|
||||
private static final String XML = """
|
||||
<ResponseHeadersPolicyConfig>
|
||||
<Name>sec</Name>
|
||||
<Comment>full config</Comment>
|
||||
<SecurityHeadersConfig>
|
||||
<XSSProtection><Override>true</Override><Protection>true</Protection><ModeBlock>true</ModeBlock></XSSProtection>
|
||||
<FrameOptions><Override>true</Override><FrameOption>DENY</FrameOption></FrameOptions>
|
||||
<ReferrerPolicy><Override>true</Override><ReferrerPolicy>same-origin</ReferrerPolicy></ReferrerPolicy>
|
||||
<ContentSecurityPolicy><Override>false</Override><ContentSecurityPolicy>default-src 'self'</ContentSecurityPolicy></ContentSecurityPolicy>
|
||||
<ContentTypeOptions><Override>true</Override></ContentTypeOptions>
|
||||
<StrictTransportSecurity><Override>true</Override><IncludeSubdomains>true</IncludeSubdomains><Preload>false</Preload><AccessControlMaxAgeSec>31536000</AccessControlMaxAgeSec></StrictTransportSecurity>
|
||||
</SecurityHeadersConfig>
|
||||
<CorsConfig>
|
||||
<AccessControlAllowOrigins><Quantity>1</Quantity><Items><Origin>*</Origin></Items></AccessControlAllowOrigins>
|
||||
<AccessControlAllowMethods><Quantity>2</Quantity><Items><Method>GET</Method><Method>HEAD</Method></Items></AccessControlAllowMethods>
|
||||
<AccessControlExposeHeaders><Quantity>1</Quantity><Items><Header>X-App</Header></Items></AccessControlExposeHeaders>
|
||||
<AccessControlAllowCredentials>false</AccessControlAllowCredentials>
|
||||
<AccessControlMaxAgeSec>600</AccessControlMaxAgeSec>
|
||||
<OriginOverride>true</OriginOverride>
|
||||
</CorsConfig>
|
||||
<CustomHeadersConfig>
|
||||
<Quantity>1</Quantity>
|
||||
<Items>
|
||||
<ResponseHeadersPolicyCustomHeader><Header>X-App</Header><Value>floci</Value><Override>true</Override></ResponseHeadersPolicyCustomHeader>
|
||||
</Items>
|
||||
</CustomHeadersConfig>
|
||||
<RemoveHeadersConfig>
|
||||
<Quantity>1</Quantity>
|
||||
<Items><ResponseHeadersPolicyRemoveHeader><Header>Server</Header></ResponseHeadersPolicyRemoveHeader></Items>
|
||||
</RemoveHeadersConfig>
|
||||
</ResponseHeadersPolicyConfig>
|
||||
""";
|
||||
|
||||
@Test
|
||||
void parsesConfigIntoResponseHeaderDirectives() {
|
||||
Map<String, String> headers = headers(ResponseHeadersPolicyConfigCodec.parse(XML));
|
||||
|
||||
assertEquals("max-age=31536000; includeSubDomains", headers.get("Strict-Transport-Security"));
|
||||
assertEquals("nosniff", headers.get("X-Content-Type-Options"));
|
||||
assertEquals("DENY", headers.get("X-Frame-Options"));
|
||||
assertEquals("same-origin", headers.get("Referrer-Policy"));
|
||||
assertEquals("default-src 'self'", headers.get("Content-Security-Policy"));
|
||||
assertEquals("1; mode=block", headers.get("X-XSS-Protection"));
|
||||
assertEquals("floci", headers.get("X-App"));
|
||||
assertEquals("*", headers.get("Access-Control-Allow-Origin"));
|
||||
assertEquals("X-App", headers.get("Access-Control-Expose-Headers"));
|
||||
assertFalse(headers.containsKey("Access-Control-Allow-Methods"));
|
||||
assertFalse(headers.containsKey("Access-Control-Max-Age"));
|
||||
// AllowCredentials=false is omitted, matching CloudFront (the header is only sent when true).
|
||||
assertFalse(headers.containsKey("Access-Control-Allow-Credentials"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void collidingMaxAgeFieldsStayInTheirOwnBlocks() {
|
||||
// AccessControlMaxAgeSec appears under both StrictTransportSecurity and CorsConfig; a flat
|
||||
// parse would conflate them. Structure-aware parsing keeps HSTS at 31536000 and CORS at 600.
|
||||
Map<String, String> headers = headers(
|
||||
ResponseHeadersPolicyConfigCodec.parse(XML), "https://a.example", true);
|
||||
assertTrue(headers.get("Strict-Transport-Security").contains("31536000"));
|
||||
assertEquals("600", headers.get("Access-Control-Max-Age"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void removeHeadersConfigIsCaptured() {
|
||||
var directives = ResponseHeadersPolicyConfigCodec.directives(
|
||||
ResponseHeadersPolicyConfigCodec.parse(XML));
|
||||
assertEquals(List.of("Server"), directives.remove());
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowOriginIsASingleValueNotACommaJoinedList() {
|
||||
// Access-Control-Allow-Origin must be a single origin (or "*"); joining multiple configured
|
||||
// origins with a comma would be an invalid header value.
|
||||
String xml = """
|
||||
<ResponseHeadersPolicyConfig><Name>multi</Name><CorsConfig>
|
||||
<AccessControlAllowOrigins><Quantity>2</Quantity><Items>
|
||||
<Origin>https://a.example</Origin><Origin>https://b.example</Origin>
|
||||
</Items></AccessControlAllowOrigins>
|
||||
<OriginOverride>true</OriginOverride>
|
||||
</CorsConfig></ResponseHeadersPolicyConfig>
|
||||
""";
|
||||
String value = headers(ResponseHeadersPolicyConfigCodec.parse(xml)).get("Access-Control-Allow-Origin");
|
||||
assertEquals("https://a.example", value);
|
||||
assertFalse(value.contains(","), value);
|
||||
}
|
||||
|
||||
@Test
|
||||
void corsHeadersEchoTheMatchingViewerOriginAndOmitUnmatchedRequests() {
|
||||
Map<String, Object> config = ResponseHeadersPolicyConfigCodec.parse("""
|
||||
<ResponseHeadersPolicyConfig><CorsConfig>
|
||||
<AccessControlAllowOrigins><Quantity>2</Quantity><Items>
|
||||
<Origin>https://*.example.org</Origin><Origin>https://exact.test:8443</Origin>
|
||||
</Items></AccessControlAllowOrigins>
|
||||
<AccessControlAllowMethods><Quantity>1</Quantity><Items><Method>GET</Method></Items></AccessControlAllowMethods>
|
||||
<OriginOverride>true</OriginOverride>
|
||||
</CorsConfig></ResponseHeadersPolicyConfig>
|
||||
""");
|
||||
|
||||
Map<String, String> matching = headers(config, "https://api.example.org", true);
|
||||
assertEquals("https://api.example.org", matching.get("Access-Control-Allow-Origin"));
|
||||
assertEquals("GET", matching.get("Access-Control-Allow-Methods"));
|
||||
|
||||
Map<String, String> unmatched = headers(config, "https://attacker.example.com");
|
||||
assertFalse(unmatched.containsKey("Access-Control-Allow-Origin"));
|
||||
assertFalse(unmatched.containsKey("Access-Control-Allow-Methods"));
|
||||
assertTrue(headers(config, null).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void preflightResponsesIncludeAllowListsAndMaxAge() {
|
||||
Map<String, String> headers = headers(
|
||||
ResponseHeadersPolicyConfigCodec.parse(XML), "https://a.example", true);
|
||||
|
||||
assertEquals("GET, HEAD", headers.get("Access-Control-Allow-Methods"));
|
||||
assertEquals("600", headers.get("Access-Control-Max-Age"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void preflightExpandsAllMethodsAndPreservesAuthorizationAlongsideWildcard() {
|
||||
Map<String, Object> cors = new LinkedHashMap<>();
|
||||
cors.put("AccessControlAllowOrigins", List.of("*"));
|
||||
cors.put("AccessControlAllowMethods", List.of("ALL"));
|
||||
cors.put("AccessControlAllowHeaders", List.of("*", "Authorization"));
|
||||
cors.put("AccessControlAllowCredentials", "false");
|
||||
cors.put("OriginOverride", "true");
|
||||
|
||||
Map<String, String> result = headers(
|
||||
Map.of("CorsConfig", cors), "https://viewer.example", true);
|
||||
|
||||
assertEquals("DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT",
|
||||
result.get("Access-Control-Allow-Methods"));
|
||||
assertEquals("*, Authorization", result.get("Access-Control-Allow-Headers"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void managedPreflightPolicyExposesHeadersOnlyOnPreflightRequests() {
|
||||
Map<String, Object> cors = new LinkedHashMap<>();
|
||||
cors.put("AccessControlAllowOrigins", List.of("*"));
|
||||
cors.put("AccessControlAllowMethods", List.of("GET", "HEAD", "OPTIONS"));
|
||||
cors.put("AccessControlExposeHeaders", List.of("*"));
|
||||
cors.put("OriginOverride", "false");
|
||||
Map<String, Object> config = Map.of("CorsConfig", cors);
|
||||
|
||||
var simple = ResponseHeadersPolicyConfigCodec.directives(
|
||||
config, "https://viewer.example", false, true, null);
|
||||
Map<String, String> simpleHeaders = simple.add().stream().collect(
|
||||
java.util.stream.Collectors.toMap(
|
||||
ResponseHeadersPolicyConfigCodec.PolicyHeader::name,
|
||||
ResponseHeadersPolicyConfigCodec.PolicyHeader::value));
|
||||
assertEquals(Map.of("Access-Control-Allow-Origin", "*"), simpleHeaders);
|
||||
|
||||
var preflight = ResponseHeadersPolicyConfigCodec.directives(
|
||||
config, "https://viewer.example", true, true, null);
|
||||
Map<String, String> preflightHeaders = preflight.add().stream().collect(
|
||||
java.util.stream.Collectors.toMap(
|
||||
ResponseHeadersPolicyConfigCodec.PolicyHeader::name,
|
||||
ResponseHeadersPolicyConfigCodec.PolicyHeader::value));
|
||||
assertEquals("*", preflightHeaders.get("Access-Control-Allow-Origin"));
|
||||
assertEquals("*", preflightHeaders.get("Access-Control-Expose-Headers"));
|
||||
assertEquals("GET, HEAD, OPTIONS",
|
||||
preflightHeaders.get("Access-Control-Allow-Methods"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void serverTimingSamplingAndPragmaFollowCloudFrontRules() {
|
||||
Map<String, Object> sampled = Map.of("ServerTimingHeadersConfig",
|
||||
Map.of("Enabled", "true", "SamplingRate", "100"));
|
||||
Map<String, Object> unsampled = Map.of("ServerTimingHeadersConfig",
|
||||
Map.of("Enabled", "true", "SamplingRate", "0"));
|
||||
Map<String, Object> disabled = Map.of("ServerTimingHeadersConfig",
|
||||
Map.of("Enabled", "false", "SamplingRate", "100"));
|
||||
|
||||
assertTrue(ResponseHeadersPolicyConfigCodec.directives(
|
||||
sampled, null, false, false, null).serverTiming());
|
||||
assertFalse(ResponseHeadersPolicyConfigCodec.directives(
|
||||
unsampled, null, false, false, null).serverTiming());
|
||||
assertTrue(ResponseHeadersPolicyConfigCodec.directives(
|
||||
unsampled, null, false, false,
|
||||
"other-token, Server-Timing").serverTiming());
|
||||
assertFalse(ResponseHeadersPolicyConfigCodec.directives(
|
||||
disabled, null, false, false,
|
||||
"server-timing").serverTiming());
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedOrMissingPolicyConfigIsRejected() {
|
||||
AwsException malformed = assertThrows(AwsException.class,
|
||||
() -> ResponseHeadersPolicyConfigCodec.parse(
|
||||
"<ResponseHeadersPolicyConfig><Name>broken</ResponseHeadersPolicyConfig>"));
|
||||
assertEquals("InvalidArgument", malformed.getErrorCode());
|
||||
|
||||
AwsException missing = assertThrows(AwsException.class,
|
||||
() -> ResponseHeadersPolicyConfigCodec.parse("<OtherConfig/>"));
|
||||
assertEquals("InvalidArgument", missing.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMissingAndInconsistentListQuantities() {
|
||||
AwsException inconsistent = assertThrows(AwsException.class,
|
||||
() -> ResponseHeadersPolicyConfigCodec.parse("""
|
||||
<ResponseHeadersPolicyConfig><CorsConfig>
|
||||
<AccessControlAllowOrigins><Quantity>2</Quantity><Items>
|
||||
<Origin>*</Origin>
|
||||
</Items></AccessControlAllowOrigins>
|
||||
</CorsConfig></ResponseHeadersPolicyConfig>
|
||||
"""));
|
||||
assertEquals("InconsistentQuantities", inconsistent.getErrorCode());
|
||||
|
||||
AwsException missing = assertThrows(AwsException.class,
|
||||
() -> ResponseHeadersPolicyConfigCodec.parse("""
|
||||
<ResponseHeadersPolicyConfig><RemoveHeadersConfig>
|
||||
<Items><ResponseHeadersPolicyRemoveHeader>
|
||||
<Header>Server</Header>
|
||||
</ResponseHeadersPolicyRemoveHeader></Items>
|
||||
</RemoveHeadersConfig></ResponseHeadersPolicyConfig>
|
||||
"""));
|
||||
assertEquals("InvalidArgument", missing.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void originWildcardMatchingFollowsCloudFrontSchemeHostAndPortRules() {
|
||||
assertTrue(ResponseHeadersPolicyConfigCodec.originMatches(
|
||||
"http://*.example.org", "http://www.example.org"));
|
||||
assertFalse(ResponseHeadersPolicyConfigCodec.originMatches(
|
||||
"http://*.example.org", "https://www.example.org"));
|
||||
assertFalse(ResponseHeadersPolicyConfigCodec.originMatches(
|
||||
"http://*.example.org", "http://www.example.org:123"));
|
||||
assertTrue(ResponseHeadersPolicyConfigCodec.originMatches(
|
||||
"example.org", "https://example.org"));
|
||||
assertTrue(ResponseHeadersPolicyConfigCodec.originMatches(
|
||||
"http://example.org:*", "http://example.org"));
|
||||
assertTrue(ResponseHeadersPolicyConfigCodec.originMatches(
|
||||
"http://example.org:1*3", "http://example.org:1893"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void serializedConfigRoundTripsToTheSameHeaders() {
|
||||
Map<String, Object> config = ResponseHeadersPolicyConfigCodec.parse(XML);
|
||||
XmlBuilder xml = new XmlBuilder().start("ResponseHeadersPolicyConfig");
|
||||
ResponseHeadersPolicyConfigCodec.serialize(xml, config);
|
||||
String out = xml.end("ResponseHeadersPolicyConfig").build();
|
||||
|
||||
assertTrue(out.contains("<FrameOption>DENY</FrameOption>"), out);
|
||||
assertTrue(out.contains("<ResponseHeadersPolicyCustomHeader>"), out);
|
||||
assertTrue(out.contains("<Origin>*</Origin>"), out);
|
||||
|
||||
assertEquals(headers(config), headers(ResponseHeadersPolicyConfigCodec.parse(out)));
|
||||
}
|
||||
|
||||
private static Map<String, String> headers(Map<String, Object> config) {
|
||||
return headers(config, "https://a.example");
|
||||
}
|
||||
|
||||
private static Map<String, String> headers(Map<String, Object> config, String viewerOrigin) {
|
||||
return headers(config, viewerOrigin, false);
|
||||
}
|
||||
|
||||
private static Map<String, String> headers(Map<String, Object> config, String viewerOrigin,
|
||||
boolean preflightRequest) {
|
||||
Map<String, String> map = new LinkedHashMap<>();
|
||||
for (ResponseHeadersPolicyConfigCodec.PolicyHeader h
|
||||
: ResponseHeadersPolicyConfigCodec.directives(
|
||||
config, viewerOrigin, preflightRequest).add()) {
|
||||
map.put(h.name(), h.value());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
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 org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class ResponseHeadersPolicyValidatorTest {
|
||||
|
||||
@Test
|
||||
void acceptsCompleteCorsSecurityAndServerTimingConfiguration() {
|
||||
Map<String, Object> config = new LinkedHashMap<>();
|
||||
config.put("CorsConfig", validCors());
|
||||
config.put("SecurityHeadersConfig", Map.of(
|
||||
"StrictTransportSecurity", Map.of(
|
||||
"AccessControlMaxAgeSec", "31536000",
|
||||
"IncludeSubdomains", "true",
|
||||
"Preload", "false",
|
||||
"Override", "true"),
|
||||
"FrameOptions", Map.of("FrameOption", "DENY", "Override", "true"),
|
||||
"ReferrerPolicy", Map.of(
|
||||
"ReferrerPolicy", "same-origin", "Override", "true"),
|
||||
"ContentTypeOptions", Map.of("Override", "true"),
|
||||
"XSSProtection", Map.of(
|
||||
"Protection", "true", "ModeBlock", "true", "Override", "true")));
|
||||
config.put("ServerTimingHeadersConfig", Map.of("Enabled", "true"));
|
||||
|
||||
assertDoesNotThrow(() -> ResponseHeadersPolicyValidator.validate(policy("valid-policy", config)));
|
||||
assertDoesNotThrow(() -> ResponseHeadersPolicyValidator.validate(policy(
|
||||
"optional-hsts-flags", Map.of("SecurityHeadersConfig", Map.of(
|
||||
"StrictTransportSecurity", Map.of(
|
||||
"AccessControlMaxAgeSec", "31536000", "Override", "false"))))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMissingCorsFieldsAndInvalidMethods() {
|
||||
Map<String, Object> missing = new LinkedHashMap<>();
|
||||
missing.put("AccessControlAllowOrigins", List.of("*"));
|
||||
missing.put("AccessControlAllowMethods", List.of("GET"));
|
||||
missing.put("AccessControlAllowCredentials", "false");
|
||||
missing.put("OriginOverride", "false");
|
||||
|
||||
assertError("InvalidArgument", policy("missing-cors-field", Map.of("CorsConfig", missing)));
|
||||
|
||||
Map<String, Object> invalidMethod = validCors();
|
||||
invalidMethod.put("AccessControlAllowMethods", List.of("TRACE"));
|
||||
assertError("InvalidArgument",
|
||||
policy("invalid-cors-method", Map.of("CorsConfig", invalidMethod)));
|
||||
|
||||
Map<String, Object> lowercaseMethod = validCors();
|
||||
lowercaseMethod.put("AccessControlAllowMethods", List.of("get"));
|
||||
assertError("InvalidArgument",
|
||||
policy("lowercase-cors-method", Map.of("CorsConfig", lowercaseMethod)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsOneEmbeddedWildcardInCorsAllowHeaderPatterns() {
|
||||
assertDoesNotThrow(() -> ResponseHeadersPolicyValidator.validate(policy(
|
||||
"allow-header-wildcard",
|
||||
Map.of("CorsConfig", corsWith(
|
||||
"AccessControlAllowHeaders",
|
||||
List.of("x-amz-*", "x-*-amz", "Authorization"))))));
|
||||
|
||||
assertError("InvalidArgument", policy(
|
||||
"multiple-allow-header-wildcards",
|
||||
Map.of("CorsConfig", corsWith(
|
||||
"AccessControlAllowHeaders",
|
||||
List.of("x-*-amz-*")))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsWildcardAllowHeadersWhenCredentialsAreAllowed() {
|
||||
Map<String, Object> exactWildcard = validCors();
|
||||
exactWildcard.put("AccessControlAllowCredentials", "true");
|
||||
exactWildcard.put("AccessControlAllowHeaders", List.of("*"));
|
||||
assertError("InvalidArgument", policy(
|
||||
"credentialed-exact-wildcard", Map.of("CorsConfig", exactWildcard)));
|
||||
|
||||
Map<String, Object> embeddedWildcard = validCors();
|
||||
embeddedWildcard.put("AccessControlAllowCredentials", "true");
|
||||
embeddedWildcard.put("AccessControlAllowHeaders", List.of("x-amz-*"));
|
||||
assertError("InvalidArgument", policy(
|
||||
"credentialed-embedded-wildcard", Map.of("CorsConfig", embeddedWildcard)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsUnsafeDuplicateAndForbiddenHeaders() {
|
||||
assertError("InvalidArgument", policy("unsafe-header", Map.of(
|
||||
"CustomHeadersConfig", List.of(Map.of(
|
||||
"Header", "X-Test", "Value", "safe\r\nInjected: true", "Override", "true")))));
|
||||
|
||||
assertError("InvalidArgument", policy("duplicate-header", Map.of(
|
||||
"CustomHeadersConfig", List.of(
|
||||
Map.of("Header", "X-Test", "Value", "a", "Override", "true"),
|
||||
Map.of("Header", "x-test", "Value", "b", "Override", "false")))));
|
||||
|
||||
assertError("InvalidArgument", policy("forbidden-removal", Map.of(
|
||||
"RemoveHeadersConfig", List.of("Content-Encoding"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void enforcesHeaderCountAndCspLengthSpecificErrors() {
|
||||
List<Map<String, String>> custom = IntStream.range(0, 11)
|
||||
.mapToObj(index -> Map.of(
|
||||
"Header", "X-Test-" + index,
|
||||
"Value", "value",
|
||||
"Override", "true"))
|
||||
.toList();
|
||||
assertError("TooManyCustomHeadersInResponseHeadersPolicy",
|
||||
policy("too-many-custom", Map.of("CustomHeadersConfig", custom)));
|
||||
|
||||
ResponseHeadersPolicy tooLongCsp = policy("too-long-csp", Map.of(
|
||||
"SecurityHeadersConfig", Map.of(
|
||||
"ContentSecurityPolicy", Map.of(
|
||||
"ContentSecurityPolicy", "a".repeat(1_784),
|
||||
"Override", "true"))));
|
||||
assertError("TooLongCSPInResponseHeadersPolicy", tooLongCsp);
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatesPolicyMetadataAndSecurityEnums() {
|
||||
assertError("InvalidArgument", policy("spaces are invalid", Map.of()));
|
||||
assertError("InvalidArgument", policy("bad-frame", Map.of(
|
||||
"SecurityHeadersConfig", Map.of(
|
||||
"FrameOptions", Map.of("FrameOption", "ALLOW", "Override", "true")))));
|
||||
assertError("InvalidArgument", policy("lowercase-frame", Map.of(
|
||||
"SecurityHeadersConfig", Map.of(
|
||||
"FrameOptions", Map.of("FrameOption", "deny", "Override", "true")))));
|
||||
assertError("InvalidArgument", policy("invalid-origin", Map.of(
|
||||
"CorsConfig", corsWith("AccessControlAllowOrigins", List.of("example.*")))));
|
||||
assertError("InvalidArgument", policy("invalid-expose-wildcard", Map.of(
|
||||
"CorsConfig", corsWith("AccessControlExposeHeaders", List.of("X-*")))));
|
||||
assertError("InvalidArgument", policy("sampling-precision", Map.of(
|
||||
"ServerTimingHeadersConfig", Map.of(
|
||||
"Enabled", "true", "SamplingRate", "12.34567"))));
|
||||
assertError("InvalidArgument", policy("max-age-overflow", Map.of(
|
||||
"CorsConfig", corsWith(
|
||||
"AccessControlMaxAgeSec", Long.toString((long) Integer.MAX_VALUE + 1)))));
|
||||
}
|
||||
|
||||
private static Map<String, Object> validCors() {
|
||||
Map<String, Object> cors = new LinkedHashMap<>();
|
||||
cors.put("AccessControlAllowCredentials", "false");
|
||||
cors.put("AccessControlAllowHeaders", List.of("*", "Authorization"));
|
||||
cors.put("AccessControlAllowMethods", List.of("GET", "HEAD", "OPTIONS"));
|
||||
cors.put("AccessControlAllowOrigins", List.of("https://*.example.com"));
|
||||
cors.put("AccessControlExposeHeaders", List.of("ETag"));
|
||||
cors.put("AccessControlMaxAgeSec", "600");
|
||||
cors.put("OriginOverride", "true");
|
||||
return cors;
|
||||
}
|
||||
|
||||
private static Map<String, Object> corsWith(String field, Object value) {
|
||||
Map<String, Object> cors = validCors();
|
||||
cors.put(field, value);
|
||||
return cors;
|
||||
}
|
||||
|
||||
private static ResponseHeadersPolicy policy(String name, Map<String, Object> config) {
|
||||
ResponseHeadersPolicy policy = new ResponseHeadersPolicy();
|
||||
policy.setName(name);
|
||||
policy.setConfig(config);
|
||||
return policy;
|
||||
}
|
||||
|
||||
private static void assertError(String expectedCode, ResponseHeadersPolicy policy) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> ResponseHeadersPolicyValidator.validate(policy));
|
||||
assertEquals(expectedCode, error.getErrorCode());
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -120,7 +120,8 @@ class KinesisIntegrationTest {
|
||||
.path("StreamDescription")
|
||||
.path("StreamCreationTimestamp");
|
||||
assertTrue(timestampNode.isNumber());
|
||||
assertEquals(timestamp, timestampNode.decimalValue());
|
||||
assertEquals(0, timestamp.compareTo(timestampNode.decimalValue()),
|
||||
"serialized timestamp must preserve the numeric value");
|
||||
assertFalse(timestampLexeme.contains("E"));
|
||||
assertFalse(timestampLexeme.contains("e"));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user