fix(s3): preserve configured endpoint roots (#8323)

Signed-off-by: Andre Kurait <akurait@amazon.com>
Signed-off-by: Jackson Price <jxnprice@amazon.com>
Co-authored-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
Jackson PriceandAndre Kurait authored and GitHub committed 2026-11-14 12:47:02 -04:00
1 parent f665d5f5e7
commit 5df26c5135
7 files changed
+208 -2

No files matched your search

+7
View File
@@ -703,6 +703,13 @@ Virtual-hosted style puts the bucket name in the hostname:
http://my-bucket.s3.localhost.floci.io:4566/my-key
```
An exact configured `FLOCI_HOSTNAME` or `floci.dns.extra-suffixes` root is an
endpoint without a bucket. For example, with `FLOCI_HOSTNAME=edge.localhost.floci.io`,
`ListBuckets` at that hostname lists the account's buckets, while
`my-bucket.edge.localhost.floci.io` addresses `my-bucket`. Exact endpoint roots
take precedence over shorter DNS suffixes and existing bucket-name matches,
including controller fallback for object PUT and multipart requests.
Floci supports this natively, no `forcePathStyle` needed. The following wildcard DNS domains resolve to `127.0.0.1` via public DNS, so virtual-hosted requests reach Floci on the host machine automatically:
| Domain pattern | Resolves to |
@@ -149,6 +149,7 @@ public class S3Controller {
private final IamService iamService;
private final IamEnforcementFilter iamEnforcementFilter;
private final EmulatorConfig config;
private final S3VirtualHostFilter virtualHostFilter;
private final Clock clock;
@Inject
@@ -163,6 +164,7 @@ public class S3Controller {
IamService iamService,
IamEnforcementFilter iamEnforcementFilter,
EmulatorConfig config,
S3VirtualHostFilter virtualHostFilter,
Clock clock) {
this.s3Service = s3Service;
this.s3SelectService = s3SelectService;
@@ -176,6 +178,7 @@ public class S3Controller {
this.iamService = iamService;
this.iamEnforcementFilter = iamEnforcementFilter;
this.config = config;
this.virtualHostFilter = virtualHostFilter;
this.clock = clock;
}
@@ -4995,7 +4998,7 @@ public class S3Controller {
httpHeaders.getHeaderString("Host"),
httpHeaders.getHeaderString("X-Forwarded-Host"),
uriInfo.getRequestUri());
if (host == null) {
if (host == null || virtualHostFilter.isEndpointRoot(host)) {
return null;
}
String bucket = S3VirtualHostFilter.extractBucketFromExisting(host, s3Service);
@@ -151,6 +151,9 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
return;
}
if (isEndpointRoot(host)) {
return;
}
String bucket = extractBucket(host, baseHostname, serviceHostSuffixes);
if (bucket == null && signedForS3 && s3ServiceInstance != null && s3ServiceInstance.isResolvable()) {
bucket = extractBucketFromExisting(host, s3ServiceInstance.get());
@@ -270,6 +273,9 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
// Strip port if present
String hostname = stripPort(host);
if (isEndpointRoot(hostname, baseHostname, serviceHostSuffixes)) {
return null;
}
// Need at least one dot for a subdomain to exist
int firstDot = hostname.indexOf('.');
@@ -319,6 +325,19 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
return bucketBeforeS3Qualifier(hostname);
}
/** Whether the host names a configured endpoint rather than a bucket, including controller fallback paths. */
boolean isEndpointRoot(String host) {
return isEndpointRoot(host, baseHostname, serviceHostSuffixes);
}
private static boolean isEndpointRoot(String host, String baseHostname, Set<String> serviceHostSuffixes) {
String withoutPort = stripPort(host);
String hostname = withoutPort.endsWith(".")
? withoutPort.substring(0, withoutPort.length() - 1) : withoutPort;
return hostname.equalsIgnoreCase(baseHostname)
|| serviceHostSuffixes.stream().anyMatch(hostname::equalsIgnoreCase);
}
/**
* Returns the part of {@code hostname} preceding the longest known endpoint host it ends
* with, or {@code null} if it ends with none of them. Candidates are the configured base
@@ -0,0 +1,152 @@
package io.floci.aws.services.s3;
import io.floci.aws.testutil.S3RequestSigner;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.MultipartUpload;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(S3ConfiguredEndpointIntegrationTest.Profile.class)
class S3ConfiguredEndpointIntegrationTest {
private static final String ENDPOINT = "configured-endpoint.localhost.floci.io";
@TestHTTPResource("/")
URI baseUri;
@ParameterizedTest
@ValueSource(strings = {ENDPOINT, "alias." + ENDPOINT})
void signedEndpointListsBucketsWhileItsSubdomainStillAddressesABucket(String hostname) throws Exception {
String bucket = "configured-endpoint";
try (S3Client client = client()) {
client.createBucket(request -> request.bucket(bucket));
try {
assertTrue(client.listBuckets().buckets().stream().anyMatch(row -> bucket.equals(row.name())));
URI endpoint = endpoint(hostname, "/");
List<String> buckets = signedRequest("GET", endpoint, new byte[0])
.when().get("/")
.then().statusCode(200)
.extract().xmlPath().getList("ListAllMyBucketsResult.Buckets.Bucket.Name", String.class);
assertTrue(buckets.contains(bucket));
URI virtualHost = endpoint(bucket + "." + hostname, "/");
signedRequest("GET", virtualHost, new byte[0])
.when().get("/")
.then().statusCode(200)
.body("ListBucketResult.Name", is(bucket));
} finally {
client.deleteBucket(request -> request.bucket(bucket));
}
}
}
@ParameterizedTest
@ValueSource(strings = {ENDPOINT, "alias." + ENDPOINT})
void endpointRootPutCannotAddressPrefixBucket(String hostname) throws Exception {
String bucket = hostname.substring(0, hostname.indexOf(".localhost"));
String key = "endpoint-object";
byte[] body = "endpoint-root-payload".getBytes(StandardCharsets.UTF_8);
try (S3Client client = client()) {
client.createBucket(request -> request.bucket(bucket));
try {
signedRequest("PUT", endpoint(hostname, "/" + key), body)
.header("Content-Disposition", "attachment")
.when().put("/" + key)
.then().statusCode(400).body("Error.Code", is("MalformedXML"));
assertTrue(client.listObjectsV2(request -> request.bucket(bucket)).contents().isEmpty());
signedRequest("PUT", endpoint(bucket + "." + hostname, "/" + key), body)
.header("Content-Disposition", "attachment")
.when().put("/" + key)
.then().statusCode(200);
assertEquals("endpoint-root-payload", client.getObjectAsBytes(request -> request
.bucket(bucket).key(key)).asUtf8String());
} finally {
client.deleteObject(request -> request.bucket(bucket).key(key));
client.deleteBucket(request -> request.bucket(bucket));
}
}
}
@ParameterizedTest
@ValueSource(strings = {ENDPOINT, "alias." + ENDPOINT})
void endpointRootMultipartCannotAddressPrefixBucket(String hostname) throws Exception {
String bucket = hostname.substring(0, hostname.indexOf(".localhost"));
String path = "/endpoint-multipart?uploads";
try (S3Client client = client()) {
client.createBucket(request -> request.bucket(bucket));
try {
signedRequest("POST", endpoint(hostname, path), new byte[0])
.when().post(path)
.then().statusCode(405).body("Error.Code", is("MethodNotAllowed"));
assertTrue(client.listMultipartUploads(request -> request.bucket(bucket)).uploads().isEmpty());
String uploadId = signedRequest("POST", endpoint(bucket + "." + hostname, path), new byte[0])
.when().post(path)
.then().statusCode(200)
.extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId");
assertFalse(uploadId.isBlank());
assertEquals(1, client.listMultipartUploads(request -> request.bucket(bucket)).uploads().size());
} finally {
for (MultipartUpload upload : client.listMultipartUploads(request -> request.bucket(bucket)).uploads()) {
client.abortMultipartUpload(request -> request.bucket(bucket)
.key(upload.key()).uploadId(upload.uploadId()));
}
client.deleteBucket(request -> request.bucket(bucket));
}
}
}
private URI endpoint(String hostname, String path) {
return URI.create("http://" + hostname + ":" + baseUri.getPort() + path);
}
private RequestSpecification signedRequest(String method, URI uri, byte[] body) throws Exception {
RequestSpecification request = given().headers(S3RequestSigner.signedAs("test", "test")
.headersFor(method, uri, body))
.header("Host", uri.getAuthority());
if (body.length > 0) {
request.body(body);
}
return request;
}
private S3Client client() {
return S3Client.builder()
.endpointOverride(baseUri)
.httpClientBuilder(UrlConnectionHttpClient.builder())
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))
.region(Region.US_EAST_1)
.forcePathStyle(true)
.build();
}
public static class Profile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.hostname", ENDPOINT,
"floci.dns.extra-suffixes", "alias." + ENDPOINT,
"floci.services.s3.enforce-auth", "true");
}
}
}
@@ -112,7 +112,7 @@ class S3GlobalLegacyListingTest {
AccountResolver accounts = mock(AccountResolver.class);
when(accounts.extractS3AccessKeyId(anyString())).thenAnswer(invocation -> request.getAccountId());
controller = new S3Controller(s3, null, region, null, vertx, null, trail, accounts,
request, null, null, config, Clock.systemUTC());
request, null, null, config, new S3VirtualHostFilter(), Clock.systemUTC());
headers = mock(HttpHeaders.class);
uri = mock(UriInfo.class);
when(uri.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
@@ -64,6 +64,7 @@ class S3PolicyStatusControllerTest {
mock(IamService.class),
mock(IamEnforcementFilter.class),
mock(EmulatorConfig.class),
new S3VirtualHostFilter(),
Clock.systemUTC());
Response response = controller.listObjects(bucket, null, null, null, null, null, null, null,
@@ -122,6 +122,30 @@ class S3VirtualHostFilterTest {
assertNull(S3VirtualHostFilter.extractBucket(host, baseHostname, DEFAULT_SUFFIXES));
}
@ParameterizedTest
@CsvSource({
"edge.localhost.floci.io, edge.localhost.floci.io",
"edge.localhost.floci.io:4566, edge.localhost.floci.io",
"EDGE.LOCALHOST.FLOCI.IO.:4566, edge.localhost.floci.io",
"edge.localhost.localstack.cloud, edge.localhost.localstack.cloud",
"edge.localhost, edge.localhost",
})
void configuredEndpointRootWinsOverShorterBuiltinSuffix(String host, String baseHostname) {
assertNull(S3VirtualHostFilter.extractBucket(host, baseHostname, DEFAULT_SUFFIXES));
assertEquals("bucket", S3VirtualHostFilter.extractBucket(
"bucket." + baseHostname, baseHostname, DEFAULT_SUFFIXES));
}
@Test
void configuredSuffixRootWinsOverShorterEndpointSuffix() {
Set<String> suffixes = Set.of("localhost.floci.io", "tenant.localhost.floci.io",
"alias.tenant.localhost.floci.io");
assertNull(S3VirtualHostFilter.extractBucket(
"alias.tenant.localhost.floci.io:4566", "tenant.localhost.floci.io", suffixes));
assertEquals("bucket", S3VirtualHostFilter.extractBucket(
"bucket.alias.tenant.localhost.floci.io:4566", "tenant.localhost.floci.io", suffixes));
}
@ParameterizedTest
@CsvSource({
"192.168.1.1, localhost",