diff --git a/docs/services/s3.md b/docs/services/s3.md index 55434ae8e4..4dc3f5db21 100644 --- a/docs/services/s3.md +++ b/docs/services/s3.md @@ -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 | diff --git a/src/main/java/io/floci/aws/services/s3/S3Controller.java b/src/main/java/io/floci/aws/services/s3/S3Controller.java index a142aa0777..e9a07a4fae 100644 --- a/src/main/java/io/floci/aws/services/s3/S3Controller.java +++ b/src/main/java/io/floci/aws/services/s3/S3Controller.java @@ -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); diff --git a/src/main/java/io/floci/aws/services/s3/S3VirtualHostFilter.java b/src/main/java/io/floci/aws/services/s3/S3VirtualHostFilter.java index 9368e4e016..e37ecb6c4a 100644 --- a/src/main/java/io/floci/aws/services/s3/S3VirtualHostFilter.java +++ b/src/main/java/io/floci/aws/services/s3/S3VirtualHostFilter.java @@ -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 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 diff --git a/src/test/java/io/floci/aws/services/s3/S3ConfiguredEndpointIntegrationTest.java b/src/test/java/io/floci/aws/services/s3/S3ConfiguredEndpointIntegrationTest.java new file mode 100644 index 0000000000..1e8811ccb5 --- /dev/null +++ b/src/test/java/io/floci/aws/services/s3/S3ConfiguredEndpointIntegrationTest.java @@ -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 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 getConfigOverrides() { + return Map.of("floci.hostname", ENDPOINT, + "floci.dns.extra-suffixes", "alias." + ENDPOINT, + "floci.services.s3.enforce-auth", "true"); + } + } +} diff --git a/src/test/java/io/floci/aws/services/s3/S3GlobalLegacyListingTest.java b/src/test/java/io/floci/aws/services/s3/S3GlobalLegacyListingTest.java index 6a7f68b953..ca9ff1e319 100644 --- a/src/test/java/io/floci/aws/services/s3/S3GlobalLegacyListingTest.java +++ b/src/test/java/io/floci/aws/services/s3/S3GlobalLegacyListingTest.java @@ -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<>()); diff --git a/src/test/java/io/floci/aws/services/s3/S3PolicyStatusControllerTest.java b/src/test/java/io/floci/aws/services/s3/S3PolicyStatusControllerTest.java index 480d2fecb5..2016b4b692 100644 --- a/src/test/java/io/floci/aws/services/s3/S3PolicyStatusControllerTest.java +++ b/src/test/java/io/floci/aws/services/s3/S3PolicyStatusControllerTest.java @@ -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, diff --git a/src/test/java/io/floci/aws/services/s3/S3VirtualHostFilterTest.java b/src/test/java/io/floci/aws/services/s3/S3VirtualHostFilterTest.java index 5848cc2f2a..61126eba08 100644 --- a/src/test/java/io/floci/aws/services/s3/S3VirtualHostFilterTest.java +++ b/src/test/java/io/floci/aws/services/s3/S3VirtualHostFilterTest.java @@ -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 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",