diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml index b91b7c3e7f..48dfb434ca 100644 --- a/compatibility-tests/sdk-test-java/pom.xml +++ b/compatibility-tests/sdk-test-java/pom.xml @@ -326,6 +326,10 @@ software.amazon.awssdk cloudformation + + software.amazon.awssdk + cloudfront + software.amazon.awssdk diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java index c894a2406c..0eea320471 100644 --- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java +++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java @@ -4,6 +4,7 @@ import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudfront.CloudFrontClient; import software.amazon.awssdk.services.cloudtrail.CloudTrailClient; import software.amazon.awssdk.services.cloudwatch.CloudWatchClient; import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; @@ -528,6 +529,14 @@ public final class TestFixtures { .build(); } + public static CloudFrontClient cloudFrontClient() { + return CloudFrontClient.builder() + .endpointOverride(ENDPOINT) + .region(REGION) + .credentialsProvider(CREDENTIALS) + .build(); + } + public static EventBridgeClient eventBridgeClient() { return EventBridgeClient.builder() .endpointOverride(ENDPOINT) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFrontTrustedKeyGroupsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFrontTrustedKeyGroupsTest.java new file mode 100644 index 0000000000..68bb202f61 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFrontTrustedKeyGroupsTest.java @@ -0,0 +1,193 @@ +package com.floci.test; + +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.cloudfront.CloudFrontClient; +import software.amazon.awssdk.services.cloudfront.model.CreateDistributionResponse; +import software.amazon.awssdk.services.cloudfront.model.CreateKeyGroupResponse; +import software.amazon.awssdk.services.cloudfront.model.CreatePublicKeyResponse; +import software.amazon.awssdk.services.cloudfront.model.DistributionConfig; +import software.amazon.awssdk.services.cloudfront.model.GetDistributionConfigResponse; +import software.amazon.awssdk.services.cloudfront.model.GetDistributionResponse; +import software.amazon.awssdk.services.cloudfront.model.S3OriginConfig; +import software.amazon.awssdk.services.cloudfront.model.ViewerProtocolPolicy; + +import java.security.KeyPairGenerator; +import java.util.Base64; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +class CloudFrontTrustedKeyGroupsTest { + + @Test + void roundTripsTrustedKeyGroupsWithTheAwsSdk() throws Exception { + assumeFalse( + TestFixtures.isRealAws(), + "The immediate distribution lifecycle in this test is emulator-specific"); + + String suffix = TestFixtures.uniqueName("cloudfront-trust"); + String publicKeyId = null; + String publicKeyEtag = null; + String keyGroupId = null; + String keyGroupEtag = null; + String distributionId = null; + String encodedPublicKey = rsaPublicKeyPem(); + + try (CloudFrontClient cloudFront = TestFixtures.cloudFrontClient()) { + CreatePublicKeyResponse publicKey = cloudFront.createPublicKey( + request -> request.publicKeyConfig(config -> config + .callerReference("key-reference-" + suffix) + .name("key-" + suffix) + .encodedKey(encodedPublicKey))); + String createdPublicKeyId = publicKey.publicKey().id(); + publicKeyId = createdPublicKeyId; + publicKeyEtag = publicKey.eTag(); + + CreateKeyGroupResponse keyGroup = cloudFront.createKeyGroup( + request -> request.keyGroupConfig(config -> config + .name("group-" + suffix) + .items(createdPublicKeyId))); + String createdKeyGroupId = keyGroup.keyGroup().id(); + keyGroupId = createdKeyGroupId; + keyGroupEtag = keyGroup.eTag(); + assertEquals( + List.of(createdPublicKeyId), + keyGroup.keyGroup().keyGroupConfig().items()); + assertEquals( + List.of(createdPublicKeyId), + cloudFront.getKeyGroupConfig( + request -> request.id(createdKeyGroupId)) + .keyGroupConfig() + .items()); + var listedKeyGroup = + cloudFront.listKeyGroups(request -> request.maxItems("100")) + .keyGroupList() + .items() + .stream() + .map(summary -> summary.keyGroup()) + .filter(group -> createdKeyGroupId.equals(group.id())) + .findFirst() + .orElseThrow(); + assertEquals( + List.of(createdPublicKeyId), + listedKeyGroup.keyGroupConfig().items()); + + DistributionConfig configuration = DistributionConfig.builder() + .callerReference("distribution-reference-" + suffix) + .enabled(true) + .origins(origins -> origins + .quantity(1) + .items(origin -> origin + .id("origin") + .domainName( + "signed-content.s3.amazonaws.com") + .s3OriginConfig( + S3OriginConfig.builder() + .originAccessIdentity("") + .build()))) + .defaultCacheBehavior(behavior -> behavior + .targetOriginId("origin") + .viewerProtocolPolicy( + ViewerProtocolPolicy.ALLOW_ALL) + .trustedKeyGroups(groups -> groups + .enabled(true) + .quantity(1) + .items(createdKeyGroupId))) + .build(); + + CreateDistributionResponse created = + cloudFront.createDistribution( + request -> request.distributionConfig(configuration)); + String createdDistributionId = created.distribution().id(); + distributionId = createdDistributionId; + + GetDistributionResponse fetched = + cloudFront.getDistribution( + request -> request.id(createdDistributionId)); + assertTrue(fetched.distribution() + .activeTrustedKeyGroups().enabled()); + assertEquals( + keyGroupId, + fetched.distribution() + .activeTrustedKeyGroups() + .items() + .get(0) + .keyGroupId()); + assertEquals( + publicKeyId, + fetched.distribution() + .activeTrustedKeyGroups() + .items() + .get(0) + .keyPairIds() + .items() + .get(0)); + assertFalse(fetched.distribution() + .activeTrustedSigners().enabled()); + + GetDistributionConfigResponse fetchedConfig = + cloudFront.getDistributionConfig( + request -> request.id(createdDistributionId)); + assertEquals( + keyGroupId, + fetchedConfig.distributionConfig() + .defaultCacheBehavior() + .trustedKeyGroups() + .items() + .get(0)); + } finally { + try (CloudFrontClient cloudFront = + TestFixtures.cloudFrontClient()) { + if (distributionId != null) { + String id = distributionId; + GetDistributionConfigResponse current = + cloudFront.getDistributionConfig( + request -> request.id(id)); + var disabled = current.distributionConfig() + .toBuilder() + .enabled(false) + .build(); + var updated = cloudFront.updateDistribution( + request -> request + .id(id) + .ifMatch(current.eTag()) + .distributionConfig(disabled)); + cloudFront.deleteDistribution( + request -> request + .id(id) + .ifMatch(updated.eTag())); + } + if (keyGroupId != null) { + String id = keyGroupId; + String etag = keyGroupEtag; + cloudFront.deleteKeyGroup( + request -> request + .id(id) + .ifMatch(etag)); + } + if (publicKeyId != null) { + String id = publicKeyId; + String etag = publicKeyEtag; + cloudFront.deletePublicKey( + request -> request + .id(id) + .ifMatch(etag)); + } + } + } + } + + private static String rsaPublicKeyPem() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + byte[] encoded = generator.generateKeyPair() + .getPublic() + .getEncoded(); + return "-----BEGIN PUBLIC KEY-----\n" + + Base64.getMimeEncoder().encodeToString(encoded) + + "\n-----END PUBLIC KEY-----"; + } +} diff --git a/docs/services/cloudfront.md b/docs/services/cloudfront.md index 1ee7129ad6..12146a7ebe 100644 --- a/docs/services/cloudfront.md +++ b/docs/services/cloudfront.md @@ -1,6 +1,6 @@ # 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, 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 delivery from S3 or custom origins. **Protocol:** REST XML **API version:** `2020-05-31` @@ -97,6 +97,23 @@ CloudFront management-plane and local content-delivery emulation. Supports distr | `DeleteFunction` | DELETE | `/2020-05-31/function/{Name}` | | `ListFunctions` | GET | `/2020-05-31/function` | +### Public Keys and Key Groups + +| Operation | Method | Path | +|---|---|---| +| `CreatePublicKey` | POST | `/2020-05-31/public-key` | +| `GetPublicKey` | GET | `/2020-05-31/public-key/{Id}` | +| `GetPublicKeyConfig` | GET | `/2020-05-31/public-key/{Id}/config` | +| `UpdatePublicKey` | PUT | `/2020-05-31/public-key/{Id}/config` | +| `DeletePublicKey` | DELETE | `/2020-05-31/public-key/{Id}` | +| `ListPublicKeys` | GET | `/2020-05-31/public-key` | +| `CreateKeyGroup` | POST | `/2020-05-31/key-group` | +| `GetKeyGroup` | GET | `/2020-05-31/key-group/{Id}` | +| `GetKeyGroupConfig` | GET | `/2020-05-31/key-group/{Id}/config` | +| `UpdateKeyGroup` | PUT | `/2020-05-31/key-group/{Id}` | +| `DeleteKeyGroup` | DELETE | `/2020-05-31/key-group/{Id}` | +| `ListKeyGroups` | GET | `/2020-05-31/key-group` | + ### Tagging | Operation | Method | Path | @@ -113,7 +130,10 @@ CloudFront management-plane and local content-delivery emulation. Supports distr - ARNs are global — no region segment: `arn:aws:cloudfront::{accountId}:distribution/{id}`. - 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`. A missing or incorrect `ETag` returns `InvalidIfMatchVersion` (400). +- 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 + (`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. - List operations emit the payload root declared by the CloudFront REST XML model (for example, `ListDistributions` returns ``), with list contents represented by @@ -125,6 +145,19 @@ CloudFront management-plane and local content-delivery emulation. Supports distr - 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. +- 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 + keys. Custom policies enforce resource wildcards, expiration, optional activation time, and + IPv4 CIDR restrictions. Canned resources compare literally, including query strings. Exact custom + resources can include one raw query delimiter. As a conservative limitation, other custom + resources containing a raw `?` fail closed because the character is ambiguous with CloudFront's + one-character wildcard; custom query-string wildcards are therefore not supported. Invalid or + expired signatures return 403. +- A key group must contain one to five existing public keys. Public keys that belong to a key group + and key groups referenced by a cache behavior cannot be deleted until those references are removed. +- Application query parameters are retained when constructing the resource covered by a signature. + CloudFront signing parameters are excluded from that resource and are never sent to the origin. - S3-origin reads honor anonymous access, OAI bucket-policy or object-ACL grants, and OAC service-principal bucket-policy grants (including the distribution `AWS:SourceArn`) when strict S3 authentication is enabled. OAC `always`, `never`, and unsigned `no-override` requests follow their @@ -233,9 +266,8 @@ aws cloudfront delete-distribution --id E1Z2X3C4V5B6N7 --if-match "$ETAG" - `CopyDistribution` (staging distributions) - Real-time log configs (`CreateRealtimeLogConfig`, etc.) - Field-level encryption (`CreateFieldLevelEncryptionConfig`, etc.) -- Public keys and key groups (`CreatePublicKey`, `CreateKeyGroup`, etc.) - `TestFunction` execution (function is stored, not executed) - Streaming distributions (RTMP — deprecated by AWS) - VPC origins, Anycast IP lists, key value stores - Monitoring subscriptions -- Actual CDN content delivery and caching +- Persistent edge caching and global CDN propagation diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java index b284493190..11b7bf885d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java @@ -5791,6 +5791,10 @@ public class CloudFormationResourceProvisioner { if (node != null && !node.isMissingNode() && !node.isNull()) { dcb.setTargetOriginId(cfnText(node, "TargetOriginId", engine)); dcb.setViewerProtocolPolicy(cfnTextOrDefault(node, "ViewerProtocolPolicy", engine, "allow-all")); + List trustedKeyGroups = cfnStringList(node.path("TrustedKeyGroups"), engine); + if (!trustedKeyGroups.isEmpty()) { + dcb.setTrustedKeyGroups(trustedKeyGroups); + } } return dcb; } @@ -5804,6 +5808,10 @@ public class CloudFormationResourceProvisioner { cb.setPathPattern(cfnText(node, "PathPattern", engine)); cb.setTargetOriginId(cfnText(node, "TargetOriginId", engine)); cb.setViewerProtocolPolicy(cfnTextOrDefault(node, "ViewerProtocolPolicy", engine, "allow-all")); + List trustedKeyGroups = cfnStringList(node.path("TrustedKeyGroups"), engine); + if (!trustedKeyGroups.isEmpty()) { + cb.setTrustedKeyGroups(trustedKeyGroups); + } behaviors.add(cb); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java index 9a4220a708..77f3517899 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontController.java @@ -1245,8 +1245,7 @@ public class CloudFrontController { .start("KeyGroupConfig", NS) .elem("Name", group.getName() != null ? group.getName() : "") .elem("Comment", group.getComment() != null ? group.getComment() : "") - .raw(xmlQuantityItems("Items", "PublicKey", items.size(), - items.stream().map(k -> "" + XmlBuilder.escape(k) + "").toList())) + .raw(xmlDirectItems("Items", "PublicKey", items)) .end("KeyGroupConfig") .build(); return Response.ok(xml, XML).header("ETag", group.getEtag()).build(); @@ -1723,6 +1722,11 @@ public class CloudFrontController { .elem("DomainName", dist.getDomainName()) .elem("LastModifiedTime", dist.getLastModifiedTime() != null ? dist.getLastModifiedTime().toString() : "") + .raw(xmlActiveTrustedKeyGroups(dist.getConfig())) + .start("ActiveTrustedSigners") + .elem("Enabled", false) + .elem("Quantity", 0) + .end("ActiveTrustedSigners") .start("DistributionConfig") .raw(xmlDistributionConfigBody(dist.getConfig())) .end("DistributionConfig") @@ -1853,6 +1857,9 @@ public class CloudFrontController { .elem("ResponseHeadersPolicyId", dcb.getResponseHeadersPolicyId()) .elem("Compress", dcb.isCompress()); + xml.raw(xmlTrustedKeyGroups( + dcb.isTrustedKeyGroupsEnabled(), dcb.getTrustedKeyGroups())); + List allowed = dcb.getAllowedMethods(); if (allowed == null || allowed.isEmpty()) { allowed = List.of("GET", "HEAD"); @@ -1879,6 +1886,9 @@ public class CloudFrontController { .elem("ResponseHeadersPolicyId", cb.getResponseHeadersPolicyId()) .elem("Compress", cb.isCompress()); + xml.raw(xmlTrustedKeyGroups( + cb.isTrustedKeyGroupsEnabled(), cb.getTrustedKeyGroups())); + List allowed = cb.getAllowedMethods(); if (allowed == null || allowed.isEmpty()) { allowed = List.of("GET", "HEAD"); @@ -1893,6 +1903,52 @@ public class CloudFrontController { return xml.build(); } + private String xmlTrustedKeyGroups( + boolean enabled, List trustedKeyGroups) { + List keyGroups = trustedKeyGroups != null ? trustedKeyGroups : List.of(); + XmlBuilder xml = new XmlBuilder() + .start("TrustedKeyGroups") + .elem("Enabled", enabled) + .elem("Quantity", keyGroups.size()); + if (!keyGroups.isEmpty()) { + xml.start("Items"); + for (String keyGroup : keyGroups) { + xml.elem("KeyGroup", keyGroup); + } + xml.end("Items"); + } + return xml.end("TrustedKeyGroups").build(); + } + + private String xmlActiveTrustedKeyGroups(DistributionConfig config) { + List groups = service.activeTrustedKeyGroups(config); + XmlBuilder xml = new XmlBuilder() + .start("ActiveTrustedKeyGroups") + .elem("Enabled", !groups.isEmpty()) + .elem("Quantity", groups.size()); + if (!groups.isEmpty()) { + xml.start("Items"); + for (KeyGroup group : groups) { + List keyPairIds = + group.getItems() != null ? group.getItems() : List.of(); + xml.start("KeyGroup") + .elem("KeyGroupId", group.getId()) + .start("KeyPairIds") + .elem("Quantity", keyPairIds.size()); + if (!keyPairIds.isEmpty()) { + xml.start("Items"); + for (String keyPairId : keyPairIds) { + xml.elem("KeyPairId", keyPairId); + } + xml.end("Items"); + } + xml.end("KeyPairIds").end("KeyGroup"); + } + xml.end("Items"); + } + return xml.end("ActiveTrustedKeyGroups").build(); + } + private String xmlViewerCertificate(Map vc) { XmlBuilder xml = new XmlBuilder().start("ViewerCertificate"); if (vc != null && !vc.isEmpty()) { @@ -2099,6 +2155,14 @@ public class CloudFrontController { return xml.build(); } + private String xmlDirectItems(String wrapper, String itemTag, List items) { + XmlBuilder xml = new XmlBuilder().start(wrapper); + for (String item : items) { + xml.elem(itemTag, item); + } + return xml.end(wrapper).build(); + } + private static int paginationFetchLimit(int maxItems) { return maxItems > 0 && maxItems < Integer.MAX_VALUE ? maxItems + 1 : maxItems; } @@ -2131,17 +2195,25 @@ public class CloudFrontController { // ── Request parsers ─────────────────────────────────────────────────────── private DistributionConfig parseDistributionConfig(String body) { + Map values = + parseDistributionConfigTopLevelValues(body); DistributionConfig cfg = new DistributionConfig(); - cfg.setCallerReference(XmlParser.extractFirst(body, "CallerReference", null)); - cfg.setEnabled("true".equalsIgnoreCase(XmlParser.extractFirst(body, "Enabled", "true"))); - cfg.setComment(XmlParser.extractFirst(body, "Comment", "")); - cfg.setDefaultRootObject(XmlParser.extractFirst(body, "DefaultRootObject", "")); - cfg.setHttpVersion(XmlParser.extractFirst(body, "HttpVersion", "http2")); - cfg.setPriceClass(XmlParser.extractFirst(body, "PriceClass", "PriceClass_All")); - cfg.setIPV6Enabled("true".equalsIgnoreCase(XmlParser.extractFirst(body, "IsIPV6Enabled", "true"))); - cfg.setWebAclId(XmlParser.extractFirst(body, "WebAclId", null)); - cfg.setContinuousDeploymentPolicyId(XmlParser.extractFirst(body, "ContinuousDeploymentPolicyId", null)); - cfg.setStaging("true".equalsIgnoreCase(XmlParser.extractFirst(body, "Staging", "false"))); + cfg.setCallerReference(values.get("CallerReference")); + cfg.setEnabled("true".equalsIgnoreCase( + values.getOrDefault("Enabled", "true"))); + cfg.setComment(values.getOrDefault("Comment", "")); + cfg.setDefaultRootObject( + values.getOrDefault("DefaultRootObject", "")); + cfg.setHttpVersion(values.getOrDefault("HttpVersion", "http2")); + cfg.setPriceClass( + values.getOrDefault("PriceClass", "PriceClass_All")); + cfg.setIPV6Enabled("true".equalsIgnoreCase( + values.getOrDefault("IsIPV6Enabled", "true"))); + cfg.setWebAclId(values.get("WebAclId")); + cfg.setContinuousDeploymentPolicyId( + values.get("ContinuousDeploymentPolicyId")); + cfg.setStaging("true".equalsIgnoreCase( + values.getOrDefault("Staging", "false"))); cfg.setOrigins(parseOrigins(body)); cfg.setDefaultCacheBehavior(parseDefaultCacheBehavior(body)); @@ -2153,6 +2225,75 @@ public class CloudFrontController { return cfg; } + private Map parseDistributionConfigTopLevelValues( + String body) { + Map values = new LinkedHashMap<>(); + if (body == null || body.isEmpty()) { + return values; + } + try { + XMLStreamReader reader = XML_FACTORY.createXMLStreamReader( + new StringReader(body)); + boolean inDistributionConfig = false; + int nestedDepth = 0; + while (reader.hasNext()) { + int event = reader.next(); + if (event == XMLStreamConstants.START_ELEMENT) { + String local = reader.getLocalName(); + if (!inDistributionConfig + && "DistributionConfig".equals(local)) { + inDistributionConfig = true; + continue; + } + if (!inDistributionConfig) { + continue; + } + nestedDepth++; + if (nestedDepth == 1 + && isDistributionConfigScalar(local)) { + values.put(local, reader.getElementText()); + nestedDepth--; + } + } else if (event == XMLStreamConstants.END_ELEMENT + && inDistributionConfig) { + if (nestedDepth == 0 + && "DistributionConfig".equals( + reader.getLocalName())) { + inDistributionConfig = false; + } else { + nestedDepth--; + } + } + } + reader.close(); + } catch (Exception e) { + LOG.debugv( + "Invalid DistributionConfig XML: {0}", + e.getMessage()); + throw new AwsException( + "InvalidArgument", + "The DistributionConfig XML is invalid.", + 400); + } + return values; + } + + private static boolean isDistributionConfigScalar(String local) { + return switch (local) { + case "CallerReference", + "Enabled", + "Comment", + "DefaultRootObject", + "HttpVersion", + "PriceClass", + "IsIPV6Enabled", + "WebAclId", + "ContinuousDeploymentPolicyId", + "Staging" -> true; + default -> false; + }; + } + /** * Parses the {@code CustomErrorResponses} block into a list of maps keyed by * {@code ErrorCode}, {@code ResponsePagePath}, {@code ResponseCode} and {@code ErrorCachingMinTTL} @@ -2355,7 +2496,12 @@ public class CloudFrontController { XMLStreamReader r = XML_FACTORY.createXMLStreamReader(new StringReader(body)); boolean inDcb = false; boolean inAllowedMethods = false; + boolean inTrustedKeyGroups = false; + boolean sawTrustedKeyGroups = false; + Boolean trustedKeyGroupsEnabled = null; + Integer trustedKeyGroupsQuantity = null; List allowedMethods = new ArrayList<>(); + List trustedKeyGroups = new ArrayList<>(); while (r.hasNext()) { int event = r.next(); @@ -2363,6 +2509,29 @@ public class CloudFrontController { String local = r.getLocalName(); switch (local) { case "DefaultCacheBehavior" -> inDcb = true; + case "TrustedKeyGroups" -> { + if (inDcb) { + inTrustedKeyGroups = true; + sawTrustedKeyGroups = true; + } + } + case "Enabled" -> { + if (inTrustedKeyGroups) { + trustedKeyGroupsEnabled = + parseTrustedKeyGroupsEnabled(r.getElementText()); + } + } + case "Quantity" -> { + if (inTrustedKeyGroups) { + trustedKeyGroupsQuantity = + parseTrustedKeyGroupsQuantity(r.getElementText()); + } + } + case "KeyGroup" -> { + if (inTrustedKeyGroups) { + trustedKeyGroups.add(r.getElementText()); + } + } case "AllowedMethods" -> { if (inDcb) inAllowedMethods = true; } @@ -2399,6 +2568,7 @@ public class CloudFrontController { } else if (event == XMLStreamConstants.END_ELEMENT) { switch (r.getLocalName()) { case "AllowedMethods" -> inAllowedMethods = false; + case "TrustedKeyGroups" -> inTrustedKeyGroups = false; case "DefaultCacheBehavior" -> inDcb = false; default -> { } @@ -2409,7 +2579,28 @@ public class CloudFrontController { if (!allowedMethods.isEmpty()) { dcb.setAllowedMethods(allowedMethods); } - } catch (Exception ignored) { + if (!trustedKeyGroups.isEmpty()) { + dcb.setTrustedKeyGroups(trustedKeyGroups); + } + if (sawTrustedKeyGroups) { + if (trustedKeyGroupsEnabled == null) { + throw new AwsException( + "InvalidArgument", + "TrustedKeyGroups must include Enabled.", + 400); + } + validateTrustedKeyGroupsQuantity( + trustedKeyGroupsQuantity, trustedKeyGroups.size()); + validateEnabledTrustedKeyGroups( + trustedKeyGroupsEnabled, trustedKeyGroups.size()); + dcb.setTrustedKeyGroupsEnabled(trustedKeyGroupsEnabled); + } + } catch (AwsException e) { + throw e; + } catch (Exception e) { + LOG.debugv("Invalid DefaultCacheBehavior XML: {0}", e.getMessage()); + throw new AwsException( + "InvalidArgument", "The DefaultCacheBehavior configuration is invalid.", 400); } return dcb; } @@ -2424,8 +2615,13 @@ public class CloudFrontController { boolean inCacheBehaviors = false; boolean inCacheBehavior = false; boolean inAllowedMethods = false; + boolean inTrustedKeyGroups = false; CacheBehavior current = null; + boolean sawTrustedKeyGroups = false; + Boolean trustedKeyGroupsEnabled = null; + Integer trustedKeyGroupsQuantity = null; List allowedMethods = new ArrayList<>(); + List trustedKeyGroups = new ArrayList<>(); while (r.hasNext()) { int event = r.next(); @@ -2437,7 +2633,34 @@ public class CloudFrontController { if (inCacheBehaviors) { inCacheBehavior = true; current = new CacheBehavior(); + sawTrustedKeyGroups = false; + trustedKeyGroupsEnabled = null; + trustedKeyGroupsQuantity = null; allowedMethods = new ArrayList<>(); + trustedKeyGroups = new ArrayList<>(); + } + } + case "TrustedKeyGroups" -> { + if (inCacheBehavior) { + inTrustedKeyGroups = true; + sawTrustedKeyGroups = true; + } + } + case "Enabled" -> { + if (inTrustedKeyGroups) { + trustedKeyGroupsEnabled = + parseTrustedKeyGroupsEnabled(r.getElementText()); + } + } + case "Quantity" -> { + if (inTrustedKeyGroups) { + trustedKeyGroupsQuantity = + parseTrustedKeyGroupsQuantity(r.getElementText()); + } + } + case "KeyGroup" -> { + if (inTrustedKeyGroups) { + trustedKeyGroups.add(r.getElementText()); } } case "AllowedMethods" -> { @@ -2477,11 +2700,31 @@ public class CloudFrontController { } else if (event == XMLStreamConstants.END_ELEMENT) { switch (r.getLocalName()) { case "AllowedMethods" -> inAllowedMethods = false; + case "TrustedKeyGroups" -> inTrustedKeyGroups = false; case "CacheBehavior" -> { if (inCacheBehavior && current != null) { if (!allowedMethods.isEmpty()) { current.setAllowedMethods(allowedMethods); } + if (!trustedKeyGroups.isEmpty()) { + current.setTrustedKeyGroups(trustedKeyGroups); + } + if (sawTrustedKeyGroups) { + if (trustedKeyGroupsEnabled == null) { + throw new AwsException( + "InvalidArgument", + "TrustedKeyGroups must include Enabled.", + 400); + } + validateTrustedKeyGroupsQuantity( + trustedKeyGroupsQuantity, + trustedKeyGroups.size()); + validateEnabledTrustedKeyGroups( + trustedKeyGroupsEnabled, + trustedKeyGroups.size()); + current.setTrustedKeyGroupsEnabled( + trustedKeyGroupsEnabled); + } result.add(current); } inCacheBehavior = false; @@ -2494,11 +2737,68 @@ public class CloudFrontController { } } r.close(); - } catch (Exception ignored) { + } catch (AwsException e) { + throw e; + } catch (Exception e) { + LOG.debugv("Invalid CacheBehaviors XML: {0}", e.getMessage()); + throw new AwsException( + "InvalidArgument", "The CacheBehaviors configuration is invalid.", 400); } return result; } + private static boolean parseTrustedKeyGroupsEnabled(String value) { + if (!"true".equalsIgnoreCase(value) + && !"false".equalsIgnoreCase(value)) { + throw new AwsException( + "InvalidArgument", + "TrustedKeyGroups Enabled must be true or false.", + 400); + } + return Boolean.parseBoolean(value); + } + + private static int parseTrustedKeyGroupsQuantity(String value) { + try { + int quantity = Integer.parseInt(value); + if (quantity < 0) { + throw new NumberFormatException("negative quantity"); + } + return quantity; + } catch (NumberFormatException e) { + throw new AwsException( + "InvalidArgument", + "TrustedKeyGroups Quantity must be a non-negative integer.", + 400); + } + } + + private static void validateTrustedKeyGroupsQuantity( + Integer quantity, int itemCount) { + if (quantity == null) { + throw new AwsException( + "InvalidArgument", + "TrustedKeyGroups must include Quantity.", + 400); + } + if (quantity != itemCount) { + throw new AwsException( + "InconsistentQuantities", + "The value of Quantity does not match the number of items.", + 400); + } + } + + private static void validateEnabledTrustedKeyGroups( + boolean enabled, int itemCount) { + if (enabled && itemCount == 0) { + throw new AwsException( + "InvalidArgument", + "TrustedKeyGroups cannot be enabled without a key group.", + 400); + } + } + private List parseAliases(String body) { List result = new ArrayList<>(); if (body == null || body.isEmpty()) { @@ -2676,8 +2976,7 @@ public class CloudFrontController { .start("KeyGroupConfig") .elem("Name", group.getName() != null ? group.getName() : "") .elem("Comment", group.getComment() != null ? group.getComment() : "") - .raw(xmlQuantityItems("Items", "PublicKey", items.size(), - items.stream().map(k -> "" + XmlBuilder.escape(k) + "").toList())) + .raw(xmlDirectItems("Items", "PublicKey", items)) .end("KeyGroupConfig") .end("KeyGroup"); return xml.build(); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontRequestRouter.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontRequestRouter.java index 1653434c39..85acd06fb7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontRequestRouter.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontRequestRouter.java @@ -104,6 +104,32 @@ public final class CloudFrontRequestRouter { return dflt != null ? dflt.getTargetOriginId() : 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 + * the matched behavior serves public content — no request signature is required. + */ + public static List trustedKeyGroupsFor(DistributionConfig config, String normalizedPath) { + List behaviors = config.getCacheBehaviors(); + if (behaviors != null) { + for (CacheBehavior behavior : behaviors) { + if (pathPatternMatches(behavior.getPathPattern(), normalizedPath)) { + return behavior.isTrustedKeyGroupsEnabled() + && behavior.getTrustedKeyGroups() != null + ? behavior.getTrustedKeyGroups() + : List.of(); + } + } + } + DefaultCacheBehavior dflt = config.getDefaultCacheBehavior(); + if (dflt != null + && dflt.isTrustedKeyGroupsEnabled() + && dflt.getTrustedKeyGroups() != null) { + return dflt.getTrustedKeyGroups(); + } + return List.of(); + } + /** * 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 diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java index 8041c389e4..20c7114428 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java @@ -6,10 +6,12 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.StorageBackend; 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.CachePolicy; import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontFunction; import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontOriginAccessIdentity; import io.github.hectorvent.floci.services.cloudfront.model.ContinuousDeploymentPolicy; +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.FieldLevelEncryptionConfig; @@ -31,8 +33,10 @@ import java.security.SecureRandom; import java.time.Instant; import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.function.Function; @@ -111,6 +115,7 @@ public class CloudFrontService { public synchronized Distribution createDistribution(Distribution dist, Map tags) { ensureAliasesAvailable(dist.getConfig(), null); + validateTrustedKeyGroups(dist.getConfig()); String id = generateDistributionId(); dist.setId(id); dist.setArn(AwsArnUtils.Arn.of("cloudfront", "", accountId, "distribution/" + id).toString()); @@ -138,6 +143,7 @@ public class CloudFrontService { "The If-Match version is missing or not valid for the resource.", 400); } ensureAliasesAvailable(updated.getConfig(), id); + validateTrustedKeyGroups(updated.getConfig()); updated.setId(id); updated.setArn(existing.getArn()); updated.setDomainName(existing.getDomainName()); @@ -914,6 +920,18 @@ public class CloudFrontService { // ── Public Keys ─────────────────────────────────────────────────────────── public synchronized PublicKey createPublicKey(PublicKey key) { + validatePublicKey(key); + boolean duplicateCallerReference = + publicKeyStore.scan(existing -> true).stream() + .anyMatch(existing -> Objects.equals( + existing.getCallerReference(), + key.getCallerReference())); + if (duplicateCallerReference) { + throw new AwsException( + "PublicKeyAlreadyExists", + "A public key with this caller reference already exists.", + 409); + } key.setId(UUID.randomUUID().toString()); key.setCreatedTime(Instant.now()); key.setEtag(UUID.randomUUID().toString()); @@ -929,8 +947,22 @@ public class CloudFrontService { public synchronized PublicKey updatePublicKey(String id, String ifMatch, PublicKey updated) { PublicKey existing = getPublicKey(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 request-header fields evaluated to false.", + 412); + } + validatePublicKey(updated); + if (!Objects.equals( + existing.getCallerReference(), + updated.getCallerReference()) + || !Objects.equals(existing.getName(), updated.getName()) + || !Objects.equals( + existing.getEncodedKey(), updated.getEncodedKey())) { + throw new AwsException( + "CannotChangeImmutablePublicKeyFields", + "The caller reference, name, and encoded public key cannot be changed.", + 400); } updated.setId(id); updated.setCreatedTime(existing.getCreatedTime()); @@ -942,8 +974,14 @@ public class CloudFrontService { public synchronized void deletePublicKey(String id, String ifMatch) { PublicKey existing = getPublicKey(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 request-header fields evaluated to false.", + 412); + } + if (publicKeyInUse(id)) { + throw new AwsException( + "PublicKeyInUse", "The specified public key is in use.", 409); } publicKeyStore.delete(id); } @@ -954,9 +992,56 @@ public class CloudFrontService { return paginate(all, marker, maxItems, PublicKey::getId); } + /** + * Resolves the PEM public key for a {@code Key-Pair-Id} used to sign a request, but only when that + * public key is a member of one of the supplied key groups. Returns {@code null} when the key is + * unknown or is not a member of any of those groups — i.e. it is not a trusted signer. + */ + public String trustedPublicKeyPem(String keyPairId, List keyGroupIds) { + if (keyPairId == null || keyGroupIds == null || keyGroupIds.isEmpty()) { + return null; + } + boolean trusted = false; + for (String keyGroupId : keyGroupIds) { + KeyGroup group = keyGroupStore.get(keyGroupId).orElse(null); + if (group != null && group.getItems() != null && group.getItems().contains(keyPairId)) { + trusted = true; + break; + } + } + if (!trusted) { + return null; + } + return publicKeyStore.get(keyPairId).map(PublicKey::getEncodedKey).orElse(null); + } + + public List activeTrustedKeyGroups(DistributionConfig config) { + LinkedHashSet ids = new LinkedHashSet<>(); + if (config != null) { + DefaultCacheBehavior defaultBehavior = config.getDefaultCacheBehavior(); + if (defaultBehavior != null + && defaultBehavior.isTrustedKeyGroupsEnabled() + && defaultBehavior.getTrustedKeyGroups() != null) { + ids.addAll(defaultBehavior.getTrustedKeyGroups()); + } + if (config.getCacheBehaviors() != null) { + for (CacheBehavior behavior : config.getCacheBehaviors()) { + if (behavior != null + && behavior.isTrustedKeyGroupsEnabled() + && behavior.getTrustedKeyGroups() != null) { + ids.addAll(behavior.getTrustedKeyGroups()); + } + } + } + } + return ids.stream().map(this::getKeyGroup).toList(); + } + // ── Key Groups ──────────────────────────────────────────────────────────── public synchronized KeyGroup createKeyGroup(KeyGroup group) { + validateKeyGroup(group); + validateUniqueKeyGroupName(group.getName(), null); group.setId(UUID.randomUUID().toString()); group.setLastModifiedTime(Instant.now()); group.setEtag(UUID.randomUUID().toString()); @@ -972,9 +1057,13 @@ public class CloudFrontService { public synchronized KeyGroup updateKeyGroup(String id, String ifMatch, KeyGroup updated) { KeyGroup existing = getKeyGroup(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 request-header fields evaluated to false.", + 412); } + validateKeyGroup(updated); + validateUniqueKeyGroupName(updated.getName(), id); updated.setId(id); updated.setLastModifiedTime(Instant.now()); updated.setEtag(UUID.randomUUID().toString()); @@ -985,18 +1074,183 @@ public class CloudFrontService { public synchronized void deleteKeyGroup(String id, String ifMatch) { KeyGroup existing = getKeyGroup(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 request-header fields evaluated to false.", + 412); + } + if (keyGroupInUse(id)) { + throw new AwsException( + "ResourceInUse", + "Cannot delete this resource because it is in use.", + 409); } keyGroupStore.delete(id); } + private void validateUniqueKeyGroupName(String name, String excludedId) { + boolean duplicate = keyGroupStore.scan(group -> true).stream() + .anyMatch(group -> !Objects.equals(excludedId, group.getId()) + && Objects.equals(name, group.getName())); + if (duplicate) { + throw new AwsException( + "KeyGroupAlreadyExists", + "A key group with this name already exists.", + 409); + } + } + public List listKeyGroups(String marker, int maxItems) { List all = new ArrayList<>(keyGroupStore.scan(k -> true)); all.sort((a, b) -> a.getId().compareTo(b.getId())); return paginate(all, marker, maxItems, KeyGroup::getId); } + private static void validatePublicKey(PublicKey key) { + if (key == null + || key.getCallerReference() == null + || key.getCallerReference().isBlank() + || key.getName() == null + || key.getName().isBlank() + || key.getEncodedKey() == null + || key.getEncodedKey().isBlank()) { + throw new AwsException( + "InvalidArgument", + "CallerReference, Name, and EncodedKey are required.", + 400); + } + if (key.getComment() != null && key.getComment().length() > 128) { + throw new AwsException( + "InvalidArgument", "The comment must be 128 characters or fewer.", 400); + } + try { + CloudFrontSignatureVerifier.parseSupportedPublicKey( + key.getEncodedKey()); + } catch (Exception e) { + throw new AwsException( + "InvalidArgument", + "The encoded public key must be RSA-2048 or ECDSA P-256 in X.509 PEM format.", + 400); + } + } + + private void validateKeyGroup(KeyGroup group) { + if (group == null || group.getName() == null || group.getName().isBlank()) { + throw new AwsException( + "InvalidArgument", "The parameter Name is required.", 400); + } + if (group.getComment() != null && group.getComment().length() > 128) { + throw new AwsException( + "InvalidArgument", "The comment must be 128 characters or fewer.", 400); + } + List items = group.getItems(); + if (items == null || items.isEmpty()) { + throw new AwsException( + "InvalidArgument", + "A key group must contain at least one public key.", + 400); + } + if (items.size() > 5) { + throw new AwsException( + "TooManyPublicKeysInKeyGroup", + "A key group can contain at most five public keys.", + 400); + } + if (new LinkedHashSet<>(items).size() != items.size()) { + throw new AwsException( + "InvalidArgument", + "A public key cannot appear more than once in a key group.", + 400); + } + for (String publicKeyId : items) { + if (publicKeyId == null + || publicKeyId.isBlank() + || publicKeyStore.get(publicKeyId).isEmpty()) { + throw new AwsException( + "InvalidArgument", + "The specified public key does not exist.", + 400); + } + } + } + + private void validateTrustedKeyGroups(DistributionConfig config) { + if (config == null) { + return; + } + DefaultCacheBehavior defaultBehavior = config.getDefaultCacheBehavior(); + if (defaultBehavior != null) { + validateTrustedKeyGroups( + defaultBehavior.isTrustedKeyGroupsEnabled(), + defaultBehavior.getTrustedKeyGroups()); + } + if (config.getCacheBehaviors() != null) { + for (CacheBehavior behavior : config.getCacheBehaviors()) { + if (behavior != null) { + validateTrustedKeyGroups( + behavior.isTrustedKeyGroupsEnabled(), + behavior.getTrustedKeyGroups()); + } + } + } + } + + private void validateTrustedKeyGroups( + boolean enabled, List keyGroupIds) { + List ids = keyGroupIds != null ? keyGroupIds : List.of(); + if (enabled && ids.isEmpty()) { + throw new AwsException( + "InvalidArgument", + "TrustedKeyGroups cannot be enabled without a key group.", + 400); + } + for (String keyGroupId : ids) { + if (keyGroupId == null + || keyGroupId.isBlank() + || keyGroupStore.get(keyGroupId).isEmpty()) { + throw new AwsException( + "TrustedKeyGroupDoesNotExist", + "The specified key group does not exist.", + 400); + } + } + } + + private boolean publicKeyInUse(String id) { + for (KeyGroup group : keyGroupStore.scan(k -> true)) { + if (group.getItems() != null && group.getItems().contains(id)) { + return true; + } + } + return false; + } + + private boolean keyGroupInUse(String id) { + for (Distribution distribution : distStore.scan(k -> true)) { + DistributionConfig config = distribution.getConfig(); + if (config == null) { + continue; + } + DefaultCacheBehavior defaultBehavior = + config.getDefaultCacheBehavior(); + if (defaultBehavior != null + && defaultBehavior.getTrustedKeyGroups() != null + && defaultBehavior.getTrustedKeyGroups().contains(id)) { + return true; + } + if (config.getCacheBehaviors() != null) { + for (CacheBehavior behavior : config.getCacheBehaviors()) { + if (behavior != null + && behavior.getTrustedKeyGroups() != null + && behavior.getTrustedKeyGroups().contains(id)) { + return true; + } + } + } + } + return false; + } + // ── Realtime Log Configs ────────────────────────────────────────────────── public synchronized RealtimeLogConfig createRealtimeLogConfig(RealtimeLogConfig cfg) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java index b7602be8ae..9afd58efe5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java @@ -71,6 +71,9 @@ public class CloudFrontServingController { "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade", "via", "content-length", "content-type"); + private static final java.util.Set CLOUDFRONT_SIGNING_PARAMS = + java.util.Set.of("Expires", "Signature", "Key-Pair-Id", "Policy", "Hash-Algorithm"); + private final CloudFrontService service; private final S3Service s3Service; private final CurrentVertxRequest currentVertxRequest; @@ -133,6 +136,18 @@ public class CloudFrontServingController { String normalized = CloudFrontRequestRouter.normalizePath(decodedViewerPath); + List trustedKeyGroups = + CloudFrontRequestRouter.trustedKeyGroupsFor(config, normalized); + if (!trustedKeyGroups.isEmpty()) { + CloudFrontSignatureVerifier.Result verdict = + verifySignedRequest(dist, rawViewerPath, trustedKeyGroups); + if (!verdict.allowed()) { + LOG.debugv("CloudFront denied a request for distribution {0}, path {1}: {2}", + dist.getId(), rawViewerPath, verdict.reason()); + return textError(403, "Access denied: " + verdict.reason()); + } + } + OriginResponse origin = route(dist, normalized, rawViewerPath, decodedViewerPath, viewerScheme, viewerAuthorization, includeBody); @@ -146,6 +161,111 @@ public class CloudFrontServingController { return toResponse(origin, includeBody); } + /** + * Verifies the live request against the behavior's trusted key groups, resolving a Key-Pair-Id + * only when its public key belongs to one of those groups. + */ + private CloudFrontSignatureVerifier.Result verifySignedRequest( + Distribution distribution, + String rawViewerPath, + List trustedKeyGroups) { + io.vertx.core.http.HttpServerRequest request = + currentVertxRequest.getCurrent().request(); + + Map query = new LinkedHashMap<>(); + for (String name : request.params().names()) { + query.put(name, request.getParam(name)); + } + Map cookies = parseCookies(request.getHeader("Cookie")); + String resourceUrl = + buildResourceUrl(distribution, request, rawViewerPath); + String sourceIp = request.remoteAddress() != null + ? request.remoteAddress().hostAddress() + : null; + + return CloudFrontSignatureVerifier.verify( + resourceUrl, + query, + cookies, + sourceIp, + keyPairId -> service.trustedPublicKeyPem( + keyPairId, trustedKeyGroups), + java.time.Instant.now()); + } + + /** + * Rebuilds the URL exactly as a signer sees it, preserving the encoded path and application + * query while excluding CloudFront's signing parameters. + */ + private static String buildResourceUrl( + Distribution distribution, + io.vertx.core.http.HttpServerRequest request, + String rawViewerPath) { + String scheme = request.scheme() != null ? request.scheme() : "https"; + String host = request.getHeader("Host"); + if (host == null || host.isBlank()) { + host = distribution.getDomainName(); + } + return scheme + "://" + host + rawViewerPath + + rawAppQuery(request.query()); + } + + private static String rawAppQuery(String rawQuery) { + String appQuery = stripCloudFrontSigningParams(rawQuery); + return appQuery.isEmpty() ? "" : "?" + appQuery; + } + + static String stripCloudFrontSigningParams(String rawQuery) { + if (rawQuery == null || rawQuery.isEmpty()) { + return ""; + } + StringBuilder appQuery = new StringBuilder(); + boolean emitted = false; + for (String pair : rawQuery.split("&", -1)) { + int eq = pair.indexOf('='); + String rawName = eq >= 0 ? pair.substring(0, eq) : pair; + String decodedName = decodeQueryName(rawName); + if (decodedName != null + && CLOUDFRONT_SIGNING_PARAMS.contains(decodedName)) { + continue; + } + if (emitted) { + appQuery.append('&'); + } + appQuery.append(pair); + emitted = true; + } + return appQuery.toString(); + } + + private static String decodeQueryName(String rawName) { + try { + return java.net.URLDecoder.decode( + rawName, StandardCharsets.UTF_8); + } catch (IllegalArgumentException e) { + LOG.debugv( + "Preserving malformed CloudFront query parameter name {0}: {1}", + rawName, e.getMessage()); + return null; + } + } + + private static Map parseCookies(String cookieHeader) { + Map cookies = new LinkedHashMap<>(); + if (cookieHeader == null || cookieHeader.isBlank()) { + return cookies; + } + for (String part : cookieHeader.split(";")) { + int eq = part.indexOf('='); + if (eq > 0) { + cookies.put( + part.substring(0, eq).trim(), + part.substring(eq + 1).trim()); + } + } + return cookies; + } + /** Selects an origin with the normalized path, then forwards the original viewer path. */ private OriginResponse route(Distribution distribution, String normalized, String rawViewerPath, String decodedViewerPath, diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontSignatureVerifier.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontSignatureVerifier.java new file mode 100644 index 0000000000..aebc5f80d8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontSignatureVerifier.java @@ -0,0 +1,448 @@ +package io.github.hectorvent.floci.services.cloudfront; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.net.InetAddress; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.AlgorithmParameters; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.Signature; +import java.security.interfaces.ECPublicKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.ECGenParameterSpec; +import java.security.spec.ECParameterSpec; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.X509EncodedKeySpec; +import java.time.Instant; +import java.util.Base64; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; + +/** + * Verifies CloudFront signed-URL and signed-cookie signatures for private content, per the AWS + * CloudFront trusted-key-group spec. Pure and stateless: the caller supplies the request details, a + * resolver from {@code Key-Pair-Id} to the trusted public-key PEM (returning {@code null} when the + * key does not belong to one of the behavior's trusted key groups), and the current time. + * + *

Supported: canned and custom policies; signed URLs (query parameters) and signed cookies + * ({@code CloudFront-*} cookies); SHA-1 and SHA-256 signatures with RSA-2048 and ECDSA P-256 keys; + * the {@code DateLessThan}, {@code DateGreaterThan} and {@code IpAddress} conditions; and wildcard + * {@code Resource} matching. + */ +public final class CloudFrontSignatureVerifier { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final Set SIGNED_URL_PARAMETERS = + Set.of("Expires", "Policy", "Signature", "Key-Pair-Id", "Hash-Algorithm"); + + private CloudFrontSignatureVerifier() { + } + + /** The outcome of verifying a request against a behavior's trusted key groups. */ + public record Result(boolean allowed, String reason) { + static Result allow() { + return new Result(true, "ok"); + } + + static Result deny(String reason) { + return new Result(false, reason); + } + } + + /** + * @param resourceUrl the request URL as the signer would have signed it + * ({@code scheme://host/path[?app-query]}, excluding the CloudFront parameters) + * @param query request query parameters (may hold {@code Expires}/{@code Signature}/ + * {@code Key-Pair-Id}/{@code Policy}/{@code Hash-Algorithm}) + * @param cookies request cookies (may hold the {@code CloudFront-*} signed-cookie names) + * @param sourceIp the request source IP for the {@code IpAddress} condition, or {@code null} + * @param trustedKeyPem resolves a {@code Key-Pair-Id} to its PEM public key, or {@code null} when + * the key is not a trusted signer for the matched behavior + * @param now the current time (expiration is checked against this) + */ + public static Result verify(String resourceUrl, Map query, Map cookies, + String sourceIp, Function trustedKeyPem, Instant now) { + boolean signedUrl = query.keySet().stream().anyMatch(SIGNED_URL_PARAMETERS::contains); + String keyPairId = signedUrl + ? query.get("Key-Pair-Id") + : cookies.get("CloudFront-Key-Pair-Id"); + String signatureB64 = signedUrl + ? query.get("Signature") + : cookies.get("CloudFront-Signature"); + if (keyPairId == null || signatureB64 == null) { + return Result.deny("Missing CloudFront signature"); + } + String policyParam = signedUrl + ? query.get("Policy") + : cookies.get("CloudFront-Policy"); + String expires = signedUrl + ? query.get("Expires") + : cookies.get("CloudFront-Expires"); + String hashAlgorithm = signedUrl + ? query.get("Hash-Algorithm") + : cookies.get("CloudFront-Hash-Algorithm"); + if (policyParam != null && expires != null) { + return Result.deny("Policy and Expires cannot both be supplied"); + } + if (hashAlgorithm == null) { + hashAlgorithm = "SHA1"; + } else if (!"SHA1".equals(hashAlgorithm) && !"SHA256".equals(hashAlgorithm)) { + return Result.deny("Unsupported CloudFront hash algorithm"); + } + + String pem = trustedKeyPem.apply(keyPairId); + if (pem == null) { + return Result.deny("Key-Pair-Id " + keyPairId + " is not a trusted signer"); + } + PublicKey publicKey; + try { + publicKey = parseSupportedPublicKey(pem); + } catch (Exception e) { + return Result.deny("Unsupported public key for " + keyPairId); + } + + String policyJson; + boolean customPolicy = policyParam != null; + if (policyParam != null) { + try { + policyJson = new String(cfBase64Decode(policyParam), StandardCharsets.UTF_8); + } catch (IllegalArgumentException e) { + // A malformed Policy value is a bad request, not a server fault: CloudFront denies + // it (403) rather than surfacing a decode error. cfBase64Decode delegates to + // Base64.getDecoder().decode(), which throws IllegalArgumentException on invalid input. + return Result.deny("Policy parameter is not valid CloudFront base64"); + } + } else if (expires != null) { + policyJson = cannedPolicy(resourceUrl, expires); + } else { + return Result.deny("Neither a Policy nor an Expires value was supplied"); + } + + try { + String signatureAlgorithm = hashAlgorithm + switch (publicKey.getAlgorithm()) { + case "RSA" -> "withRSA"; + case "EC" -> "withECDSA"; + default -> throw new GeneralSecurityException("Unsupported public key algorithm"); + }; + Signature signature = Signature.getInstance(signatureAlgorithm); + signature.initVerify(publicKey); + signature.update(policyJson.getBytes(StandardCharsets.UTF_8)); + if (!signature.verify(cfBase64Decode(signatureB64))) { + return Result.deny("Signature does not match the policy"); + } + } catch (Exception e) { + return Result.deny("Signature verification failed"); + } + + return enforcePolicy(policyJson, resourceUrl, sourceIp, now, signedUrl, customPolicy); + } + + /** The exact canned-policy document AWS signs (no whitespace); the signer must produce it byte-for-byte. */ + static String cannedPolicy(String resourceUrl, String expires) { + return "{\"Statement\":[{\"Resource\":\"" + resourceUrl + + "\",\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":" + expires + "}}}]}"; + } + + private static Result enforcePolicy( + String policyJson, String resourceUrl, String sourceIp, Instant now, + boolean signedUrl, boolean customPolicy) { + JsonNode statements; + try { + statements = MAPPER.readTree(policyJson).path("Statement"); + } catch (Exception e) { + return Result.deny("Malformed policy document"); + } + if (!statements.isArray() || statements.size() != 1) { + return Result.deny("Policy must contain exactly one statement"); + } + long epochNow = now.getEpochSecond(); + JsonNode statement = statements.get(0); + JsonNode resourceNode = statement.get("Resource"); + if (resourceNode != null + && (!resourceNode.isTextual() + || (!signedUrl && !hasExplicitHttpProtocol(resourceNode.asText())) + || !(customPolicy + ? wildcardMatches(resourceNode.asText(), resourceUrl) + : exactResourceMatches(resourceNode.asText(), resourceUrl)))) { + return Result.deny("The policy resource does not match the requested resource"); + } + JsonNode condition = statement.path("Condition"); + JsonNode lessThan = condition.path("DateLessThan").path("AWS:EpochTime"); + if (!isEpochTime(lessThan)) { + return Result.deny("Policy is missing a DateLessThan condition"); + } + if (epochNow >= lessThan.asLong()) { + return Result.deny("The signed request has expired"); + } + JsonNode greaterThanCondition = condition.get("DateGreaterThan"); + if (greaterThanCondition != null) { + JsonNode greaterThan = greaterThanCondition.path("AWS:EpochTime"); + if (!isEpochTime(greaterThan)) { + return Result.deny("Policy has an invalid DateGreaterThan condition"); + } + if (epochNow <= greaterThan.asLong()) { + return Result.deny("The signed request is not yet valid"); + } + } + JsonNode ipCondition = condition.get("IpAddress"); + if (ipCondition != null) { + JsonNode ip = ipCondition.path("AWS:SourceIp"); + if (!ip.isTextual()) { + return Result.deny("Policy has an invalid IpAddress condition"); + } + if (sourceIp == null || !ipInCidr(sourceIp, ip.asText())) { + return Result.deny("Source IP is not permitted by the policy"); + } + } + return Result.allow(); + } + + private static boolean isEpochTime(JsonNode value) { + return value.isIntegralNumber() && value.canConvertToLong(); + } + + static PublicKey parseSupportedPublicKey(String pem) throws GeneralSecurityException { + if (pem == null) { + throw new InvalidKeySpecException("The encoded public key is required"); + } + String trimmed = pem.trim(); + String begin = "-----BEGIN PUBLIC KEY-----"; + String end = "-----END PUBLIC KEY-----"; + if (!trimmed.startsWith(begin) || !trimmed.endsWith(end)) { + throw new InvalidKeySpecException("The public key must use X.509 PEM encoding"); + } + String base64 = trimmed.substring(begin.length(), trimmed.length() - end.length()) + .replaceAll("\\s", ""); + byte[] der; + try { + der = Base64.getDecoder().decode(base64); + } catch (IllegalArgumentException e) { + throw new InvalidKeySpecException("The public key is not valid base64", e); + } + X509EncodedKeySpec spec = new X509EncodedKeySpec(der); + PublicKey publicKey; + try { + publicKey = KeyFactory.getInstance("RSA").generatePublic(spec); + } catch (GeneralSecurityException rsaError) { + try { + publicKey = KeyFactory.getInstance("EC").generatePublic(spec); + } catch (GeneralSecurityException ecError) { + ecError.addSuppressed(rsaError); + throw ecError; + } + } + if (!isSupportedPublicKey(publicKey)) { + throw new InvalidKeySpecException( + "CloudFront supports only RSA-2048 and ECDSA P-256 public keys"); + } + return publicKey; + } + + private static boolean isSupportedPublicKey(PublicKey publicKey) + throws GeneralSecurityException { + if (publicKey instanceof RSAPublicKey rsa) { + return rsa.getModulus().bitLength() == 2048; + } + if (publicKey instanceof ECPublicKey ec) { + AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC"); + parameters.init(new ECGenParameterSpec("secp256r1")); + ECParameterSpec p256 = + parameters.getParameterSpec(ECParameterSpec.class); + ECParameterSpec actual = ec.getParams(); + return actual.getCurve().equals(p256.getCurve()) + && actual.getGenerator().equals(p256.getGenerator()) + && actual.getOrder().equals(p256.getOrder()) + && actual.getCofactor() == p256.getCofactor(); + } + return false; + } + + /** Reverses CloudFront's URL-safe base64 alphabet (+ - = _ / ~) before decoding. */ + static byte[] cfBase64Decode(String value) { + String standard = value.replace('-', '+').replace('_', '=').replace('~', '/'); + return Base64.getDecoder().decode(standard); + } + + /** + * Matches a custom-policy resource using CloudFront's URL-section wildcard rules. Wildcards stay + * inside protocol, domain, path, and query sections, except for CloudFront's documented trailing + * domain/path {@code *} behavior. + */ + static boolean wildcardMatches(String pattern, String value) { + if ("*".equals(pattern)) { + return true; + } + ResourceParts actual = parseActualResource(value); + if (actual == null) { + return false; + } + ResourcePattern expected = parseResourcePattern(pattern); + if (expected == null + || !globMatches( + expected.protocol().toLowerCase(Locale.ROOT), + actual.protocol().toLowerCase(Locale.ROOT)) + || !globMatches( + expected.domain().toLowerCase(Locale.ROOT), + actual.domain().toLowerCase(Locale.ROOT))) { + return false; + } + if (expected.domainStarCoversRemainder()) { + return true; + } + if (!globMatches(expected.path(), actual.path())) { + return false; + } + if (expected.query() != null) { + return actual.query() != null + && globMatches(expected.query(), actual.query()); + } + return actual.query() == null || expected.pathStarCoversQuery(); + } + + private static boolean hasExplicitHttpProtocol(String resource) { + return resource.startsWith("http://") || resource.startsWith("https://"); + } + + private static boolean exactResourceMatches(String expected, String actual) { + return expected.equals(actual) && parseActualResource(actual) != null; + } + + private static ResourceParts parseActualResource(String value) { + try { + URI uri = URI.create(value); + if (uri.getScheme() == null || uri.getRawAuthority() == null) { + return null; + } + String path = uri.getRawPath(); + return new ResourceParts( + uri.getScheme(), + uri.getRawAuthority(), + path == null || path.isEmpty() ? "/" : path, + uri.getRawQuery()); + } catch (IllegalArgumentException e) { + return null; + } + } + + private static ResourcePattern parseResourcePattern(String pattern) { + if (pattern == null || pattern.isEmpty()) { + return null; + } + int schemeEnd = pattern.indexOf("://"); + String protocol; + String remainder; + if (schemeEnd >= 0) { + protocol = pattern.substring(0, schemeEnd); + remainder = pattern.substring(schemeEnd + 3); + } else if (pattern.startsWith("*")) { + protocol = "*"; + remainder = pattern; + } else { + return null; + } + int pathStart = remainder.indexOf('/'); + String domain = pathStart >= 0 ? remainder.substring(0, pathStart) : remainder; + if (protocol.isEmpty() || domain.isEmpty()) { + return null; + } + if (!"http".equals(protocol) + && !"https".equals(protocol) + && !"*".equals(protocol)) { + return null; + } + boolean domainStarCoversRemainder = pathStart < 0 && domain.endsWith("*"); + String pathAndQuery = pathStart >= 0 ? remainder.substring(pathStart) : "/"; + int queryStart = pathAndQuery.indexOf('?'); + String path = queryStart >= 0 + ? pathAndQuery.substring(0, queryStart) + : pathAndQuery; + String query = queryStart >= 0 + ? pathAndQuery.substring(queryStart + 1) + : null; + boolean pathStarCoversQuery = + query == null && path.endsWith("*"); + return new ResourcePattern( + protocol, + domain, + path.isEmpty() ? "/" : path, + query, + domainStarCoversRemainder, + pathStarCoversQuery); + } + + private static boolean globMatches(String pattern, String value) { + StringBuilder regex = new StringBuilder(); + for (int i = 0; i < pattern.length(); i++) { + char c = pattern.charAt(i); + switch (c) { + case '*' -> regex.append(".*"); + case '?' -> regex.append('.'); + default -> { + if ("\\.[]{}()+-^$|".indexOf(c) >= 0) { + regex.append('\\'); + } + regex.append(c); + } + } + } + return value != null && value.matches(regex.toString()); + } + + /** + * IPv4 CIDR containment for custom-policy {@code IpAddress}. CloudFront does not support IPv6 + * values in this condition, so IPv6 and malformed values fail closed. + */ + static boolean ipInCidr(String ip, String cidr) { + try { + int slash = cidr.indexOf('/'); + if (slash <= 0 + || slash == cidr.length() - 1 + || slash != cidr.lastIndexOf('/')) { + return false; + } + String network = cidr.substring(0, slash); + byte[] ipBytes = InetAddress.ofLiteral(ip).getAddress(); + byte[] netBytes = InetAddress.ofLiteral(network).getAddress(); + if (ipBytes.length != 4 || netBytes.length != 4) { + return false; + } + String prefix = cidr.substring(slash + 1); + if (!prefix.chars().allMatch(Character::isDigit)) { + return false; + } + int bits = Integer.parseInt(prefix); + if (bits < 0 || bits > 32) { + return false; + } + for (int i = 0; i < ipBytes.length; i++) { + int maskBits = Math.min(8, Math.max(0, bits - i * 8)); + int mask = maskBits == 0 ? 0 : (0xFF << (8 - maskBits)) & 0xFF; + if ((ipBytes[i] & mask) != (netBytes[i] & mask)) { + return false; + } + } + return true; + } catch (Exception e) { + return false; + } + } + + private record ResourceParts( + String protocol, String domain, String path, String query) { + } + + private record ResourcePattern( + String protocol, + String domain, + String path, + String query, + boolean domainStarCoversRemainder, + boolean pathStarCoversQuery) { + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CacheBehavior.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CacheBehavior.java index 354c8f2b52..10f2a0989f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CacheBehavior.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/CacheBehavior.java @@ -24,6 +24,10 @@ public class CacheBehavior { private long defaultTTL; private long minTTL; private long maxTTL; + // Private-content key group IDs whose public keys may sign requests. + // Explicit enablement controls signature enforcement. + private Boolean trustedKeyGroupsEnabled; + private List trustedKeyGroups; public CacheBehavior() {} @@ -74,4 +78,16 @@ public class CacheBehavior { public long getMaxTTL() { return maxTTL; } public void setMaxTTL(long maxTTL) { this.maxTTL = maxTTL; } + + public boolean isTrustedKeyGroupsEnabled() { + return trustedKeyGroupsEnabled != null + ? trustedKeyGroupsEnabled + : trustedKeyGroups != null && !trustedKeyGroups.isEmpty(); + } + public void setTrustedKeyGroupsEnabled(boolean trustedKeyGroupsEnabled) { + this.trustedKeyGroupsEnabled = trustedKeyGroupsEnabled; + } + + public List getTrustedKeyGroups() { return trustedKeyGroups; } + public void setTrustedKeyGroups(List trustedKeyGroups) { this.trustedKeyGroups = trustedKeyGroups; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/DefaultCacheBehavior.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/DefaultCacheBehavior.java index bb0edc802e..83f49df338 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/DefaultCacheBehavior.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/model/DefaultCacheBehavior.java @@ -23,6 +23,10 @@ public class DefaultCacheBehavior { private long defaultTTL; private long minTTL; private long maxTTL; + // Private-content key group IDs whose public keys may sign requests. + // Explicit enablement controls signature enforcement. + private Boolean trustedKeyGroupsEnabled; + private List trustedKeyGroups; public DefaultCacheBehavior() {} @@ -70,4 +74,16 @@ public class DefaultCacheBehavior { public long getMaxTTL() { return maxTTL; } public void setMaxTTL(long maxTTL) { this.maxTTL = maxTTL; } + + public boolean isTrustedKeyGroupsEnabled() { + return trustedKeyGroupsEnabled != null + ? trustedKeyGroupsEnabled + : trustedKeyGroups != null && !trustedKeyGroups.isEmpty(); + } + public void setTrustedKeyGroupsEnabled(boolean trustedKeyGroupsEnabled) { + this.trustedKeyGroupsEnabled = trustedKeyGroupsEnabled; + } + + public List getTrustedKeyGroups() { return trustedKeyGroups; } + public void setTrustedKeyGroups(List trustedKeyGroups) { this.trustedKeyGroups = trustedKeyGroups; } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontDistributionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontDistributionIntegrationTest.java index f1851c91b2..911cafc753 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontDistributionIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationCloudFrontDistributionIntegrationTest.java @@ -2,13 +2,17 @@ package io.github.hectorvent.floci.services.cloudformation; import io.github.hectorvent.floci.services.cloudfront.CloudFrontService; import io.github.hectorvent.floci.services.cloudfront.model.Distribution; +import io.github.hectorvent.floci.services.cloudfront.model.KeyGroup; import io.github.hectorvent.floci.services.cloudfront.model.OriginAccessControl; +import io.github.hectorvent.floci.services.cloudfront.model.PublicKey; import io.github.hectorvent.floci.services.s3.S3Service; import io.quarkus.test.junit.QuarkusTest; import jakarta.inject.Inject; import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; +import java.security.KeyPairGenerator; +import java.util.Base64; import java.util.List; import java.util.Map; @@ -168,6 +172,84 @@ class CloudFormationCloudFrontDistributionIntegrationTest { assertEquals("after-" + suffix, updated.getConfig().getComment()); } + @Test + void preservesTrustedKeyGroupsOnDefaultAndOrderedBehaviors() throws Exception { + String suffix = Long.toString(System.nanoTime(), 36); + String alias = "cfn-private-" + suffix + ".example.test"; + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + PublicKey publicKey = new PublicKey(); + publicKey.setCallerReference("cfn-key-reference-" + suffix); + publicKey.setName("cfn-key-" + suffix); + publicKey.setEncodedKey("-----BEGIN PUBLIC KEY-----\n" + + Base64.getMimeEncoder().encodeToString( + generator.generateKeyPair().getPublic().getEncoded()) + + "\n-----END PUBLIC KEY-----"); + publicKey = cloudFrontService.createPublicKey(publicKey); + KeyGroup defaultKeyGroup = createKeyGroup("cfn-default-" + suffix, publicKey.getId()); + KeyGroup orderedKeyGroupA = createKeyGroup("cfn-ordered-a-" + suffix, publicKey.getId()); + KeyGroup orderedKeyGroupB = createKeyGroup("cfn-ordered-b-" + suffix, publicKey.getId()); + String template = """ + { + "Resources": { + "Dist": { + "Type": "AWS::CloudFront::Distribution", + "Properties": { + "DistributionConfig": { + "Enabled": true, + "Aliases": ["%s"], + "Origins": [{ + "Id": "s3-origin", + "DomainName": "private-content.s3.us-east-1.amazonaws.com", + "S3OriginConfig": {"OriginAccessIdentity": ""} + }], + "DefaultCacheBehavior": { + "TargetOriginId": "s3-origin", + "ViewerProtocolPolicy": "allow-all", + "TrustedKeyGroups": ["%s"] + }, + "CacheBehaviors": [{ + "PathPattern": "/private/*", + "TargetOriginId": "s3-origin", + "ViewerProtocolPolicy": "allow-all", + "TrustedKeyGroups": ["%s", "%s"] + }] + } + } + } + } + } + """.formatted( + alias, + defaultKeyGroup.getId(), + orderedKeyGroupA.getId(), + orderedKeyGroupB.getId()); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "CreateStack") + .formParam("StackName", "cfn-cloudfront-private-" + suffix) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + + Distribution distribution = distributionsWithAlias(alias).getFirst(); + assertEquals(List.of(defaultKeyGroup.getId()), + distribution.getConfig().getDefaultCacheBehavior().getTrustedKeyGroups()); + assertEquals(List.of(orderedKeyGroupA.getId(), orderedKeyGroupB.getId()), + distribution.getConfig().getCacheBehaviors().getFirst().getTrustedKeyGroups()); + } + + private KeyGroup createKeyGroup(String name, String publicKeyId) { + KeyGroup keyGroup = new KeyGroup(); + keyGroup.setName(name); + keyGroup.setItems(List.of(publicKeyId)); + return cloudFrontService.createKeyGroup(keyGroup); + } + private List distributionsWithAlias(String alias) { return cloudFrontService.listDistributions(null, 1000).stream() .filter(distribution -> distribution.getConfig() != null diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontDistributionServingTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontDistributionServingTest.java index f0a42e508a..4fe5043b20 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontDistributionServingTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontDistributionServingTest.java @@ -1,11 +1,14 @@ package io.github.hectorvent.floci.services.cloudfront; import com.sun.net.httpserver.HttpServer; +import io.github.hectorvent.floci.core.common.XmlParser; import io.github.hectorvent.floci.services.cloudfront.model.CacheBehavior; 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.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.s3.S3Service; import io.github.hectorvent.floci.services.s3.model.PutObjectOptions; import io.github.hectorvent.floci.services.s3.model.S3Object; @@ -15,8 +18,10 @@ import org.junit.jupiter.api.Test; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; +import java.security.KeyPairGenerator; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; +import java.util.Base64; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -27,6 +32,8 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * End-to-end tests for CloudFront distribution request-serving: a viewer request addressed to a @@ -385,8 +392,448 @@ class CloudFrontDistributionServingTest { .body(containsString("/index.html")); } + @Test + void roundTripsTrustedKeyGroupsThroughDistributionConfigApi() + throws Exception { + String suffix = suffix(); + SignerResources defaultSigner = + createSignerResources("default-" + suffix); + SignerResources privateSigner = + createSignerResources("private-" + suffix); + String body = distributionConfigXml("trusted-key-groups-roundtrip-" + suffix, """ + + o1 + allow-all + + true + 1 + %s + + + + 1 + + + /private/* + o1 + allow-all + + true + 1 + %s + + + + + """.formatted( + defaultSigner.keyGroupId(), + privateSigner.keyGroupId())); + + var created = given() + .contentType("application/xml") + .body(body) + .when() + .post("/2020-05-31/distribution") + .then() + .statusCode(201) + .body(containsString("")) + .body(containsString("true")) + .body(containsString( + "" + defaultSigner.keyGroupId() + + "")) + .body(containsString( + "" + defaultSigner.publicKeyId() + + "")) + .body(containsString("")) + .extract().response(); + + String configPath = created.header("Location") + "/config"; + var config = given() + .when() + .get(configPath) + .then() + .statusCode(200) + .extract().response(); + + String configXml = config.asString(); + assertTrue(configXml.contains( + trustedKeyGroupsXml(defaultSigner.keyGroupId()))); + assertTrue(configXml.contains( + trustedKeyGroupsXml(privateSigner.keyGroupId()))); + + given() + .contentType("application/xml") + .header("If-Match", config.header("ETag")) + .body(configXml) + .when() + .put(configPath) + .then() + .statusCode(200) + .body(containsString( + trustedKeyGroupsXml(defaultSigner.keyGroupId()))) + .body(containsString( + trustedKeyGroupsXml(privateSigner.keyGroupId()))) + .body(containsString("")) + .body(containsString( + "" + privateSigner.keyGroupId() + + "")); + } + + @Test + void disabledTrustedKeyGroupsRemainConfiguredButDoNotRequireSignatures() + throws Exception { + String suffix = suffix(); + SignerResources defaultSigner = + createSignerResources("disabled-default-" + suffix); + SignerResources privateSigner = + createSignerResources("disabled-private-" + suffix); + String body = distributionConfigXml("disabled-key-groups-" + suffix, """ + + o1 + allow-all + + false + 1 + %s + + + + 1 + + + /private/* + o1 + allow-all + + false + 1 + %s + + + + + """.formatted( + defaultSigner.keyGroupId(), + privateSigner.keyGroupId())); + + var created = given() + .contentType("application/xml") + .body(body) + .when() + .post("/2020-05-31/distribution") + .then() + .statusCode(201) + .body(containsString("false")) + .body(containsString( + "false" + + "0")) + .extract().response(); + + String configPath = created.header("Location") + "/config"; + var config = given() + .when() + .get(configPath) + .then() + .statusCode(200) + .body(containsString("false")) + .extract().response(); + + given() + .contentType("application/xml") + .header("If-Match", config.header("ETag")) + .body(config.asString()) + .when() + .put(configPath) + .then() + .statusCode(200) + .body(containsString("false")); + + String distributionId = XmlParser.extractFirst( + created.asString(), "Id", null); + DistributionConfig stored = cloudFrontService + .getDistribution(distributionId) + .getConfig(); + + assertFalse(stored.getDefaultCacheBehavior() + .isTrustedKeyGroupsEnabled()); + assertEquals( + List.of(defaultSigner.keyGroupId()), + stored.getDefaultCacheBehavior().getTrustedKeyGroups()); + assertFalse(stored.getCacheBehaviors().getFirst() + .isTrustedKeyGroupsEnabled()); + assertEquals( + List.of(privateSigner.keyGroupId()), + stored.getCacheBehaviors().getFirst().getTrustedKeyGroups()); + assertTrue(CloudFrontRequestRouter + .trustedKeyGroupsFor(stored, "/public/file.txt") + .isEmpty()); + assertTrue(CloudFrontRequestRouter + .trustedKeyGroupsFor(stored, "/private/file.txt") + .isEmpty()); + } + + @Test + void rejectsEnabledTrustedKeyGroupsWithoutItems() { + String callerReference = + "empty-enabled-key-groups-" + suffix(); + String body = distributionConfigXml(callerReference, """ + + o1 + allow-all + + true + 0 + + + """); + + given() + .contentType("application/xml") + .body(body) + .when() + .post("/2020-05-31/distribution") + .then() + .statusCode(400) + .body(containsString("InvalidArgument")); + + assertDistributionWasNotCreated(callerReference); + } + + @Test + void rejectsUnknownTrustedKeyGroup() { + String callerReference = + "unknown-key-group-" + suffix(); + String body = distributionConfigXml(callerReference, """ + + o1 + allow-all + + true + 1 + missing-key-group + + + """); + + given() + .contentType("application/xml") + .body(body) + .when() + .post("/2020-05-31/distribution") + .then() + .statusCode(400) + .body(containsString( + "TrustedKeyGroupDoesNotExist")); + + assertDistributionWasNotCreated(callerReference); + } + + @Test + void rejectsMalformedTrustedKeyGroupsInDefaultBehavior() { + String callerReference = "malformed-default-key-groups-" + suffix(); + String body = distributionConfigXml(callerReference, """ + + o1 + allow-all + + 1 + kg-private + + + """); + + given() + .contentType("application/xml") + .body(body) + .when() + .post("/2020-05-31/distribution") + .then() + .statusCode(400) + .body(containsString("InvalidArgument")); + + assertDistributionWasNotCreated(callerReference); + } + + @Test + void rejectsTrustedKeyGroupsWithoutQuantityInDefaultBehavior() { + String callerReference = "missing-default-key-group-quantity-" + suffix(); + String body = distributionConfigXml(callerReference, """ + + o1 + allow-all + + true + kg-private + + + """); + + given() + .contentType("application/xml") + .body(body) + .when() + .post("/2020-05-31/distribution") + .then() + .statusCode(400) + .body(containsString("InvalidArgument")); + + assertDistributionWasNotCreated(callerReference); + } + + @Test + void rejectsTrustedKeyGroupsWithInconsistentQuantity() { + String callerReference = "inconsistent-key-group-quantity-" + suffix(); + String body = distributionConfigXml(callerReference, """ + + o1 + allow-all + + true + 2 + kg-private + + + """); + + given() + .contentType("application/xml") + .body(body) + .when() + .post("/2020-05-31/distribution") + .then() + .statusCode(400) + .body(containsString("InconsistentQuantities")); + + assertDistributionWasNotCreated(callerReference); + } + + @Test + void rejectsMalformedTrustedKeyGroupsInOrderedBehavior() { + String callerReference = "malformed-ordered-key-groups-" + suffix(); + String body = distributionConfigXml(callerReference, """ + + o1 + allow-all + + + 1 + + + /private/* + o1 + allow-all + + 1 + kg-private + + + + + """); + + given() + .contentType("application/xml") + .body(body) + .when() + .post("/2020-05-31/distribution") + .then() + .statusCode(400) + .body(containsString("InvalidArgument")); + + assertDistributionWasNotCreated(callerReference); + } + + @Test + void rejectsTrustedKeyGroupsWithoutQuantityInOrderedBehavior() { + String callerReference = "missing-ordered-key-group-quantity-" + suffix(); + String body = distributionConfigXml(callerReference, """ + + o1 + allow-all + + + 1 + + + /private/* + o1 + allow-all + + true + kg-private + + + + + """); + + given() + .contentType("application/xml") + .body(body) + .when() + .post("/2020-05-31/distribution") + .then() + .statusCode(400) + .body(containsString("InvalidArgument")); + + assertDistributionWasNotCreated(callerReference); + } + // ── Helpers ────────────────────────────────────────────────────────────────── + private static String trustedKeyGroupsXml(String keyGroup) { + return "true1" + + "" + keyGroup + ""; + } + + private String distributionConfigXml(String callerReference, String cacheBehaviors) { + return """ + + + %s + + 1 + + + o1 + malformed-key-groups.s3.us-east-1.amazonaws.com + + + + + %s + must not be created + true + + """.formatted(callerReference, cacheBehaviors); + } + + private void assertDistributionWasNotCreated(String callerReference) { + assertTrue(cloudFrontService.listDistributions(null, Integer.MAX_VALUE).stream() + .noneMatch(d -> callerReference.equals(d.getConfig().getCallerReference()))); + } + + private SignerResources createSignerResources(String name) + throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + String encodedKey = "-----BEGIN PUBLIC KEY-----\n" + + Base64.getMimeEncoder().encodeToString( + generator.generateKeyPair().getPublic().getEncoded()) + + "\n-----END PUBLIC KEY-----"; + PublicKey publicKey = new PublicKey(); + publicKey.setCallerReference("reference-" + name); + publicKey.setName("key-" + name); + publicKey.setEncodedKey(encodedKey); + publicKey = cloudFrontService.createPublicKey(publicKey); + + KeyGroup keyGroup = new KeyGroup(); + keyGroup.setName("group-" + name); + keyGroup.setItems(List.of(publicKey.getId())); + keyGroup = cloudFrontService.createKeyGroup(keyGroup); + return new SignerResources(publicKey.getId(), keyGroup.getId()); + } + private void createBucket(String bucket) { s3Service.createBucket(bucket, REGION); } @@ -435,4 +882,8 @@ class CloudFrontDistributionServingTest { private static String suffix() { return Long.toString(System.nanoTime(), 36); } + + private record SignerResources( + String publicKeyId, String keyGroupId) { + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java index 74fda873dc..3671a8e0d6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java @@ -5,14 +5,20 @@ 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.CloudFrontOriginAccessIdentity; +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.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.StreamingDistribution; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import java.security.KeyPairGenerator; +import java.security.spec.ECGenParameterSpec; +import java.util.Base64; import java.util.List; import java.util.Map; @@ -263,6 +269,261 @@ class CloudFrontServiceTest { assertEquals(409, error.getHttpStatus()); } + @Test + void validatesCloudFrontSignerKeyTypes() throws Exception { + CloudFrontService service = serviceWithDomainSuffix("cloudfront.net"); + + KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); + rsa.initialize(2048); + PublicKey rsaKey = publicKey( + "rsa-key", pem(rsa.generateKeyPair().getPublic())); + assertEquals( + rsaKey.getName(), + service.createPublicKey(rsaKey).getName()); + + KeyPairGenerator ec = KeyPairGenerator.getInstance("EC"); + ec.initialize(new ECGenParameterSpec("secp256r1")); + PublicKey ecKey = publicKey( + "ec-key", pem(ec.generateKeyPair().getPublic())); + assertEquals( + ecKey.getName(), + service.createPublicKey(ecKey).getName()); + + KeyPairGenerator shortRsa = KeyPairGenerator.getInstance("RSA"); + shortRsa.initialize(1024); + AwsException error = assertThrows( + AwsException.class, + () -> service.createPublicKey(publicKey( + "short-rsa", + pem(shortRsa.generateKeyPair().getPublic())))); + assertEquals("InvalidArgument", error.getErrorCode()); + } + + @Test + void rejectsDuplicatePublicKeyCallerReferences() throws Exception { + CloudFrontService service = serviceWithDomainSuffix("cloudfront.net"); + PublicKey existing = + service.createPublicKey(validPublicKey("existing")); + PublicKey duplicate = validPublicKey("duplicate"); + duplicate.setCallerReference(existing.getCallerReference()); + + AwsException error = assertThrows( + AwsException.class, + () -> service.createPublicKey(duplicate)); + + assertEquals("PublicKeyAlreadyExists", error.getErrorCode()); + assertEquals(409, error.getHttpStatus()); + assertEquals(1, service.listPublicKeys(null, 100).size()); + } + + @Test + void validatesKeyGroupMembership() throws Exception { + CloudFrontService service = serviceWithDomainSuffix("cloudfront.net"); + KeyGroup empty = new KeyGroup(); + empty.setName("empty"); + empty.setItems(List.of()); + + AwsException emptyError = assertThrows( + AwsException.class, () -> service.createKeyGroup(empty)); + assertEquals("InvalidArgument", emptyError.getErrorCode()); + + KeyGroup missing = new KeyGroup(); + missing.setName("missing"); + missing.setItems(List.of("missing-public-key")); + AwsException missingError = assertThrows( + AwsException.class, () -> service.createKeyGroup(missing)); + assertEquals("InvalidArgument", missingError.getErrorCode()); + + PublicKey key = service.createPublicKey(validPublicKey("member")); + KeyGroup valid = keyGroup("valid", key.getId()); + assertEquals( + List.of(key.getId()), + service.createKeyGroup(valid).getItems()); + } + + @Test + void rejectsKeyGroupsWithMoreThanFivePublicKeys() throws Exception { + CloudFrontService service = serviceWithDomainSuffix("cloudfront.net"); + KeyGroup overQuota = new KeyGroup(); + overQuota.setName("over-quota"); + overQuota.setItems(List.of( + "key-1", "key-2", "key-3", "key-4", "key-5", "key-6")); + + AwsException createError = assertThrows( + AwsException.class, + () -> service.createKeyGroup(overQuota)); + assertEquals( + "TooManyPublicKeysInKeyGroup", + createError.getErrorCode()); + assertEquals(400, createError.getHttpStatus()); + + PublicKey key = service.createPublicKey(validPublicKey("member")); + KeyGroup existing = + service.createKeyGroup(keyGroup("existing", key.getId())); + AwsException updateError = assertThrows( + AwsException.class, + () -> service.updateKeyGroup( + existing.getId(), existing.getEtag(), overQuota)); + assertEquals( + "TooManyPublicKeysInKeyGroup", + updateError.getErrorCode()); + assertEquals(400, updateError.getHttpStatus()); + } + + @Test + void rejectsDuplicateKeyGroupNamesOnCreateAndUpdate() + throws Exception { + CloudFrontService service = serviceWithDomainSuffix("cloudfront.net"); + PublicKey key = service.createPublicKey(validPublicKey("member")); + KeyGroup first = + service.createKeyGroup(keyGroup("existing", key.getId())); + + AwsException createError = assertThrows( + AwsException.class, + () -> service.createKeyGroup( + keyGroup("existing", key.getId()))); + assertEquals("KeyGroupAlreadyExists", createError.getErrorCode()); + assertEquals(409, createError.getHttpStatus()); + + KeyGroup second = + service.createKeyGroup(keyGroup("other", key.getId())); + KeyGroup renamed = keyGroup("existing", key.getId()); + AwsException updateError = assertThrows( + AwsException.class, + () -> service.updateKeyGroup( + second.getId(), second.getEtag(), renamed)); + assertEquals("KeyGroupAlreadyExists", updateError.getErrorCode()); + assertEquals(409, updateError.getHttpStatus()); + + assertEquals( + "existing", + service.updateKeyGroup( + first.getId(), + first.getEtag(), + keyGroup("existing", key.getId())) + .getName()); + } + + @Test + void returnsPreconditionFailedForStaleSignerResourceEtags() + throws Exception { + CloudFrontService service = serviceWithDomainSuffix("cloudfront.net"); + PublicKey key = service.createPublicKey(validPublicKey("stale")); + KeyGroup group = + service.createKeyGroup(keyGroup("stale", key.getId())); + + AwsException updatePublicKeyError = assertThrows( + AwsException.class, + () -> service.updatePublicKey( + key.getId(), "stale-etag", key)); + assertEquals( + "PreconditionFailed", + updatePublicKeyError.getErrorCode()); + assertEquals(412, updatePublicKeyError.getHttpStatus()); + + AwsException deletePublicKeyError = assertThrows( + AwsException.class, + () -> service.deletePublicKey( + key.getId(), "stale-etag")); + assertEquals( + "PreconditionFailed", + deletePublicKeyError.getErrorCode()); + assertEquals(412, deletePublicKeyError.getHttpStatus()); + + AwsException updateKeyGroupError = assertThrows( + AwsException.class, + () -> service.updateKeyGroup( + group.getId(), "stale-etag", group)); + assertEquals( + "PreconditionFailed", + updateKeyGroupError.getErrorCode()); + assertEquals(412, updateKeyGroupError.getHttpStatus()); + + AwsException deleteKeyGroupError = assertThrows( + AwsException.class, + () -> service.deleteKeyGroup( + group.getId(), "stale-etag")); + assertEquals( + "PreconditionFailed", + deleteKeyGroupError.getErrorCode()); + assertEquals(412, deleteKeyGroupError.getHttpStatus()); + } + + @Test + void validatesTrustedKeyGroupsOnDistributionCreateAndUpdate() + throws Exception { + CloudFrontService service = serviceWithDomainSuffix("cloudfront.net"); + PublicKey key = service.createPublicKey(validPublicKey("trusted")); + KeyGroup group = + service.createKeyGroup(keyGroup("trusted", key.getId())); + + Distribution valid = distributionWithTrustedGroup(group.getId()); + assertEquals( + group.getId(), + service.createDistribution(valid, Map.of()) + .getConfig() + .getDefaultCacheBehavior() + .getTrustedKeyGroups() + .getFirst()); + + AwsException missingError = assertThrows( + AwsException.class, + () -> service.createDistribution( + distributionWithTrustedGroup("missing-group"), + Map.of())); + assertEquals( + "TrustedKeyGroupDoesNotExist", + missingError.getErrorCode()); + + DistributionConfig emptyConfig = new DistributionConfig(); + DefaultCacheBehavior emptyBehavior = new DefaultCacheBehavior(); + emptyBehavior.setTrustedKeyGroupsEnabled(true); + emptyConfig.setDefaultCacheBehavior(emptyBehavior); + Distribution empty = new Distribution(); + empty.setConfig(emptyConfig); + AwsException emptyError = assertThrows( + AwsException.class, + () -> service.createDistribution(empty, Map.of())); + assertEquals("InvalidArgument", emptyError.getErrorCode()); + + Distribution existing = + service.createDistribution(distribution(false, List.of()), Map.of()); + AwsException updateError = assertThrows( + AwsException.class, + () -> service.updateDistribution( + existing.getId(), + existing.getEtag(), + distributionWithTrustedGroup("missing-group"))); + assertEquals( + "TrustedKeyGroupDoesNotExist", + updateError.getErrorCode()); + assertEquals( + existing.getEtag(), + service.getDistribution(existing.getId()).getEtag()); + } + + @Test + void rejectsDeletingSignerResourcesThatAreInUse() throws Exception { + CloudFrontService service = serviceWithDomainSuffix("cloudfront.net"); + PublicKey key = service.createPublicKey(validPublicKey("in-use")); + KeyGroup group = + service.createKeyGroup(keyGroup("in-use", key.getId())); + service.createDistribution( + distributionWithTrustedGroup(group.getId()), Map.of()); + + AwsException publicKeyError = assertThrows( + AwsException.class, + () -> service.deletePublicKey(key.getId(), key.getEtag())); + assertEquals("PublicKeyInUse", publicKeyError.getErrorCode()); + assertEquals(409, publicKeyError.getHttpStatus()); + + AwsException keyGroupError = assertThrows( + AwsException.class, + () -> service.deleteKeyGroup(group.getId(), group.getEtag())); + assertEquals("ResourceInUse", keyGroupError.getErrorCode()); + assertEquals(409, keyGroupError.getHttpStatus()); + } + private static Distribution distribution(boolean enabled, List aliases) { DistributionConfig config = new DistributionConfig(); config.setEnabled(enabled); @@ -281,6 +542,45 @@ class CloudFrontServiceTest { return oac; } + private static PublicKey validPublicKey(String name) throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return publicKey(name, pem(generator.generateKeyPair().getPublic())); + } + + private static PublicKey publicKey(String name, String encodedKey) { + PublicKey key = new PublicKey(); + key.setCallerReference("reference-" + name); + key.setName(name); + key.setEncodedKey(encodedKey); + return key; + } + + private static String pem(java.security.PublicKey key) { + return "-----BEGIN PUBLIC KEY-----\n" + + Base64.getMimeEncoder().encodeToString(key.getEncoded()) + + "\n-----END PUBLIC KEY-----"; + } + + private static KeyGroup keyGroup(String name, String publicKeyId) { + KeyGroup group = new KeyGroup(); + group.setName(name); + group.setItems(List.of(publicKeyId)); + return group; + } + + private static Distribution distributionWithTrustedGroup( + String keyGroupId) { + DefaultCacheBehavior behavior = new DefaultCacheBehavior(); + behavior.setTrustedKeyGroupsEnabled(true); + behavior.setTrustedKeyGroups(List.of(keyGroupId)); + DistributionConfig config = new DistributionConfig(); + config.setDefaultCacheBehavior(behavior); + Distribution distribution = new Distribution(); + distribution.setConfig(config); + return distribution; + } + private static CloudFrontOriginAccessIdentity originAccessIdentity( CloudFrontService service) { CloudFrontOriginAccessIdentity oai = new CloudFrontOriginAccessIdentity(); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontSignatureVerifierTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontSignatureVerifierTest.java new file mode 100644 index 0000000000..286a120b77 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontSignatureVerifierTest.java @@ -0,0 +1,581 @@ +package io.github.hectorvent.floci.services.cloudfront; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PublicKey; +import java.security.Signature; +import java.security.spec.ECGenParameterSpec; +import java.time.Instant; +import java.util.Base64; +import java.util.Map; +import java.util.function.Function; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit tests for {@link CloudFrontSignatureVerifier}: signs requests with a real in-test RSA key pair + * and asserts the AWS accept/reject behavior for canned and custom policies, signed URLs and signed + * cookies, expiry, resource binding, and trust. + */ +class CloudFrontSignatureVerifierTest { + + private static final String KEY_ID = "APKAEXAMPLEKEYID"; + private static final String RESOURCE = "https://d123.cloudfront.net/private/file.jpg"; + private final Instant now = Instant.parse("2026-01-01T00:00:00Z"); + + private KeyPair keyPair; + private String pem; + + @BeforeEach + void setUp() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + keyPair = generator.generateKeyPair(); + pem = pem(keyPair.getPublic()); + } + + /** Resolver that trusts KEY_ID only (mimics a public key that is a member of a trusted key group). */ + private Function trusted() { + return id -> KEY_ID.equals(id) ? pem : null; + } + + private String signCfBase64(String data, String algorithm) throws Exception { + return signCfBase64(keyPair, data, algorithm); + } + + private static String signCfBase64( + KeyPair signingKeyPair, String data, String algorithm) + throws Exception { + Signature signature = Signature.getInstance(algorithm); + signature.initSign(signingKeyPair.getPrivate()); + signature.update(data.getBytes(StandardCharsets.UTF_8)); + return cfBase64(signature.sign()); + } + + private static String pem(PublicKey publicKey) { + return "-----BEGIN PUBLIC KEY-----\n" + + Base64.getMimeEncoder().encodeToString(publicKey.getEncoded()) + + "\n-----END PUBLIC KEY-----"; + } + + private static String cfBase64(byte[] bytes) { + return Base64.getEncoder().encodeToString(bytes).replace('+', '-').replace('=', '_').replace('/', '~'); + } + + private long soon() { + return now.getEpochSecond() + 3600; + } + + @Test + void cannedPolicySignedUrlIsAccepted() throws Exception { + String policy = CloudFrontSignatureVerifier.cannedPolicy(RESOURCE, Long.toString(soon())); + Map query = Map.of( + "Expires", Long.toString(soon()), + "Signature", signCfBase64(policy, "SHA1withRSA"), + "Key-Pair-Id", KEY_ID); + + var result = CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), null, trusted(), now); + assertTrue(result.allowed(), result.reason()); + } + + @Test + void cannedPolicyWithBareApplicationQueryIsAccepted() throws Exception { + String resource = RESOURCE + "?flag"; + String policy = CloudFrontSignatureVerifier.cannedPolicy( + resource, Long.toString(soon())); + Map query = Map.of( + "Expires", Long.toString(soon()), + "Signature", signCfBase64(policy, "SHA1withRSA"), + "Key-Pair-Id", KEY_ID); + + var result = CloudFrontSignatureVerifier.verify( + resource, query, Map.of(), null, trusted(), now); + assertTrue(result.allowed(), result.reason()); + } + + @Test + void exactCustomPolicyWithApplicationQueryIsAccepted() throws Exception { + String resource = RESOURCE + "?license=paid"; + String policyJson = "{\"Statement\":[{\"Resource\":\"" + resource + "\"," + + "\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":" + soon() + "}}}]}"; + Map query = Map.of( + "Policy", cfBase64(policyJson.getBytes(StandardCharsets.UTF_8)), + "Signature", signCfBase64(policyJson, "SHA1withRSA"), + "Key-Pair-Id", KEY_ID); + + var result = CloudFrontSignatureVerifier.verify( + resource, query, Map.of(), null, trusted(), now); + assertTrue(result.allowed(), result.reason()); + } + + @Test + void sha256CannedPolicyIsAccepted() throws Exception { + String policy = CloudFrontSignatureVerifier.cannedPolicy(RESOURCE, Long.toString(soon())); + Map query = Map.of( + "Expires", Long.toString(soon()), + "Signature", signCfBase64(policy, "SHA256withRSA"), + "Key-Pair-Id", KEY_ID, + "Hash-Algorithm", "SHA256"); + + assertTrue(CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), null, trusted(), now).allowed()); + } + + @Test + void sha256SignedCookieIsAccepted() throws Exception { + String policy = + CloudFrontSignatureVerifier.cannedPolicy( + RESOURCE, Long.toString(soon())); + Map cookies = Map.of( + "CloudFront-Expires", Long.toString(soon()), + "CloudFront-Signature", + signCfBase64(policy, "SHA256withRSA"), + "CloudFront-Key-Pair-Id", KEY_ID, + "CloudFront-Hash-Algorithm", "SHA256"); + + assertTrue(CloudFrontSignatureVerifier.verify( + RESOURCE, Map.of(), cookies, null, trusted(), now).allowed()); + } + + @Test + void unsupportedHashAlgorithmIsRejected() throws Exception { + String policy = + CloudFrontSignatureVerifier.cannedPolicy( + RESOURCE, Long.toString(soon())); + Map query = Map.of( + "Expires", Long.toString(soon()), + "Signature", signCfBase64(policy, "SHA1withRSA"), + "Key-Pair-Id", KEY_ID, + "Hash-Algorithm", "SHA512"); + + assertFalse(CloudFrontSignatureVerifier.verify( + RESOURCE, query, Map.of(), null, trusted(), now).allowed()); + } + + @Test + void anySignedUrlParameterMakesCloudFrontIgnoreSignedCookies() + throws Exception { + String policy = + CloudFrontSignatureVerifier.cannedPolicy( + RESOURCE, Long.toString(soon())); + Map cookies = Map.of( + "CloudFront-Expires", Long.toString(soon()), + "CloudFront-Signature", + signCfBase64(policy, "SHA1withRSA"), + "CloudFront-Key-Pair-Id", KEY_ID); + + var result = CloudFrontSignatureVerifier.verify( + RESOURCE, + Map.of("Expires", Long.toString(soon())), + cookies, + null, + trusted(), + now); + + assertFalse(result.allowed()); + assertEquals("Missing CloudFront signature", result.reason()); + } + + @Test + void ecdsaP256Sha256SignatureIsAccepted() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("EC"); + generator.initialize(new ECGenParameterSpec("secp256r1")); + KeyPair ecKeyPair = generator.generateKeyPair(); + String policy = + CloudFrontSignatureVerifier.cannedPolicy( + RESOURCE, Long.toString(soon())); + Map query = Map.of( + "Expires", Long.toString(soon()), + "Signature", + signCfBase64(ecKeyPair, policy, "SHA256withECDSA"), + "Key-Pair-Id", KEY_ID, + "Hash-Algorithm", "SHA256"); + + assertTrue(CloudFrontSignatureVerifier.verify( + RESOURCE, + query, + Map.of(), + null, + id -> KEY_ID.equals(id) ? pem(ecKeyPair.getPublic()) : null, + now).allowed()); + } + + @Test + void unsupportedRsaKeySizeIsRejected() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(1024); + KeyPair shortKeyPair = generator.generateKeyPair(); + String policy = + CloudFrontSignatureVerifier.cannedPolicy( + RESOURCE, Long.toString(soon())); + Map query = Map.of( + "Expires", Long.toString(soon()), + "Signature", + signCfBase64(shortKeyPair, policy, "SHA1withRSA"), + "Key-Pair-Id", KEY_ID); + + assertFalse(CloudFrontSignatureVerifier.verify( + RESOURCE, + query, + Map.of(), + null, + id -> KEY_ID.equals(id) ? pem(shortKeyPair.getPublic()) : null, + now).allowed()); + } + + @Test + void expiredSignedUrlIsRejected() throws Exception { + long expired = now.getEpochSecond() - 1; + String policy = CloudFrontSignatureVerifier.cannedPolicy(RESOURCE, Long.toString(expired)); + Map query = Map.of( + "Expires", Long.toString(expired), + "Signature", signCfBase64(policy, "SHA1withRSA"), + "Key-Pair-Id", KEY_ID); + + var result = CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), null, trusted(), now); + assertFalse(result.allowed()); + assertTrue(result.reason().contains("expired"), result.reason()); + } + + @Test + void signatureForADifferentResourceIsRejected() throws Exception { + // Sign for RESOURCE but present the signature against a different requested URL. + String policy = CloudFrontSignatureVerifier.cannedPolicy(RESOURCE, Long.toString(soon())); + Map query = Map.of( + "Expires", Long.toString(soon()), + "Signature", signCfBase64(policy, "SHA1withRSA"), + "Key-Pair-Id", KEY_ID); + + var result = CloudFrontSignatureVerifier.verify( + "https://d123.cloudfront.net/private/OTHER.jpg", query, Map.of(), null, trusted(), now); + assertFalse(result.allowed()); + } + + @Test + void untrustedKeyPairIdIsRejected() throws Exception { + String policy = CloudFrontSignatureVerifier.cannedPolicy(RESOURCE, Long.toString(soon())); + Map query = Map.of( + "Expires", Long.toString(soon()), + "Signature", signCfBase64(policy, "SHA1withRSA"), + "Key-Pair-Id", "SOME-OTHER-KEY"); + + var result = CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), null, trusted(), now); + assertFalse(result.allowed()); + assertTrue(result.reason().contains("trusted signer"), result.reason()); + } + + @Test + void missingSignatureIsRejected() { + var result = CloudFrontSignatureVerifier.verify(RESOURCE, Map.of(), Map.of(), null, trusted(), now); + assertFalse(result.allowed()); + assertEquals("Missing CloudFront signature", result.reason()); + } + + @Test + void malformedPolicyBase64IsDeniedNotThrown() { + // A Policy value that is not valid CloudFront base64 is a bad request: verify() must deny + // it (CloudFront answers 403) rather than let the base64 decode throw and become a 500. + Map query = Map.of( + "Policy", "@@@not-valid-base64@@@", + "Signature", "AAAA", + "Key-Pair-Id", KEY_ID); + + var result = CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), null, trusted(), now); + assertFalse(result.allowed()); + assertTrue(result.reason().contains("base64"), result.reason()); + } + + @Test + void customPolicyWithWildcardResourceIsAccepted() throws Exception { + String policyJson = "{\"Statement\":[{\"Resource\":\"https://d123.cloudfront.net/private/*\"," + + "\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":" + soon() + "}}}]}"; + Map query = Map.of( + "Policy", cfBase64(policyJson.getBytes(StandardCharsets.UTF_8)), + "Signature", signCfBase64(policyJson, "SHA1withRSA"), + "Key-Pair-Id", KEY_ID); + + assertTrue(CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), null, trusted(), now).allowed()); + } + + @Test + void questionMarkAfterQueryDelimiterActsAsWildcard() throws Exception { + String resourcePattern = + "https://d123.cloudfront.net/private/?ile.jpg?license=*"; + String policyJson = "{\"Statement\":[{\"Resource\":\"" + resourcePattern + "\"," + + "\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":" + soon() + "}}}]}"; + Map query = Map.of( + "Policy", cfBase64(policyJson.getBytes(StandardCharsets.UTF_8)), + "Signature", signCfBase64(policyJson, "SHA1withRSA"), + "Key-Pair-Id", KEY_ID); + + assertFalse(CloudFrontSignatureVerifier.verify( + "https://d123.cloudfront.net/private/file.jpg?license=paid", + query, Map.of(), null, trusted(), now).allowed()); + assertTrue(CloudFrontSignatureVerifier.verify( + "https://d123.cloudfront.net/private/?ile.jpgXlicense=paid", + query, Map.of(), null, trusted(), now).allowed()); + assertTrue(CloudFrontSignatureVerifier.verify( + resourcePattern, + query, Map.of(), null, trusted(), now).allowed()); + } + + @Test + void signedCookieCustomPolicyRequiresAnExplicitHttpProtocol() + throws Exception { + String policyJson = "{\"Statement\":[{\"Resource\":\"*\"," + + "\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":" + + soon() + "}}}]}"; + Map cookies = customPolicyCookies(policyJson); + + assertFalse(CloudFrontSignatureVerifier.verify( + RESOURCE, Map.of(), cookies, null, trusted(), now).allowed()); + } + + @Test + void signedCookieCustomPolicyAcceptsHttpsWildcardResource() + throws Exception { + String policyJson = "{\"Statement\":[{\"Resource\":\"https://*\"," + + "\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":" + + soon() + "}}}]}"; + Map cookies = customPolicyCookies(policyJson); + + assertTrue(CloudFrontSignatureVerifier.verify( + RESOURCE, Map.of(), cookies, null, trusted(), now).allowed()); + } + + @Test + void signedCookieCustomPolicyMayOmitResource() + throws Exception { + String policyJson = "{\"Statement\":[{\"Condition\":{\"DateLessThan\":" + + "{\"AWS:EpochTime\":" + soon() + "}}}]}"; + Map cookies = customPolicyCookies(policyJson); + + assertTrue(CloudFrontSignatureVerifier.verify( + RESOURCE, Map.of(), cookies, null, trusted(), now).allowed()); + } + + @Test + void customPolicyMayOmitResource() throws Exception { + String policyJson = "{\"Statement\":[{\"Condition\":{\"DateLessThan\":" + + "{\"AWS:EpochTime\":" + soon() + "}}}]}"; + Map query = customPolicyQuery(policyJson); + + assertTrue(CloudFrontSignatureVerifier.verify( + RESOURCE, query, Map.of(), null, trusted(), now).allowed()); + } + + @Test + void customPolicyMustContainExactlyOneStatement() throws Exception { + String statement = "{\"Resource\":\"*\",\"Condition\":{\"DateLessThan\":" + + "{\"AWS:EpochTime\":" + soon() + "}}}"; + String policyJson = + "{\"Statement\":[" + statement + "," + statement + "]}"; + + assertFalse(CloudFrontSignatureVerifier.verify( + RESOURCE, + customPolicyQuery(policyJson), + Map.of(), + null, + trusted(), + now).allowed()); + } + + @Test + void customPolicyRequiresIntegralEpochTimes() throws Exception { + String policyJson = "{\"Statement\":[{\"Resource\":\"*\"," + + "\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":" + + soon() + ".5}}}]}"; + + assertFalse(CloudFrontSignatureVerifier.verify( + RESOURCE, + customPolicyQuery(policyJson), + Map.of(), + null, + trusted(), + now).allowed()); + } + + @Test + void dateGreaterThanRejectsTheBoundarySecond() throws Exception { + String policyJson = "{\"Statement\":[{\"Resource\":\"*\"," + + "\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":" + + soon() + "},\"DateGreaterThan\":{\"AWS:EpochTime\":" + + now.getEpochSecond() + "}}}]}"; + + assertFalse(CloudFrontSignatureVerifier.verify( + RESOURCE, + customPolicyQuery(policyJson), + Map.of(), + null, + trusted(), + now).allowed()); + } + + @Test + void customPolicyIpAddressConditionIsEnforced() throws Exception { + String policyJson = "{\"Statement\":[{\"Resource\":\"https://d123.cloudfront.net/private/*\"," + + "\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":" + soon() + "}," + + "\"IpAddress\":{\"AWS:SourceIp\":\"203.0.113.0/24\"}}}]}"; + Map query = Map.of( + "Policy", cfBase64(policyJson.getBytes(StandardCharsets.UTF_8)), + "Signature", signCfBase64(policyJson, "SHA1withRSA"), + "Key-Pair-Id", KEY_ID); + + assertTrue(CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), "203.0.113.5", trusted(), now).allowed()); + assertFalse(CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), "198.51.100.5", trusted(), now).allowed()); + assertFalse(CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), null, trusted(), now).allowed()); + // An IPv6 client must not bypass an IPv4-only allow-list (containment fails closed). + assertFalse(CloudFrontSignatureVerifier.verify(RESOURCE, query, Map.of(), "2001:db8::1", trusted(), now).allowed()); + } + + private Map customPolicyCookies(String policyJson) + throws Exception { + return Map.of( + "CloudFront-Policy", + cfBase64(policyJson.getBytes(StandardCharsets.UTF_8)), + "CloudFront-Signature", + signCfBase64(policyJson, "SHA1withRSA"), + "CloudFront-Key-Pair-Id", + KEY_ID); + } + + @Test + void resourceWildcardsRespectUrlSectionBoundaries() { + assertTrue(CloudFrontSignatureVerifier.wildcardMatches( + "https://d123.cloudfront.net/hello*world", + "https://d123.cloudfront.net/hello-world")); + assertFalse(CloudFrontSignatureVerifier.wildcardMatches( + "https://d123.cloudfront.net/hello*world", + "https://d123.cloudfront.net/hello?world")); + assertTrue(CloudFrontSignatureVerifier.wildcardMatches( + "https://d123.cloudfront.net/file.jpg?license=?", + "https://d123.cloudfront.net/file.jpg?license=x")); + assertFalse(CloudFrontSignatureVerifier.wildcardMatches( + "https://d123.cloudfront.net/private/?ile.jpg", + "https://d123.cloudfront.net/private/file.jpg")); + assertFalse(CloudFrontSignatureVerifier.wildcardMatches( + "https://d123.cloudfront.net/private/?ile.jpg?license=*", + "https://d123.cloudfront.net/private/file.jpg?license=paid")); + assertTrue(CloudFrontSignatureVerifier.wildcardMatches( + "https://d123.cloudfront.net/private/?ile.jpg?license=*", + "https://d123.cloudfront.net/private/?ile.jpgXlicense=paid")); + assertTrue(CloudFrontSignatureVerifier.wildcardMatches( + "https://d123.cloudfront.net/file?flag", + "https://d123.cloudfront.net/file?flag")); + assertTrue(CloudFrontSignatureVerifier.wildcardMatches( + "https://d123.cloudfront.net/file?lic?nse=*", + "https://d123.cloudfront.net/file?license=value")); + assertFalse(CloudFrontSignatureVerifier.wildcardMatches( + "https://d123.cloudfront.net/file?lic?nse=*", + "https://d123.cloudfront.net/fileXlic?nse=value")); + assertFalse(CloudFrontSignatureVerifier.wildcardMatches( + "https://d123.cloudfront.net/private/?ile.jpg=download?license=*", + "https://d123.cloudfront.net/private/file.jpg=download?license=paid")); + assertTrue(CloudFrontSignatureVerifier.wildcardMatches( + "https://d123.cloudfront.net/private/?ile.jpg=download?license=*", + "https://d123.cloudfront.net/private/?ile.jpg=downloadXlicense=paid")); + assertTrue(CloudFrontSignatureVerifier.wildcardMatches( + "https://d123.cloudfront.net/private/?ile.jpg?license=*", + "https://d123.cloudfront.net/private/?ile.jpg?license=*")); + assertTrue(CloudFrontSignatureVerifier.wildcardMatches( + "https://d123.cloudfront.net/private/?ile=download*", + "https://d123.cloudfront.net/private/?ile=download-secret")); + assertFalse(CloudFrontSignatureVerifier.wildcardMatches( + "https://d123.cloudfront.net/file.jpg?license=*", + "https://d123.cloudfront.net/file.jpgXlicense=paid")); + assertTrue(CloudFrontSignatureVerifier.wildcardMatches( + "https://d123.cloudfront.net/file.jpg?license=*", + "https://d123.cloudfront.net/file.jpg?license=paid")); + } + + @Test + void trailingWildcardsUseCloudFrontPropagationRules() { + assertTrue(CloudFrontSignatureVerifier.wildcardMatches( + "https://d123.cloudfront.net/private/*", + "https://d123.cloudfront.net/private/file.jpg?license=yes")); + assertTrue(CloudFrontSignatureVerifier.wildcardMatches( + "https://d123.cloudfront.net*", + "https://d123.cloudfront.net/private/file.jpg?license=yes")); + assertTrue(CloudFrontSignatureVerifier.wildcardMatches( + "*d123.cloudfront.net", + "https://media.d123.cloudfront.net/")); + assertFalse(CloudFrontSignatureVerifier.wildcardMatches( + "*d123.cloudfront.net", + "https://media.d123.cloudfront.net/private/file.jpg")); + assertTrue(CloudFrontSignatureVerifier.wildcardMatches( + "*", "https://any.example.test/file")); + } + + @Test + void resourceProtocolMustUseAnAwsSupportedForm() { + assertFalse(CloudFrontSignatureVerifier.wildcardMatches( + "h*://d123.cloudfront.net/private/*", RESOURCE)); + assertTrue(CloudFrontSignatureVerifier.wildcardMatches( + "*://d123.cloudfront.net/private/*", RESOURCE)); + } + + @Test + void ipInCidrSupportsOnlyExplicitIpv4Cidr() { + assertFalse(CloudFrontSignatureVerifier.ipInCidr( + "2001:db8::5", "2001:db8::/32")); + assertFalse(CloudFrontSignatureVerifier.ipInCidr("2001:dead::5", "2001:db8::/32")); + assertFalse(CloudFrontSignatureVerifier.ipInCidr("2001:db8::1", "192.0.2.0/24")); + assertFalse(CloudFrontSignatureVerifier.ipInCidr("not-an-ip", "192.0.2.0/24")); + assertFalse(CloudFrontSignatureVerifier.ipInCidr("203.0.113.5", "203.0.113.5")); + assertTrue(CloudFrontSignatureVerifier.ipInCidr("203.0.113.5", "203.0.113.5/32")); + assertTrue(CloudFrontSignatureVerifier.ipInCidr("10.0.0.1", "0.0.0.0/0")); + } + + @Test + void signedCookiesAreAccepted() throws Exception { + String policy = CloudFrontSignatureVerifier.cannedPolicy(RESOURCE, Long.toString(soon())); + Map cookies = Map.of( + "CloudFront-Expires", Long.toString(soon()), + "CloudFront-Signature", signCfBase64(policy, "SHA1withRSA"), + "CloudFront-Key-Pair-Id", KEY_ID); + + assertTrue(CloudFrontSignatureVerifier.verify(RESOURCE, Map.of(), cookies, null, trusted(), now).allowed()); + } + + @Test + void signingParametersAreRemovedFromTheOriginQuery() { + String rawQuery = "color=blue&Policy=opaque&Signature=sig&Key-Pair-Id=key" + + "&Hash-Algorithm=SHA256&encoded=a%2Fb&%45xpires=123"; + + assertEquals("color=blue&encoded=a%2Fb", + CloudFrontServingController.stripCloudFrontSigningParams(rawQuery)); + } + + @Test + void emptyApplicationQueryComponentsArePreserved() { + assertEquals( + "&color=blue", + CloudFrontServingController.stripCloudFrontSigningParams( + "&color=blue&Signature=sig")); + assertEquals( + "color=blue&&", + CloudFrontServingController.stripCloudFrontSigningParams( + "color=blue&&Signature=sig&")); + } + + @Test + void malformedQueryParameterNameIsPreservedWithoutThrowing() { + String rawQuery = "%ZZ=value&Signature=sig&color=blue"; + + assertEquals("%ZZ=value&color=blue", + CloudFrontServingController.stripCloudFrontSigningParams(rawQuery)); + } + + private Map customPolicyQuery(String policyJson) + throws Exception { + return Map.of( + "Policy", cfBase64(policyJson.getBytes(StandardCharsets.UTF_8)), + "Signature", signCfBase64(policyJson, "SHA1withRSA"), + "Key-Pair-Id", KEY_ID); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontSignedUrlServingTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontSignedUrlServingTest.java new file mode 100644 index 0000000000..e055071682 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontSignedUrlServingTest.java @@ -0,0 +1,267 @@ +package io.github.hectorvent.floci.services.cloudfront; + +import io.github.hectorvent.floci.services.cloudfront.model.CacheBehavior; +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.KeyGroup; +import io.github.hectorvent.floci.services.cloudfront.model.Origin; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.time.Instant; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * End-to-end test for CloudFront private content: a cache behavior with trusted key groups requires a + * valid signed request (signed URL) and returns 403 otherwise, while a public behavior serves without + * a signature. Registers a real RSA public key + key group through the CloudFront service and signs the + * request with the matching private key. + */ +@QuarkusTest +class CloudFrontSignedUrlServingTest { + + private static final String REGION = "us-east-1"; + + @Inject + S3Service s3Service; + + @Inject + CloudFrontService cloudFrontService; + + @Test + void privateContentRequiresAValidSignedUrl() throws Exception { + String suffix = Long.toString(System.nanoTime(), 36); + String bucket = "cf-private-" + suffix; + s3Service.createBucket(bucket, REGION); + s3Service.putObject(bucket, "private/secret.txt", ("SECRET-" + suffix).getBytes(StandardCharsets.UTF_8), + "text/plain", Map.of()); + s3Service.putObject(bucket, "public/open.txt", ("OPEN-" + suffix).getBytes(StandardCharsets.UTF_8), + "text/plain", Map.of()); + + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair keyPair = generator.generateKeyPair(); + String pem = "-----BEGIN PUBLIC KEY-----\n" + + Base64.getMimeEncoder().encodeToString(keyPair.getPublic().getEncoded()) + + "\n-----END PUBLIC KEY-----"; + + io.github.hectorvent.floci.services.cloudfront.model.PublicKey publicKey = + new io.github.hectorvent.floci.services.cloudfront.model.PublicKey(); + publicKey.setName("pk-" + suffix); + publicKey.setCallerReference("cr-" + suffix); + publicKey.setEncodedKey(pem); + publicKey = cloudFrontService.createPublicKey(publicKey); + + KeyGroup keyGroup = new KeyGroup(); + keyGroup.setName("kg-" + suffix); + keyGroup.setItems(List.of(publicKey.getId())); + keyGroup = cloudFrontService.createKeyGroup(keyGroup); + + DistributionConfig cfg = new DistributionConfig(); + cfg.setEnabled(true); + cfg.setOrigins(List.of(s3Origin("o", bucket))); + cfg.setDefaultCacheBehavior(defaultBehavior("o")); + CacheBehavior priv = new CacheBehavior(); + priv.setPathPattern("/private/*"); + priv.setTargetOriginId("o"); + priv.setViewerProtocolPolicy("allow-all"); + priv.setTrustedKeyGroups(List.of(keyGroup.getId())); + cfg.setCacheBehaviors(List.of(priv)); + + Distribution dist = cloudFrontService.createDistribution(distribution(cfg), Map.of()); + String host = dist.getDomainName(); + + // Public behavior: served without a signature. + given().header("Host", host).when().get("/public/open.txt") + .then().statusCode(200).body(containsString("OPEN-" + suffix)); + + // Private behavior without a signature → 403. + given().header("Host", host).when().get("/private/secret.txt") + .then().statusCode(403); + + // Vert.x rejects a malformed raw query name at ingress; it must fail closed, never become a 500. + String malformedResponse = rawGet(host, "/private/secret.txt?%ZZ=value"); + assertTrue(malformedResponse.startsWith("HTTP/1.1 400"), malformedResponse); + + // A valid signed URL (custom policy, wildcard resource) → 200 with the private content. + long expires = Instant.now().getEpochSecond() + 3600; + String policyJson = "{\"Statement\":[{\"Resource\":\"*\",\"Condition\":{\"DateLessThan\":" + + "{\"AWS:EpochTime\":" + expires + "}}}]}"; + Signature signer = Signature.getInstance("SHA1withRSA"); + signer.initSign(keyPair.getPrivate()); + signer.update(policyJson.getBytes(StandardCharsets.UTF_8)); + String signature = cfBase64(signer.sign()); + String policyParam = cfBase64(policyJson.getBytes(StandardCharsets.UTF_8)); + + given().header("Host", host) + .queryParam("Policy", policyParam) + .queryParam("Signature", signature) + .queryParam("Key-Pair-Id", publicKey.getId()) + .when().get("/private/secret.txt") + .then().statusCode(200).body(containsString("SECRET-" + suffix)); + + // Signed-cookie custom policies require an explicit http:// or https:// protocol. + String cookiePolicyJson = "{\"Statement\":[{\"Resource\":\"http://*\",\"Condition\":" + + "{\"DateLessThan\":{\"AWS:EpochTime\":" + expires + "}}}]}"; + String cookiePolicyParam = + cfBase64(cookiePolicyJson.getBytes(StandardCharsets.UTF_8)); + + // A valid SHA-256 signed cookie is accepted through the real HTTP cookie path. + Signature cookieSigner = Signature.getInstance("SHA256withRSA"); + cookieSigner.initSign(keyPair.getPrivate()); + cookieSigner.update(cookiePolicyJson.getBytes(StandardCharsets.UTF_8)); + String signedCookies = "CloudFront-Policy=" + cookiePolicyParam + + "; CloudFront-Signature=" + cfBase64(cookieSigner.sign()) + + "; CloudFront-Key-Pair-Id=" + publicKey.getId() + + "; CloudFront-Hash-Algorithm=SHA256"; + + given().header("Host", host) + .header("Cookie", signedCookies) + .when().get("/private/secret.txt") + .then().statusCode(200).body(containsString("SECRET-" + suffix)); + + // The presence of any signed-URL field makes CloudFront ignore valid signed cookies. + given().header("Host", host) + .header("Cookie", signedCookies) + .queryParam("Expires", expires) + .when().get("/private/secret.txt") + .then().statusCode(403); + + // Application-query bytes remain part of the signed resource after signing fields are removed. + String queryResource = "http://" + host + "/private/secret.txt?color=blue"; + String queryPolicy = "{\"Statement\":[{\"Resource\":\"" + queryResource + "\"," + + "\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":" + expires + "}}}]}"; + Signature querySigner = Signature.getInstance("SHA1withRSA"); + querySigner.initSign(keyPair.getPrivate()); + querySigner.update(queryPolicy.getBytes(StandardCharsets.UTF_8)); + + given().header("Host", host) + .queryParam("color", "blue") + .queryParam("Policy", + cfBase64(queryPolicy.getBytes(StandardCharsets.UTF_8))) + .queryParam("Signature", cfBase64(querySigner.sign())) + .queryParam("Key-Pair-Id", publicKey.getId()) + .when().get("/private/secret.txt") + .then().statusCode(200).body(containsString("SECRET-" + suffix)); + + // Same signature but an unknown Key-Pair-Id (not a trusted signer) → 403. + given().header("Host", host) + .queryParam("Policy", policyParam) + .queryParam("Signature", signature) + .queryParam("Key-Pair-Id", "not-a-real-key") + .when().get("/private/secret.txt") + .then().statusCode(403); + } + + @Test + void signedUrlForAPercentEncodedPathVerifiesAgainstTheRawUrl() throws Exception { + String suffix = Long.toString(System.nanoTime(), 36); + String bucket = "cf-enc-" + suffix; + s3Service.createBucket(bucket, REGION); + // The object key contains a space; on the wire the viewer requests it percent-encoded. + s3Service.putObject(bucket, "private/my report.pdf", ("DOC-" + suffix).getBytes(StandardCharsets.UTF_8), + "application/pdf", Map.of()); + + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair keyPair = generator.generateKeyPair(); + String pem = "-----BEGIN PUBLIC KEY-----\n" + + Base64.getMimeEncoder().encodeToString(keyPair.getPublic().getEncoded()) + + "\n-----END PUBLIC KEY-----"; + io.github.hectorvent.floci.services.cloudfront.model.PublicKey publicKey = + new io.github.hectorvent.floci.services.cloudfront.model.PublicKey(); + publicKey.setName("pk-" + suffix); + publicKey.setCallerReference("cr-" + suffix); + publicKey.setEncodedKey(pem); + publicKey = cloudFrontService.createPublicKey(publicKey); + + KeyGroup keyGroup = new KeyGroup(); + keyGroup.setName("kg-" + suffix); + keyGroup.setItems(List.of(publicKey.getId())); + keyGroup = cloudFrontService.createKeyGroup(keyGroup); + + DistributionConfig cfg = new DistributionConfig(); + cfg.setEnabled(true); + cfg.setOrigins(List.of(s3Origin("o", bucket))); + cfg.setDefaultCacheBehavior(defaultBehavior("o")); + CacheBehavior priv = new CacheBehavior(); + priv.setPathPattern("/private/*"); + priv.setTargetOriginId("o"); + priv.setViewerProtocolPolicy("allow-all"); + priv.setTrustedKeyGroups(List.of(keyGroup.getId())); + cfg.setCacheBehaviors(List.of(priv)); + Distribution dist = cloudFrontService.createDistribution(distribution(cfg), Map.of()); + String host = dist.getDomainName(); + + // Custom policy whose Resource carries the EXACT percent-encoded path the signer signs (scheme + // and host are wildcarded so the assertion isolates path encoding). If the resource URL were + // rebuilt from the decoded path, "my%20report.pdf" would not match "my report.pdf" → wrongly 403. + long expires = Instant.now().getEpochSecond() + 3600; + String resource = "*/private/my%20report.pdf"; + String policyJson = "{\"Statement\":[{\"Resource\":\"" + resource + "\",\"Condition\":" + + "{\"DateLessThan\":{\"AWS:EpochTime\":" + expires + "}}}]}"; + Signature signer = Signature.getInstance("SHA1withRSA"); + signer.initSign(keyPair.getPrivate()); + signer.update(policyJson.getBytes(StandardCharsets.UTF_8)); + String signature = cfBase64(signer.sign()); + String policyParam = cfBase64(policyJson.getBytes(StandardCharsets.UTF_8)); + + given().header("Host", host).urlEncodingEnabled(false) + .queryParam("Policy", policyParam) + .queryParam("Signature", signature) + .queryParam("Key-Pair-Id", publicKey.getId()) + .when().get("/private/my%20report.pdf") + .then().statusCode(200).body(containsString("DOC-" + suffix)); + } + + private static String cfBase64(byte[] bytes) { + return Base64.getEncoder().encodeToString(bytes).replace('+', '-').replace('=', '_').replace('/', '~'); + } + + private static String rawGet(String host, String pathAndQuery) throws Exception { + try (Socket socket = new Socket("127.0.0.1", io.restassured.RestAssured.port)) { + String request = "GET " + pathAndQuery + " HTTP/1.1\r\n" + + "Host: " + host + "\r\n" + + "Connection: close\r\n\r\n"; + socket.getOutputStream().write(request.getBytes(StandardCharsets.US_ASCII)); + socket.getOutputStream().flush(); + return new String(socket.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + } + } + + private static Distribution distribution(DistributionConfig cfg) { + Distribution dist = new Distribution(); + dist.setConfig(cfg); + return dist; + } + + private static Origin s3Origin(String id, String bucket) { + Origin origin = new Origin(); + origin.setId(id); + origin.setDomainName(bucket + ".s3." + REGION + ".amazonaws.com"); + origin.setS3OriginConfig(new LinkedHashMap<>(Map.of("OriginAccessIdentity", ""))); + return origin; + } + + private static DefaultCacheBehavior defaultBehavior(String originId) { + DefaultCacheBehavior dcb = new DefaultCacheBehavior(); + dcb.setTargetOriginId(originId); + dcb.setViewerProtocolPolicy("allow-all"); + return dcb; + } +}