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

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

* 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
This commit is contained in:
Alex Banna authored and GitHub committed 2026-08-12 19:34:18 -04:00
1 parent 527615bdf0
commit 82f80165fb
37 files changed
+4339 -158

No files matched your search

@@ -1311,6 +1311,12 @@ public interface EmulatorConfig {
@WithDefault("cloudfront.net")
String domainSuffix();
/**
* Exact custom-origin hostnames allowed to resolve to private or otherwise non-routable
* addresses. Empty by default to match CloudFront's public custom-origin boundary.
*/
Optional<List<String>> allowedPrivateOriginHosts();
}
interface AppSyncServiceConfig {
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsControll
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaNetworkConnectorsController;
import io.github.hectorvent.floci.services.opensearch.OpenSearchController;
import io.github.hectorvent.floci.services.cloudfront.CloudFrontController;
import io.github.hectorvent.floci.services.cloudfront.CloudFrontServingController;
import io.github.hectorvent.floci.services.route53.Route53Controller;
import io.github.hectorvent.floci.services.ses.SesController;
import io.github.hectorvent.floci.services.appsync.AppSyncController;
@@ -400,7 +401,8 @@ public class ResolvedServiceCatalog {
"cloudfront", storageMode(config.storage().services().cloudfront().mode(), config.storage().mode()),
5000L, AwsNamespaces.CLOUDFRONT, ServiceProtocol.REST_XML,
protocols(ServiceProtocol.REST_XML),
Set.of(), Set.of("cloudfront"), Set.of(), Set.of(CloudFrontController.class)),
Set.of(), Set.of("cloudfront"), Set.of(),
Set.of(CloudFrontController.class, CloudFrontServingController.class)),
descriptor("appsync", "appsync", config.services().appsync().enabled(), true,
"appsync", storageMode(config.storage().services().appsync().mode(), config.storage().mode()),
config.storage().services().appsync().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
@@ -4,6 +4,12 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.batch.BatchService;
import io.github.hectorvent.floci.services.cloudfront.CloudFrontService;
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.Origin;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
@@ -182,6 +188,7 @@ public class CloudFormationResourceProvisioner {
private final AutoScalingService autoScalingService;
private final FirehoseService firehoseService;
private final DocDbService docDbService;
private final CloudFrontService cloudFrontService;
// Item 15 decomposition: extracted per-service provisioners are consulted before the switch
// below. As types migrate, their switch cases and provisionXxx methods are removed here; the
// now-dead service deps above are cleared in the final cleanup once the switch is empty.
@@ -216,6 +223,7 @@ public class CloudFormationResourceProvisioner {
AutoScalingService autoScalingService,
FirehoseService firehoseService,
DocDbService docDbService,
CloudFrontService cloudFrontService,
CloudFormationResourceRegistry resourceRegistry) {
this.s3Service = s3Service;
this.sqsService = sqsService;
@@ -249,6 +257,7 @@ public class CloudFormationResourceProvisioner {
this.autoScalingService = autoScalingService;
this.firehoseService = firehoseService;
this.docDbService = docDbService;
this.cloudFrontService = cloudFrontService;
this.resourceRegistry = resourceRegistry;
}
@@ -389,6 +398,8 @@ public class CloudFormationResourceProvisioner {
provisionLaunchConfiguration(resource, properties, engine, region, stackName);
case "AWS::AutoScaling::AutoScalingGroup" ->
provisionAutoScalingGroup(resource, properties, engine, region, stackName);
case "AWS::CloudFront::Distribution" ->
provisionCloudFrontDistribution(resource, properties, engine);
default -> {
if (resourceType != null && resourceType.startsWith("Custom::")) {
provisionCustomResource(resource, properties, engine, region, accountId, stackName);
@@ -561,6 +572,7 @@ public class CloudFormationResourceProvisioner {
autoScalingService.deleteLaunchConfiguration(region, physicalId);
case "AWS::AutoScaling::AutoScalingGroup" ->
autoScalingService.deleteAutoScalingGroup(region, physicalId, true);
case "AWS::CloudFront::Distribution" -> cloudFrontService.removeDistribution(physicalId);
default -> LOG.debugv("Skipping delete of unsupported resource type: {0}", resourceType);
}
}
@@ -4988,6 +5000,161 @@ public class CloudFormationResourceProvisioner {
return node != null && node.hasNonNull(field) ? node.path(field).asText() : null;
}
// ── CloudFront ────────────────────────────────────────────────────────────
/**
* Provisions an {@code AWS::CloudFront::Distribution} by translating its {@code DistributionConfig}
* property tree into a {@link DistributionConfig} and creating or updating the distribution.
* {@code Ref} returns the distribution id; {@code Fn::GetAtt} exposes {@code Id} and
* {@code DomainName} (closes #1147, where {@code Fn::GetAtt DomainName} previously returned an
* unresolved token).
*/
private void provisionCloudFrontDistribution(StackResource r, JsonNode props,
CloudFormationTemplateEngine engine) {
JsonNode dc = props != null ? props.path("DistributionConfig") : null;
DistributionConfig config = new DistributionConfig();
if (dc != null && !dc.isMissingNode() && !dc.isNull()) {
config.setEnabled(cfnBool(dc, "Enabled", engine, true));
config.setComment(cfnText(dc, "Comment", engine));
config.setDefaultRootObject(cfnText(dc, "DefaultRootObject", engine));
config.setHttpVersion(cfnTextOrDefault(dc, "HttpVersion", engine, "http2"));
config.setPriceClass(cfnTextOrDefault(dc, "PriceClass", engine, "PriceClass_All"));
config.setAliases(cfnStringList(dc.path("Aliases"), engine));
config.setOrigins(cfnOrigins(dc, engine));
config.setDefaultCacheBehavior(cfnDefaultCacheBehavior(dc.path("DefaultCacheBehavior"), engine));
config.setCacheBehaviors(cfnCacheBehaviors(dc, engine));
config.setCustomErrorResponses(cfnCustomErrorResponses(dc, engine));
}
Distribution dist = new Distribution();
dist.setConfig(config);
if (r.getPhysicalId() == null || r.getPhysicalId().isBlank()) {
dist = cloudFrontService.createDistribution(dist, Map.of());
} else {
Distribution existing = cloudFrontService.getDistribution(r.getPhysicalId());
dist = cloudFrontService.updateDistribution(
existing.getId(), existing.getEtag(), dist);
}
r.setPhysicalId(dist.getId());
r.getAttributes().put("Id", dist.getId());
r.getAttributes().put("DomainName", dist.getDomainName());
r.getAttributes().put("Arn", dist.getArn());
}
private List<Origin> cfnOrigins(JsonNode dc, CloudFormationTemplateEngine engine) {
List<Origin> origins = new ArrayList<>();
JsonNode items = dc.path("Origins");
if (items.isArray()) {
for (JsonNode node : items) {
Origin origin = new Origin();
origin.setId(cfnText(node, "Id", engine));
origin.setDomainName(cfnText(node, "DomainName", engine));
String originPath = cfnText(node, "OriginPath", engine);
if (!originPath.isEmpty()) {
origin.setOriginPath(originPath);
}
String originAccessControlId =
cfnText(node, "OriginAccessControlId", engine);
if (!originAccessControlId.isEmpty()) {
origin.setOriginAccessControlId(originAccessControlId);
}
JsonNode s3 = node.path("S3OriginConfig");
JsonNode custom = node.path("CustomOriginConfig");
if (!custom.isMissingNode() && !custom.isNull()) {
Map<String, Object> coc = new LinkedHashMap<>();
coc.put("HTTPPort", cfnTextOrDefault(custom, "HTTPPort", engine, "80"));
coc.put("HTTPSPort", cfnTextOrDefault(custom, "HTTPSPort", engine, "443"));
coc.put("OriginProtocolPolicy",
cfnTextOrDefault(custom, "OriginProtocolPolicy", engine, "https-only"));
origin.setCustomOriginConfig(coc);
} else {
// No CustomOriginConfig => S3 origin (S3OriginConfig may be present or defaulted).
Map<String, String> s3c = new LinkedHashMap<>();
s3c.put("OriginAccessIdentity",
s3.isMissingNode() || s3.isNull() ? "" : cfnText(s3, "OriginAccessIdentity", engine));
origin.setS3OriginConfig(s3c);
}
origins.add(origin);
}
}
return origins;
}
private DefaultCacheBehavior cfnDefaultCacheBehavior(JsonNode node, CloudFormationTemplateEngine engine) {
DefaultCacheBehavior dcb = new DefaultCacheBehavior();
if (node != null && !node.isMissingNode() && !node.isNull()) {
dcb.setTargetOriginId(cfnText(node, "TargetOriginId", engine));
dcb.setViewerProtocolPolicy(cfnTextOrDefault(node, "ViewerProtocolPolicy", engine, "allow-all"));
}
return dcb;
}
private List<CacheBehavior> cfnCacheBehaviors(JsonNode dc, CloudFormationTemplateEngine engine) {
List<CacheBehavior> behaviors = new ArrayList<>();
JsonNode items = dc.path("CacheBehaviors");
if (items.isArray()) {
for (JsonNode node : items) {
CacheBehavior cb = new CacheBehavior();
cb.setPathPattern(cfnText(node, "PathPattern", engine));
cb.setTargetOriginId(cfnText(node, "TargetOriginId", engine));
cb.setViewerProtocolPolicy(cfnTextOrDefault(node, "ViewerProtocolPolicy", engine, "allow-all"));
behaviors.add(cb);
}
}
return behaviors;
}
private List<Map<String, Object>> cfnCustomErrorResponses(JsonNode dc, CloudFormationTemplateEngine engine) {
List<Map<String, Object>> result = new ArrayList<>();
JsonNode items = dc.path("CustomErrorResponses");
if (items.isArray()) {
for (JsonNode node : items) {
Map<String, Object> cer = new LinkedHashMap<>();
cer.put("ErrorCode", cfnText(node, "ErrorCode", engine));
putIfPresent(cer, "ResponseCode", cfnText(node, "ResponseCode", engine));
putIfPresent(cer, "ResponsePagePath", cfnText(node, "ResponsePagePath", engine));
putIfPresent(cer, "ErrorCachingMinTTL", cfnText(node, "ErrorCachingMinTTL", engine));
result.add(cer);
}
}
return result;
}
private static void putIfPresent(Map<String, Object> map, String key, String value) {
if (value != null && !value.isEmpty()) {
map.put(key, value);
}
}
private List<String> cfnStringList(JsonNode arrayNode, CloudFormationTemplateEngine engine) {
List<String> result = new ArrayList<>();
if (arrayNode != null && arrayNode.isArray()) {
for (JsonNode item : arrayNode) {
String value = engine.resolve(item);
if (value != null && !value.isEmpty()) {
result.add(value);
}
}
}
return result;
}
private String cfnText(JsonNode parent, String field, CloudFormationTemplateEngine engine) {
return parent == null ? "" : engine.resolve(parent.path(field));
}
private String cfnTextOrDefault(JsonNode parent, String field, CloudFormationTemplateEngine engine,
String dflt) {
String value = cfnText(parent, field, engine);
return value.isEmpty() ? dflt : value;
}
private boolean cfnBool(JsonNode parent, String field, CloudFormationTemplateEngine engine, boolean dflt) {
String value = cfnText(parent, field, engine);
return value.isEmpty() ? dflt : "true".equalsIgnoreCase(value);
}
private String resolveOptional(JsonNode props, String name, CloudFormationTemplateEngine engine) {
if (props == null || !props.has(name) || props.get(name).isNull()) {
return null;
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.cloudfront.model.*;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
@@ -19,10 +20,13 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
@Path("/2020-05-31")
public class CloudFrontController {
private static final Logger LOG = Logger.getLogger(CloudFrontController.class);
private static final String NS = AwsNamespaces.CLOUDFRONT;
private static final String XML = "application/xml";
@@ -137,27 +141,24 @@ public class CloudFrontController {
public Response listDistributions(@QueryParam("Marker") String marker,
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
try {
List<Distribution> dists = service.listDistributions(marker, maxItems);
long total = service.listDistributions(null, Integer.MAX_VALUE).size();
boolean truncated = dists.size() == maxItems && dists.size() < total;
Page<Distribution> page = page(
service.listDistributions(marker, paginationFetchLimit(maxItems)),
maxItems, Distribution::getId);
int totalDistributions =
service.listDistributions(null, Integer.MAX_VALUE).size();
XmlBuilder xml = new XmlBuilder()
.start("ListDistributionsResult", NS)
.start("DistributionList")
.start("DistributionList", NS)
.elem("Marker", marker != null ? marker : "")
.elem("NextMarker", page.nextMarker())
.elem("MaxItems", maxItems)
.elem("IsTruncated", truncated);
if (truncated && !dists.isEmpty()) {
xml.elem("NextMarker", dists.get(dists.size() - 1).getId());
}
xml.elem("Quantity", dists.size())
.elem("IsTruncated", page.truncated())
.elem("Quantity", totalDistributions)
.start("Items");
for (Distribution d : dists) {
for (Distribution d : page.items()) {
xml.raw(xmlDistributionSummary(d));
}
xml.end("Items")
.end("DistributionList")
.end("ListDistributionsResult");
xml.end("Items").end("DistributionList");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
@@ -222,17 +223,19 @@ public class CloudFrontController {
@QueryParam("Marker") String marker,
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
try {
List<Invalidation> invs = service.listInvalidations(id, marker, maxItems);
boolean truncated = invs.size() == maxItems;
Page<Invalidation> page = page(
service.listInvalidations(id, marker, paginationFetchLimit(maxItems)),
maxItems, Invalidation::getId);
XmlBuilder xml = new XmlBuilder()
.start("InvalidationList", NS)
.elem("Marker", marker != null ? marker : "")
.elem("NextMarker", page.nextMarker())
.elem("MaxItems", maxItems)
.elem("IsTruncated", truncated)
.elem("Quantity", invs.size())
.elem("IsTruncated", page.truncated())
.elem("Quantity", page.items().size())
.start("Items");
for (Invalidation inv : invs) {
for (Invalidation inv : page.items()) {
xml.start("InvalidationSummary")
.elem("Id", inv.getId())
.elem("Status", inv.getStatus())
@@ -335,24 +338,23 @@ public class CloudFrontController {
@QueryParam("MaxItems") @DefaultValue("100") int maxItems,
@QueryParam("Type") String type) {
try {
List<CachePolicy> policies = service.listCachePolicies(marker, maxItems);
boolean truncated = policies.size() == maxItems;
Page<CachePolicy> page = page(
service.listCachePolicies(marker, paginationFetchLimit(maxItems)),
maxItems, CachePolicy::getId);
XmlBuilder xml = new XmlBuilder()
.start("ListCachePoliciesResult", NS)
.start("CachePolicyList")
.elem("Marker", marker != null ? marker : "")
.start("CachePolicyList", NS)
.elem("NextMarker", page.nextMarker())
.elem("MaxItems", maxItems)
.elem("IsTruncated", truncated)
.elem("Quantity", policies.size())
.elem("Quantity", page.items().size())
.start("Items");
for (CachePolicy p : policies) {
for (CachePolicy p : page.items()) {
xml.start("CachePolicySummary")
.elem("Type", "custom")
.raw(xmlCachePolicyResponse(p))
.end("CachePolicySummary");
}
xml.end("Items").end("CachePolicyList").end("ListCachePoliciesResult");
xml.end("Items").end("CachePolicyList");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
@@ -448,24 +450,23 @@ public class CloudFrontController {
@QueryParam("MaxItems") @DefaultValue("100") int maxItems,
@QueryParam("Type") String type) {
try {
List<OriginRequestPolicy> policies = service.listOriginRequestPolicies(marker, maxItems);
boolean truncated = policies.size() == maxItems;
Page<OriginRequestPolicy> page = page(
service.listOriginRequestPolicies(marker, paginationFetchLimit(maxItems)),
maxItems, OriginRequestPolicy::getId);
XmlBuilder xml = new XmlBuilder()
.start("ListOriginRequestPoliciesResult", NS)
.start("OriginRequestPolicyList")
.elem("Marker", marker != null ? marker : "")
.start("OriginRequestPolicyList", NS)
.elem("NextMarker", page.nextMarker())
.elem("MaxItems", maxItems)
.elem("IsTruncated", truncated)
.elem("Quantity", policies.size())
.elem("Quantity", page.items().size())
.start("Items");
for (OriginRequestPolicy p : policies) {
for (OriginRequestPolicy p : page.items()) {
xml.start("OriginRequestPolicySummary")
.elem("Type", "custom")
.raw(xmlOriginRequestPolicyResponse(p))
.end("OriginRequestPolicySummary");
}
xml.end("Items").end("OriginRequestPolicyList").end("ListOriginRequestPoliciesResult");
xml.end("Items").end("OriginRequestPolicyList");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
@@ -562,24 +563,23 @@ public class CloudFrontController {
@QueryParam("MaxItems") @DefaultValue("100") int maxItems,
@QueryParam("Type") String type) {
try {
List<ResponseHeadersPolicy> policies = service.listResponseHeadersPolicies(marker, maxItems);
boolean truncated = policies.size() == maxItems;
Page<ResponseHeadersPolicy> page = page(
service.listResponseHeadersPolicies(marker, paginationFetchLimit(maxItems)),
maxItems, ResponseHeadersPolicy::getId);
XmlBuilder xml = new XmlBuilder()
.start("ListResponseHeadersPoliciesResult", NS)
.start("ResponseHeadersPolicyList")
.elem("Marker", marker != null ? marker : "")
.start("ResponseHeadersPolicyList", NS)
.elem("NextMarker", page.nextMarker())
.elem("MaxItems", maxItems)
.elem("IsTruncated", truncated)
.elem("Quantity", policies.size())
.elem("Quantity", page.items().size())
.start("Items");
for (ResponseHeadersPolicy p : policies) {
for (ResponseHeadersPolicy p : page.items()) {
xml.start("ResponseHeadersPolicySummary")
.elem("Type", "custom")
.raw(xmlResponseHeadersPolicyResponse(p))
.end("ResponseHeadersPolicySummary");
}
xml.end("Items").end("ResponseHeadersPolicyList").end("ListResponseHeadersPoliciesResult");
xml.end("Items").end("ResponseHeadersPolicyList");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
@@ -677,21 +677,22 @@ public class CloudFrontController {
public Response listOriginAccessControls(@QueryParam("Marker") String marker,
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
try {
List<OriginAccessControl> oacs = service.listOriginAccessControls(marker, maxItems);
boolean truncated = oacs.size() == maxItems;
Page<OriginAccessControl> page = page(
service.listOriginAccessControls(marker, paginationFetchLimit(maxItems)),
maxItems, OriginAccessControl::getId);
XmlBuilder xml = new XmlBuilder()
.start("ListOriginAccessControlsResult", NS)
.start("OriginAccessControlList")
.start("OriginAccessControlList", NS)
.elem("Marker", marker != null ? marker : "")
.elem("NextMarker", page.nextMarker())
.elem("MaxItems", maxItems)
.elem("IsTruncated", truncated)
.elem("Quantity", oacs.size())
.elem("IsTruncated", page.truncated())
.elem("Quantity", page.items().size())
.start("Items");
for (OriginAccessControl o : oacs) {
for (OriginAccessControl o : page.items()) {
xml.raw(xmlOriginAccessControlSummary(o));
}
xml.end("Items").end("OriginAccessControlList").end("ListOriginAccessControlsResult");
xml.end("Items").end("OriginAccessControlList");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
@@ -786,27 +787,27 @@ public class CloudFrontController {
@QueryParam("Marker") String marker,
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
try {
List<CloudFrontOriginAccessIdentity> oais =
service.listCloudFrontOriginAccessIdentities(marker, maxItems);
boolean truncated = oais.size() == maxItems;
Page<CloudFrontOriginAccessIdentity> page = page(
service.listCloudFrontOriginAccessIdentities(
marker, paginationFetchLimit(maxItems)),
maxItems, CloudFrontOriginAccessIdentity::getId);
XmlBuilder xml = new XmlBuilder()
.start("ListCloudFrontOriginAccessIdentitiesResult", NS)
.start("CloudFrontOriginAccessIdentityList")
.start("CloudFrontOriginAccessIdentityList", NS)
.elem("Marker", marker != null ? marker : "")
.elem("NextMarker", page.nextMarker())
.elem("MaxItems", maxItems)
.elem("IsTruncated", truncated)
.elem("Quantity", oais.size())
.elem("IsTruncated", page.truncated())
.elem("Quantity", page.items().size())
.start("Items");
for (CloudFrontOriginAccessIdentity o : oais) {
for (CloudFrontOriginAccessIdentity o : page.items()) {
xml.start("CloudFrontOriginAccessIdentitySummary")
.elem("Id", o.getId())
.elem("S3CanonicalUserId", o.getS3CanonicalUserId())
.elem("Comment", o.getComment() != null ? o.getComment() : "")
.end("CloudFrontOriginAccessIdentitySummary");
}
xml.end("Items").end("CloudFrontOriginAccessIdentityList")
.end("ListCloudFrontOriginAccessIdentitiesResult");
xml.end("Items").end("CloudFrontOriginAccessIdentityList");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
@@ -900,14 +901,16 @@ public class CloudFrontController {
@QueryParam("Marker") String marker,
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
try {
List<CloudFrontFunction> fns = service.listFunctions(stage);
Page<CloudFrontFunction> page = page(
service.listFunctions(stage, marker, paginationFetchLimit(maxItems)),
maxItems, CloudFrontFunction::getName);
XmlBuilder xml = new XmlBuilder()
.start("ListFunctionsResult", NS)
.start("FunctionList")
.start("FunctionList", NS)
.elem("NextMarker", page.nextMarker())
.elem("MaxItems", maxItems)
.elem("Quantity", fns.size())
.elem("Quantity", page.items().size())
.start("Items");
for (CloudFrontFunction fn : fns) {
for (CloudFrontFunction fn : page.items()) {
xml.start("FunctionSummary")
.elem("Name", fn.getName())
.elem("Status", fn.getStatus())
@@ -925,7 +928,7 @@ public class CloudFrontController {
.end("FunctionMetadata")
.end("FunctionSummary");
}
xml.end("Items").end("FunctionList").end("ListFunctionsResult");
xml.end("Items").end("FunctionList");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
@@ -940,8 +943,7 @@ public class CloudFrontController {
try {
Map<String, String> tags = service.listTagsForResource(resource);
XmlBuilder xml = new XmlBuilder()
.start("ListTagsForResourceResult", NS)
.start("Tags")
.start("Tags", NS)
.start("Items");
for (Map.Entry<String, String> entry : tags.entrySet()) {
xml.start("Tag")
@@ -949,7 +951,7 @@ public class CloudFrontController {
.elem("Value", entry.getValue())
.end("Tag");
}
xml.end("Items").end("Tags").end("ListTagsForResourceResult");
xml.end("Items").end("Tags");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
@@ -1048,26 +1050,26 @@ public class CloudFrontController {
public Response listContinuousDeploymentPolicies(@QueryParam("Marker") String marker,
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
try {
List<ContinuousDeploymentPolicy> policies =
service.listContinuousDeploymentPolicies(marker, maxItems);
boolean truncated = policies.size() == maxItems;
Page<ContinuousDeploymentPolicy> page = page(
service.listContinuousDeploymentPolicies(
marker, paginationFetchLimit(maxItems)),
maxItems, ContinuousDeploymentPolicy::getId);
int totalPolicies = service.listContinuousDeploymentPolicies(
null, Integer.MAX_VALUE).size();
XmlBuilder xml = new XmlBuilder()
.start("ListContinuousDeploymentPoliciesResult", NS)
.start("ContinuousDeploymentPolicyList")
.elem("Marker", marker != null ? marker : "")
.start("ContinuousDeploymentPolicyList", NS)
.elem("NextMarker", page.nextMarker())
.elem("MaxItems", maxItems)
.elem("IsTruncated", truncated)
.elem("Quantity", policies.size())
.elem("Quantity", totalPolicies)
.start("Items");
for (ContinuousDeploymentPolicy p : policies) {
for (ContinuousDeploymentPolicy p : page.items()) {
xml.start("ContinuousDeploymentPolicySummary")
.elem("Type", "custom")
.raw(xmlContinuousDeploymentPolicyResponse(p))
.end("ContinuousDeploymentPolicySummary");
}
xml.end("Items").end("ContinuousDeploymentPolicyList")
.end("ListContinuousDeploymentPoliciesResult");
xml.end("Items").end("ContinuousDeploymentPolicyList");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
@@ -1183,21 +1185,20 @@ public class CloudFrontController {
public Response listPublicKeys(@QueryParam("Marker") String marker,
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
try {
List<PublicKey> keys = service.listPublicKeys(marker, maxItems);
boolean truncated = keys.size() == maxItems;
Page<PublicKey> page = page(
service.listPublicKeys(marker, paginationFetchLimit(maxItems)),
maxItems, PublicKey::getId);
XmlBuilder xml = new XmlBuilder()
.start("ListPublicKeysResult", NS)
.start("PublicKeyList")
.elem("Marker", marker != null ? marker : "")
.start("PublicKeyList", NS)
.elem("NextMarker", page.nextMarker())
.elem("MaxItems", maxItems)
.elem("IsTruncated", truncated)
.elem("Quantity", keys.size())
.elem("Quantity", page.items().size())
.start("Items");
for (PublicKey k : keys) {
for (PublicKey k : page.items()) {
xml.raw(xmlPublicKeySummary(k));
}
xml.end("Items").end("PublicKeyList").end("ListPublicKeysResult");
xml.end("Items").end("PublicKeyList");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
@@ -1293,21 +1294,20 @@ public class CloudFrontController {
public Response listKeyGroups(@QueryParam("Marker") String marker,
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
try {
List<KeyGroup> groups = service.listKeyGroups(marker, maxItems);
boolean truncated = groups.size() == maxItems;
Page<KeyGroup> page = page(
service.listKeyGroups(marker, paginationFetchLimit(maxItems)),
maxItems, KeyGroup::getId);
XmlBuilder xml = new XmlBuilder()
.start("ListKeyGroupsResult", NS)
.start("KeyGroupList")
.elem("Marker", marker != null ? marker : "")
.start("KeyGroupList", NS)
.elem("NextMarker", page.nextMarker())
.elem("MaxItems", maxItems)
.elem("IsTruncated", truncated)
.elem("Quantity", groups.size())
.elem("Quantity", page.items().size())
.start("Items");
for (KeyGroup g : groups) {
for (KeyGroup g : page.items()) {
xml.start("KeyGroupSummary").raw(xmlKeyGroupResponse(g)).end("KeyGroupSummary");
}
xml.end("Items").end("KeyGroupList").end("ListKeyGroupsResult");
xml.end("Items").end("KeyGroupList");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
@@ -1389,20 +1389,22 @@ public class CloudFrontController {
public Response listRealtimeLogConfigs(@QueryParam("Marker") String marker,
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
try {
List<RealtimeLogConfig> configs = service.listRealtimeLogConfigs(marker, maxItems);
boolean truncated = configs.size() == maxItems;
Page<RealtimeLogConfig> page = page(
service.listRealtimeLogConfigs(marker, paginationFetchLimit(maxItems)),
maxItems, RealtimeLogConfig::getName);
XmlBuilder xml = new XmlBuilder()
.start("ListRealtimeLogConfigsResult", NS)
.start("RealtimeLogConfigs")
.start("RealtimeLogConfigs", NS)
.elem("MaxItems", maxItems)
.elem("IsTruncated", truncated)
.elem("Quantity", configs.size())
.start("Items");
for (RealtimeLogConfig c : configs) {
for (RealtimeLogConfig c : page.items()) {
xml.raw(xmlRealtimeLogConfigBody(c));
}
xml.end("Items").end("RealtimeLogConfigs").end("ListRealtimeLogConfigsResult");
xml.end("Items")
.elem("IsTruncated", page.truncated())
.elem("Marker", marker != null ? marker : "")
.elem("NextMarker", page.nextMarker())
.end("RealtimeLogConfigs");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
@@ -1558,22 +1560,21 @@ public class CloudFrontController {
public Response listFieldLevelEncryptionConfigs(@QueryParam("Marker") String marker,
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
try {
List<FieldLevelEncryptionConfig> configs =
service.listFieldLevelEncryptionConfigs(marker, maxItems);
boolean truncated = configs.size() == maxItems;
Page<FieldLevelEncryptionConfig> page = page(
service.listFieldLevelEncryptionConfigs(
marker, paginationFetchLimit(maxItems)),
maxItems, FieldLevelEncryptionConfig::getId);
XmlBuilder xml = new XmlBuilder()
.start("ListFieldLevelEncryptionConfigsResult", NS)
.start("FieldLevelEncryptionList")
.elem("Marker", marker != null ? marker : "")
.start("FieldLevelEncryptionList", NS)
.elem("NextMarker", page.nextMarker())
.elem("MaxItems", maxItems)
.elem("IsTruncated", truncated)
.elem("Quantity", configs.size())
.elem("Quantity", page.items().size())
.start("Items");
for (FieldLevelEncryptionConfig c : configs) {
for (FieldLevelEncryptionConfig c : page.items()) {
xml.raw(xmlFieldLevelEncryptionConfigResponse(c));
}
xml.end("Items").end("FieldLevelEncryptionList").end("ListFieldLevelEncryptionConfigsResult");
xml.end("Items").end("FieldLevelEncryptionList");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
@@ -1652,23 +1653,21 @@ public class CloudFrontController {
public Response listFieldLevelEncryptionProfiles(@QueryParam("Marker") String marker,
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
try {
List<FieldLevelEncryptionProfile> profiles =
service.listFieldLevelEncryptionProfiles(marker, maxItems);
boolean truncated = profiles.size() == maxItems;
Page<FieldLevelEncryptionProfile> page = page(
service.listFieldLevelEncryptionProfiles(
marker, paginationFetchLimit(maxItems)),
maxItems, FieldLevelEncryptionProfile::getId);
XmlBuilder xml = new XmlBuilder()
.start("ListFieldLevelEncryptionProfilesResult", NS)
.start("FieldLevelEncryptionProfileList")
.elem("Marker", marker != null ? marker : "")
.start("FieldLevelEncryptionProfileList", NS)
.elem("NextMarker", page.nextMarker())
.elem("MaxItems", maxItems)
.elem("IsTruncated", truncated)
.elem("Quantity", profiles.size())
.elem("Quantity", page.items().size())
.start("Items");
for (FieldLevelEncryptionProfile p : profiles) {
for (FieldLevelEncryptionProfile p : page.items()) {
xml.raw(xmlFieldLevelEncryptionProfileResponse(p));
}
xml.end("Items").end("FieldLevelEncryptionProfileList")
.end("ListFieldLevelEncryptionProfilesResult");
xml.end("Items").end("FieldLevelEncryptionProfileList");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
@@ -1765,7 +1764,30 @@ public class CloudFrontController {
}
xml.end("CacheBehaviors");
xml.start("CustomErrorResponses").elem("Quantity", 0).end("CustomErrorResponses");
List<Map<String, Object>> customErrors = cfg.getCustomErrorResponses();
int cerCount = customErrors != null ? customErrors.size() : 0;
xml.start("CustomErrorResponses").elem("Quantity", cerCount);
if (cerCount > 0) {
xml.start("Items");
for (Map<String, Object> cer : customErrors) {
xml.start("CustomErrorResponse").elem("ErrorCode", str(cer.get("ErrorCode")));
// ResponsePagePath and ResponseCode are optional; CloudFront omits them when unset
// rather than returning empty elements.
String pagePath = str(cer.get("ResponsePagePath"));
if (!pagePath.isEmpty()) {
xml.elem("ResponsePagePath", pagePath);
}
String responseCode = str(cer.get("ResponseCode"));
if (!responseCode.isEmpty()) {
xml.elem("ResponseCode", responseCode);
}
xml.elem("ErrorCachingMinTTL", cer.get("ErrorCachingMinTTL") != null
? str(cer.get("ErrorCachingMinTTL")) : "0")
.end("CustomErrorResponse");
}
xml.end("Items");
}
xml.end("CustomErrorResponses");
List<String> aliases = cfg.getAliases();
int aliasCount = aliases != null ? aliases.size() : 0;
@@ -2059,6 +2081,11 @@ public class CloudFrontController {
.build();
}
/** Renders a possibly-null value as a string, using the empty string for {@code null}. */
private static String str(Object value) {
return value != null ? value.toString() : "";
}
private String xmlQuantityItems(String wrapper, String itemTag, int count, List<String> items) {
XmlBuilder xml = new XmlBuilder().start(wrapper).elem("Quantity", count);
if (count > 0 && items != null && !items.isEmpty()) {
@@ -2072,6 +2099,21 @@ public class CloudFrontController {
return xml.build();
}
private static int paginationFetchLimit(int maxItems) {
return maxItems > 0 && maxItems < Integer.MAX_VALUE ? maxItems + 1 : maxItems;
}
private static <T> Page<T> page(List<T> candidates, int maxItems,
Function<T, String> markerFunction) {
boolean truncated = maxItems > 0 && candidates.size() > maxItems;
List<T> items = truncated ? candidates.subList(0, maxItems) : candidates;
String nextMarker = truncated && !items.isEmpty()
? markerFunction.apply(items.get(items.size() - 1)) : null;
return new Page<>(items, truncated, nextMarker);
}
private record Page<T>(List<T> items, boolean truncated, String nextMarker) {}
private Response xmlErrorResponse(AwsException e) {
String xml = new XmlBuilder()
.start("ErrorResponse", NS)
@@ -2106,10 +2148,71 @@ public class CloudFrontController {
cfg.setCacheBehaviors(parseCacheBehaviors(body));
cfg.setAliases(parseAliases(body));
cfg.setViewerCertificate(parseViewerCertificate(body));
cfg.setCustomErrorResponses(parseCustomErrorResponses(body));
return cfg;
}
/**
* Parses the {@code CustomErrorResponses} block into a list of maps keyed by
* {@code ErrorCode}, {@code ResponsePagePath}, {@code ResponseCode} and {@code ErrorCachingMinTTL}
* (values kept as strings). CloudFront uses these to override an origin error with a custom
* page/status — most notably the SPA fallback that turns a 403/404 into 200 {@code /index.html}.
*/
private List<Map<String, Object>> parseCustomErrorResponses(String body) {
List<Map<String, Object>> result = new ArrayList<>();
if (body == null || body.isEmpty()) {
return result;
}
try {
XMLStreamReader r = XML_FACTORY.createXMLStreamReader(new StringReader(body));
boolean inBlock = false;
boolean inItem = false;
Map<String, Object> current = null;
while (r.hasNext()) {
int event = r.next();
if (event == XMLStreamConstants.START_ELEMENT) {
String local = r.getLocalName();
switch (local) {
case "CustomErrorResponses" -> inBlock = true;
case "CustomErrorResponse" -> {
if (inBlock) {
inItem = true;
current = new LinkedHashMap<>();
}
}
case "ErrorCode", "ResponsePagePath", "ResponseCode", "ErrorCachingMinTTL" -> {
if (inItem && current != null) {
current.put(local, r.getElementText());
}
}
default -> {
}
}
} else if (event == XMLStreamConstants.END_ELEMENT) {
switch (r.getLocalName()) {
case "CustomErrorResponse" -> {
if (inItem && current != null) {
result.add(current);
}
inItem = false;
current = null;
}
case "CustomErrorResponses" -> inBlock = false;
default -> {
}
}
}
}
r.close();
} catch (Exception e) {
// A malformed CustomErrorResponses block yields the entries parsed so far rather than
// failing the whole distribution create/update; log it so the cause is diagnosable.
LOG.debugv("Ignoring malformed CustomErrorResponses during parse: {0}", e.getMessage());
}
return result;
}
private List<Origin> parseOrigins(String body) {
List<Origin> result = new ArrayList<>();
if (body == null || body.isEmpty()) {
@@ -2487,9 +2590,10 @@ public class CloudFrontController {
OriginAccessControl oac = new OriginAccessControl();
oac.setName(XmlParser.extractFirst(body, "Name", null));
oac.setDescription(XmlParser.extractFirst(body, "Description", null));
oac.setSigningProtocol(XmlParser.extractFirst(body, "SigningProtocol", "sigv4"));
oac.setSigningBehavior(XmlParser.extractFirst(body, "SigningBehavior", "always"));
oac.setOriginAccessControlOriginType(XmlParser.extractFirst(body, "OriginAccessControlOriginType", "s3"));
oac.setSigningProtocol(XmlParser.extractFirst(body, "SigningProtocol", null));
oac.setSigningBehavior(XmlParser.extractFirst(body, "SigningBehavior", null));
oac.setOriginAccessControlOriginType(
XmlParser.extractFirst(body, "OriginAccessControlOriginType", null));
return oac;
}
@@ -0,0 +1,90 @@
package io.github.hectorvent.floci.services.cloudfront;
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
import jakarta.annotation.Priority;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.PreMatching;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.Provider;
import org.jboss.logging.Logger;
import java.net.URI;
/**
* Routes viewer requests addressed to a CloudFront distribution's domain to the distribution
* request-serving controller.
*
* <p>When a request arrives with a {@code Host} header matching a distribution's assigned
* CloudFront domain name ({@code <id>.cloudfront.net}) or one of its alternate domain names
* (CNAME aliases), this filter rewrites the request URI to
* {@code /_cloudfront/{distributionId}{rawPath}} so {@link CloudFrontServingController} can resolve
* the matching origin and return the content — mirroring how CloudFront fronts an S3 or custom
* origin.
*
* <p>Runs at priority 15: after the Lambda function URL (5) and API Gateway custom domain (10)
* filters, but before the S3 virtual-host filter (default 5000), so a distribution or alias host
* is not mistaken for an S3 virtual-hosted bucket.
*/
@Provider
@PreMatching
@Priority(15)
public class CloudFrontDistributionFilter implements ContainerRequestFilter {
public static final String ROUTED_PROPERTY = CloudFrontDistributionFilter.class.getName() + ".routed";
private static final Logger LOG = Logger.getLogger(CloudFrontDistributionFilter.class);
// A @PreMatching filter is wired into the request pipeline at build time, so holding the
// CloudFrontService proxy directly would place it in the native-image build heap — illegal because
// CloudFrontService is initialized at image run time (it uses SecureRandom). Inject a lazy Instance
// and resolve the bean per request instead.
private final Instance<CloudFrontService> service;
@Inject
public CloudFrontDistributionFilter(Instance<CloudFrontService> service) {
this.service = service;
}
@Override
public void filter(ContainerRequestContext requestContext) {
String host = requestContext.getHeaderString("Host");
if (host == null) {
return;
}
Distribution dist = service.get().findByHost(host);
if (dist == null) {
return;
}
if (dist.getConfig() == null || !dist.getConfig().isEnabled()) {
requestContext.abortWith(Response.status(404).build());
return;
}
URI originalUri = requestContext.getUriInfo().getRequestUri();
String rawPath = originalUri.getRawPath();
if (rawPath == null || rawPath.isEmpty()) {
rawPath = "/";
}
// The serving controller lives at /_cloudfront/{distId}/{proxy:.*}; the leading slash from
// rawPath supplies the separator (root "/" becomes /_cloudfront/{id}/).
String newPath = "/_cloudfront/" + dist.getId() + rawPath;
StringBuilder rewritten = new StringBuilder();
if (originalUri.getScheme() != null) {
rewritten.append(originalUri.getScheme()).append("://").append(originalUri.getRawAuthority());
}
rewritten.append(newPath);
if (originalUri.getRawQuery() != null) {
rewritten.append('?').append(originalUri.getRawQuery());
}
URI newUri = URI.create(rewritten.toString());
LOG.debugv("CloudFront distribution routing: {0}{1} -> {2}", host, rawPath, newUri.getPath());
requestContext.setProperty(ROUTED_PROPERTY, Boolean.TRUE);
requestContext.setRequestUri(newUri);
}
}
@@ -0,0 +1,215 @@
package io.github.hectorvent.floci.services.cloudfront;
import org.apache.hc.client5.http.DnsResolver;
import org.apache.hc.client5.http.SystemDefaultDnsResolver;
import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.config.TlsConfig;
import org.apache.hc.client5.http.impl.DefaultSchemePortResolver;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.impl.routing.DefaultRoutePlanner;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpVersion;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
import org.apache.hc.core5.http2.HttpVersionPolicy;
import org.apache.hc.core5.util.Timeout;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* HTTP/1.1 transport for CloudFront custom origins that validates and pins each DNS resolution to
* the addresses used by the connection. Keeping the logical hostname in the request URI preserves
* the origin Host header, TLS SNI, and certificate hostname verification.
*/
final class CloudFrontOriginHttpClient implements AutoCloseable {
private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(10);
private static final Duration RESPONSE_TIMEOUT = Duration.ofSeconds(30);
private final CloseableHttpClient client;
CloudFrontOriginHttpClient(Collection<String> allowedPrivateOriginHosts) {
this(SystemDefaultDnsResolver.INSTANCE, allowedPrivateOriginHosts, null);
}
CloudFrontOriginHttpClient(DnsResolver delegate, Collection<String> allowedPrivateOriginHosts) {
this(delegate, allowedPrivateOriginHosts, null);
}
CloudFrontOriginHttpClient(
DnsResolver delegate,
Collection<String> allowedPrivateOriginHosts,
SSLContext sslContext) {
Set<String> allowedHosts = allowedPrivateOriginHosts.stream()
.map(CloudFrontServingController::normalizeHost)
.collect(Collectors.toUnmodifiableSet());
DnsResolver validatingResolver = new ValidatingDnsResolver(delegate, allowedHosts);
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setConnectTimeout(Timeout.of(CONNECT_TIMEOUT))
.setSocketTimeout(Timeout.of(RESPONSE_TIMEOUT))
.build();
TlsConfig tlsConfig = TlsConfig.custom()
.setHandshakeTimeout(Timeout.of(CONNECT_TIMEOUT))
.setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_1)
.build();
PoolingHttpClientConnectionManagerBuilder connectionManagerBuilder =
PoolingHttpClientConnectionManagerBuilder.create()
.setDnsResolver(validatingResolver)
.setDefaultConnectionConfig(connectionConfig)
.setDefaultTlsConfig(tlsConfig)
.setMaxConnTotal(100)
.setMaxConnPerRoute(20);
if (sslContext != null) {
connectionManagerBuilder.setTlsSocketStrategy(ClientTlsStrategyBuilder.create()
.setSslContext(sslContext)
.buildClassic());
}
PoolingHttpClientConnectionManager connectionManager = connectionManagerBuilder.build();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(Timeout.of(CONNECT_TIMEOUT))
.setResponseTimeout(Timeout.of(RESPONSE_TIMEOUT))
.setRedirectsEnabled(false)
.setContentCompressionEnabled(false)
.setProtocolUpgradeEnabled(false)
.build();
this.client = HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
.disableAutomaticRetries()
.disableRedirectHandling()
.disableContentCompression()
.disableCookieManagement()
.setRoutePlanner(new DefaultRoutePlanner(DefaultSchemePortResolver.INSTANCE))
.build();
}
HttpResponse<byte[]> send(HttpRequest request, HttpResponse.BodyHandler<byte[]> bodyHandler)
throws IOException, InterruptedException {
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException("CloudFront origin request interrupted");
}
if (request.bodyPublisher().filter(publisher -> publisher.contentLength() != 0).isPresent()) {
throw new IOException("CloudFront origin request bodies are not supported");
}
ClassicRequestBuilder builder = ClassicRequestBuilder.create(request.method())
.setUri(request.uri())
.setVersion(HttpVersion.HTTP_1_1);
request.headers().map().forEach((name, values) ->
values.forEach(value -> builder.addHeader(name, value)));
HttpClientContext context = HttpClientContext.create();
Duration responseTimeout = request.timeout().orElse(RESPONSE_TIMEOUT);
context.setRequestConfig(RequestConfig.custom()
.setConnectionRequestTimeout(Timeout.of(CONNECT_TIMEOUT))
.setResponseTimeout(Timeout.of(responseTimeout))
.setRedirectsEnabled(false)
.setContentCompressionEnabled(false)
.setProtocolUpgradeEnabled(false)
.build());
try {
return client.execute(builder.build(), context, response -> {
Map<String, List<String>> responseHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
for (Header header : response.getHeaders()) {
responseHeaders.computeIfAbsent(header.getName(), ignored -> new ArrayList<>())
.add(header.getValue());
}
byte[] body = response.getEntity() != null
? EntityUtils.toByteArray(response.getEntity())
: new byte[0];
return new PinnedHttpResponse(
response.getCode(), request,
HttpHeaders.of(responseHeaders, (name, value) -> true),
body, request.uri());
});
} catch (InterruptedIOException e) {
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException("CloudFront origin request interrupted");
}
throw e;
}
}
@Override
public void close() throws IOException {
client.close();
}
private record PinnedHttpResponse(
int statusCode,
HttpRequest request,
HttpHeaders headers,
byte[] body,
URI uri) implements HttpResponse<byte[]> {
@Override
public Optional<HttpResponse<byte[]>> previousResponse() {
return Optional.empty();
}
@Override
public Optional<SSLSession> sslSession() {
return Optional.empty();
}
@Override
public HttpClient.Version version() {
return HttpClient.Version.HTTP_1_1;
}
}
private record ValidatingDnsResolver(DnsResolver delegate, Set<String> allowedHosts)
implements DnsResolver {
@Override
public InetAddress[] resolve(String host) throws UnknownHostException {
InetAddress[] addresses = delegate.resolve(host);
String normalizedHost = CloudFrontServingController.normalizeHost(host);
if (addresses == null || addresses.length == 0) {
throw new UnknownHostException("CloudFront origin host has no addresses: " + normalizedHost);
}
if (!allowedHosts.contains(normalizedHost)) {
for (InetAddress address : addresses) {
if (CloudFrontServingController.isBlockedOriginAddress(address)) {
throw new UnknownHostException(
"CloudFront origin host resolves to a blocked address: " + normalizedHost);
}
}
}
return addresses.clone();
}
@Override
public String resolveCanonicalHostname(String host) {
return CloudFrontServingController.normalizeHost(host);
}
}
}
@@ -0,0 +1,255 @@
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.DistributionConfig;
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Pure request-routing logic for CloudFront distribution serving, implemented to the AWS data-plane
* spec (verified against the CloudFront Developer Guide):
*
* <ul>
* <li>The requested path is normalized per RFC 3986 (collapse {@code //}, resolve {@code .}/{@code ..})
* before behavior matching; the raw path is what gets forwarded to the origin.</li>
* <li>Cache behaviors are evaluated in the order listed; the <em>default</em> behavior is always
* processed <em>last</em>. The first matching path pattern wins.</li>
* <li>Path patterns use {@code *} (0+ chars) and {@code ?} (exactly 1 char), are case-sensitive, and a
* leading {@code /} is optional (ignored).</li>
* <li>The default root object is returned <em>only</em> for the distribution root ({@code /}); it is
* never appended for subdirectory requests (this differs from S3 website index documents).</li>
* <li>The origin path is prepended to the request URI when forwarding to the origin.</li>
* </ul>
*
* This class holds no distribution state and does no I/O. It keeps only a bounded compiled-pattern
* cache so the routing rules remain cheap and can be unit-tested in isolation.
*/
public final class CloudFrontRequestRouter {
private static final int PATTERN_CACHE_CAPACITY = 256;
private static final String REGION_PATTERN = "[a-z0-9-]+-[0-9]+";
private static final Pattern AWS_S3_ENDPOINT = Pattern.compile(
"(?:s3|s3\\.(?:dualstack\\.)?" + REGION_PATTERN
+ "|s3-" + REGION_PATTERN
+ "|s3-website[.-]" + REGION_PATTERN
+ "|s3-accelerate(?:\\.dualstack)?)\\.amazonaws\\.com(?:\\.cn)?");
private static final Pattern LOCAL_S3_ENDPOINT = Pattern.compile(
"(?:s3(?:\\." + REGION_PATTERN + ")?"
+ "|s3-website[.-]" + REGION_PATTERN
+ ")\\.localhost(?:\\.(?:floci\\.io|localstack\\.cloud))?");
private static final Map<String, Pattern> PATTERN_CACHE =
new LinkedHashMap<>(PATTERN_CACHE_CAPACITY, 0.75f, true);
private CloudFrontRequestRouter() {
}
/**
* Normalizes a viewer request path per RFC 3986 the way CloudFront does before behavior matching:
* resolves {@code .} / {@code ..} segments and collapses repeated slashes. Always returns a path
* beginning with {@code /}.
*/
public static String normalizePath(String rawPath) {
String path = (rawPath == null || rawPath.isEmpty()) ? "/" : rawPath;
if (!path.startsWith("/")) {
path = "/" + path;
}
boolean trailingSlash = path.length() > 1
&& (path.endsWith("/") || path.endsWith("/.") || path.endsWith("/.."));
Deque<String> out = new ArrayDeque<>();
for (String seg : path.split("/")) {
if (seg.isEmpty() || seg.equals(".")) {
continue; // collapses "//" and drops "."
}
if (seg.equals("..")) {
if (!out.isEmpty()) {
out.removeLast();
}
continue;
}
out.addLast(seg);
}
if (out.isEmpty()) {
return "/";
}
String joined = "/" + String.join("/", out);
return trailingSlash ? joined + "/" : joined;
}
/** True when {@code path} is the distribution root. */
public static boolean isRoot(String normalizedPath) {
return normalizedPath == null || normalizedPath.isEmpty() || normalizedPath.equals("/");
}
/**
* Returns the {@code targetOriginId} for a normalized path by evaluating the ordered cache
* behaviors first (first match wins) and falling back to the default behavior last.
*/
public static String matchTargetOriginId(DistributionConfig config, String normalizedPath) {
List<CacheBehavior> behaviors = config.getCacheBehaviors();
if (behaviors != null) {
for (CacheBehavior behavior : behaviors) {
if (pathPatternMatches(behavior.getPathPattern(), normalizedPath)) {
return behavior.getTargetOriginId();
}
}
}
DefaultCacheBehavior dflt = config.getDefaultCacheBehavior();
return dflt != null ? dflt.getTargetOriginId() : null;
}
/**
* 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
* case-sensitive. A {@code null}/blank or {@code *} pattern matches everything (the default behavior).
*/
public static boolean pathPatternMatches(String pattern, String path) {
if (pattern == null || pattern.isEmpty() || pattern.equals("*") || pattern.equals("/*")) {
return true;
}
String p = pattern.startsWith("/") ? pattern.substring(1) : pattern;
String candidate = path.startsWith("/") ? path.substring(1) : path;
return compiledPattern(p).matcher(candidate).matches();
}
private static Pattern compiledPattern(String pattern) {
synchronized (PATTERN_CACHE) {
Pattern compiled = PATTERN_CACHE.get(pattern);
if (compiled != null) {
return compiled;
}
if (PATTERN_CACHE.size() >= PATTERN_CACHE_CAPACITY) {
String eldest = PATTERN_CACHE.keySet().iterator().next();
PATTERN_CACHE.remove(eldest);
}
compiled = Pattern.compile(wildcardToRegex(pattern));
PATTERN_CACHE.put(pattern, compiled);
return compiled;
}
}
static int patternCacheSize() {
synchronized (PATTERN_CACHE) {
return PATTERN_CACHE.size();
}
}
static void clearPatternCache() {
synchronized (PATTERN_CACHE) {
PATTERN_CACHE.clear();
}
}
private static String wildcardToRegex(String pattern) {
StringBuilder regex = new StringBuilder(pattern.length() + 8);
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
switch (c) {
case '*' -> regex.append(".*");
case '?' -> regex.append('.');
// Escape every other regex metacharacter so patterns match literally.
case '.', '\\', '+', '(', ')', '[', ']', '{', '}', '^', '$', '|' -> regex.append('\\').append(c);
default -> regex.append(c);
}
}
return regex.toString();
}
/**
* Computes the origin object key for a request: the default root object is used only for the root
* request; the origin path is prepended; the result never begins with {@code /} (S3-object form).
*/
public static String resolveOriginKey(String originPath, String normalizedPath, String defaultRootObject) {
String combined = resolveForwardUri(originPath, normalizedPath, defaultRootObject);
return combined.startsWith("/") ? combined.substring(1) : combined;
}
/**
* Computes the URI to forward to the origin: the default root object replaces the path only for the
* root request (applies to custom origins as well as S3), then the origin path is prepended. The
* result keeps its leading {@code /} (custom-origin URI form).
*/
public static String resolveForwardUri(String originPath, String normalizedPath, String defaultRootObject) {
String object;
if (isRoot(normalizedPath) && defaultRootObject != null && !defaultRootObject.isBlank()) {
object = defaultRootObject;
} else {
object = normalizedPath;
}
return joinPath(originPath, object);
}
/** Joins an optional origin path with the object path, normalizing the slash between them. */
public static String joinPath(String originPath, String object) {
String base = (originPath == null) ? "" : originPath.trim();
if (base.endsWith("/")) {
base = base.substring(0, base.length() - 1);
}
String obj = (object == null) ? "" : object;
if (!obj.startsWith("/")) {
obj = "/" + obj;
}
return base + obj;
}
/** Finds the origin with the given id, or {@code null}. */
public static Origin findOrigin(DistributionConfig config, String originId) {
if (config.getOrigins() == null || originId == null) {
return null;
}
for (Origin origin : config.getOrigins()) {
if (originId.equals(origin.getId())) {
return origin;
}
}
return null;
}
/** True when the origin is an S3 (non-website) origin — modeled by the presence of {@code S3OriginConfig}. */
public static boolean isS3Origin(Origin origin) {
return origin != null && origin.getS3OriginConfig() != null && origin.getCustomOriginConfig() == null;
}
/**
* Extracts the bucket name from an S3 origin domain name. Handles the regional/global REST endpoints
* ({@code bucket.s3.us-east-1.amazonaws.com}, {@code bucket.s3.amazonaws.com}) and the website
* endpoint ({@code bucket.s3-website-us-east-1.amazonaws.com}) — the bucket is the leading label(s)
* before the {@code .s3} / {@code .s3-website} marker.
*/
public static String bucketFromS3Domain(String domainName) {
if (domainName == null || domainName.isBlank()) {
return null;
}
String host = domainName;
int colon = host.lastIndexOf(':');
if (colon > 0) {
String port = host.substring(colon + 1);
if (port.isEmpty() || !port.chars().allMatch(Character::isDigit)) {
return null;
}
host = host.substring(0, colon);
}
String lowerHost = host.toLowerCase(java.util.Locale.ROOT);
int endpointMarker = -1;
for (String marker : new String[] {".s3-website-", ".s3-website.", ".s3.", ".s3-"}) {
endpointMarker = Math.max(endpointMarker, lowerHost.lastIndexOf(marker));
}
if (endpointMarker > 0 && supportedS3Endpoint(lowerHost.substring(endpointMarker + 1))) {
return host.substring(0, endpointMarker);
}
// A bare bucket name is accepted for local configuration. An unrecognized dotted host is
// not an S3 endpoint and must not be truncated into a different local bucket name.
return host.indexOf('.') < 0 ? host : null;
}
private static boolean supportedS3Endpoint(String endpoint) {
return AWS_S3_ENDPOINT.matcher(endpoint).matches()
|| LOCAL_S3_ENDPOINT.matcher(endpoint).matches();
}
}
@@ -11,11 +11,13 @@ 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.Distribution;
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
import io.github.hectorvent.floci.services.cloudfront.model.FieldLevelEncryptionConfig;
import io.github.hectorvent.floci.services.cloudfront.model.FieldLevelEncryptionProfile;
import io.github.hectorvent.floci.services.cloudfront.model.Invalidation;
import io.github.hectorvent.floci.services.cloudfront.model.KeyGroup;
import io.github.hectorvent.floci.services.cloudfront.model.MonitoringSubscription;
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.OriginRequestPolicy;
import io.github.hectorvent.floci.services.cloudfront.model.PublicKey;
@@ -31,6 +33,7 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
@@ -39,6 +42,10 @@ public class CloudFrontService {
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final SecureRandom RANDOM = new SecureRandom();
private static final Set<String> OAC_ORIGIN_TYPES =
Set.of("s3", "mediastore", "mediapackagev2", "lambda");
private static final Set<String> OAC_SIGNING_BEHAVIORS =
Set.of("always", "never", "no-override");
private final StorageBackend<String, Distribution> distStore;
private final StorageBackend<String, List<Invalidation>> invalidationStore;
@@ -103,6 +110,7 @@ public class CloudFrontService {
// ── Distributions ─────────────────────────────────────────────────────────
public synchronized Distribution createDistribution(Distribution dist, Map<String, String> tags) {
ensureAliasesAvailable(dist.getConfig(), null);
String id = generateDistributionId();
dist.setId(id);
dist.setArn(AwsArnUtils.Arn.of("cloudfront", "", accountId, "distribution/" + id).toString());
@@ -129,6 +137,7 @@ public class CloudFrontService {
throw new AwsException("InvalidIfMatchVersion",
"The If-Match version is missing or not valid for the resource.", 400);
}
ensureAliasesAvailable(updated.getConfig(), id);
updated.setId(id);
updated.setArn(existing.getArn());
updated.setDomainName(existing.getDomainName());
@@ -155,6 +164,17 @@ public class CloudFrontService {
tagStore.delete("distribution/" + id);
}
/**
* Removes a distribution and its associated invalidations/tags without the disable/If-Match guards
* enforced by {@link #deleteDistribution(String, String)}. Used by CloudFormation stack deletion,
* which owns the resource lifecycle at the stack level.
*/
public synchronized void removeDistribution(String id) {
distStore.delete(id);
invalidationStore.delete(id);
tagStore.delete("distribution/" + id);
}
public List<Distribution> listDistributions(String marker, int maxItems) {
List<Distribution> all = new ArrayList<>(distStore.scan(k -> true));
all.sort((a, b) -> a.getId().compareTo(b.getId()));
@@ -175,23 +195,138 @@ public class CloudFrontService {
}
public synchronized void associateAlias(String targetDistributionId, String alias) {
if (alias == null || alias.isBlank()) {
throw new AwsException("InvalidArgument", "The alias must not be empty.", 400);
}
Distribution dist = getDistribution(targetDistributionId);
List<String> aliases = dist.getConfig() != null ? dist.getConfig().getAliases() : null;
if (dist.getConfig() == null) {
throw new AwsException("InvalidArgument", "The target distribution has no configuration.", 400);
}
for (Distribution candidate : distStore.scan(k -> true)) {
if (targetDistributionId.equals(candidate.getId()) || candidate.getConfig() == null
|| candidate.getConfig().getAliases() == null) {
continue;
}
List<String> previousAliases = candidate.getConfig().getAliases();
List<String> remaining = new ArrayList<>(previousAliases);
remaining.removeIf(existing -> alias.equalsIgnoreCase(existing));
if (remaining.size() != previousAliases.size()) {
candidate.getConfig().setAliases(remaining);
candidate.setEtag(UUID.randomUUID().toString());
candidate.setLastModifiedTime(Instant.now());
distStore.put(candidate.getId(), candidate);
}
}
List<String> aliases = dist.getConfig().getAliases();
if (aliases == null) {
aliases = new ArrayList<>();
} else {
aliases = new ArrayList<>(aliases);
}
if (!aliases.contains(alias)) {
aliases.add(alias);
}
if (dist.getConfig() != null) {
dist.getConfig().setAliases(aliases);
}
aliases.removeIf(existing -> alias.equalsIgnoreCase(existing));
aliases.add(alias);
dist.getConfig().setAliases(aliases);
dist.setEtag(UUID.randomUUID().toString());
dist.setLastModifiedTime(Instant.now());
distStore.put(targetDistributionId, dist);
}
/**
* Finds the distribution whose data-plane requests should be served for the given {@code Host}
* header. A distribution matches when the host equals its assigned CloudFront domain name
* ({@code <id>.cloudfront.net}) or one of its alternate domain names (CNAME aliases). Any port
* suffix is ignored and matching is case-insensitive. Returns {@code null} when nothing matches.
*/
public Distribution findByHost(String host) {
if (host == null || host.isBlank()) {
return null;
}
String hostname = stripPort(host);
List<Distribution> distributions = new ArrayList<>(distStore.scan(k -> true));
for (Distribution dist : distributions) {
if (hostname.equalsIgnoreCase(dist.getDomainName())) {
return dist;
}
}
for (Distribution dist : distributions) {
DistributionConfig cfg = dist.getConfig();
if (cfg != null && cfg.getAliases() != null) {
for (String alias : cfg.getAliases()) {
if (hostname.equalsIgnoreCase(alias)) {
return dist;
}
}
}
}
Distribution best = null;
int bestSpecificity = -1;
for (Distribution dist : distributions) {
DistributionConfig cfg = dist.getConfig();
if (cfg == null || cfg.getAliases() == null) {
continue;
}
for (String alias : cfg.getAliases()) {
if (wildcardAliasMatches(alias, hostname) && alias.length() > bestSpecificity) {
best = dist;
bestSpecificity = alias.length();
}
}
}
return best;
}
private void ensureAliasesAvailable(DistributionConfig config, String currentDistributionId) {
if (config == null || config.getAliases() == null) {
return;
}
for (String requested : config.getAliases()) {
if (requested == null || requested.isBlank()) {
continue;
}
for (Distribution existing : distStore.scan(k -> true)) {
if (existing.getId().equals(currentDistributionId) || existing.getConfig() == null
|| existing.getConfig().getAliases() == null) {
continue;
}
for (String assigned : existing.getConfig().getAliases()) {
if (requested.equalsIgnoreCase(assigned)) {
throw new AwsException("CNAMEAlreadyExists",
"The CNAME you provided is already associated with a different resource.", 409);
}
}
}
}
}
private static boolean wildcardAliasMatches(String alias, String hostname) {
if (alias == null || !alias.startsWith("*.") || hostname == null) {
return false;
}
String suffix = alias.substring(1); // ".example.com"
if (hostname.length() <= suffix.length()
|| !hostname.regionMatches(true, hostname.length() - suffix.length(),
suffix, 0, suffix.length())) {
return false;
}
// A CloudFront wildcard replaces exactly one label, so the part standing in for the "*"
// must not itself contain a dot: "*.example.com" covers marketing.example.com but not
// marketing.product.example.com. AWS is explicit that names at a level higher or lower
// than the wildcard are not covered.
return hostname.lastIndexOf('.', hostname.length() - suffix.length() - 1) < 0;
}
private static String stripPort(String host) {
int colon = host.lastIndexOf(':');
if (colon > 0) {
String maybePort = host.substring(colon + 1);
if (!maybePort.isEmpty() && maybePort.chars().allMatch(Character::isDigit)) {
return host.substring(0, colon);
}
}
return host;
}
// ── Invalidations ─────────────────────────────────────────────────────────
public synchronized Invalidation createInvalidation(String distributionId, Invalidation inv) {
@@ -414,6 +549,7 @@ public class CloudFrontService {
// ── Origin Access Control ─────────────────────────────────────────────────
public synchronized OriginAccessControl createOriginAccessControl(OriginAccessControl oac) {
validateOriginAccessControl(oac);
oac.setId(UUID.randomUUID().toString());
oac.setEtag(UUID.randomUUID().toString());
oac.setLastModifiedTime(Instant.now());
@@ -434,6 +570,7 @@ public class CloudFrontService {
throw new AwsException("InvalidIfMatchVersion",
"The If-Match version is missing or not valid for the resource.", 400);
}
validateOriginAccessControl(updated);
updated.setId(id);
updated.setEtag(UUID.randomUUID().toString());
updated.setLastModifiedTime(Instant.now());
@@ -447,6 +584,11 @@ public class CloudFrontService {
throw new AwsException("InvalidIfMatchVersion",
"The If-Match version is missing or not valid for the resource.", 400);
}
if (originAccessControlInUse(id)) {
throw new AwsException("OriginAccessControlInUse",
"Cannot delete the origin access control because it's in use by one or more distributions.",
409);
}
oacStore.delete(id);
}
@@ -514,6 +656,10 @@ public class CloudFrontService {
throw new AwsException("InvalidIfMatchVersion",
"The If-Match version is missing or not valid for the resource.", 400);
}
if (originAccessIdentityInUse(id)) {
throw new AwsException("CloudFrontOriginAccessIdentityInUse",
"The Origin Access Identity specified is already in use.", 409);
}
oaiStore.delete(id);
}
@@ -536,6 +682,84 @@ public class CloudFrontService {
return all;
}
private static void validateOriginAccessControl(OriginAccessControl oac) {
if (oac == null) {
throw new AwsException("InvalidArgument",
"The origin access control configuration is required.", 400);
}
if (oac.getName() == null || oac.getName().isBlank()) {
throw new AwsException("InvalidArgument", "The parameter Name is required.", 400);
}
if (oac.getName().length() > 64) {
throw new AwsException("InvalidArgument",
"The parameter Name must be 64 characters or fewer.", 400);
}
if (!"sigv4".equals(oac.getSigningProtocol())) {
throw new AwsException("InvalidArgument",
"The parameter SigningProtocol must be sigv4.", 400);
}
if (oac.getSigningBehavior() == null
|| !OAC_SIGNING_BEHAVIORS.contains(oac.getSigningBehavior())) {
throw new AwsException("InvalidArgument",
"The parameter SigningBehavior must be one of always, never, or no-override.",
400);
}
if (oac.getOriginAccessControlOriginType() == null
|| !OAC_ORIGIN_TYPES.contains(oac.getOriginAccessControlOriginType())) {
throw new AwsException("InvalidArgument",
"The parameter OriginAccessControlOriginType must be one of s3, mediastore, "
+ "mediapackagev2, or lambda.",
400);
}
}
private boolean originAccessControlInUse(String id) {
for (Distribution distribution : distStore.scan(k -> true)) {
DistributionConfig config = distribution.getConfig();
if (config == null || config.getOrigins() == null) {
continue;
}
for (Origin origin : config.getOrigins()) {
if (origin != null && id.equals(origin.getOriginAccessControlId())) {
return true;
}
}
}
return false;
}
private boolean originAccessIdentityInUse(String id) {
for (Distribution distribution : distStore.scan(k -> true)) {
DistributionConfig config = distribution.getConfig();
if (config == null || config.getOrigins() == null) {
continue;
}
for (Origin origin : config.getOrigins()) {
if (origin != null && originAccessIdentityMatches(
origin.getS3OriginConfig() != null
? origin.getS3OriginConfig().get("OriginAccessIdentity")
: null,
id)) {
return true;
}
}
}
for (StreamingDistribution distribution : streamingDistStore.scan(k -> true)) {
if (originAccessIdentityMatches(distribution.getS3OriginAccessIdentity(), id)) {
return true;
}
}
return false;
}
private static boolean originAccessIdentityMatches(String reference, String id) {
if (reference == null || reference.isBlank()) {
return false;
}
String normalized = reference.startsWith("/") ? reference.substring(1) : reference;
return normalized.equals("origin-access-identity/cloudfront/" + id);
}
// ── CloudFront Functions ──────────────────────────────────────────────────
public synchronized CloudFrontFunction createFunction(CloudFrontFunction fn) {
@@ -599,14 +823,14 @@ public class CloudFrontService {
functionStore.delete(name);
}
public List<CloudFrontFunction> listFunctions(String stage) {
public List<CloudFrontFunction> listFunctions(String stage, String marker, int maxItems) {
List<CloudFrontFunction> all = new ArrayList<>(functionStore.scan(k -> true));
if (stage != null && !stage.isEmpty()) {
all = all.stream().filter(f -> stage.equals(f.getStage())).toList();
all = new ArrayList<>(all);
}
all.sort((a, b) -> a.getName().compareTo(b.getName()));
return all;
return paginate(all, marker, maxItems, CloudFrontFunction::getName);
}
// ── Tags ──────────────────────────────────────────────────────────────────
@@ -0,0 +1,603 @@
package io.github.hectorvent.floci.services.cloudfront;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
import io.github.hectorvent.floci.services.cloudfront.model.OriginAccessControl;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import jakarta.annotation.PreDestroy;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HEAD;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import org.jboss.logging.Logger;
import java.net.IDN;
import java.net.InetAddress;
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* Serves viewer requests routed to a CloudFront distribution (via {@link CloudFrontDistributionFilter})
* by resolving the matching cache behavior + origin and returning the origin content, implemented to
* the AWS CloudFront data-plane spec.
*
* <p>The internal path is {@code /_cloudfront/{distId}/{proxy:.*}}; {@code proxy} is the viewer's path
* relative to the distribution. Routing (behavior/path-pattern matching, default-root-object, origin
* path) is delegated to {@link CloudFrontRequestRouter}. This controller performs the origin I/O:
*
* <ul>
* <li>S3 origins are read in-process through {@link S3Service} (the bucket is derived from the
* origin domain name).</li>
* <li>Custom origins are fetched over HTTP(S) with {@link java.net.http.HttpClient}.</li>
* <li>When an origin returns an error status, a matching {@code CustomErrorResponse} is applied —
* most importantly the single-page-app fallback that rewrites 403/404 to 200 {@code /index.html}.
* If the configured error page is itself missing, the received status is returned (no loop).</li>
* </ul>
*
* <p>Viewer-protocol-policy and allowed-method enforcement are intentionally out of scope for this
* layer: the emulator is HTTP-first and serves GET/HEAD regardless of scheme.
*/
@Path("/_cloudfront/{distId}")
public class CloudFrontServingController {
private static final Logger LOG = Logger.getLogger(CloudFrontServingController.class);
private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";
private static final DateTimeFormatter HTTP_DATE = DateTimeFormatter.RFC_1123_DATE_TIME
.withZone(ZoneOffset.UTC);
private static final Set<String> NON_FORWARDED_RESPONSE_HEADERS = Set.of(
"connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
"proxy-connection", "te", "trailer", "transfer-encoding", "upgrade", "via",
"content-length", "content-type");
private final CloudFrontService service;
private final S3Service s3Service;
private final CurrentVertxRequest currentVertxRequest;
private final CloudFrontOriginHttpClient httpClient;
@Inject
public CloudFrontServingController(CloudFrontService service, S3Service s3Service,
EmulatorConfig emulatorConfig,
CurrentVertxRequest currentVertxRequest) {
this.service = service;
this.s3Service = s3Service;
this.currentVertxRequest = currentVertxRequest;
this.httpClient = new CloudFrontOriginHttpClient(
emulatorConfig.services().cloudfront().allowedPrivateOriginHosts().orElse(List.of()));
}
@PreDestroy
void closeHttpClient() {
try {
httpClient.close();
} catch (Exception e) {
LOG.debugv("Could not close CloudFront origin HTTP client: {0}", e.getMessage());
}
}
@GET
@Path("/{proxy:.*}")
public Response get(@PathParam("distId") String distId, @PathParam("proxy") String proxy,
@Context HttpHeaders headers, @Context UriInfo uriInfo) {
String rawViewerPath = rawViewerPath(currentVertxRequest.getCurrent().request().uri());
return serve(distId, rawViewerPath, decodedViewerPath(rawViewerPath),
uriInfo.getRequestUri().getScheme(), headers.getHeaderString("Host"),
headers.getHeaderString(HttpHeaders.AUTHORIZATION), true);
}
@HEAD
@Path("/{proxy:.*}")
public Response head(@PathParam("distId") String distId, @PathParam("proxy") String proxy,
@Context HttpHeaders headers, @Context UriInfo uriInfo) {
String rawViewerPath = rawViewerPath(currentVertxRequest.getCurrent().request().uri());
return serve(distId, rawViewerPath, decodedViewerPath(rawViewerPath),
uriInfo.getRequestUri().getScheme(), headers.getHeaderString("Host"),
headers.getHeaderString(HttpHeaders.AUTHORIZATION), false);
}
private Response serve(String distId, String rawViewerPath, String decodedViewerPath,
String viewerScheme, String viewerHost, String viewerAuthorization,
boolean includeBody) {
Distribution dist = service.findByHost(viewerHost);
if (dist == null || !distId.equals(dist.getId())) {
return textError(404, "Distribution not found.");
}
DistributionConfig config = dist.getConfig();
if (config == null) {
return textError(502, "Distribution has no configuration.");
}
if (!config.isEnabled()) {
return textError(404, "Distribution is disabled.");
}
String normalized = CloudFrontRequestRouter.normalizePath(decodedViewerPath);
OriginResponse origin = route(dist, normalized, rawViewerPath, decodedViewerPath,
viewerScheme, viewerAuthorization, includeBody);
if (origin.status() >= 400) {
Response fallback = applyCustomError(
dist, origin, viewerScheme, viewerAuthorization, includeBody);
if (fallback != null) {
return fallback;
}
}
return toResponse(origin, includeBody);
}
/** Selects an origin with the normalized path, then forwards the original viewer path. */
private OriginResponse route(Distribution distribution, String normalized,
String rawViewerPath, String decodedViewerPath,
String viewerScheme, String viewerAuthorization,
boolean includeBody) {
DistributionConfig config = distribution.getConfig();
String originId = CloudFrontRequestRouter.matchTargetOriginId(config, normalized);
Origin origin = CloudFrontRequestRouter.findOrigin(config, originId);
if (origin == null) {
return OriginResponse.error(502, "No origin matched the request.");
}
if (CloudFrontRequestRouter.isS3Origin(origin)) {
String key = CloudFrontRequestRouter.resolveOriginKey(
origin.getOriginPath(), decodedViewerPath, config.getDefaultRootObject());
return fetchFromS3(
distribution, origin, key, viewerAuthorization, includeBody);
}
String forwardUri = CloudFrontRequestRouter.resolveForwardUri(
origin.getOriginPath(), rawViewerPath, config.getDefaultRootObject());
// CloudFront forwards viewer query strings only when selected by a cache policy,
// origin request policy, or legacy ForwardedValues configuration. Those policy
// semantics are not modeled in the data plane yet, so the AWS default is to omit them.
return fetchFromCustomOrigin(origin, forwardUri, null, viewerScheme, includeBody);
}
private OriginResponse fetchFromS3(
Distribution distribution,
Origin origin,
String key,
String viewerAuthorization,
boolean includeBody) {
String bucket = CloudFrontRequestRouter.bucketFromS3Domain(origin.getDomainName());
if (bucket == null) {
return OriginResponse.error(502, "Could not determine S3 bucket for origin.");
}
try {
authorizeS3OriginRead(
distribution, origin, bucket, key, viewerAuthorization);
if (includeBody) {
S3Object obj = s3Service.getObject(bucket, key);
byte[] data = obj.getData() != null ? obj.getData() : new byte[0];
return new OriginResponse(
200, contentType(obj), data, data.length, s3ObjectHeaders(obj));
}
S3Object meta = s3Service.headObject(bucket, key);
return new OriginResponse(
200, contentType(meta), null, meta.getSize(), s3ObjectHeaders(meta));
} catch (AwsException e) {
return OriginResponse.error(e.getHttpStatus(), e.getMessage());
}
}
private void authorizeS3OriginRead(
Distribution distribution,
Origin origin,
String bucket,
String key,
String viewerAuthorization) {
String oacId = origin.getOriginAccessControlId();
if (oacId != null && !oacId.isBlank()) {
OriginAccessControl oac = service.getOriginAccessControl(oacId);
String signingBehavior = oac.getSigningBehavior();
boolean viewerSigned = viewerAuthorization != null && !viewerAuthorization.isBlank();
boolean cloudFrontSigns = "always".equalsIgnoreCase(signingBehavior)
|| ("no-override".equalsIgnoreCase(signingBehavior) && !viewerSigned);
if (cloudFrontSigns) {
s3Service.authorizeCloudFrontOacGetObject(
bucket, key, distribution.getArn());
return;
}
if ("no-override".equalsIgnoreCase(signingBehavior) && viewerSigned) {
s3Service.authorizeCloudFrontViewerGetObject(
bucket, key, viewerAuthorization);
return;
}
s3Service.authorizeAnonymousGetObject(bucket, key);
return;
}
String oaiId = originAccessIdentityId(origin);
if (oaiId != null) {
var oai = service.getCloudFrontOriginAccessIdentity(oaiId);
s3Service.authorizeCloudFrontOaiGetObject(
bucket, key, oaiId, oai.getS3CanonicalUserId());
return;
}
s3Service.authorizeAnonymousGetObject(bucket, key);
}
private static String originAccessIdentityId(Origin origin) {
Map<String, String> config = origin.getS3OriginConfig();
String value = config != null ? config.get("OriginAccessIdentity") : null;
if (value == null || value.isBlank()) {
return null;
}
String normalized = value.startsWith("/") ? value.substring(1) : value;
String prefix = "origin-access-identity/cloudfront/";
if (!normalized.startsWith(prefix)
|| normalized.length() == prefix.length()
|| normalized.substring(prefix.length()).contains("/")) {
throw new AwsException(
"InvalidArgument", "The S3 origin access identity is invalid.", 400);
}
return normalized.substring(prefix.length());
}
/** Fetches from a custom (non-S3) origin. {@code forwardUri} already includes the origin path. */
private OriginResponse fetchFromCustomOrigin(Origin origin, String forwardUri, String rawQuery,
String viewerScheme, boolean includeBody) {
try {
URI target = buildCustomOriginUri(
origin, viewerScheme, forwardUri, rawQuery);
HttpRequest.Builder rb = HttpRequest.newBuilder()
.uri(target)
.timeout(Duration.ofSeconds(30));
if (includeBody) {
rb.GET();
} else {
rb.method("HEAD", HttpRequest.BodyPublishers.noBody());
}
HttpResponse<byte[]> resp = httpClient.send(rb.build(), HttpResponse.BodyHandlers.ofByteArray());
String ct = resp.headers().firstValue("content-type").orElse(DEFAULT_CONTENT_TYPE);
byte[] body = resp.body() != null ? resp.body() : new byte[0];
long contentLength = includeBody ? body.length : responseContentLength(resp);
return new OriginResponse(resp.statusCode(), ct, includeBody ? body : null,
contentLength, resp.headers().map());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.warnv("CloudFront custom origin fetch was interrupted for host {0}",
safeOriginName(origin));
return OriginResponse.error(502, "Bad Gateway.");
} catch (Exception e) {
// Do not log the target URI: forwarded query strings can contain credentials or tokens.
LOG.warnv("CloudFront custom origin fetch failed for host {0}: {1}",
safeOriginName(origin), e.getClass().getSimpleName());
return OriginResponse.error(502, "Bad Gateway.");
}
}
static boolean isBlockedOriginAddress(InetAddress address) {
if (address.isAnyLocalAddress() || address.isLoopbackAddress()
|| address.isLinkLocalAddress() || address.isSiteLocalAddress()
|| address.isMulticastAddress()) {
return true;
}
byte[] bytes = address.getAddress();
if (bytes.length == 4) {
return isBlockedIpv4Address(bytes, 0);
}
if (bytes.length == 16) {
if (isIpv4MappedAddress(bytes)) {
return isBlockedIpv4Address(bytes, 12);
}
int first = Byte.toUnsignedInt(bytes[0]);
boolean uniqueLocal = (first & 0xfe) == 0xfc;
boolean documentation = first == 0x20
&& Byte.toUnsignedInt(bytes[1]) == 0x01
&& Byte.toUnsignedInt(bytes[2]) == 0x0d
&& Byte.toUnsignedInt(bytes[3]) == 0xb8;
return uniqueLocal || documentation;
}
return true;
}
private static boolean isIpv4MappedAddress(byte[] bytes) {
for (int i = 0; i < 10; i++) {
if (bytes[i] != 0) {
return false;
}
}
return bytes[10] == (byte) 0xff && bytes[11] == (byte) 0xff;
}
private static boolean isBlockedIpv4Address(byte[] bytes, int offset) {
int first = Byte.toUnsignedInt(bytes[offset]);
int second = Byte.toUnsignedInt(bytes[offset + 1]);
int third = Byte.toUnsignedInt(bytes[offset + 2]);
return first == 0
|| first == 10
|| first == 127
|| (first == 100 && second >= 64 && second <= 127)
|| (first == 169 && second == 254)
|| (first == 172 && second >= 16 && second <= 31)
|| (first == 192 && second == 168)
|| (first == 192 && second == 0 && third == 0)
|| (first == 192 && second == 0 && third == 2)
|| (first == 198 && (second == 18 || second == 19))
|| (first == 198 && second == 51 && third == 100)
|| (first == 203 && second == 0 && third == 113)
|| first >= 224;
}
static URI buildCustomOriginUri(String protocol, String domainName, int port,
String forwardUri, String rawQuery) {
if (port < 1 || port > 65535) {
throw new IllegalArgumentException("Custom origin port is outside the valid range");
}
String host = normalizeOriginHost(domainName);
String path = forwardUri == null || forwardUri.isBlank() ? "/" : forwardUri;
if (!path.startsWith("/") || path.indexOf('?') >= 0 || path.indexOf('#') >= 0) {
throw new IllegalArgumentException("Custom origin path is invalid");
}
String authorityHost = host.indexOf(':') >= 0 ? "[" + host + "]" : host;
return URI.create(protocol + "://" + authorityHost + ":" + port + path
+ (rawQuery == null || rawQuery.isEmpty() ? "" : "?" + rawQuery));
}
static URI buildCustomOriginUri(Origin origin, String viewerScheme,
String forwardUri, String rawQuery) {
Map<String, Object> config = origin.getCustomOriginConfig();
String policy = config != null ? str(config.get("OriginProtocolPolicy")) : "";
boolean useHttps = "https-only".equalsIgnoreCase(policy)
|| ("match-viewer".equalsIgnoreCase(policy)
&& "https".equalsIgnoreCase(viewerScheme));
String protocol = useHttps ? "https" : "http";
int port = useHttps
? intOrDefault(config, "HTTPSPort", 443)
: intOrDefault(config, "HTTPPort", 80);
return buildCustomOriginUri(
protocol, origin.getDomainName(), port, forwardUri, rawQuery);
}
static String rawViewerPath(String requestUri) {
if (requestUri == null || requestUri.isBlank()) {
return "/";
}
int query = requestUri.indexOf('?');
String path = query >= 0 ? requestUri.substring(0, query) : requestUri;
if (path.startsWith("http://") || path.startsWith("https://")) {
path = URI.create(path).getRawPath();
}
if (path == null || path.isEmpty()) {
return "/";
}
return path.startsWith("/") ? path : "/" + path;
}
static String decodedViewerPath(String rawViewerPath) {
return URI.create("http://viewer.invalid" + rawViewerPath).getPath();
}
static String normalizeOriginHost(String domainName) {
if (domainName == null || domainName.isBlank()) {
throw new IllegalArgumentException("Custom origin domain name is empty");
}
URI authority = URI.create("//" + domainName.trim());
if (authority.getRawUserInfo() != null
|| (authority.getRawPath() != null && !authority.getRawPath().isEmpty())
|| authority.getRawQuery() != null || authority.getRawFragment() != null
|| authority.getHost() == null) {
throw new IllegalArgumentException("Custom origin domain name is not a valid authority");
}
return normalizeHost(authority.getHost());
}
static String normalizeHost(String host) {
String normalized = host.trim();
if (normalized.startsWith("[") && normalized.endsWith("]")) {
normalized = normalized.substring(1, normalized.length() - 1);
}
while (normalized.endsWith(".")) {
normalized = normalized.substring(0, normalized.length() - 1);
}
if (normalized.isEmpty()) {
throw new IllegalArgumentException("Custom origin host is empty");
}
if (normalized.indexOf(':') < 0) {
normalized = IDN.toASCII(normalized);
}
return normalized.toLowerCase(Locale.ROOT);
}
private static long responseContentLength(HttpResponse<?> response) {
try {
return response.headers().firstValueAsLong("content-length").orElse(-1L);
} catch (NumberFormatException e) {
LOG.debugv("Ignoring invalid custom-origin Content-Length: {0}", e.getMessage());
return -1L;
}
}
private static String safeOriginName(Origin origin) {
try {
return normalizeOriginHost(origin.getDomainName());
} catch (RuntimeException e) {
return "<invalid>";
}
}
/**
* Applies a matching {@code CustomErrorResponse} to an origin error, per the AWS CloudFront spec.
* Returns {@code null} when no custom handling applies, so the caller returns the original origin
* response unchanged. Otherwise:
*
* <ul>
* <li>with no {@code ResponsePagePath}, the origin body is kept but the status is overridden by
* {@code ResponseCode};</li>
* <li>with a {@code ResponsePagePath}, the page is fetched through behavior/origin routing and,
* on success, returned with {@code ResponseCode} (the single-page-app 403/404 -&gt; 200
* {@code /index.html} fallback);</li>
* <li>if the custom error page is itself unavailable, CloudFront returns the status code it
* received from the origin that holds the error pages — not the original status — and does
* not recurse (no loop).</li>
* </ul>
*/
private Response applyCustomError(
Distribution distribution,
OriginResponse origin,
String viewerScheme,
String viewerAuthorization,
boolean includeBody) {
DistributionConfig config = distribution.getConfig();
Map<String, Object> cer = matchCustomError(config, origin.status());
if (cer == null) {
return null;
}
int responseCode = parseIntOr(cer.get("ResponseCode"), origin.status());
String pagePath = str(cer.get("ResponsePagePath"));
if (pagePath.isBlank()) {
// ResponseCode override with no custom page: keep the origin body, change the status.
return toResponse(new OriginResponse(responseCode, origin.contentType(), origin.body(),
origin.contentLength(), origin.headers()), includeBody);
}
String errNormalized = CloudFrontRequestRouter.normalizePath(pagePath);
String errOriginId = CloudFrontRequestRouter.matchTargetOriginId(config, errNormalized);
Origin errOrigin = CloudFrontRequestRouter.findOrigin(config, errOriginId);
if (errOrigin == null) {
return null;
}
OriginResponse page;
if (CloudFrontRequestRouter.isS3Origin(errOrigin)) {
String key = CloudFrontRequestRouter.resolveOriginKey(errOrigin.getOriginPath(), errNormalized, null);
page = fetchFromS3(
distribution, errOrigin, key, viewerAuthorization, includeBody);
} else {
String forwardUri = CloudFrontRequestRouter.resolveForwardUri(errOrigin.getOriginPath(), errNormalized, null);
page = fetchFromCustomOrigin(
errOrigin, forwardUri, null, viewerScheme, includeBody);
}
if (page.status() >= 400) {
// Custom error page unavailable → return the status received from the error-page origin
// (AWS behavior), without recursively applying custom error handling.
return toResponse(page, includeBody);
}
return toResponse(new OriginResponse(responseCode, page.contentType(), page.body(),
page.contentLength(), page.headers()), includeBody);
}
private Map<String, Object> matchCustomError(DistributionConfig config, int status) {
List<Map<String, Object>> list = config.getCustomErrorResponses();
if (list == null) {
return null;
}
for (Map<String, Object> cer : list) {
if (parseIntOr(cer.get("ErrorCode"), -1) == status) {
return cer;
}
}
return null;
}
private Response toResponse(OriginResponse origin, boolean includeBody) {
Response.ResponseBuilder rb = Response.status(origin.status());
Set<String> excludedHeaders = new HashSet<>(NON_FORWARDED_RESPONSE_HEADERS);
origin.headers().forEach((name, values) -> {
if ("connection".equalsIgnoreCase(name)) {
values.forEach(value -> {
for (String token : value.split(",")) {
excludedHeaders.add(token.trim().toLowerCase(Locale.ROOT));
}
});
}
});
origin.headers().forEach((name, values) -> {
if (!excludedHeaders.contains(name.toLowerCase(Locale.ROOT))) {
values.forEach(value -> rb.header(name, value));
}
});
if (origin.contentType() != null) {
rb.type(origin.contentType());
}
if (includeBody && origin.body() != null) {
rb.entity(origin.body());
} else if (origin.contentLength() >= 0) {
rb.header("Content-Length", origin.contentLength());
}
return rb.build();
}
private Response textError(int status, String message) {
return Response.status(status)
.type(MediaType.TEXT_PLAIN)
.entity(message == null ? "" : message)
.build();
}
private static String contentType(S3Object obj) {
return obj.getContentType() != null ? obj.getContentType() : DEFAULT_CONTENT_TYPE;
}
private static Map<String, List<String>> s3ObjectHeaders(S3Object object) {
Map<String, List<String>> headers = new LinkedHashMap<>();
putHeader(headers, "Accept-Ranges", "bytes");
putHeader(headers, "ETag", object.getETag());
if (object.getLastModified() != null) {
putHeader(headers, "Last-Modified", HTTP_DATE.format(object.getLastModified()));
}
putHeader(headers, "Cache-Control", object.getCacheControl());
putHeader(headers, "Content-Encoding", object.getContentEncoding());
putHeader(headers, "Content-Disposition", object.getContentDisposition());
putHeader(headers, "x-amz-storage-class", object.getStorageClass());
if (object.getMetadata() != null) {
object.getMetadata().forEach((name, value) ->
putHeader(headers, "x-amz-meta-" + name, value));
}
return headers;
}
private static void putHeader(Map<String, List<String>> headers, String name, String value) {
if (value != null) {
headers.put(name, List.of(value));
}
}
private static String str(Object value) {
return value != null ? value.toString() : "";
}
private static int intOrDefault(Map<String, Object> map, String key, int dflt) {
return map == null ? dflt : parseIntOr(map.get(key), dflt);
}
private static int parseIntOr(Object value, int dflt) {
if (value == null) {
return dflt;
}
try {
return Integer.parseInt(value.toString().trim());
} catch (NumberFormatException e) {
LOG.debugv("Ignoring non-integer CloudFront configuration value {0}: {1}", value, e.getMessage());
return dflt;
}
}
/** The result of fetching from an origin, including end-to-end response headers. */
private record OriginResponse(int status, String contentType, byte[] body, long contentLength,
Map<String, List<String>> headers) {
static OriginResponse error(int status, String message) {
byte[] b = message == null ? new byte[0] : message.getBytes(StandardCharsets.UTF_8);
return new OriginResponse(status, MediaType.TEXT_PLAIN, b, b.length, Map.of());
}
}
}
@@ -75,8 +75,9 @@ record S3AclPolicy(List<S3AclPolicy.Grant> grants) {
private static Grant parseGrant(Element grantElement) {
Element granteeElement = firstChildElement(grantElement, "Grantee");
String uri = granteeElement != null ? descendantText(granteeElement, "URI") : null;
String id = granteeElement != null ? descendantText(granteeElement, "ID") : null;
String permissionText = childText(grantElement, "Permission");
return new Grant(new Grantee(uri), Permission.fromXml(permissionText));
return new Grant(new Grantee(uri, id), Permission.fromXml(permissionText));
}
private static Element firstChildElement(Element parent, String localName) {
@@ -112,12 +113,20 @@ record S3AclPolicy(List<S3AclPolicy.Grant> grants) {
boolean allowsPublicRead() {
return grantee.isAllUsersGroup() && permission.allowsRead();
}
boolean allowsCanonicalUserRead(String canonicalUserId) {
return grantee.isCanonicalUser(canonicalUserId) && permission.allowsRead();
}
}
record Grantee(String uri) {
record Grantee(String uri, String id) {
boolean isAllUsersGroup() {
return ALL_USERS_GROUP_URI.equals(uri);
}
boolean isCanonicalUser(String canonicalUserId) {
return canonicalUserId != null && canonicalUserId.equals(id);
}
}
enum Permission {
@@ -8,6 +8,7 @@ import org.jboss.logging.Logger;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
final class S3PublicAccessEvaluator {
@@ -57,6 +58,46 @@ final class S3PublicAccessEvaluator {
}
}
static PublicAccessDecision principalPolicyDecision(
ObjectMapper objectMapper,
String policy,
String principalType,
String principalValue,
String action,
String resourceArn,
Map<String, String> context) {
if (policy == null || policy.isBlank()) {
return PublicAccessDecision.NEUTRAL;
}
try {
JsonNode statements = objectMapper.readTree(policy).path("Statement");
boolean allowed = false;
Iterable<JsonNode> iterable = statements.isArray() ? statements : List.of(statements);
for (JsonNode statement : iterable) {
String effect = statement.path("Effect").asText("");
if (!"Allow".equalsIgnoreCase(effect) && !"Deny".equalsIgnoreCase(effect)) {
continue;
}
if (!principalMatches(statement, principalType, principalValue)
|| !actionMatches(statement, action)
|| !resourceMatches(statement, resourceArn)) {
continue;
}
if (!conditionsMatch(statement.path("Condition"), context)) {
continue;
}
if ("Deny".equalsIgnoreCase(effect)) {
return PublicAccessDecision.DENY;
}
allowed = true;
}
return allowed ? PublicAccessDecision.ALLOW : PublicAccessDecision.NEUTRAL;
} catch (JsonProcessingException e) {
LOG.debugv("Failed to evaluate S3 bucket policy for principal access: {0}", e.getMessage());
return PublicAccessDecision.NEUTRAL;
}
}
static String bucketArn(String bucketName) {
return "arn:aws:s3:::" + bucketName;
}
@@ -81,6 +122,118 @@ final class S3PublicAccessEvaluator {
return false;
}
private static boolean principalMatches(
JsonNode statement, String principalType, String principalValue) {
if (statement.hasNonNull("Principal")) {
return principalNodeMatches(statement.path("Principal"), principalType, principalValue);
}
if (statement.hasNonNull("NotPrincipal")) {
return !principalNodeMatches(
statement.path("NotPrincipal"), principalType, principalValue);
}
return false;
}
private static boolean principalNodeMatches(
JsonNode principal, String principalType, String principalValue) {
if (principal == null || principal.isMissingNode() || principal.isNull()) {
return false;
}
if (principal.isTextual() || principal.isArray()) {
return principalValueMatches(principal, principalValue);
}
if (!principal.isObject()) {
return false;
}
Iterator<Map.Entry<String, JsonNode>> fields = principal.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
if (field.getKey().equalsIgnoreCase(principalType)
&& principalValueMatches(field.getValue(), principalValue)) {
return true;
}
}
return false;
}
private static boolean principalValueMatches(JsonNode candidate, String principalValue) {
if (candidate == null || candidate.isNull()) {
return false;
}
if (candidate.isTextual()) {
String value = candidate.asText();
return "*".equals(value) || value.equals(principalValue);
}
if (candidate.isArray()) {
for (JsonNode item : candidate) {
if (principalValueMatches(item, principalValue)) {
return true;
}
}
}
return false;
}
private static boolean conditionsMatch(JsonNode conditions, Map<String, String> context) {
if (conditions == null || conditions.isMissingNode() || conditions.isNull()) {
return true;
}
if (!conditions.isObject()) {
return false;
}
Iterator<Map.Entry<String, JsonNode>> operators = conditions.fields();
while (operators.hasNext()) {
Map.Entry<String, JsonNode> operator = operators.next();
boolean glob = "StringLike".equalsIgnoreCase(operator.getKey())
|| "ArnLike".equalsIgnoreCase(operator.getKey());
boolean exact = "StringEquals".equalsIgnoreCase(operator.getKey())
|| "ArnEquals".equalsIgnoreCase(operator.getKey());
if ((!glob && !exact) || !operator.getValue().isObject()) {
return false;
}
Iterator<Map.Entry<String, JsonNode>> entries = operator.getValue().fields();
while (entries.hasNext()) {
Map.Entry<String, JsonNode> entry = entries.next();
String actual = contextValue(context, entry.getKey());
if (actual == null || !conditionValueMatches(entry.getValue(), actual, glob)) {
return false;
}
}
}
return true;
}
private static String contextValue(Map<String, String> context, String key) {
if (context == null) {
return null;
}
for (Map.Entry<String, String> entry : context.entrySet()) {
if (entry.getKey().equalsIgnoreCase(key)) {
return entry.getValue();
}
}
return null;
}
private static boolean conditionValueMatches(JsonNode expected, String actual, boolean glob) {
if (expected == null || expected.isNull()) {
return false;
}
if (expected.isTextual()) {
return glob
? IamPolicyEvaluator.globMatches(expected.asText(), actual)
: expected.asText().equals(actual);
}
if (expected.isArray()) {
for (JsonNode item : expected) {
if (conditionValueMatches(item, actual, glob)) {
return true;
}
}
}
return false;
}
private static boolean actionMatches(JsonNode statement, String action) {
if (statement.hasNonNull("Action")) {
return nodeMatches(statement.get("Action"), action);
@@ -24,6 +24,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Event;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.MultivaluedHashMap;
import org.jboss.logging.Logger;
import java.io.ByteArrayOutputStream;
@@ -509,6 +510,75 @@ public class S3Service implements Resettable {
authorizeObjectRead(bucketName, key, versionId, action, authorization);
}
public void authorizeAnonymousGetObject(String bucketName, String key) {
authorizeGetObject(bucketName, key, null, RequestAuthorization.unsigned());
}
public void authorizeCloudFrontOacGetObject(
String bucketName, String key, String distributionArn) {
authorizeCloudFrontGetObject(
bucketName,
key,
"Service",
"cloudfront.amazonaws.com",
Map.of("AWS:SourceArn", distributionArn),
null);
}
public void authorizeCloudFrontOaiGetObject(
String bucketName, String key, String originAccessIdentityId,
String canonicalUserId) {
authorizeCloudFrontGetObject(
bucketName,
key,
"AWS",
"arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity "
+ originAccessIdentityId,
Map.of(),
canonicalUserId);
}
public void authorizeCloudFrontViewerGetObject(
String bucketName, String key, String viewerAuthorization) {
RequestAuthorization authorization =
S3RequestAuthorizationParser.parseIfRequired(
enforceAuth, viewerAuthorization, new MultivaluedHashMap<>());
authorizeGetObject(bucketName, key, null, authorization);
}
private void authorizeCloudFrontGetObject(
String bucketName,
String key,
String principalType,
String principalValue,
Map<String, String> context,
String canonicalUserId) {
if (!enforceAuth) {
return;
}
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() ->
new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
String resourceArn = S3PublicAccessEvaluator.objectArn(bucketName, key);
S3PublicAccessEvaluator.PublicAccessDecision decision =
S3PublicAccessEvaluator.principalPolicyDecision(
objectMapper,
bucket.getPolicy(),
principalType,
principalValue,
"s3:GetObject",
resourceArn,
context);
if (decision == S3PublicAccessEvaluator.PublicAccessDecision.DENY) {
throw new AwsException("AccessDenied", "Access Denied", 403);
}
if (decision == S3PublicAccessEvaluator.PublicAccessDecision.ALLOW
|| canonicalUserObjectAclAllowsRead(bucketName, key, canonicalUserId)) {
return;
}
throw new AwsException("AccessDenied", "Access Denied", 403);
}
void authorizeBucketRead(String bucketName, String action, RequestAuthorization authorization) {
String bucketArn = S3PublicAccessEvaluator.bucketArn(bucketName);
authorizeS3Read(bucketName, null, null, action, bucketArn, authorization);
@@ -605,6 +675,27 @@ public class S3Service implements Resettable {
.orElse(false);
}
private boolean canonicalUserObjectAclAllowsRead(
String bucketName, String key, String canonicalUserId) {
if (canonicalUserId == null || canonicalUserId.isBlank()) {
return false;
}
return objectStore.get(objectKey(bucketName, key))
.filter(object -> !object.isDeleteMarker())
.map(S3Object::getAcl)
.map(acl -> {
try {
return S3AclPolicy.parse(acl).grants().stream()
.anyMatch(grant ->
grant.allowsCanonicalUserRead(canonicalUserId));
} catch (S3AclPolicy.AclParseException e) {
LOG.debugv(e, "Failed to parse S3 ACL for CloudFront OAI access");
return false;
}
})
.orElse(false);
}
private void applyObjectLock(S3Object object, Bucket bucket,
String objectLockMode, Instant retainUntilDate, String legalHoldStatus) {
if (objectLockMode != null) {
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.services.cloudfront.CloudFrontDistributionFilter;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
@@ -69,6 +70,12 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
return;
}
// A higher-priority CloudFront distribution filter may have already routed this request.
// Use its server-side marker rather than trusting a user-controlled path prefix.
if (Boolean.TRUE.equals(requestContext.getProperty(CloudFrontDistributionFilter.ROUTED_PROPERTY))) {
return;
}
// Rewrite path from /key to /bucket/key
String newPath = "/" + bucket + (path.startsWith("/") ? "" : "/") + path;