feat(cloudfront): enforce signed private content (#1831)

* feat(cloudfront): serve distribution requests from S3 and custom origins

* feat(cloudfront): enforce signed private content

* chore: re-run CI

The Build and Test failure on the previous head was RuntimeApiServerTest's
extension/stop race, a pre-existing flake unrelated to this change — it also failed
on #1820, #1823 and on #2131's own branch (the PR that tried to de-flake it).
Reproduced locally under `--cpus=1` and fixed separately.

* fix(cloudfront): wildcard aliases match exactly one subdomain level

wildcardAliasMatches did a plain suffix check, so "*.example.com" also matched
a.b.example.com. AWS is explicit that a wildcard alternate domain name replaces the
wildcard at that level only:

  "you can't add alternate domain names that are at levels higher or lower than the
   wildcard. For example, you can't add the alternate domain names example.com or
   marketing.product.example.com."

  https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html

Practical effect: a distribution owning "*.example.com" would answer for
a.b.example.com, which on AWS belongs to whoever owns "*.b.example.com" — or to
nobody. Require the label standing in for the wildcard to contain no dot.

wildcardAliasesMatchSubdomainsAndPreferMoreSpecificNames asserted the old behaviour
(a.b.example.test resolving to the *.example.test distribution); it now asserts no
match, plus the same for a deeper wildcard.

* test(dynamodb): retain Quarkus port for cleanup

* fix(cloudfront): isolate mocked storage backends

* fix(cloudfront): match wildcards in signed policy queries
This commit is contained in:
Alex Banna authored and GitHub committed 2026-08-13 23:32:24 -04:00
1 parent 2ab795c6dc
commit 5657e35007
17 files changed
+3134 -28

No files matched your search

@@ -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<Distribution> distributionsWithAlias(String alias) {
return cloudFrontService.listDistributions(null, 1000).stream()
.filter(distribution -> distribution.getConfig() != null
@@ -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("<ResponsePagePath>/index.html</ResponsePagePath>"));
}
@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, """
<DefaultCacheBehavior>
<TargetOriginId>o1</TargetOriginId>
<ViewerProtocolPolicy>allow-all</ViewerProtocolPolicy>
<TrustedKeyGroups>
<Enabled>true</Enabled>
<Quantity>1</Quantity>
<Items><KeyGroup>%s</KeyGroup></Items>
</TrustedKeyGroups>
</DefaultCacheBehavior>
<CacheBehaviors>
<Quantity>1</Quantity>
<Items>
<CacheBehavior>
<PathPattern>/private/*</PathPattern>
<TargetOriginId>o1</TargetOriginId>
<ViewerProtocolPolicy>allow-all</ViewerProtocolPolicy>
<TrustedKeyGroups>
<Enabled>true</Enabled>
<Quantity>1</Quantity>
<Items><KeyGroup>%s</KeyGroup></Items>
</TrustedKeyGroups>
</CacheBehavior>
</Items>
</CacheBehaviors>
""".formatted(
defaultSigner.keyGroupId(),
privateSigner.keyGroupId()));
var created = given()
.contentType("application/xml")
.body(body)
.when()
.post("/2020-05-31/distribution")
.then()
.statusCode(201)
.body(containsString("<ActiveTrustedKeyGroups>"))
.body(containsString("<Enabled>true</Enabled>"))
.body(containsString(
"<KeyGroupId>" + defaultSigner.keyGroupId()
+ "</KeyGroupId>"))
.body(containsString(
"<KeyPairId>" + defaultSigner.publicKeyId()
+ "</KeyPairId>"))
.body(containsString("<ActiveTrustedSigners>"))
.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("<ActiveTrustedKeyGroups>"))
.body(containsString(
"<KeyGroupId>" + privateSigner.keyGroupId()
+ "</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, """
<DefaultCacheBehavior>
<TargetOriginId>o1</TargetOriginId>
<ViewerProtocolPolicy>allow-all</ViewerProtocolPolicy>
<TrustedKeyGroups>
<Enabled>false</Enabled>
<Quantity>1</Quantity>
<Items><KeyGroup>%s</KeyGroup></Items>
</TrustedKeyGroups>
</DefaultCacheBehavior>
<CacheBehaviors>
<Quantity>1</Quantity>
<Items>
<CacheBehavior>
<PathPattern>/private/*</PathPattern>
<TargetOriginId>o1</TargetOriginId>
<ViewerProtocolPolicy>allow-all</ViewerProtocolPolicy>
<TrustedKeyGroups>
<Enabled>false</Enabled>
<Quantity>1</Quantity>
<Items><KeyGroup>%s</KeyGroup></Items>
</TrustedKeyGroups>
</CacheBehavior>
</Items>
</CacheBehaviors>
""".formatted(
defaultSigner.keyGroupId(),
privateSigner.keyGroupId()));
var created = given()
.contentType("application/xml")
.body(body)
.when()
.post("/2020-05-31/distribution")
.then()
.statusCode(201)
.body(containsString("<Enabled>false</Enabled>"))
.body(containsString(
"<ActiveTrustedKeyGroups><Enabled>false</Enabled>"
+ "<Quantity>0</Quantity></ActiveTrustedKeyGroups>"))
.extract().response();
String configPath = created.header("Location") + "/config";
var config = given()
.when()
.get(configPath)
.then()
.statusCode(200)
.body(containsString("<Enabled>false</Enabled>"))
.extract().response();
given()
.contentType("application/xml")
.header("If-Match", config.header("ETag"))
.body(config.asString())
.when()
.put(configPath)
.then()
.statusCode(200)
.body(containsString("<Enabled>false</Enabled>"));
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, """
<DefaultCacheBehavior>
<TargetOriginId>o1</TargetOriginId>
<ViewerProtocolPolicy>allow-all</ViewerProtocolPolicy>
<TrustedKeyGroups>
<Enabled>true</Enabled>
<Quantity>0</Quantity>
</TrustedKeyGroups>
</DefaultCacheBehavior>
""");
given()
.contentType("application/xml")
.body(body)
.when()
.post("/2020-05-31/distribution")
.then()
.statusCode(400)
.body(containsString("<Code>InvalidArgument</Code>"));
assertDistributionWasNotCreated(callerReference);
}
@Test
void rejectsUnknownTrustedKeyGroup() {
String callerReference =
"unknown-key-group-" + suffix();
String body = distributionConfigXml(callerReference, """
<DefaultCacheBehavior>
<TargetOriginId>o1</TargetOriginId>
<ViewerProtocolPolicy>allow-all</ViewerProtocolPolicy>
<TrustedKeyGroups>
<Enabled>true</Enabled>
<Quantity>1</Quantity>
<Items><KeyGroup>missing-key-group</KeyGroup></Items>
</TrustedKeyGroups>
</DefaultCacheBehavior>
""");
given()
.contentType("application/xml")
.body(body)
.when()
.post("/2020-05-31/distribution")
.then()
.statusCode(400)
.body(containsString(
"<Code>TrustedKeyGroupDoesNotExist</Code>"));
assertDistributionWasNotCreated(callerReference);
}
@Test
void rejectsMalformedTrustedKeyGroupsInDefaultBehavior() {
String callerReference = "malformed-default-key-groups-" + suffix();
String body = distributionConfigXml(callerReference, """
<DefaultCacheBehavior>
<TargetOriginId>o1</TargetOriginId>
<ViewerProtocolPolicy>allow-all</ViewerProtocolPolicy>
<TrustedKeyGroups>
<Quantity>1</Quantity>
<Items><KeyGroup>kg-private</KeyGroup></Items>
</TrustedKeyGroups>
</DefaultCacheBehavior>
""");
given()
.contentType("application/xml")
.body(body)
.when()
.post("/2020-05-31/distribution")
.then()
.statusCode(400)
.body(containsString("<Code>InvalidArgument</Code>"));
assertDistributionWasNotCreated(callerReference);
}
@Test
void rejectsTrustedKeyGroupsWithoutQuantityInDefaultBehavior() {
String callerReference = "missing-default-key-group-quantity-" + suffix();
String body = distributionConfigXml(callerReference, """
<DefaultCacheBehavior>
<TargetOriginId>o1</TargetOriginId>
<ViewerProtocolPolicy>allow-all</ViewerProtocolPolicy>
<TrustedKeyGroups>
<Enabled>true</Enabled>
<Items><KeyGroup>kg-private</KeyGroup></Items>
</TrustedKeyGroups>
</DefaultCacheBehavior>
""");
given()
.contentType("application/xml")
.body(body)
.when()
.post("/2020-05-31/distribution")
.then()
.statusCode(400)
.body(containsString("<Code>InvalidArgument</Code>"));
assertDistributionWasNotCreated(callerReference);
}
@Test
void rejectsTrustedKeyGroupsWithInconsistentQuantity() {
String callerReference = "inconsistent-key-group-quantity-" + suffix();
String body = distributionConfigXml(callerReference, """
<DefaultCacheBehavior>
<TargetOriginId>o1</TargetOriginId>
<ViewerProtocolPolicy>allow-all</ViewerProtocolPolicy>
<TrustedKeyGroups>
<Enabled>true</Enabled>
<Quantity>2</Quantity>
<Items><KeyGroup>kg-private</KeyGroup></Items>
</TrustedKeyGroups>
</DefaultCacheBehavior>
""");
given()
.contentType("application/xml")
.body(body)
.when()
.post("/2020-05-31/distribution")
.then()
.statusCode(400)
.body(containsString("<Code>InconsistentQuantities</Code>"));
assertDistributionWasNotCreated(callerReference);
}
@Test
void rejectsMalformedTrustedKeyGroupsInOrderedBehavior() {
String callerReference = "malformed-ordered-key-groups-" + suffix();
String body = distributionConfigXml(callerReference, """
<DefaultCacheBehavior>
<TargetOriginId>o1</TargetOriginId>
<ViewerProtocolPolicy>allow-all</ViewerProtocolPolicy>
</DefaultCacheBehavior>
<CacheBehaviors>
<Quantity>1</Quantity>
<Items>
<CacheBehavior>
<PathPattern>/private/*</PathPattern>
<TargetOriginId>o1</TargetOriginId>
<ViewerProtocolPolicy>allow-all</ViewerProtocolPolicy>
<TrustedKeyGroups>
<Quantity>1</Quantity>
<Items><KeyGroup>kg-private</KeyGroup></Items>
</TrustedKeyGroups>
</CacheBehavior>
</Items>
</CacheBehaviors>
""");
given()
.contentType("application/xml")
.body(body)
.when()
.post("/2020-05-31/distribution")
.then()
.statusCode(400)
.body(containsString("<Code>InvalidArgument</Code>"));
assertDistributionWasNotCreated(callerReference);
}
@Test
void rejectsTrustedKeyGroupsWithoutQuantityInOrderedBehavior() {
String callerReference = "missing-ordered-key-group-quantity-" + suffix();
String body = distributionConfigXml(callerReference, """
<DefaultCacheBehavior>
<TargetOriginId>o1</TargetOriginId>
<ViewerProtocolPolicy>allow-all</ViewerProtocolPolicy>
</DefaultCacheBehavior>
<CacheBehaviors>
<Quantity>1</Quantity>
<Items>
<CacheBehavior>
<PathPattern>/private/*</PathPattern>
<TargetOriginId>o1</TargetOriginId>
<ViewerProtocolPolicy>allow-all</ViewerProtocolPolicy>
<TrustedKeyGroups>
<Enabled>true</Enabled>
<Items><KeyGroup>kg-private</KeyGroup></Items>
</TrustedKeyGroups>
</CacheBehavior>
</Items>
</CacheBehaviors>
""");
given()
.contentType("application/xml")
.body(body)
.when()
.post("/2020-05-31/distribution")
.then()
.statusCode(400)
.body(containsString("<Code>InvalidArgument</Code>"));
assertDistributionWasNotCreated(callerReference);
}
// ── Helpers ──────────────────────────────────────────────────────────────────
private static String trustedKeyGroupsXml(String keyGroup) {
return "<TrustedKeyGroups><Enabled>true</Enabled><Quantity>1</Quantity>"
+ "<Items><KeyGroup>" + keyGroup + "</KeyGroup></Items></TrustedKeyGroups>";
}
private String distributionConfigXml(String callerReference, String cacheBehaviors) {
return """
<?xml version="1.0" encoding="UTF-8"?>
<DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
<CallerReference>%s</CallerReference>
<Origins>
<Quantity>1</Quantity>
<Items>
<Origin>
<Id>o1</Id>
<DomainName>malformed-key-groups.s3.us-east-1.amazonaws.com</DomainName>
<S3OriginConfig><OriginAccessIdentity></OriginAccessIdentity></S3OriginConfig>
</Origin>
</Items>
</Origins>
%s
<Comment>must not be created</Comment>
<Enabled>true</Enabled>
</DistributionConfig>
""".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) {
}
}
@@ -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<String> 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();
@@ -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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> customPolicyQuery(String policyJson)
throws Exception {
return Map.of(
"Policy", cfBase64(policyJson.getBytes(StandardCharsets.UTF_8)),
"Signature", signCfBase64(policyJson, "SHA1withRSA"),
"Key-Pair-Id", KEY_ID);
}
}
@@ -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;
}
}