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;
+ }
+}