Light, fluffy, and always free - The AWS Local Emulator alternative
fix(s3): keep a bucket's data inside its own account directory (#4244)
Priamo Germosen2e21c013c515
diff --git a/docs/services/s3.md b/docs/services/s3.mdindex 13a012bfa0..f1f1e1f9f8 100644--- a/docs/services/s3.md+++ b/docs/services/s3.md@@ -190,6 +190,14 @@ aws s3api select-object-content \When `FLOCI_SERVICES_ATHENA_MOCK=true` is set, Athena queries are stubbed but floci-duck does **not** start. In that configuration, S3 Select uses the Java evaluator for CSV and JSON. Parquet queries will fail unless `FLOCI_SERVICES_DUCK_URL` points to an already-running floci-duck instance.+## Bucket Names++Floci does not hold bucket names to AWS's full DNS naming rules, so a name AWS would refuse is+usually accepted here. The exception is a name that would not stay a single directory under its+account's storage root: an empty name, `.`, `..`, `.accounts`, or a name containing a path+separator is rejected with `InvalidBucketName`. On the persistent and hybrid backends such a name+climbs out of the owning account's directory, and that directory is the account boundary.+## Global Bucket NamespaceBy default S3 buckets are isolated per account (see [Multi-Account Isolation](../configuration/multi-account.md)),diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.javaindex 8f9c5e6d6f..3b26eefc2f 100644--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java@@ -334,12 +334,7 @@ public class S3Service implements Resettable, ResourceProvider {}public Bucket createBucket(String bucketName, String region) {- if (ACCOUNT_STORAGE_ROOT.equals(bucketName)) {- // Floci doesn't otherwise validate bucket name format, but this name must stay- // unavailable — it's the root every account's disk storage lives under.- throw new AwsException("InvalidBucketName",- "The specified bucket is not valid.", 400);- }+ requirePathSafeBucketName(bucketName);var existing = bucketStore.get(bucketName);if (existing.isPresent()) {Bucket bucket = existing.get();@@ -391,9 +386,10 @@ public class S3Service implements Resettable, ResourceProvider {memoryDataStore.keySet().removeIf(k -> k.startsWith(prefix));memoryAnnotationStore.keySet().removeIf(k -> k.startsWith(prefix));} else {- deleteDirectory(dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(ownerId()).resolve(bucketName));- deleteDirectory(dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(ownerId())- .resolve(ANNOTATION_STORAGE_ROOT).resolve(bucketName));+ deleteDirectory(bucketDirectory(dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(ownerId()),+ bucketName));+ deleteDirectory(bucketDirectory(dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(ownerId())+ .resolve(ANNOTATION_STORAGE_ROOT), bucketName));}}@@ -2362,8 +2358,8 @@ public class S3Service implements Resettable, ResourceProvider {}private Path resolveAnnotationPath(String bucketName, String key, String versionId, String annotationName) {- Path bucketDir = dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(ownerId())- .resolve(ANNOTATION_STORAGE_ROOT).resolve(bucketName).normalize();+ Path bucketDir = bucketDirectory(dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(ownerId())+ .resolve(ANNOTATION_STORAGE_ROOT), bucketName);// Both directory components are SHA-256 hex of our own injective identity (the object key// is URL-encoded inside it), so the path is bounded in length, filesystem-safe, and// collision-free across object keys that contain '#v#', '@', or path-like characters.@@ -4739,6 +4735,37 @@ public class S3Service implements Resettable, ResourceProvider {// layout. A leading "." keeps this namespace unreachable by any real bucket name.private static final String ACCOUNT_STORAGE_ROOT = ".accounts";+ /**+ * Floci does not hold bucket names to AWS's DNS rules, but a name must still be one directory:+ * on the disk-backed stores anything else climbs out of the owning account's directory, and+ * that directory is the account boundary.+ */+ private static void requirePathSafeBucketName(String bucketName) {+ boolean pathSafe = bucketName != null+ && !bucketName.isBlank()+ && !bucketName.contains("/")+ && !bucketName.contains("\\")+ && bucketName.indexOf('\0') < 0+ && !".".equals(bucketName)+ && !"..".equals(bucketName)+ && !ACCOUNT_STORAGE_ROOT.equals(bucketName);+ if (!pathSafe) {+ throw new AwsException("InvalidBucketName", "The specified bucket is not valid.", 400);+ }+ }++ /**+ * One bucket's directory, asserted to sit directly under {@code parent}. Checked on the+ * resolved path, not the name, so a bucket persisted before the name was refused is caught too.+ */+ private static Path bucketDirectory(Path parent, String bucketName) {+ Path resolved = parent.resolve(bucketName).normalize();+ if (!parent.normalize().equals(resolved.getParent())) {+ throw new AwsException("InvalidBucketName", "The specified bucket is not valid.", 400);+ }+ return resolved;+ }+// Unlike bucketStore/objectStore, object bytes get no automatic account prefixing — two// accounts can own a bucket named "orders" and would collide here without this scoping.private String physicalKey(String bucketName, String key) {@@ -4762,7 +4789,7 @@ public class S3Service implements Resettable, ResourceProvider {}private Path resolveObjectPath(String accountId, String bucketName, String key) {- Path bucketDir = dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(accountId).resolve(bucketName).normalize();+ Path bucketDir = bucketDirectory(dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(accountId), bucketName);String safeKey = key;while (safeKey.startsWith("/")) {@@ -4806,7 +4833,8 @@ public class S3Service implements Resettable, ResourceProvider {}private Path resolveVersionedPath(String accountId, String bucketName, String key, String versionId) {- Path baseDir = dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(accountId).resolve(".versions").resolve(bucketName).normalize();+ Path baseDir = bucketDirectory(+ dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(accountId).resolve(".versions"), bucketName);String safeKey = key;while (safeKey.startsWith("/")) {diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3BucketNameTraversalIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3BucketNameTraversalIntegrationTest.javanew file mode 100644index 0000000000..280e62f3b2--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3BucketNameTraversalIntegrationTest.java@@ -0,0 +1,70 @@+package io.github.hectorvent.floci.services.s3;++import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.anyOf;+import static org.hamcrest.Matchers.is;+import static org.hamcrest.Matchers.not;++/**+ * No spelling of a traversing bucket name reaches another account's objects. The status codes vary+ * by spelling: JAX-RS answers a literal {@code ..} or {@code .} path itself, while the encoded+ * forms reach the service undecoded and name an ordinary directory. {@code S3ServiceTest} pins the+ * service guard directly, for the callers that never come through this router.+ */+@QuarkusTest+class S3BucketNameTraversalIntegrationTest {++ private static final String VICTIM =+ "AWS4-HMAC-SHA256 Credential=000000000011/20260215/us-east-1/s3/aws4_request, SignedHeaders=host, Signature=abc";+ private static final String ATTACKER =+ "AWS4-HMAC-SHA256 Credential=000000000012/20260215/us-east-1/s3/aws4_request, SignedHeaders=host, Signature=abc";++ @Test+ void createBucketRefusesTheAccountStorageRoot() {+ given()+ .header("Authorization", ATTACKER)+ .when()+ .put("/.accounts")+ .then()+ .statusCode(400)+ .body(containsString("InvalidBucketName"));+ }++ @ParameterizedTest+ @ValueSource(strings = {"..", ".", "%2E%2E", "..%2Fvictim"})+ void noSpellingOfATraversalBucketReachesAnotherAccountsObject(String bucketName) {+ given()+ .header("Authorization", VICTIM)+ .when()+ .put("/traversal-victim-bucket")+ .then()+ .statusCode(anyOf(is(200), is(409)));++ given()+ .header("Authorization", VICTIM)+ .body("victim-secret")+ .when()+ .put("/traversal-victim-bucket/secret.txt")+ .then()+ .statusCode(200);++ given()+ .header("Authorization", ATTACKER)+ .when()+ .put("/" + bucketName);++ given()+ .header("Authorization", ATTACKER)+ .when()+ .get("/" + bucketName + "/000000000011/traversal-victim-bucket/secret.txt")+ .then()+ .statusCode(not(200))+ .body(not(containsString("victim-secret")));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.javaindex 8f48075ca0..b22a5ed620 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java@@ -17,6 +17,8 @@ import io.github.hectorvent.floci.services.s3.model.WebsiteConfiguration;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;import java.nio.charset.StandardCharsets;import java.nio.file.Files;@@ -202,6 +204,39 @@ class S3ServiceTest {assertArrayEquals(data, assertDoesNotThrow(() -> Files.readAllBytes(filePath)));}+ @ParameterizedTest+ @ValueSource(strings = {"..", ".", "../", "a/b", "../victim", ".accounts", "a\\b", " "})+ void createBucketRejectsANameThatWouldNotStayInsideTheAccountDirectory(String bucketName) {+ AwsException ex = assertThrows(AwsException.class,+ () -> s3Service.createBucket(bucketName, "us-east-1"), bucketName);+ assertEquals("InvalidBucketName", ex.getErrorCode());+ }++ @Test+ void objectPathsRefuseABucketNameThatEscapesTheAccountDirectory() {+ InMemoryStorage<String, Bucket> bucketStore = new InMemoryStorage<>();+ InMemoryStorage<String, S3Object> objectStore = new InMemoryStorage<>();+ Path dataRoot = tempDir.resolve("escape-s3");+ S3Service service = new S3Service(bucketStore, objectStore, dataRoot, false);+ // Straight into the store, as a bucket persisted before the name was refused would be.+ bucketStore.put("..", new Bucket(".."));++ AwsException put = assertThrows(AwsException.class, () -> service.putObject(+ "..", "000000000002/victim-bucket/secret.txt", "stolen".getBytes(StandardCharsets.UTF_8),+ "text/plain", null));++ assertEquals("InvalidBucketName", put.getErrorCode());+ }++ @Test+ void aBucketNamedLikeADotDirectoryStillResolvesInsideTheAccount() {+ // ".hidden" normalises to a real child, unlike "..".+ s3Service.createBucket(".hidden", "us-east-1");+ s3Service.putObject(".hidden", "k.txt", "v".getBytes(StandardCharsets.UTF_8), "text/plain", null);++ assertTrue(Files.exists(tempDir.resolve("s3/.accounts/000000000000/.hidden/k.txt.s3data")));+ }+@Testvoid putObjectDoesNotRetainBytesInObjectStore() {InMemoryStorage<String, Bucket> bucketStore = new InMemoryStorage<>();