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

@@ -5791,6 +5791,10 @@ public class CloudFormationResourceProvisioner {
if (node != null && !node.isMissingNode() && !node.isNull()) {
dcb.setTargetOriginId(cfnText(node, "TargetOriginId", engine));
dcb.setViewerProtocolPolicy(cfnTextOrDefault(node, "ViewerProtocolPolicy", engine, "allow-all"));
List<String> trustedKeyGroups = cfnStringList(node.path("TrustedKeyGroups"), engine);
if (!trustedKeyGroups.isEmpty()) {
dcb.setTrustedKeyGroups(trustedKeyGroups);
}
}
return dcb;
}
@@ -5804,6 +5808,10 @@ public class CloudFormationResourceProvisioner {
cb.setPathPattern(cfnText(node, "PathPattern", engine));
cb.setTargetOriginId(cfnText(node, "TargetOriginId", engine));
cb.setViewerProtocolPolicy(cfnTextOrDefault(node, "ViewerProtocolPolicy", engine, "allow-all"));
List<String> trustedKeyGroups = cfnStringList(node.path("TrustedKeyGroups"), engine);
if (!trustedKeyGroups.isEmpty()) {
cb.setTrustedKeyGroups(trustedKeyGroups);
}
behaviors.add(cb);
}
}
@@ -1245,8 +1245,7 @@ public class CloudFrontController {
.start("KeyGroupConfig", NS)
.elem("Name", group.getName() != null ? group.getName() : "")
.elem("Comment", group.getComment() != null ? group.getComment() : "")
.raw(xmlQuantityItems("Items", "PublicKey", items.size(),
items.stream().map(k -> "<PublicKey>" + XmlBuilder.escape(k) + "</PublicKey>").toList()))
.raw(xmlDirectItems("Items", "PublicKey", items))
.end("KeyGroupConfig")
.build();
return Response.ok(xml, XML).header("ETag", group.getEtag()).build();
@@ -1723,6 +1722,11 @@ public class CloudFrontController {
.elem("DomainName", dist.getDomainName())
.elem("LastModifiedTime",
dist.getLastModifiedTime() != null ? dist.getLastModifiedTime().toString() : "")
.raw(xmlActiveTrustedKeyGroups(dist.getConfig()))
.start("ActiveTrustedSigners")
.elem("Enabled", false)
.elem("Quantity", 0)
.end("ActiveTrustedSigners")
.start("DistributionConfig")
.raw(xmlDistributionConfigBody(dist.getConfig()))
.end("DistributionConfig")
@@ -1853,6 +1857,9 @@ public class CloudFrontController {
.elem("ResponseHeadersPolicyId", dcb.getResponseHeadersPolicyId())
.elem("Compress", dcb.isCompress());
xml.raw(xmlTrustedKeyGroups(
dcb.isTrustedKeyGroupsEnabled(), dcb.getTrustedKeyGroups()));
List<String> allowed = dcb.getAllowedMethods();
if (allowed == null || allowed.isEmpty()) {
allowed = List.of("GET", "HEAD");
@@ -1879,6 +1886,9 @@ public class CloudFrontController {
.elem("ResponseHeadersPolicyId", cb.getResponseHeadersPolicyId())
.elem("Compress", cb.isCompress());
xml.raw(xmlTrustedKeyGroups(
cb.isTrustedKeyGroupsEnabled(), cb.getTrustedKeyGroups()));
List<String> allowed = cb.getAllowedMethods();
if (allowed == null || allowed.isEmpty()) {
allowed = List.of("GET", "HEAD");
@@ -1893,6 +1903,52 @@ public class CloudFrontController {
return xml.build();
}
private String xmlTrustedKeyGroups(
boolean enabled, List<String> trustedKeyGroups) {
List<String> keyGroups = trustedKeyGroups != null ? trustedKeyGroups : List.of();
XmlBuilder xml = new XmlBuilder()
.start("TrustedKeyGroups")
.elem("Enabled", enabled)
.elem("Quantity", keyGroups.size());
if (!keyGroups.isEmpty()) {
xml.start("Items");
for (String keyGroup : keyGroups) {
xml.elem("KeyGroup", keyGroup);
}
xml.end("Items");
}
return xml.end("TrustedKeyGroups").build();
}
private String xmlActiveTrustedKeyGroups(DistributionConfig config) {
List<KeyGroup> groups = service.activeTrustedKeyGroups(config);
XmlBuilder xml = new XmlBuilder()
.start("ActiveTrustedKeyGroups")
.elem("Enabled", !groups.isEmpty())
.elem("Quantity", groups.size());
if (!groups.isEmpty()) {
xml.start("Items");
for (KeyGroup group : groups) {
List<String> keyPairIds =
group.getItems() != null ? group.getItems() : List.of();
xml.start("KeyGroup")
.elem("KeyGroupId", group.getId())
.start("KeyPairIds")
.elem("Quantity", keyPairIds.size());
if (!keyPairIds.isEmpty()) {
xml.start("Items");
for (String keyPairId : keyPairIds) {
xml.elem("KeyPairId", keyPairId);
}
xml.end("Items");
}
xml.end("KeyPairIds").end("KeyGroup");
}
xml.end("Items");
}
return xml.end("ActiveTrustedKeyGroups").build();
}
private String xmlViewerCertificate(Map<String, String> vc) {
XmlBuilder xml = new XmlBuilder().start("ViewerCertificate");
if (vc != null && !vc.isEmpty()) {
@@ -2099,6 +2155,14 @@ public class CloudFrontController {
return xml.build();
}
private String xmlDirectItems(String wrapper, String itemTag, List<String> items) {
XmlBuilder xml = new XmlBuilder().start(wrapper);
for (String item : items) {
xml.elem(itemTag, item);
}
return xml.end(wrapper).build();
}
private static int paginationFetchLimit(int maxItems) {
return maxItems > 0 && maxItems < Integer.MAX_VALUE ? maxItems + 1 : maxItems;
}
@@ -2131,17 +2195,25 @@ public class CloudFrontController {
// ── Request parsers ───────────────────────────────────────────────────────
private DistributionConfig parseDistributionConfig(String body) {
Map<String, String> values =
parseDistributionConfigTopLevelValues(body);
DistributionConfig cfg = new DistributionConfig();
cfg.setCallerReference(XmlParser.extractFirst(body, "CallerReference", null));
cfg.setEnabled("true".equalsIgnoreCase(XmlParser.extractFirst(body, "Enabled", "true")));
cfg.setComment(XmlParser.extractFirst(body, "Comment", ""));
cfg.setDefaultRootObject(XmlParser.extractFirst(body, "DefaultRootObject", ""));
cfg.setHttpVersion(XmlParser.extractFirst(body, "HttpVersion", "http2"));
cfg.setPriceClass(XmlParser.extractFirst(body, "PriceClass", "PriceClass_All"));
cfg.setIPV6Enabled("true".equalsIgnoreCase(XmlParser.extractFirst(body, "IsIPV6Enabled", "true")));
cfg.setWebAclId(XmlParser.extractFirst(body, "WebAclId", null));
cfg.setContinuousDeploymentPolicyId(XmlParser.extractFirst(body, "ContinuousDeploymentPolicyId", null));
cfg.setStaging("true".equalsIgnoreCase(XmlParser.extractFirst(body, "Staging", "false")));
cfg.setCallerReference(values.get("CallerReference"));
cfg.setEnabled("true".equalsIgnoreCase(
values.getOrDefault("Enabled", "true")));
cfg.setComment(values.getOrDefault("Comment", ""));
cfg.setDefaultRootObject(
values.getOrDefault("DefaultRootObject", ""));
cfg.setHttpVersion(values.getOrDefault("HttpVersion", "http2"));
cfg.setPriceClass(
values.getOrDefault("PriceClass", "PriceClass_All"));
cfg.setIPV6Enabled("true".equalsIgnoreCase(
values.getOrDefault("IsIPV6Enabled", "true")));
cfg.setWebAclId(values.get("WebAclId"));
cfg.setContinuousDeploymentPolicyId(
values.get("ContinuousDeploymentPolicyId"));
cfg.setStaging("true".equalsIgnoreCase(
values.getOrDefault("Staging", "false")));
cfg.setOrigins(parseOrigins(body));
cfg.setDefaultCacheBehavior(parseDefaultCacheBehavior(body));
@@ -2153,6 +2225,75 @@ public class CloudFrontController {
return cfg;
}
private Map<String, String> parseDistributionConfigTopLevelValues(
String body) {
Map<String, String> values = new LinkedHashMap<>();
if (body == null || body.isEmpty()) {
return values;
}
try {
XMLStreamReader reader = XML_FACTORY.createXMLStreamReader(
new StringReader(body));
boolean inDistributionConfig = false;
int nestedDepth = 0;
while (reader.hasNext()) {
int event = reader.next();
if (event == XMLStreamConstants.START_ELEMENT) {
String local = reader.getLocalName();
if (!inDistributionConfig
&& "DistributionConfig".equals(local)) {
inDistributionConfig = true;
continue;
}
if (!inDistributionConfig) {
continue;
}
nestedDepth++;
if (nestedDepth == 1
&& isDistributionConfigScalar(local)) {
values.put(local, reader.getElementText());
nestedDepth--;
}
} else if (event == XMLStreamConstants.END_ELEMENT
&& inDistributionConfig) {
if (nestedDepth == 0
&& "DistributionConfig".equals(
reader.getLocalName())) {
inDistributionConfig = false;
} else {
nestedDepth--;
}
}
}
reader.close();
} catch (Exception e) {
LOG.debugv(
"Invalid DistributionConfig XML: {0}",
e.getMessage());
throw new AwsException(
"InvalidArgument",
"The DistributionConfig XML is invalid.",
400);
}
return values;
}
private static boolean isDistributionConfigScalar(String local) {
return switch (local) {
case "CallerReference",
"Enabled",
"Comment",
"DefaultRootObject",
"HttpVersion",
"PriceClass",
"IsIPV6Enabled",
"WebAclId",
"ContinuousDeploymentPolicyId",
"Staging" -> true;
default -> false;
};
}
/**
* Parses the {@code CustomErrorResponses} block into a list of maps keyed by
* {@code ErrorCode}, {@code ResponsePagePath}, {@code ResponseCode} and {@code ErrorCachingMinTTL}
@@ -2355,7 +2496,12 @@ public class CloudFrontController {
XMLStreamReader r = XML_FACTORY.createXMLStreamReader(new StringReader(body));
boolean inDcb = false;
boolean inAllowedMethods = false;
boolean inTrustedKeyGroups = false;
boolean sawTrustedKeyGroups = false;
Boolean trustedKeyGroupsEnabled = null;
Integer trustedKeyGroupsQuantity = null;
List<String> allowedMethods = new ArrayList<>();
List<String> trustedKeyGroups = new ArrayList<>();
while (r.hasNext()) {
int event = r.next();
@@ -2363,6 +2509,29 @@ public class CloudFrontController {
String local = r.getLocalName();
switch (local) {
case "DefaultCacheBehavior" -> inDcb = true;
case "TrustedKeyGroups" -> {
if (inDcb) {
inTrustedKeyGroups = true;
sawTrustedKeyGroups = true;
}
}
case "Enabled" -> {
if (inTrustedKeyGroups) {
trustedKeyGroupsEnabled =
parseTrustedKeyGroupsEnabled(r.getElementText());
}
}
case "Quantity" -> {
if (inTrustedKeyGroups) {
trustedKeyGroupsQuantity =
parseTrustedKeyGroupsQuantity(r.getElementText());
}
}
case "KeyGroup" -> {
if (inTrustedKeyGroups) {
trustedKeyGroups.add(r.getElementText());
}
}
case "AllowedMethods" -> {
if (inDcb) inAllowedMethods = true;
}
@@ -2399,6 +2568,7 @@ public class CloudFrontController {
} else if (event == XMLStreamConstants.END_ELEMENT) {
switch (r.getLocalName()) {
case "AllowedMethods" -> inAllowedMethods = false;
case "TrustedKeyGroups" -> inTrustedKeyGroups = false;
case "DefaultCacheBehavior" -> inDcb = false;
default -> {
}
@@ -2409,7 +2579,28 @@ public class CloudFrontController {
if (!allowedMethods.isEmpty()) {
dcb.setAllowedMethods(allowedMethods);
}
} catch (Exception ignored) {
if (!trustedKeyGroups.isEmpty()) {
dcb.setTrustedKeyGroups(trustedKeyGroups);
}
if (sawTrustedKeyGroups) {
if (trustedKeyGroupsEnabled == null) {
throw new AwsException(
"InvalidArgument",
"TrustedKeyGroups must include Enabled.",
400);
}
validateTrustedKeyGroupsQuantity(
trustedKeyGroupsQuantity, trustedKeyGroups.size());
validateEnabledTrustedKeyGroups(
trustedKeyGroupsEnabled, trustedKeyGroups.size());
dcb.setTrustedKeyGroupsEnabled(trustedKeyGroupsEnabled);
}
} catch (AwsException e) {
throw e;
} catch (Exception e) {
LOG.debugv("Invalid DefaultCacheBehavior XML: {0}", e.getMessage());
throw new AwsException(
"InvalidArgument", "The DefaultCacheBehavior configuration is invalid.", 400);
}
return dcb;
}
@@ -2424,8 +2615,13 @@ public class CloudFrontController {
boolean inCacheBehaviors = false;
boolean inCacheBehavior = false;
boolean inAllowedMethods = false;
boolean inTrustedKeyGroups = false;
CacheBehavior current = null;
boolean sawTrustedKeyGroups = false;
Boolean trustedKeyGroupsEnabled = null;
Integer trustedKeyGroupsQuantity = null;
List<String> allowedMethods = new ArrayList<>();
List<String> trustedKeyGroups = new ArrayList<>();
while (r.hasNext()) {
int event = r.next();
@@ -2437,7 +2633,34 @@ public class CloudFrontController {
if (inCacheBehaviors) {
inCacheBehavior = true;
current = new CacheBehavior();
sawTrustedKeyGroups = false;
trustedKeyGroupsEnabled = null;
trustedKeyGroupsQuantity = null;
allowedMethods = new ArrayList<>();
trustedKeyGroups = new ArrayList<>();
}
}
case "TrustedKeyGroups" -> {
if (inCacheBehavior) {
inTrustedKeyGroups = true;
sawTrustedKeyGroups = true;
}
}
case "Enabled" -> {
if (inTrustedKeyGroups) {
trustedKeyGroupsEnabled =
parseTrustedKeyGroupsEnabled(r.getElementText());
}
}
case "Quantity" -> {
if (inTrustedKeyGroups) {
trustedKeyGroupsQuantity =
parseTrustedKeyGroupsQuantity(r.getElementText());
}
}
case "KeyGroup" -> {
if (inTrustedKeyGroups) {
trustedKeyGroups.add(r.getElementText());
}
}
case "AllowedMethods" -> {
@@ -2477,11 +2700,31 @@ public class CloudFrontController {
} else if (event == XMLStreamConstants.END_ELEMENT) {
switch (r.getLocalName()) {
case "AllowedMethods" -> inAllowedMethods = false;
case "TrustedKeyGroups" -> inTrustedKeyGroups = false;
case "CacheBehavior" -> {
if (inCacheBehavior && current != null) {
if (!allowedMethods.isEmpty()) {
current.setAllowedMethods(allowedMethods);
}
if (!trustedKeyGroups.isEmpty()) {
current.setTrustedKeyGroups(trustedKeyGroups);
}
if (sawTrustedKeyGroups) {
if (trustedKeyGroupsEnabled == null) {
throw new AwsException(
"InvalidArgument",
"TrustedKeyGroups must include Enabled.",
400);
}
validateTrustedKeyGroupsQuantity(
trustedKeyGroupsQuantity,
trustedKeyGroups.size());
validateEnabledTrustedKeyGroups(
trustedKeyGroupsEnabled,
trustedKeyGroups.size());
current.setTrustedKeyGroupsEnabled(
trustedKeyGroupsEnabled);
}
result.add(current);
}
inCacheBehavior = false;
@@ -2494,11 +2737,68 @@ public class CloudFrontController {
}
}
r.close();
} catch (Exception ignored) {
} catch (AwsException e) {
throw e;
} catch (Exception e) {
LOG.debugv("Invalid CacheBehaviors XML: {0}", e.getMessage());
throw new AwsException(
"InvalidArgument", "The CacheBehaviors configuration is invalid.", 400);
}
return result;
}
private static boolean parseTrustedKeyGroupsEnabled(String value) {
if (!"true".equalsIgnoreCase(value)
&& !"false".equalsIgnoreCase(value)) {
throw new AwsException(
"InvalidArgument",
"TrustedKeyGroups Enabled must be true or false.",
400);
}
return Boolean.parseBoolean(value);
}
private static int parseTrustedKeyGroupsQuantity(String value) {
try {
int quantity = Integer.parseInt(value);
if (quantity < 0) {
throw new NumberFormatException("negative quantity");
}
return quantity;
} catch (NumberFormatException e) {
throw new AwsException(
"InvalidArgument",
"TrustedKeyGroups Quantity must be a non-negative integer.",
400);
}
}
private static void validateTrustedKeyGroupsQuantity(
Integer quantity, int itemCount) {
if (quantity == null) {
throw new AwsException(
"InvalidArgument",
"TrustedKeyGroups must include Quantity.",
400);
}
if (quantity != itemCount) {
throw new AwsException(
"InconsistentQuantities",
"The value of Quantity does not match the number of items.",
400);
}
}
private static void validateEnabledTrustedKeyGroups(
boolean enabled, int itemCount) {
if (enabled && itemCount == 0) {
throw new AwsException(
"InvalidArgument",
"TrustedKeyGroups cannot be enabled without a key group.",
400);
}
}
private List<String> parseAliases(String body) {
List<String> result = new ArrayList<>();
if (body == null || body.isEmpty()) {
@@ -2676,8 +2976,7 @@ public class CloudFrontController {
.start("KeyGroupConfig")
.elem("Name", group.getName() != null ? group.getName() : "")
.elem("Comment", group.getComment() != null ? group.getComment() : "")
.raw(xmlQuantityItems("Items", "PublicKey", items.size(),
items.stream().map(k -> "<PublicKey>" + XmlBuilder.escape(k) + "</PublicKey>").toList()))
.raw(xmlDirectItems("Items", "PublicKey", items))
.end("KeyGroupConfig")
.end("KeyGroup");
return xml.build();
@@ -104,6 +104,32 @@ public final class CloudFrontRequestRouter {
return dflt != null ? dflt.getTargetOriginId() : null;
}
/**
* Returns the trusted key group IDs of the cache behavior that matches {@code normalizedPath} (the
* same ordered-first, default-last resolution as {@link #matchTargetOriginId}). An empty list means
* the matched behavior serves public content — no request signature is required.
*/
public static List<String> trustedKeyGroupsFor(DistributionConfig config, String normalizedPath) {
List<CacheBehavior> behaviors = config.getCacheBehaviors();
if (behaviors != null) {
for (CacheBehavior behavior : behaviors) {
if (pathPatternMatches(behavior.getPathPattern(), normalizedPath)) {
return behavior.isTrustedKeyGroupsEnabled()
&& behavior.getTrustedKeyGroups() != null
? behavior.getTrustedKeyGroups()
: List.of();
}
}
}
DefaultCacheBehavior dflt = config.getDefaultCacheBehavior();
if (dflt != null
&& dflt.isTrustedKeyGroupsEnabled()
&& dflt.getTrustedKeyGroups() != null) {
return dflt.getTrustedKeyGroups();
}
return List.of();
}
/**
* Matches a CloudFront path pattern against a normalized path. A leading {@code /} on either side is
* ignored, {@code *} matches zero or more characters, {@code ?} matches exactly one, and matching is
@@ -6,10 +6,12 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudfront.model.CacheBehavior;
import io.github.hectorvent.floci.services.cloudfront.model.CachePolicy;
import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontFunction;
import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontOriginAccessIdentity;
import io.github.hectorvent.floci.services.cloudfront.model.ContinuousDeploymentPolicy;
import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
import io.github.hectorvent.floci.services.cloudfront.model.FieldLevelEncryptionConfig;
@@ -31,8 +33,10 @@ import java.security.SecureRandom;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
@@ -111,6 +115,7 @@ public class CloudFrontService {
public synchronized Distribution createDistribution(Distribution dist, Map<String, String> tags) {
ensureAliasesAvailable(dist.getConfig(), null);
validateTrustedKeyGroups(dist.getConfig());
String id = generateDistributionId();
dist.setId(id);
dist.setArn(AwsArnUtils.Arn.of("cloudfront", "", accountId, "distribution/" + id).toString());
@@ -138,6 +143,7 @@ public class CloudFrontService {
"The If-Match version is missing or not valid for the resource.", 400);
}
ensureAliasesAvailable(updated.getConfig(), id);
validateTrustedKeyGroups(updated.getConfig());
updated.setId(id);
updated.setArn(existing.getArn());
updated.setDomainName(existing.getDomainName());
@@ -914,6 +920,18 @@ public class CloudFrontService {
// ── Public Keys ───────────────────────────────────────────────────────────
public synchronized PublicKey createPublicKey(PublicKey key) {
validatePublicKey(key);
boolean duplicateCallerReference =
publicKeyStore.scan(existing -> true).stream()
.anyMatch(existing -> Objects.equals(
existing.getCallerReference(),
key.getCallerReference()));
if (duplicateCallerReference) {
throw new AwsException(
"PublicKeyAlreadyExists",
"A public key with this caller reference already exists.",
409);
}
key.setId(UUID.randomUUID().toString());
key.setCreatedTime(Instant.now());
key.setEtag(UUID.randomUUID().toString());
@@ -929,8 +947,22 @@ public class CloudFrontService {
public synchronized PublicKey updatePublicKey(String id, String ifMatch, PublicKey updated) {
PublicKey existing = getPublicKey(id);
if (!existing.getEtag().equals(ifMatch)) {
throw new AwsException("InvalidIfMatchVersion",
"The If-Match version is missing or not valid for the resource.", 400);
throw new AwsException(
"PreconditionFailed",
"The precondition in one or more request-header fields evaluated to false.",
412);
}
validatePublicKey(updated);
if (!Objects.equals(
existing.getCallerReference(),
updated.getCallerReference())
|| !Objects.equals(existing.getName(), updated.getName())
|| !Objects.equals(
existing.getEncodedKey(), updated.getEncodedKey())) {
throw new AwsException(
"CannotChangeImmutablePublicKeyFields",
"The caller reference, name, and encoded public key cannot be changed.",
400);
}
updated.setId(id);
updated.setCreatedTime(existing.getCreatedTime());
@@ -942,8 +974,14 @@ public class CloudFrontService {
public synchronized void deletePublicKey(String id, String ifMatch) {
PublicKey existing = getPublicKey(id);
if (!existing.getEtag().equals(ifMatch)) {
throw new AwsException("InvalidIfMatchVersion",
"The If-Match version is missing or not valid for the resource.", 400);
throw new AwsException(
"PreconditionFailed",
"The precondition in one or more request-header fields evaluated to false.",
412);
}
if (publicKeyInUse(id)) {
throw new AwsException(
"PublicKeyInUse", "The specified public key is in use.", 409);
}
publicKeyStore.delete(id);
}
@@ -954,9 +992,56 @@ public class CloudFrontService {
return paginate(all, marker, maxItems, PublicKey::getId);
}
/**
* Resolves the PEM public key for a {@code Key-Pair-Id} used to sign a request, but only when that
* public key is a member of one of the supplied key groups. Returns {@code null} when the key is
* unknown or is not a member of any of those groups — i.e. it is not a trusted signer.
*/
public String trustedPublicKeyPem(String keyPairId, List<String> keyGroupIds) {
if (keyPairId == null || keyGroupIds == null || keyGroupIds.isEmpty()) {
return null;
}
boolean trusted = false;
for (String keyGroupId : keyGroupIds) {
KeyGroup group = keyGroupStore.get(keyGroupId).orElse(null);
if (group != null && group.getItems() != null && group.getItems().contains(keyPairId)) {
trusted = true;
break;
}
}
if (!trusted) {
return null;
}
return publicKeyStore.get(keyPairId).map(PublicKey::getEncodedKey).orElse(null);
}
public List<KeyGroup> activeTrustedKeyGroups(DistributionConfig config) {
LinkedHashSet<String> ids = new LinkedHashSet<>();
if (config != null) {
DefaultCacheBehavior defaultBehavior = config.getDefaultCacheBehavior();
if (defaultBehavior != null
&& defaultBehavior.isTrustedKeyGroupsEnabled()
&& defaultBehavior.getTrustedKeyGroups() != null) {
ids.addAll(defaultBehavior.getTrustedKeyGroups());
}
if (config.getCacheBehaviors() != null) {
for (CacheBehavior behavior : config.getCacheBehaviors()) {
if (behavior != null
&& behavior.isTrustedKeyGroupsEnabled()
&& behavior.getTrustedKeyGroups() != null) {
ids.addAll(behavior.getTrustedKeyGroups());
}
}
}
}
return ids.stream().map(this::getKeyGroup).toList();
}
// ── Key Groups ────────────────────────────────────────────────────────────
public synchronized KeyGroup createKeyGroup(KeyGroup group) {
validateKeyGroup(group);
validateUniqueKeyGroupName(group.getName(), null);
group.setId(UUID.randomUUID().toString());
group.setLastModifiedTime(Instant.now());
group.setEtag(UUID.randomUUID().toString());
@@ -972,9 +1057,13 @@ public class CloudFrontService {
public synchronized KeyGroup updateKeyGroup(String id, String ifMatch, KeyGroup updated) {
KeyGroup existing = getKeyGroup(id);
if (!existing.getEtag().equals(ifMatch)) {
throw new AwsException("InvalidIfMatchVersion",
"The If-Match version is missing or not valid for the resource.", 400);
throw new AwsException(
"PreconditionFailed",
"The precondition in one or more request-header fields evaluated to false.",
412);
}
validateKeyGroup(updated);
validateUniqueKeyGroupName(updated.getName(), id);
updated.setId(id);
updated.setLastModifiedTime(Instant.now());
updated.setEtag(UUID.randomUUID().toString());
@@ -985,18 +1074,183 @@ public class CloudFrontService {
public synchronized void deleteKeyGroup(String id, String ifMatch) {
KeyGroup existing = getKeyGroup(id);
if (!existing.getEtag().equals(ifMatch)) {
throw new AwsException("InvalidIfMatchVersion",
"The If-Match version is missing or not valid for the resource.", 400);
throw new AwsException(
"PreconditionFailed",
"The precondition in one or more request-header fields evaluated to false.",
412);
}
if (keyGroupInUse(id)) {
throw new AwsException(
"ResourceInUse",
"Cannot delete this resource because it is in use.",
409);
}
keyGroupStore.delete(id);
}
private void validateUniqueKeyGroupName(String name, String excludedId) {
boolean duplicate = keyGroupStore.scan(group -> true).stream()
.anyMatch(group -> !Objects.equals(excludedId, group.getId())
&& Objects.equals(name, group.getName()));
if (duplicate) {
throw new AwsException(
"KeyGroupAlreadyExists",
"A key group with this name already exists.",
409);
}
}
public List<KeyGroup> listKeyGroups(String marker, int maxItems) {
List<KeyGroup> all = new ArrayList<>(keyGroupStore.scan(k -> true));
all.sort((a, b) -> a.getId().compareTo(b.getId()));
return paginate(all, marker, maxItems, KeyGroup::getId);
}
private static void validatePublicKey(PublicKey key) {
if (key == null
|| key.getCallerReference() == null
|| key.getCallerReference().isBlank()
|| key.getName() == null
|| key.getName().isBlank()
|| key.getEncodedKey() == null
|| key.getEncodedKey().isBlank()) {
throw new AwsException(
"InvalidArgument",
"CallerReference, Name, and EncodedKey are required.",
400);
}
if (key.getComment() != null && key.getComment().length() > 128) {
throw new AwsException(
"InvalidArgument", "The comment must be 128 characters or fewer.", 400);
}
try {
CloudFrontSignatureVerifier.parseSupportedPublicKey(
key.getEncodedKey());
} catch (Exception e) {
throw new AwsException(
"InvalidArgument",
"The encoded public key must be RSA-2048 or ECDSA P-256 in X.509 PEM format.",
400);
}
}
private void validateKeyGroup(KeyGroup group) {
if (group == null || group.getName() == null || group.getName().isBlank()) {
throw new AwsException(
"InvalidArgument", "The parameter Name is required.", 400);
}
if (group.getComment() != null && group.getComment().length() > 128) {
throw new AwsException(
"InvalidArgument", "The comment must be 128 characters or fewer.", 400);
}
List<String> items = group.getItems();
if (items == null || items.isEmpty()) {
throw new AwsException(
"InvalidArgument",
"A key group must contain at least one public key.",
400);
}
if (items.size() > 5) {
throw new AwsException(
"TooManyPublicKeysInKeyGroup",
"A key group can contain at most five public keys.",
400);
}
if (new LinkedHashSet<>(items).size() != items.size()) {
throw new AwsException(
"InvalidArgument",
"A public key cannot appear more than once in a key group.",
400);
}
for (String publicKeyId : items) {
if (publicKeyId == null
|| publicKeyId.isBlank()
|| publicKeyStore.get(publicKeyId).isEmpty()) {
throw new AwsException(
"InvalidArgument",
"The specified public key does not exist.",
400);
}
}
}
private void validateTrustedKeyGroups(DistributionConfig config) {
if (config == null) {
return;
}
DefaultCacheBehavior defaultBehavior = config.getDefaultCacheBehavior();
if (defaultBehavior != null) {
validateTrustedKeyGroups(
defaultBehavior.isTrustedKeyGroupsEnabled(),
defaultBehavior.getTrustedKeyGroups());
}
if (config.getCacheBehaviors() != null) {
for (CacheBehavior behavior : config.getCacheBehaviors()) {
if (behavior != null) {
validateTrustedKeyGroups(
behavior.isTrustedKeyGroupsEnabled(),
behavior.getTrustedKeyGroups());
}
}
}
}
private void validateTrustedKeyGroups(
boolean enabled, List<String> keyGroupIds) {
List<String> ids = keyGroupIds != null ? keyGroupIds : List.of();
if (enabled && ids.isEmpty()) {
throw new AwsException(
"InvalidArgument",
"TrustedKeyGroups cannot be enabled without a key group.",
400);
}
for (String keyGroupId : ids) {
if (keyGroupId == null
|| keyGroupId.isBlank()
|| keyGroupStore.get(keyGroupId).isEmpty()) {
throw new AwsException(
"TrustedKeyGroupDoesNotExist",
"The specified key group does not exist.",
400);
}
}
}
private boolean publicKeyInUse(String id) {
for (KeyGroup group : keyGroupStore.scan(k -> true)) {
if (group.getItems() != null && group.getItems().contains(id)) {
return true;
}
}
return false;
}
private boolean keyGroupInUse(String id) {
for (Distribution distribution : distStore.scan(k -> true)) {
DistributionConfig config = distribution.getConfig();
if (config == null) {
continue;
}
DefaultCacheBehavior defaultBehavior =
config.getDefaultCacheBehavior();
if (defaultBehavior != null
&& defaultBehavior.getTrustedKeyGroups() != null
&& defaultBehavior.getTrustedKeyGroups().contains(id)) {
return true;
}
if (config.getCacheBehaviors() != null) {
for (CacheBehavior behavior : config.getCacheBehaviors()) {
if (behavior != null
&& behavior.getTrustedKeyGroups() != null
&& behavior.getTrustedKeyGroups().contains(id)) {
return true;
}
}
}
}
return false;
}
// ── Realtime Log Configs ──────────────────────────────────────────────────
public synchronized RealtimeLogConfig createRealtimeLogConfig(RealtimeLogConfig cfg) {
@@ -71,6 +71,9 @@ public class CloudFrontServingController {
"proxy-connection", "te", "trailer", "transfer-encoding", "upgrade", "via",
"content-length", "content-type");
private static final java.util.Set<String> CLOUDFRONT_SIGNING_PARAMS =
java.util.Set.of("Expires", "Signature", "Key-Pair-Id", "Policy", "Hash-Algorithm");
private final CloudFrontService service;
private final S3Service s3Service;
private final CurrentVertxRequest currentVertxRequest;
@@ -133,6 +136,18 @@ public class CloudFrontServingController {
String normalized = CloudFrontRequestRouter.normalizePath(decodedViewerPath);
List<String> trustedKeyGroups =
CloudFrontRequestRouter.trustedKeyGroupsFor(config, normalized);
if (!trustedKeyGroups.isEmpty()) {
CloudFrontSignatureVerifier.Result verdict =
verifySignedRequest(dist, rawViewerPath, trustedKeyGroups);
if (!verdict.allowed()) {
LOG.debugv("CloudFront denied a request for distribution {0}, path {1}: {2}",
dist.getId(), rawViewerPath, verdict.reason());
return textError(403, "Access denied: " + verdict.reason());
}
}
OriginResponse origin = route(dist, normalized, rawViewerPath, decodedViewerPath,
viewerScheme, viewerAuthorization, includeBody);
@@ -146,6 +161,111 @@ public class CloudFrontServingController {
return toResponse(origin, includeBody);
}
/**
* Verifies the live request against the behavior's trusted key groups, resolving a Key-Pair-Id
* only when its public key belongs to one of those groups.
*/
private CloudFrontSignatureVerifier.Result verifySignedRequest(
Distribution distribution,
String rawViewerPath,
List<String> trustedKeyGroups) {
io.vertx.core.http.HttpServerRequest request =
currentVertxRequest.getCurrent().request();
Map<String, String> query = new LinkedHashMap<>();
for (String name : request.params().names()) {
query.put(name, request.getParam(name));
}
Map<String, String> cookies = parseCookies(request.getHeader("Cookie"));
String resourceUrl =
buildResourceUrl(distribution, request, rawViewerPath);
String sourceIp = request.remoteAddress() != null
? request.remoteAddress().hostAddress()
: null;
return CloudFrontSignatureVerifier.verify(
resourceUrl,
query,
cookies,
sourceIp,
keyPairId -> service.trustedPublicKeyPem(
keyPairId, trustedKeyGroups),
java.time.Instant.now());
}
/**
* Rebuilds the URL exactly as a signer sees it, preserving the encoded path and application
* query while excluding CloudFront's signing parameters.
*/
private static String buildResourceUrl(
Distribution distribution,
io.vertx.core.http.HttpServerRequest request,
String rawViewerPath) {
String scheme = request.scheme() != null ? request.scheme() : "https";
String host = request.getHeader("Host");
if (host == null || host.isBlank()) {
host = distribution.getDomainName();
}
return scheme + "://" + host + rawViewerPath
+ rawAppQuery(request.query());
}
private static String rawAppQuery(String rawQuery) {
String appQuery = stripCloudFrontSigningParams(rawQuery);
return appQuery.isEmpty() ? "" : "?" + appQuery;
}
static String stripCloudFrontSigningParams(String rawQuery) {
if (rawQuery == null || rawQuery.isEmpty()) {
return "";
}
StringBuilder appQuery = new StringBuilder();
boolean emitted = false;
for (String pair : rawQuery.split("&", -1)) {
int eq = pair.indexOf('=');
String rawName = eq >= 0 ? pair.substring(0, eq) : pair;
String decodedName = decodeQueryName(rawName);
if (decodedName != null
&& CLOUDFRONT_SIGNING_PARAMS.contains(decodedName)) {
continue;
}
if (emitted) {
appQuery.append('&');
}
appQuery.append(pair);
emitted = true;
}
return appQuery.toString();
}
private static String decodeQueryName(String rawName) {
try {
return java.net.URLDecoder.decode(
rawName, StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
LOG.debugv(
"Preserving malformed CloudFront query parameter name {0}: {1}",
rawName, e.getMessage());
return null;
}
}
private static Map<String, String> parseCookies(String cookieHeader) {
Map<String, String> 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,
@@ -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.
*
* <p>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<String> 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<String, String> query, Map<String, String> cookies,
String sourceIp, Function<String, String> 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) {
}
}
@@ -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<String> 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<String> getTrustedKeyGroups() { return trustedKeyGroups; }
public void setTrustedKeyGroups(List<String> trustedKeyGroups) { this.trustedKeyGroups = trustedKeyGroups; }
}
@@ -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<String> 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<String> getTrustedKeyGroups() { return trustedKeyGroups; }
public void setTrustedKeyGroups(List<String> trustedKeyGroups) { this.trustedKeyGroups = trustedKeyGroups; }
}