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;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontDistributionFilter.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontDistributionFilter.java
new file mode 100644
index 0000000000..52e8caa9c7
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontDistributionFilter.java
@@ -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.
+ *
+ * When a request arrives with a {@code Host} header matching a distribution's assigned
+ * CloudFront domain name ({@code .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.
+ *
+ * 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 service;
+
+ @Inject
+ public CloudFrontDistributionFilter(Instance 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);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClient.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClient.java
new file mode 100644
index 0000000000..aed4e47b89
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClient.java
@@ -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 allowedPrivateOriginHosts) {
+ this(SystemDefaultDnsResolver.INSTANCE, allowedPrivateOriginHosts, null);
+ }
+
+ CloudFrontOriginHttpClient(DnsResolver delegate, Collection allowedPrivateOriginHosts) {
+ this(delegate, allowedPrivateOriginHosts, null);
+ }
+
+ CloudFrontOriginHttpClient(
+ DnsResolver delegate,
+ Collection allowedPrivateOriginHosts,
+ SSLContext sslContext) {
+ Set 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 send(HttpRequest request, HttpResponse.BodyHandler 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> 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 {
+
+ @Override
+ public Optional> previousResponse() {
+ return Optional.empty();
+ }
+
+ @Override
+ public Optional sslSession() {
+ return Optional.empty();
+ }
+
+ @Override
+ public HttpClient.Version version() {
+ return HttpClient.Version.HTTP_1_1;
+ }
+ }
+
+ private record ValidatingDnsResolver(DnsResolver delegate, Set 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);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontRequestRouter.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontRequestRouter.java
new file mode 100644
index 0000000000..1653434c39
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontRequestRouter.java
@@ -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):
+ *
+ *
+ * - 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.
+ * - Cache behaviors are evaluated in the order listed; the default behavior is always
+ * processed last. The first matching path pattern wins.
+ * - Path patterns use {@code *} (0+ chars) and {@code ?} (exactly 1 char), are case-sensitive, and a
+ * leading {@code /} is optional (ignored).
+ * - The default root object is returned only for the distribution root ({@code /}); it is
+ * never appended for subdirectory requests (this differs from S3 website index documents).
+ * - The origin path is prepended to the request URI when forwarding to the origin.
+ *
+ *
+ * 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 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 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 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();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java
index aabf26e393..8041c389e4 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontService.java
@@ -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 OAC_ORIGIN_TYPES =
+ Set.of("s3", "mediastore", "mediapackagev2", "lambda");
+ private static final Set OAC_SIGNING_BEHAVIORS =
+ Set.of("always", "never", "no-override");
private final StorageBackend distStore;
private final StorageBackend> invalidationStore;
@@ -103,6 +110,7 @@ public class CloudFrontService {
// ── Distributions ─────────────────────────────────────────────────────────
public synchronized Distribution createDistribution(Distribution dist, Map 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 listDistributions(String marker, int maxItems) {
List 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 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 previousAliases = candidate.getConfig().getAliases();
+ List 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 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 .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 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 listFunctions(String stage) {
+ public List listFunctions(String stage, String marker, int maxItems) {
List 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 ──────────────────────────────────────────────────────────────────
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java
new file mode 100644
index 0000000000..b7602be8ae
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java
@@ -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.
+ *
+ * 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:
+ *
+ *
+ * - S3 origins are read in-process through {@link S3Service} (the bucket is derived from the
+ * origin domain name).
+ * - Custom origins are fetched over HTTP(S) with {@link java.net.http.HttpClient}.
+ * - 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).
+ *
+ *
+ * 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 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 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 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 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 "";
+ }
+ }
+
+ /**
+ * 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:
+ *
+ *
+ * - with no {@code ResponsePagePath}, the origin body is kept but the status is overridden by
+ * {@code ResponseCode};
+ * - 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 -> 200
+ * {@code /index.html} fallback);
+ * - 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).
+ *
+ */
+ private Response applyCustomError(
+ Distribution distribution,
+ OriginResponse origin,
+ String viewerScheme,
+ String viewerAuthorization,
+ boolean includeBody) {
+ DistributionConfig config = distribution.getConfig();
+ Map 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 matchCustomError(DistributionConfig config, int status) {
+ List