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

* fix(core): route by the Host header on HTTP/2 requests

HTTP/2 carries the authority in :authority and sends no Host header, so every
lookup that reads Host fell through when a client negotiated HTTP/2. curl, the
AWS SDK for Java and Go, and browsers all do that over HTTPS, which left
CloudFront distribution domains, API Gateway execute-api and custom domains,
Lambda function URLs and Cognito custom domains unreachable over https://.

Copy the authority into a Host header before routing. S3 already covered this in
its own filter.

* feat(cloudfront): serve distributions over HTTPS on local hostnames

A distribution's assigned domain name resolves to nothing local, so a signed URL
could not be downloaded over https:// the way a viewer downloads one from
CloudFront.

Serve every distribution under <id>.cloudfront.localhost.floci.io and
<id>.cloudfront.localhost as well, and add both to the SANs of the generated
server certificate. The first resolves to 127.0.0.1 through public DNS on Linux,
macOS and in containers. The second 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.

* fix(cloudfront): assign lower-case distribution domain names

AWS writes a distribution's domain name in lower case and keeps the id upper
case. Floci put the upper-case id straight into the host name, and a browser
lower-cases the authority it sends, so the rebuilt resource never matched the
one a signed URL was signed for and the download failed with 403.

* refactor(cloudfront): derive the local delivery hosts from the DNS suffixes

The suffix list was a fourth hardcoded copy of the emulator host suffixes, so a
configured FLOCI_HOSTNAME or FLOCI_DNS_EXTRA_SUFFIXES resolved and was covered by
TLS but did not route, and localhost.localstack.cloud did not either. Build it
from the same source the embedded DNS uses.

Match the host inside the scan findByHost already does, by comparing the host to
<id><suffix>, which drops a store read per request and the assumption that the
store keys distributions by an upper-case id. The tests read the default SAN list
from TlsConfigSource rather than copying it.

* fix(cloudfront): issue AWS-shaped public key ids

CreatePublicKey answered a UUID where AWS answers K followed by 13 characters,
the value a signed URL carries as Key-Pair-Id. Verified on AWS us-east-1
2026-09-18: a public key is K2VKB3XV74876Q, while key groups, cache policies,
origin request policies and response headers policies are UUIDs, which Floci
already matches.

* refactor(core): resolve the HTTP/2 authority in each host routing filter

The global Http2HostHeaderFilter made every service depend on a Host
header it wrote, and no service file showed that. RequestHost now returns
the Host header, or the HTTP/2 :authority when there is none. Each filter
that routes by host calls it. S3 and Cognito had their own copy of this
fallback and now use the helper.

* test(core): check host routing over HTTPS and HTTP/2 against the real SANs

The HTTP/2 routing test now boots with a CA-issued leaf that carries the
default SANs. The client trusts only the Floci CA and checks each
CloudFront local delivery host against that leaf. This replaces the
HTTP/1.1 local delivery test, which only set a Host header and never
reached TLS.

S3 drops three resolveHost tests that RequestHostTest now covers. Its
HTTP/2 bucket tests still guard the call to the helper.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-09-18 17:01:50 -04:00
1 parent c664b9e136
commit c603639e0b
20 files changed
+557 -73

No files matched your search

@@ -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"),
@@ -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");
}
/**
@@ -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
@@ -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");
}
}
}
@@ -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)));
}
}
@@ -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");
@@ -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