Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cloudfront): Support HTTPS locally with correct key id (#3845)

TATSUNO “Taz” Yasuhiroc603639e0b50
diff --git a/docs/configuration/tls.md b/docs/configuration/tls.md
index 79a1db9daa..75534a29b7 100644
--- a/docs/configuration/tls.md
+++ b/docs/configuration/tls.md
@@ -58,8 +58,9 @@ When `FLOCI_TLS_ENABLED=true` and no custom certificate is provided, Floci keeps
- Is persisted to `{persistent-path}/tls/` and reused across restarts
- Includes `localhost`, `127.0.0.1`, `0.0.0.0`, `*.localhost`, `localhost.floci.io`,
- `*.localhost.floci.io`, `*.execute-api.localhost.floci.io`, and
- `*.execute-api.localhost.localstack.cloud` as Subject Alternative Names (SANs)
+ `*.localhost.floci.io`, `*.execute-api.localhost.floci.io`,
+ `*.execute-api.localhost.localstack.cloud`, `*.cloudfront.localhost.floci.io`, and
+ `*.cloudfront.localhost` as Subject Alternative Names (SANs)
- Automatically includes custom hostnames from `FLOCI_HOSTNAME`, `FLOCI_BASE_URL` and `FLOCI_SERVICES_IOT_ENDPOINT_ADDRESS` in the SANs
- Is regenerated when hostname configuration changes between restarts, or when it was not issued by the current CA
diff --git a/docs/services/cloudfront.md b/docs/services/cloudfront.md
index 51e943bdce..1dd8c19b6a 100644
--- a/docs/services/cloudfront.md
+++ b/docs/services/cloudfront.md
@@ -130,7 +130,11 @@ GET/HEAD/OPTIONS delivery from S3 or custom origins.
- All distributions are immediately set to `Deployed` state (no async `InProgress` delay).
- Distribution IDs are 14 uppercase alphanumeric characters starting with `E` (e.g. `E1Z2X3C4V5B6N7`).
-- Distribution domain names follow the pattern `{id}.cloudfront.net`.
+- Distribution domain names follow the pattern `{id}.cloudfront.net`, with the id lower-cased as AWS
+ writes it in a host name.
+- Public key IDs are `K` followed by 13 uppercase alphanumeric characters (e.g. `K2JCJMDEHXQW5F`),
+ the value a signed URL carries as `Key-Pair-Id`. Key group, cache policy, origin request policy and
+ response headers policy IDs are UUIDs, as they are on AWS.
- ARNs are global — no region segment: `arn:aws:cloudfront::{accountId}:distribution/{id}`.
- Invalidations are immediately marked `Completed`.
- `DeleteDistribution` returns `DistributionNotDisabled` (409) if `Enabled` is `true` in the config.
@@ -149,6 +153,12 @@ GET/HEAD/OPTIONS delivery from S3 or custom origins.
- Viewer GET/HEAD requests, and OPTIONS requests allowed by the matched cache behavior, addressed to
an enabled distribution's generated domain or alias are routed to the matching S3 or custom
origin. Origin forwarding preserves the raw path; custom-origin redirects are not followed.
+- Every distribution is also served as `{id}.cloudfront.{host}` for each endpoint host Floci
+ resolves: `localhost`, `localhost.floci.io`, `localhost.localstack.cloud`, `FLOCI_HOSTNAME` and
+ every `FLOCI_DNS_EXTRA_SUFFIXES` entry. `{id}.cloudfront.localhost.floci.io` and
+ `{id}.cloudfront.localhost` reach loopback with no host-file edit and are covered by the generated
+ HTTPS certificate, so a signed URL for either can be downloaded over `https://`. See
+ [Downloading over HTTPS](#downloading-over-https).
- Origin custom headers are persisted through the CloudFront API and CloudFormation. They replace
same-named viewer headers on custom-origin GET/HEAD/OPTIONS requests. For in-process S3 origins, a
configured `Origin` header is used for S3 CORS evaluation. AWS-prohibited names, malformed
@@ -279,6 +289,43 @@ ETAG=$(aws cloudfront get-distribution --id E1Z2X3C4V5B6N7 \
aws cloudfront delete-distribution --id E1Z2X3C4V5B6N7 --if-match "$ETAG"
```
+## Downloading over HTTPS
+
+A distribution's own domain name (`{id}.cloudfront.net` by default) resolves to nothing local, so
+address the distribution by one of its local delivery hostnames instead. `*.cloudfront.localhost.floci.io`
+resolves to `127.0.0.1` through public DNS and works on Linux, macOS and in containers.
+`*.cloudfront.localhost` needs no DNS at all but only resolves where the runtime handles `.localhost`
+itself, which macOS and browsers do and Debian-based images do not.
+
+Start Floci with [TLS](../configuration/tls.md) enabled and trust its CA once:
+
+```bash
+docker run -e FLOCI_TLS_ENABLED=true -p 4566:4566 floci/floci:latest
+curl -s http://localhost:4566/_floci/ca.pem -o floci-root-ca.pem
+```
+
+Sign the URL of the hostname you download from — the port is part of what a canned policy signs —
+and fetch it:
+
+```bash
+HOST=e1z2x3c4v5b6n7.cloudfront.localhost.floci.io:4566
+
+SIGNED=$(aws cloudfront sign \
+ --url "https://$HOST/hello.txt" \
+ --key-pair-id K2JCJMDEHXQW5F \
+ --private-key file://private_key.pem \
+ --date-less-than 2026-12-31T00:00:00Z)
+
+curl --cacert floci-root-ca.pem "$SIGNED"
+```
+
+To drop the `:4566`, publish the HTTPS port Floci also binds when TLS is on (`-p 443:443`, see
+`FLOCI_TLS_AWS_HTTPS_PORT`) and sign `https://e1z2x3c4v5b6n7.cloudfront.localhost.floci.io/hello.txt`.
+
+Set `FLOCI_SERVICES_CLOUDFRONT_DOMAIN_SUFFIX=cloudfront.localhost.floci.io` to have
+`CreateDistribution` return that hostname as the `DomainName`, so test code can sign the API response
+as it is.
+
## Not Supported (Phase 2)
- Continuous deployment policies (`CreateContinuousDeploymentPolicy`, etc.)
diff --git a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java
index e608197dcb..e89cab9e7d 100644
--- a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java
+++ b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java
@@ -62,11 +62,15 @@ public class TlsConfigSource implements ConfigSource {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
// host.docker.internal: how Lambda containers reach Floci when it runs on the host (not in a container).
- private static final List<String> DEFAULT_SAN_HOSTNAMES = List.of(
+ // A wildcard SAN covers one label, so every two-label service form needs its own entry.
+ // Package-private so the tests assert against this list instead of copying it.
+ static final List<String> DEFAULT_SAN_HOSTNAMES = List.of(
"localhost", "127.0.0.1", "0.0.0.0", "*.localhost",
"localhost.floci.io", "*.localhost.floci.io",
"*.execute-api.localhost.floci.io",
- "*.execute-api.localhost.localstack.cloud", "host.docker.internal");
+ "*.execute-api.localhost.localstack.cloud",
+ "*.cloudfront.localhost.floci.io", "*.cloudfront.localhost",
+ "host.docker.internal");
private static volatile Path resolvedTlsDir;
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RequestHost.java b/src/main/java/io/github/hectorvent/floci/core/common/RequestHost.java
new file mode 100644
index 0000000000..b5b447e8e8
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/core/common/RequestHost.java
@@ -0,0 +1,41 @@
+package io.github.hectorvent.floci.core.common;
+
+import io.vertx.core.http.HttpServerRequest;
+import io.vertx.core.net.HostAndPort;
+import jakarta.ws.rs.container.ContainerRequestContext;
+
+import java.net.URI;
+
+/**
+ * The host a client addressed. HTTP/2 (RFC 9113 section 8.3.1) sends {@code :authority} and no
+ * {@code Host} header, and curl and browsers use HTTP/2 over HTTPS.
+ */
+public final class RequestHost {
+
+ private RequestHost() {
+ }
+
+ public static String of(ContainerRequestContext requestContext) {
+ return of(requestContext.getHeaderString("Host"), requestContext.getUriInfo().getRequestUri());
+ }
+
+ /**
+ * The {@code Host} header when present, else the request URI authority, which the container
+ * builds from {@code :authority} on HTTP/2.
+ */
+ public static String of(String hostHeader, URI requestUri) {
+ if (hostHeader != null && !hostHeader.isBlank()) {
+ return hostHeader.trim();
+ }
+ return requestUri != null ? requestUri.getAuthority() : null;
+ }
+
+ public static String of(HttpServerRequest request) {
+ String hostHeader = request.getHeader("Host");
+ if (hostHeader != null && !hostHeader.isBlank()) {
+ return hostHeader.trim();
+ }
+ HostAndPort authority = request.authority();
+ return authority != null ? authority.toString() : null;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilter.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilter.java
index c5a7077dd7..00dea9720f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayCustomDomainFilter.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.apigateway;
+import io.github.hectorvent.floci.core.common.RequestHost;
import io.github.hectorvent.floci.services.apigateway.model.BasePathMapping;
import io.github.hectorvent.floci.services.apigateway.model.CustomDomain;
import jakarta.annotation.Priority;
@@ -41,7 +42,7 @@ public class ApiGatewayCustomDomainFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) {
- String host = requestContext.getHeaderString("Host");
+ String host = RequestHost.of(requestContext);
if (host == null) {
return;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java
index f35aeb7364..100bd73441 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
+import io.github.hectorvent.floci.core.common.RequestHost;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
@@ -101,7 +102,7 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) {
- String host = requestContext.getHeaderString("Host");
+ String host = RequestHost.of(requestContext);
if (host == null) {
return;
}
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
index 52e8caa9c7..4275295f35 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontDistributionFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontDistributionFilter.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.cloudfront;
+import io.github.hectorvent.floci.core.common.RequestHost;
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
import jakarta.annotation.Priority;
import jakarta.enterprise.inject.Instance;
@@ -49,7 +50,7 @@ public class CloudFrontDistributionFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) {
- String host = requestContext.getHeaderString("Host");
+ String host = RequestHost.of(requestContext);
if (host == null) {
return;
}
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 7ad1aa7d42..8066a23e71 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
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudfront.model.CacheBehavior;
@@ -41,6 +42,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
+import java.util.SequencedSet;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
@@ -101,6 +103,16 @@ public class CloudFrontService {
private final StorageBackend<String, MonitoringSubscription> monitoringStore;
private final String accountId;
private final String domainSuffix;
+ /**
+ * Host suffixes under which every distribution is served as {@code <id><suffix>}, whatever
+ * {@code floci.services.cloudfront.domain-suffix} makes the assigned domain name. They carry the
+ * {@code cloudfront} service label on the endpoint hosts the embedded DNS resolves, the same
+ * derivation API Gateway uses for {@code <id>.execute-api.<host>}, so a name that resolves to
+ * Floci is also routed by it. {@code <id>.cloudfront.localhost.floci.io} and
+ * {@code <id>.cloudfront.localhost} are additionally covered by the generated HTTPS
+ * certificate, so a signed URL for either can be downloaded over HTTPS.
+ */
+ private final List<String> localDeliverySuffixes;
@Inject
public CloudFrontService(StorageFactory factory, EmulatorConfig config) {
@@ -140,6 +152,7 @@ public class CloudFrontService {
new TypeReference<Map<String, MonitoringSubscription>>() {});
this.accountId = config.defaultAccountId();
this.domainSuffix = config.services().cloudfront().domainSuffix();
+ this.localDeliverySuffixes = localDeliverySuffixes(config);
}
// ── Distributions ─────────────────────────────────────────────────────────
@@ -152,7 +165,7 @@ public class CloudFrontService {
String id = generateDistributionId();
dist.setId(id);
dist.setArn(AwsArnUtils.Arn.of("cloudfront", "", accountId, "distribution/" + id).toString());
- dist.setDomainName(id + "." + domainSuffix);
+ dist.setDomainName(domainNameFor(id));
dist.setStatus("Deployed");
dist.setLastModifiedTime(Instant.now());
dist.setEtag(UUID.randomUUID().toString());
@@ -310,15 +323,17 @@ public class CloudFrontService {
/**
* 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.
+ * ({@code <id>.cloudfront.net}), one of its alternate domain names (CNAME aliases), or one of
+ * the local delivery hostnames {@code <id>.cloudfront.localhost.floci.io} and
+ * {@code <id>.cloudfront.localhost}. 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));
+ List<Distribution> distributions = distStore.scan(k -> true);
for (Distribution dist : distributions) {
if (hostname.equalsIgnoreCase(dist.getDomainName())) {
return dist;
@@ -334,6 +349,11 @@ public class CloudFrontService {
}
}
}
+ for (Distribution dist : distributions) {
+ if (matchesLocalDeliveryHost(hostname, dist.getId())) {
+ return dist;
+ }
+ }
Distribution best = null;
int bestSpecificity = -1;
for (Distribution dist : distributions) {
@@ -351,6 +371,36 @@ public class CloudFrontService {
return best;
}
+ /**
+ * The domain name a new distribution is served under. AWS assigns a lower-case host, and a
+ * browser lower-cases the authority it sends, so an upper-case id in the host would never match
+ * the resource a signed URL was signed for.
+ */
+ private String domainNameFor(String id) {
+ return id.toLowerCase(Locale.ROOT) + "." + domainSuffix;
+ }
+
+ private static List<String> localDeliverySuffixes(EmulatorConfig config) {
+ SequencedSet<String> endpointHosts = new LinkedHashSet<>();
+ endpointHosts.add("localhost");
+ EmbeddedDnsServer.BUILTIN_SUFFIXES.forEach(endpointHosts::add);
+ config.hostname().ifPresent(endpointHosts::add);
+ config.dns().extraSuffixes().ifPresent(endpointHosts::addAll);
+ return endpointHosts.stream()
+ .map(host -> ".cloudfront." + host.toLowerCase(Locale.ROOT))
+ .toList();
+ }
+
+ /** True when {@code hostname} is the local delivery host of the distribution with this id. */
+ private boolean matchesLocalDeliveryHost(String hostname, String id) {
+ for (String suffix : localDeliverySuffixes) {
+ if (hostname.equalsIgnoreCase(id + suffix)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
private void ensureAliasesAvailable(DistributionConfig config, String currentDistributionId) {
if (config == null || config.getAliases() == null) {
return;
@@ -1230,7 +1280,7 @@ public class CloudFrontService {
"A public key with this caller reference already exists.",
409);
}
- key.setId(UUID.randomUUID().toString());
+ key.setId(generatePublicKeyId());
key.setCreatedTime(Instant.now());
key.setEtag(UUID.randomUUID().toString());
publicKeyStore.put(key.getId(), key);
@@ -1596,7 +1646,7 @@ public class CloudFrontService {
String id = generateDistributionId();
sd.setId(id);
sd.setArn(AwsArnUtils.Arn.of("cloudfront", "", accountId, "streaming-distribution/" + id).toString());
- sd.setDomainName(id + "." + domainSuffix);
+ sd.setDomainName(domainNameFor(id));
sd.setStatus("Deployed");
sd.setLastModifiedTime(Instant.now());
sd.setEtag(UUID.randomUUID().toString());
@@ -1767,6 +1817,15 @@ public class CloudFrontService {
return sb.toString();
}
+ /** AWS issues public key ids as K + 13 characters; the value travels in Key-Pair-Id. */
+ private static String generatePublicKeyId() {
+ StringBuilder sb = new StringBuilder("K");
+ for (int i = 0; i < 13; i++) {
+ sb.append(CHARS.charAt(RANDOM.nextInt(CHARS.length())));
+ }
+ return sb.toString();
+ }
+
private static String generateInvalidationId() {
StringBuilder sb = new StringBuilder("I");
for (int i = 0; i < 13; i++) {
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
index 99eaec12c2..3b55460fce 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java
@@ -2,6 +2,7 @@ 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.core.common.RequestHost;
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;
@@ -113,7 +114,7 @@ public class CloudFrontServingController {
String rawViewerPath = rawViewerPath(request.uri());
return serve(distId, rawViewerPath, decodedViewerPath(rawViewerPath),
uriInfo.getRequestUri().getScheme(),
- headers.getHeaderString("Host"),
+ RequestHost.of(request),
headers.getHeaderString(HttpHeaders.AUTHORIZATION),
request.getHeader("Origin"), "GET", null, null,
request.getHeader("Pragma"));
@@ -127,7 +128,7 @@ public class CloudFrontServingController {
String rawViewerPath = rawViewerPath(request.uri());
return serve(distId, rawViewerPath, decodedViewerPath(rawViewerPath),
uriInfo.getRequestUri().getScheme(),
- headers.getHeaderString("Host"),
+ RequestHost.of(request),
headers.getHeaderString(HttpHeaders.AUTHORIZATION),
request.getHeader("Origin"), "HEAD", null, null,
request.getHeader("Pragma"));
@@ -141,7 +142,7 @@ public class CloudFrontServingController {
String rawViewerPath = rawViewerPath(request.uri());
return serve(distId, rawViewerPath, decodedViewerPath(rawViewerPath),
uriInfo.getRequestUri().getScheme(),
- headers.getHeaderString("Host"),
+ RequestHost.of(request),
headers.getHeaderString(HttpHeaders.AUTHORIZATION),
request.getHeader("Origin"), "OPTIONS",
request.getHeader("Access-Control-Request-Method"),
@@ -274,7 +275,7 @@ public class CloudFrontServingController {
io.vertx.core.http.HttpServerRequest request,
String rawViewerPath) {
String scheme = request.scheme() != null ? request.scheme() : "https";
- String host = request.getHeader("Host");
+ String host = RequestHost.of(request);
if (host == null || host.isBlank()) {
host = distribution.getDomainName();
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilter.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilter.java
index 9be7bccefe..a81f560557 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilter.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.cognito;
import io.github.hectorvent.floci.core.common.AccountContextFilter;
+import io.github.hectorvent.floci.core.common.RequestHost;
import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain;
import jakarta.annotation.Priority;
import jakarta.inject.Inject;
@@ -51,11 +52,7 @@ public class CognitoCustomDomainFilter implements ContainerRequestFilter {
if (path == null || !path.startsWith(OAUTH_PREFIX)) {
return;
}
- // HTTP/2 has no Host header; its :authority arrives as the request URI authority.
- String host = requestContext.getHeaderString("Host");
- if (host == null) {
- host = originalUri.getAuthority();
- }
+ String host = RequestHost.of(requestContext);
if (host == null) {
return;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessRouteFilter.java b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessRouteFilter.java
index 68ed14ebc0..102efda8cb 100644
--- a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessRouteFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessRouteFilter.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.emrserverless;
+import io.github.hectorvent.floci.core.common.RequestHost;
import jakarta.annotation.Priority;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
@@ -34,7 +35,7 @@ public class EmrServerlessRouteFilter implements ContainerRequestFilter {
return;
}
- String host = ctx.getHeaderString("Host");
+ String host = RequestHost.of(ctx);
boolean isEmrServerlessHost = host != null && host.startsWith("emr-serverless.");
String auth = ctx.getHeaderString("Authorization");
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaUrlRoutingFilter.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaUrlRoutingFilter.java
index ec6158f4b4..57856a1efc 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaUrlRoutingFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaUrlRoutingFilter.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.lambda;
+import io.github.hectorvent.floci.core.common.RequestHost;
import jakarta.annotation.Priority;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
@@ -26,7 +27,7 @@ public class LambdaUrlRoutingFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
- String host = requestContext.getHeaderString("Host");
+ String host = RequestHost.of(requestContext);
if (host == null) return;
// Pattern: <urlId>.lambda-url.<region>.<anything>
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3VirtualHostFilter.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3VirtualHostFilter.java
index 0e066278bf..6f931f92aa 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3VirtualHostFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3VirtualHostFilter.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsRegions;
+import io.github.hectorvent.floci.core.common.RequestHost;
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;
@@ -203,10 +204,7 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
return first;
}
}
- if (hostHeader != null && !hostHeader.isBlank()) {
- return hostHeader.trim();
- }
- return requestUri != null ? requestUri.getAuthority() : null;
+ return RequestHost.of(hostHeader, requestUri);
}
static String resolveHost(String hostHeader, URI requestUri) {
diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java
index a73560c08d..17b6338639 100644
--- a/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java
+++ b/src/test/java/io/github/hectorvent/floci/config/TlsCertificateHostnameTest.java
@@ -229,10 +229,7 @@ class TlsCertificateHostnameTest {
X509Certificate cert = parseCertificate(certFile);
List<String> sans = extractSansFromCertificate(cert);
- Set<String> expectedSans = Set.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost",
- "localhost.floci.io", "*.localhost.floci.io",
- "*.execute-api.localhost.floci.io",
- "*.execute-api.localhost.localstack.cloud", "host.docker.internal");
+ Set<String> expectedSans = Set.copyOf(TlsConfigSource.DEFAULT_SAN_HOSTNAMES);
Set<String> actualSans = new HashSet<>(sans);
assertEquals(expectedSans, actualSans,
@@ -254,10 +251,7 @@ class TlsCertificateHostnameTest {
X509Certificate cert = parseCertificate(certFile);
List<String> sans = extractSansFromCertificate(cert);
- Set<String> expectedSans = Set.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost",
- "localhost.floci.io", "*.localhost.floci.io",
- "*.execute-api.localhost.floci.io",
- "*.execute-api.localhost.localstack.cloud", "host.docker.internal");
+ Set<String> expectedSans = Set.copyOf(TlsConfigSource.DEFAULT_SAN_HOSTNAMES);
Set<String> actualSans = new HashSet<>(sans);
assertEquals(expectedSans, actualSans,
@@ -410,9 +404,7 @@ class TlsCertificateHostnameTest {
CertificateGenerator gen = new CertificateGenerator();
// The exact SAN list TlsConfigSource would compute for this configuration, so only the
// issuer check can trigger regeneration here.
- List<String> sans = List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost",
- "localhost.floci.io", "*.localhost.floci.io", "*.execute-api.localhost.floci.io",
- "*.execute-api.localhost.localstack.cloud", "host.docker.internal");
+ List<String> sans = TlsConfigSource.DEFAULT_SAN_HOSTNAMES;
var legacy = gen.generateSelfSignedCertificate("localhost", sans, KeyAlgorithm.RSA_2048);
Files.writeString(tlsDir.resolve("floci-server.crt"), legacy.certificatePem());
Files.writeString(tlsDir.resolve("floci-server.key"), legacy.privateKeyPem());
@@ -436,9 +428,7 @@ class TlsCertificateHostnameTest {
Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
CertificateGenerator gen = new CertificateGenerator();
- List<String> sans = List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost",
- "localhost.floci.io", "*.localhost.floci.io", "*.execute-api.localhost.floci.io",
- "*.execute-api.localhost.localstack.cloud", "host.docker.internal");
+ List<String> sans = TlsConfigSource.DEFAULT_SAN_HOSTNAMES;
java.security.KeyPair keyPair = java.security.KeyPairGenerator.getInstance("RSA").generateKeyPair();
// Issued by the current CA with a validity that ended a day ago: only the expiry check can trigger.
X509Certificate expired = gen.signCertificate(new org.bouncycastle.asn1.x500.X500Name("CN=localhost"),
diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateGenerationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateGenerationTest.java
index b57abcaed1..0c381d2b63 100644
--- a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateGenerationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceCertificateGenerationTest.java
@@ -12,6 +12,7 @@ import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.List;
+import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
@@ -161,14 +162,9 @@ class TlsConfigSourceCertificateGenerationTest {
assertTrue(sans.contains("host.docker.internal"),
"Certificate SANs should include default 'host.docker.internal'");
- assertTrue(sans.contains("*.execute-api.localhost.floci.io"),
- "Certificate SANs should include API Gateway execution hosts");
- assertTrue(sans.contains("*.execute-api.localhost.localstack.cloud"),
- "Certificate SANs should include LocalStack-compatible API Gateway execution hosts");
-
- // Should not contain any custom hostnames
- assertEquals(9, sans.size(),
- "Certificate SANs should contain exactly 9 default entries, including API Gateway execution hosts");
+ // Should be the defaults and nothing else - no custom hostnames
+ assertEquals(Set.copyOf(TlsConfigSource.DEFAULT_SAN_HOSTNAMES), Set.copyOf(sans),
+ "Certificate SANs should be exactly the default entries");
}
/**
diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceLearnedHostnamesTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceLearnedHostnamesTest.java
index ee3f634eb0..bc12d7b378 100644
--- a/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceLearnedHostnamesTest.java
+++ b/src/test/java/io/github/hectorvent/floci/config/TlsConfigSourceLearnedHostnamesTest.java
@@ -33,9 +33,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class TlsConfigSourceLearnedHostnamesTest {
private static final String LEARNED = "api.example.localhost.floci.io";
- private static final List<String> DEFAULTS = List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost",
- "localhost.floci.io", "*.localhost.floci.io", "*.execute-api.localhost.floci.io",
- "*.execute-api.localhost.localstack.cloud", "host.docker.internal");
+ private static final List<String> DEFAULTS = TlsConfigSource.DEFAULT_SAN_HOSTNAMES;
private static final ObjectMapper MAPPER = new ObjectMapper();
@TempDir
diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsHttp2HostRoutingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsHttp2HostRoutingIntegrationTest.java
new file mode 100644
index 0000000000..2ff8ab06f1
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/config/TlsHttp2HostRoutingIntegrationTest.java
@@ -0,0 +1,239 @@
+package io.github.hectorvent.floci.config;
+
+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
+import io.github.hectorvent.floci.services.cloudfront.CloudFrontService;
+import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;
+import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
+import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
+import io.github.hectorvent.floci.services.cloudfront.model.KeyGroup;
+import io.github.hectorvent.floci.services.cloudfront.model.Origin;
+import io.github.hectorvent.floci.services.cloudfront.model.PublicKey;
+import io.github.hectorvent.floci.services.s3.S3Service;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.QuarkusTestProfile;
+import io.quarkus.test.junit.TestProfile;
+import io.restassured.http.ContentType;
+import io.vertx.core.Vertx;
+import io.vertx.core.http.HttpClient;
+import io.vertx.core.http.HttpClientOptions;
+import io.vertx.core.http.HttpMethod;
+import io.vertx.core.http.HttpVersion;
+import io.vertx.core.http.RequestOptions;
+import io.vertx.core.net.PemTrustOptions;
+import io.vertx.core.net.SocketAddress;
+import jakarta.inject.Inject;
+import org.eclipse.microprofile.config.inject.ConfigProperty;
+import org.junit.jupiter.api.Test;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.Signature;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Host-based routing over HTTPS with HTTP/2, where the client sends {@code :authority} and no
+ * {@code Host} header. The client connects to 127.0.0.1, names the service host only in
+ * {@code :authority}, trusts only the Floci CA and verifies that host against the served
+ * certificate, so no DNS lookup is needed.
+ */
+@QuarkusTest
+@TestProfile(TlsHttp2HostRoutingIntegrationTest.Profile.class)
+class TlsHttp2HostRoutingIntegrationTest {
+
+ static final Path DATA_DIR = Path.of("target", "floci-tls-http2-host-routing-test").toAbsolutePath();
+ static final Path TLS_DIR = DATA_DIR.resolve("tls");
+ static final String API_DOMAIN = "api.h2-routing.example.test";
+ private static final String REGION = "us-east-1";
+
+ @ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")
+ int sslPort;
+
+ @Inject
+ Vertx vertx;
+
+ @Inject
+ S3Service s3Service;
+
+ @Inject
+ CloudFrontService cloudFrontService;
+
+ @Test
+ void cloudFrontServesACannedSignedUrlOnEachLocalDeliveryHost() throws Exception {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String bucket = "cf-h2-" + suffix;
+ s3Service.createBucket(bucket, REGION);
+ s3Service.putObject(bucket, "private/report.txt", ("H2-" + suffix).getBytes(StandardCharsets.UTF_8),
+ "text/plain", Map.of());
+
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(2048);
+ KeyPair keyPair = generator.generateKeyPair();
+ PublicKey publicKey = new PublicKey();
+ publicKey.setName("pk-" + suffix);
+ publicKey.setCallerReference("cr-" + suffix);
+ publicKey.setEncodedKey("-----BEGIN PUBLIC KEY-----\n"
+ + Base64.getMimeEncoder().encodeToString(keyPair.getPublic().getEncoded())
+ + "\n-----END PUBLIC KEY-----");
+ publicKey = cloudFrontService.createPublicKey(publicKey);
+ KeyGroup keyGroup = new KeyGroup();
+ keyGroup.setName("kg-" + suffix);
+ keyGroup.setItems(List.of(publicKey.getId()));
+ keyGroup = cloudFrontService.createKeyGroup(keyGroup);
+
+ Origin origin = new Origin();
+ origin.setId("o");
+ origin.setDomainName(bucket + ".s3." + REGION + ".amazonaws.com");
+ origin.setS3OriginConfig(new LinkedHashMap<>(Map.of("OriginAccessIdentity", "")));
+ DefaultCacheBehavior behavior = new DefaultCacheBehavior();
+ behavior.setTargetOriginId("o");
+ behavior.setViewerProtocolPolicy("allow-all");
+ behavior.setTrustedKeyGroups(List.of(keyGroup.getId()));
+ DistributionConfig config = new DistributionConfig();
+ config.setEnabled(true);
+ config.setOrigins(List.of(origin));
+ config.setDefaultCacheBehavior(behavior);
+ Distribution distribution = new Distribution();
+ distribution.setConfig(config);
+ distribution = cloudFrontService.createDistribution(distribution, Map.of());
+
+ // A browser sends the host in lower case, and a canned policy signs the port too.
+ String id = distribution.getId().toLowerCase(Locale.ROOT);
+ for (String host : List.of(id + ".cloudfront.localhost.floci.io", id + ".cloudfront.localhost")) {
+ long expires = Instant.now().getEpochSecond() + 3600;
+ String policy = "{\"Statement\":[{\"Resource\":\"https://" + host + ":" + sslPort
+ + "/private/report.txt\",\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":" + expires + "}}}]}";
+ Signature rsa = Signature.getInstance("SHA1withRSA");
+ rsa.initSign(keyPair.getPrivate());
+ rsa.update(policy.getBytes(StandardCharsets.UTF_8));
+
+ Http2Response response = getOverHttp2(host, "/private/report.txt?Expires=" + expires
+ + "&Signature=" + cloudFrontBase64(rsa.sign()) + "&Key-Pair-Id=" + publicKey.getId());
+ assertEquals(HttpVersion.HTTP_2, response.version());
+ assertEquals(200, response.status(), host + " " + response.body());
+ assertEquals("H2-" + suffix, response.body());
+ }
+ }
+
+ @Test
+ void apiGatewayCustomDomainRoutesToTheRestApi() throws Exception {
+ String apiId = given().contentType(ContentType.JSON)
+ .body("{\"name\":\"h2-host-routing\"}")
+ .when().post("/restapis")
+ .then().statusCode(201).extract().path("id");
+ String rootId = given().when().get("/restapis/" + apiId + "/resources")
+ .then().statusCode(200).extract().path("item[0].id");
+ String resourceId = given().contentType(ContentType.JSON)
+ .body("{\"pathPart\":\"ping\"}")
+ .when().post("/restapis/" + apiId + "/resources/" + rootId)
+ .then().statusCode(201).extract().path("id");
+ String method = "/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET";
+ given().contentType(ContentType.JSON).body("{\"authorizationType\":\"NONE\"}")
+ .when().put(method).then().statusCode(201);
+ given().contentType(ContentType.JSON).body("{}")
+ .when().put(method + "/responses/200").then().statusCode(201);
+ given().contentType(ContentType.JSON)
+ .body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\":200}\"}}")
+ .when().put(method + "/integration").then().statusCode(201);
+ given().contentType(ContentType.JSON)
+ .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"{\\\"pong\\\":true}\"}}")
+ .when().put(method + "/integration/responses/200").then().statusCode(201);
+ String deploymentId = given().contentType(ContentType.JSON).body("{}")
+ .when().post("/restapis/" + apiId + "/deployments")
+ .then().statusCode(201).extract().path("id");
+ given().contentType(ContentType.JSON)
+ .body("{\"stageName\":\"dev\",\"deploymentId\":\"" + deploymentId + "\"}")
+ .when().post("/restapis/" + apiId + "/stages").then().statusCode(201);
+
+ given().contentType(ContentType.JSON)
+ .body("{\"domainName\":\"" + API_DOMAIN + "\"}")
+ .when().post("/domainnames").then().statusCode(201);
+ given().contentType(ContentType.JSON)
+ .body("{\"basePath\":\"v1\",\"restApiId\":\"" + apiId + "\",\"stage\":\"dev\"}")
+ .when().post("/domainnames/" + API_DOMAIN + "/basepathmappings").then().statusCode(201);
+
+ Http2Response response = getOverHttp2(API_DOMAIN, "/v1/ping");
+ assertEquals(HttpVersion.HTTP_2, response.version());
+ assertEquals(200, response.status(), response.body());
+ assertTrue(response.body().contains("\"pong\":true"), response.body());
+ }
+
+ private record Http2Response(HttpVersion version, int status, String body) {}
+
+ private Http2Response getOverHttp2(String host, String pathAndQuery) throws Exception {
+ HttpClient client = vertx.createHttpClient(new HttpClientOptions()
+ .setSsl(true)
+ .setUseAlpn(true)
+ .setForceSni(true)
+ .setTrustOptions(new PemTrustOptions().addCertPath(
+ FlociCertificateAuthority.loadOrCreate(TLS_DIR).certificatePath().toString()))
+ .setVerifyHost(true)
+ .setProtocolVersion(HttpVersion.HTTP_2));
+ try {
+ RequestOptions options = new RequestOptions()
+ .setServer(SocketAddress.inetSocketAddress(sslPort, "127.0.0.1"))
+ .setHost(host)
+ .setPort(sslPort)
+ .setMethod(HttpMethod.GET)
+ .setURI(pathAndQuery);
+ return client.request(options)
+ .compose(request -> request.send())
+ .compose(response -> response.body().map(body ->
+ new Http2Response(response.version(), response.statusCode(), body.toString())))
+ .toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
+ } finally {
+ client.close();
+ }
+ }
+
+ private static String cloudFrontBase64(byte[] bytes) {
+ return Base64.getEncoder().encodeToString(bytes).replace('+', '-').replace('=', '_').replace('/', '~');
+ }
+
+ /**
+ * Boots with TLS on and a CA-issued leaf carrying the SANs TlsConfigSource writes, plus the API
+ * Gateway custom domain.
+ */
+ public static final class Profile implements QuarkusTestProfile {
+
+ static {
+ try {
+ Files.createDirectories(TLS_DIR);
+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);
+ List<String> sans = new ArrayList<>(TlsConfigSource.DEFAULT_SAN_HOSTNAMES);
+ sans.add(API_DOMAIN);
+ var leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);
+ Files.writeString(TLS_DIR.resolve("floci-server.crt"), leaf.certificatePem());
+ Files.writeString(TLS_DIR.resolve("floci-server.key"), leaf.privateKeyPem());
+ } catch (IOException e) {
+ throw new IllegalStateException("could not prepare the TLS fixtures", e);
+ }
+ }
+
+ @Override
+ public Map<String, String> getConfigOverrides() {
+ return Map.of(
+ "floci.tls.enabled", "true",
+ "floci.tls.self-signed", "true",
+ "floci.tls.aws-https-port", "0",
+ "floci.storage.persistent-path", DATA_DIR.toString(),
+ "quarkus.tls.key-store.pem.0.cert", TLS_DIR.resolve("floci-server.crt").toString(),
+ "quarkus.tls.key-store.pem.0.key", TLS_DIR.resolve("floci-server.key").toString(),
+ "quarkus.http.insecure-requests", "enabled");
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/RequestHostTest.java b/src/test/java/io/github/hectorvent/floci/core/common/RequestHostTest.java
new file mode 100644
index 0000000000..5970e1bf97
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/RequestHostTest.java
@@ -0,0 +1,67 @@
+package io.github.hectorvent.floci.core.common;
+
+import io.vertx.core.http.HttpServerRequest;
+import io.vertx.core.net.HostAndPort;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.core.UriInfo;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import java.net.URI;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.Mockito.when;
+
+class RequestHostTest {
+
+ private static final URI HTTP2_URI =
+ URI.create("https://e1z2x3c4v5b6n7.cloudfront.localhost.floci.io:4566/hello.txt");
+
+ @Test
+ void prefersTheHostHeader() {
+ assertEquals("viewer.example.test", RequestHost.of("viewer.example.test", HTTP2_URI));
+ }
+
+ @Test
+ void fallsBackToTheUriAuthorityWithoutAHostHeader() {
+ assertEquals("e1z2x3c4v5b6n7.cloudfront.localhost.floci.io:4566", RequestHost.of(null, HTTP2_URI));
+ assertEquals("e1z2x3c4v5b6n7.cloudfront.localhost.floci.io:4566", RequestHost.of(" ", HTTP2_URI));
+ }
+
+ @Test
+ void answersNullWithNeitherAHostHeaderNorAnAuthority() {
+ assertNull(RequestHost.of(null, (URI) null));
+ assertNull(RequestHost.of(null, URI.create("/relative/path")));
+ }
+
+ @Test
+ void readsARequestContext() {
+ UriInfo uriInfo = Mockito.mock(UriInfo.class);
+ when(uriInfo.getRequestUri()).thenReturn(HTTP2_URI);
+ ContainerRequestContext context = Mockito.mock(ContainerRequestContext.class);
+ when(context.getUriInfo()).thenReturn(uriInfo);
+
+ assertEquals("e1z2x3c4v5b6n7.cloudfront.localhost.floci.io:4566", RequestHost.of(context));
+
+ when(context.getHeaderString("Host")).thenReturn("viewer.example.test");
+ assertEquals("viewer.example.test", RequestHost.of(context));
+ }
+
+ @Test
+ void readsTheHttp2AuthorityOfAVertxRequest() {
+ HttpServerRequest request = Mockito.mock(HttpServerRequest.class);
+ when(request.authority()).thenReturn(
+ HostAndPort.create("e1z2x3c4v5b6n7.cloudfront.localhost.floci.io", 4566));
+
+ assertEquals("e1z2x3c4v5b6n7.cloudfront.localhost.floci.io:4566", RequestHost.of(request));
+
+ when(request.getHeader("Host")).thenReturn("viewer.example.test");
+ assertEquals("viewer.example.test", RequestHost.of(request));
+ }
+
+ @Test
+ void answersNullForAVertxRequestWithoutAnAuthority() {
+ assertNull(RequestHost.of(Mockito.mock(HttpServerRequest.class)));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java
index 478d075599..82d9128a59 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServiceTest.java
@@ -29,7 +29,9 @@ import java.time.Instant;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
+import java.util.Optional;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
@@ -126,10 +128,14 @@ class CloudFrontServiceTest {
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000"));
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
+ EmulatorConfig.DnsConfig dnsConfig = Mockito.mock(EmulatorConfig.DnsConfig.class);
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
var cloudFrontConfig = Mockito.mock(EmulatorConfig.CloudFrontServiceConfig.class);
when(config.defaultAccountId()).thenReturn(ACCOUNT);
+ when(config.hostname()).thenReturn(Optional.empty());
+ when(config.dns()).thenReturn(dnsConfig);
+ when(dnsConfig.extraSuffixes()).thenReturn(Optional.empty());
when(config.services()).thenReturn(servicesConfig);
when(servicesConfig.cloudfront()).thenReturn(cloudFrontConfig);
when(cloudFrontConfig.domainSuffix()).thenReturn(domainSuffix);
@@ -231,6 +237,29 @@ class CloudFrontServiceTest {
"Expected default suffix, got: " + dist.getDomainName());
}
+ @Test
+ void createPublicKeyIssuesAnAwsShapedId() throws Exception {
+ CloudFrontService service = serviceWithDomainSuffix(DEFAULT_DOMAIN_SUFFIX);
+
+ PublicKey created = service.createPublicKey(validPublicKey("signer"));
+
+ // Verified on AWS us-east-1 2026-09-18: CreatePublicKey answers K + 13 characters
+ // (K2VKB3XV74876Q), the value a signed URL carries as Key-Pair-Id.
+ assertTrue(created.getId().matches("K[A-Z0-9]{13}"),
+ "Expected an AWS-shaped public key id, got: " + created.getId());
+ }
+
+ @Test
+ void createDistributionLowerCasesTheDomainNameId() {
+ CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
+
+ Distribution dist = service.createDistribution(new Distribution(), Map.of());
+
+ // A browser lower-cases the host it sends, so an upper-case id here would break every
+ // signed URL built from the domain name.
+ assertEquals(dist.getId().toLowerCase(Locale.ROOT) + ".cloudfront.net", dist.getDomainName());
+ }
+
@Test
void createDistributionHonorsConfiguredDomainSuffix() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.local");
@@ -273,6 +302,37 @@ class CloudFrontServiceTest {
assertNull(service.findByHost(null));
}
+ @Test
+ void findByHostMatchesLocalDeliveryHostnames() {
+ CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
+
+ Distribution dist = service.createDistribution(distribution(true, List.of()), Map.of());
+ String id = dist.getId();
+
+ assertEquals(id, service.findByHost(id + ".cloudfront.localhost.floci.io").getId());
+ assertEquals(id, service.findByHost(id + ".cloudfront.localhost:4566").getId());
+ // Clients are free to lower-case the hostname they send.
+ assertEquals(id, service.findByHost(
+ (id + ".cloudfront.localhost.floci.io").toLowerCase(Locale.ROOT)).getId());
+
+ // The id stands for one label, and an unknown id belongs to no distribution.
+ assertNull(service.findByHost("a." + id + ".cloudfront.localhost.floci.io"));
+ assertNull(service.findByHost("EABCDEFGHIJKLM.cloudfront.localhost.floci.io"));
+ assertNull(service.findByHost(".cloudfront.localhost"));
+ }
+
+ @Test
+ void findByHostPrefersExactAliasOverLocalDeliveryHostname() {
+ CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
+
+ Distribution generated = service.createDistribution(distribution(true, List.of()), Map.of());
+ String aliasOfAnother = generated.getId() + ".cloudfront.localhost";
+ Distribution aliasOwner = service.createDistribution(
+ distribution(true, List.of(aliasOfAnother)), Map.of());
+
+ assertEquals(aliasOwner.getId(), service.findByHost(aliasOfAnother).getId());
+ }
+
@Test
void findByHostRetainsOwnershipForDisabledDistribution() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3VirtualHostFilterTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3VirtualHostFilterTest.java
index 82b18a8d7a..5894fd22c2 100644
--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3VirtualHostFilterTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3VirtualHostFilterTest.java
@@ -257,25 +257,6 @@ class S3VirtualHostFilterTest {
// --- Host resolution: HTTP/1.1 Host header vs HTTP/2 :authority fallback ---
- @Test
- void resolveHostPrefersHostHeaderOverUriAuthority() {
- URI uri = URI.create("https://my-bucket.s3.us-east-1.localhost:4566/key.txt");
- assertEquals("my-bucket.localhost:4566", S3VirtualHostFilter.resolveHost("my-bucket.localhost:4566", uri));
- }
-
- @Test
- void resolveHostFallsBackToUriAuthorityWhenHostHeaderAbsent() {
- // HTTP/2 request: no Host header, authority carried by the URI (:authority).
- URI uri = URI.create("https://my-bucket.s3.us-east-1.localhost:4566/key.txt");
- assertEquals("my-bucket.s3.us-east-1.localhost:4566", S3VirtualHostFilter.resolveHost(null, uri));
- }
-
- @Test
- void resolveHostReturnsNullWhenNeitherAvailable() {
- assertNull(S3VirtualHostFilter.resolveHost(null, null));
- assertNull(S3VirtualHostFilter.resolveHost(null, URI.create("/relative/path")));
- }
-
@Test
void http2VirtualHostedRequestResolvesBucketWithoutHostHeader() {
// Regression for #1866: over HTTP/2 the Host header is null, so the bucket must