fix(s3): store object key segments past the file-name limit (#6438)

A disk-backed storage mode lays an object body out as the bucket
directory, the key, and a data suffix, so a single key segment longer
than the 255-byte file-name limit made every write of the object fail
with FileSystemException, where AWS takes keys up to 1024 bytes and
memory mode always did.

A segment that fits its byte budget is stored as written, so every path
an earlier Floci could create is still found. A longer one, and a segment
shaped like an encoded one so a crafted short key cannot land on it,
becomes a readable prefix, a separator, and the SHA-256 of the whole
segment: deterministic, so a key always resolves to one file, and
injective, so two keys never share one. The object index keeps the key,
so listing answers with the key the client used.

The temporary file a write stages beside its target no longer derives
from the target's name either: at the limit that name ran 41 bytes past
it. A constant-length name does not.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-10-24 15:03:52 -04:00
1 parent 25a63eef9e
commit 781a68b6cb
3 files changed
+335 -6

No files matched your search

+11
View File
@@ -305,6 +305,17 @@ Floci's reserved storage directories (`.accounts`, `.versions`, `.annotations`)
`InvalidBucketName`. On the persistent and hybrid backends such a name either climbs out of the
owning account's directory or collides with object version and annotation data.
## Object Keys
S3 accepts keys of up to 1024 bytes, and so does Floci in every storage mode. On the disk-backed
modes the body file is laid out as `<key>.s3data` under the bucket's directory, and a single key
segment can run past the 255-byte file-name limit the filesystem enforces. Such a segment is
stored on disk as a readable prefix followed by the SHA-256 of the whole segment; every segment
that already fits stays as written, so data written by an earlier version is still found at its
old path. The mapping is deterministic, so the same key always resolves to the same file, and
listing answers with the original key, which the object index holds, never with the encoded
on-disk name.
## Bucket Regions
`CreateBucket` follows AWS's region rules, in every partition. The endpoint a request is signed for
@@ -2852,7 +2852,7 @@ public class S3Service implements Resettable, ResourceProvider {
* links. A failed pin removes whatever it created, since the caller never gets its path.
*/
private Path pinFile(Path file) {
Path pinned = file.resolveSibling(file.getFileName() + ".tmp-" + UUID.randomUUID());
Path pinned = file.resolveSibling(tempSiblingName());
try {
try {
Files.createLink(pinned, file);
@@ -7351,6 +7351,12 @@ public class S3Service implements Resettable, ResourceProvider {
private static final String DATA_SUFFIX = ".s3data";
// Linux file names cap at 255 bytes; S3 key segments have no cap, so a segment over its
// budget below is stored as a readable prefix plus the SHA-256 of the whole segment.
private static final int MAX_FILE_NAME_BYTES = 255;
private static final char ENCODED_SEGMENT_SEPARATOR = '~';
private static final int SHA256_HEX_CHARS = 64;
// A 12-digit bucket name is valid on S3 and would otherwise collide with an account ID,
// making dataRoot/<accountId>/... indistinguishable from the legacy dataRoot/<bucket>/...
// layout. A leading "." keeps this namespace unreachable by any real bucket name.
@@ -7391,6 +7397,69 @@ public class S3Service implements Resettable, ResourceProvider {
return resolved;
}
/**
* Encodes the '/'-separated segments of an object key into names the filesystem can hold.
* A segment within its byte budget is kept as written, so every path an earlier Floci could
* create is still found; a longer one, and any segment shaped like an encoded one so a
* crafted short key cannot land on an encoded name, becomes a readable prefix, '~', and the
* SHA-256 of the whole segment. The digest keeps the mapping injective: the same key always
* resolves to one path and two keys never share a file. Listing reads keys from the object
* store, never from these names, so the encoding never needs reversing.
*/
private static String encodePathSegments(String key, int lastSegmentBudget, int segmentBudget) {
String[] segments = key.split("/", -1);
for (int i = 0; i < segments.length; i++) {
segments[i] = encodePathSegment(segments[i], i == segments.length - 1 ? lastSegmentBudget : segmentBudget);
}
return String.join("/", segments);
}
private static String encodePathSegment(String segment, int budget) {
if (utf8Length(segment) <= budget && !hasEncodedShape(segment, budget)) {
return segment;
}
return truncateUtf8(segment, budget - 1 - SHA256_HEX_CHARS)
+ ENCODED_SEGMENT_SEPARATOR + Digests.sha256Hex(segment);
}
/** Whether {@code segment} could itself be the output of {@link #encodePathSegment}. */
private static boolean hasEncodedShape(String segment, int budget) {
if (utf8Length(segment) > budget || segment.length() <= SHA256_HEX_CHARS) {
return false;
}
if (segment.charAt(segment.length() - SHA256_HEX_CHARS - 1) != ENCODED_SEGMENT_SEPARATOR) {
return false;
}
for (int i = segment.length() - SHA256_HEX_CHARS; i < segment.length(); i++) {
char c = segment.charAt(i);
if ((c < '0' || c > '9') && (c < 'a' || c > 'f')) {
return false;
}
}
return true;
}
private static String truncateUtf8(String segment, int maxBytes) {
int end = 0;
int used = 0;
int i = 0;
while (i < segment.length()) {
int codePoint = segment.codePointAt(i);
int byteCount = codePoint < 0x80 ? 1 : codePoint < 0x800 ? 2 : codePoint < 0x10000 ? 3 : 4;
if (used + byteCount > maxBytes) {
break;
}
used += byteCount;
i += Character.charCount(codePoint);
end = i;
}
return segment.substring(0, end);
}
private static int utf8Length(String segment) {
return segment.getBytes(StandardCharsets.UTF_8).length;
}
// 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) {
@@ -7421,7 +7490,9 @@ public class S3Service implements Resettable, ResourceProvider {
safeKey = safeKey.substring(1);
}
Path resolved = bucketDir.resolve(safeKey + DATA_SUFFIX).normalize();
String encodedKey = encodePathSegments(safeKey,
MAX_FILE_NAME_BYTES - DATA_SUFFIX.length(), MAX_FILE_NAME_BYTES);
Path resolved = bucketDir.resolve(encodedKey + DATA_SUFFIX).normalize();
if (!resolved.startsWith(bucketDir)) {
throw new AwsException("InvalidKey", "The specified key is invalid.", 400);
}
@@ -7466,7 +7537,8 @@ public class S3Service implements Resettable, ResourceProvider {
safeKey = safeKey.substring(1);
}
Path resolved = baseDir.resolve(safeKey).resolve(versionId + DATA_SUFFIX).normalize();
Path resolved = baseDir.resolve(encodePathSegments(safeKey, MAX_FILE_NAME_BYTES, MAX_FILE_NAME_BYTES))
.resolve(versionId + DATA_SUFFIX).normalize();
if (!resolved.startsWith(baseDir)) {
throw new AwsException("InvalidKey", "The specified key is invalid.", 400);
}
@@ -7688,11 +7760,13 @@ public class S3Service implements Resettable, ResourceProvider {
* read surfaced as an empty {@code src-Config} secondary source. Writing to a unique sibling
* temp file and atomically renaming it over the target closes that window. The temp name is
* unique per call so concurrent writers to the same key never clobber each other's temp file;
* whichever rename lands last wins, and every rename is all-or-nothing.
* whichever rename lands last wins, and every rename is all-or-nothing. It is also
* constant-length, because a name derived from the target's would exceed the 255-byte
* file-name limit for a target at that limit.
*/
private void atomicWrite(Path filePath, byte[] data) throws IOException {
Files.createDirectories(filePath.getParent());
Path tmp = filePath.resolveSibling(filePath.getFileName() + ".tmp-" + UUID.randomUUID());
Path tmp = filePath.resolveSibling(tempSiblingName());
try {
Files.write(tmp, data);
replaceAtomically(tmp, filePath);
@@ -7712,6 +7786,13 @@ public class S3Service implements Resettable, ResourceProvider {
}
}
// A name derived from the target's, like the earlier "<target>.tmp-<uuid>", would run past
// the 255-byte file-name limit for a target at that limit. This one is constant-length and
// still unique per call, and never collides with an object file (those end in ".s3data").
private static String tempSiblingName() {
return ".tmp-" + UUID.randomUUID();
}
/**
* Moves an assembled multipart object to {@code target} with the same all-or-nothing rename
* {@link #atomicWrite} ends with: a concurrent reader sees the previous file or the whole new
@@ -7740,7 +7821,7 @@ public class S3Service implements Resettable, ResourceProvider {
private void linkIntoPlace(Path source, Path target) {
ReentrantLock lock = diskFileLock(target);
lock.lock();
Path tmp = target.resolveSibling(target.getFileName() + ".tmp-" + UUID.randomUUID());
Path tmp = target.resolveSibling(tempSiblingName());
try {
Files.createDirectories(target.getParent());
try {
@@ -0,0 +1,237 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.s3.model.CopyObjectOptions;
import io.github.hectorvent.floci.services.s3.model.MultipartUpload;
import io.github.hectorvent.floci.services.s3.model.PutObjectOptions;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
/**
* Object keys whose segments run past the 255-byte file-name limit, in disk-storage mode. The
* body file gets a hashed name for the overlong segment while the object store keeps the key,
* so listing still answers with the key the client used.
*/
class S3LongKeyDiskStorageTest {
private static final int MAX_FILE_NAME_BYTES = 255;
private static final String DATA_SUFFIX = ".s3data";
private static final UploadChecksums NO_CHECKSUMS = new UploadChecksums(null, Map.of());
@TempDir
Path tempDir;
private S3Service s3Service;
private Path dataRoot;
@BeforeEach
void setUp() {
dataRoot = tempDir.resolve("s3");
s3Service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(), dataRoot, false);
s3Service.createBucket("bucket", "us-east-1");
}
@Test
void putGetHeadDeleteAndListASingleSegmentKeyOverTheFileNameLimit() throws IOException {
String key = "k".repeat(300);
byte[] body = "a body for a long key".getBytes(StandardCharsets.UTF_8);
s3Service.putObject("bucket", key, body, "text/plain", Map.of());
assertArrayEquals(body, s3Service.getObject("bucket", key).getData());
assertEquals(body.length, s3Service.headObject("bucket", key).getSize());
List<String> listedKeys = s3Service.listObjects("bucket", null, null, 1000)
.stream().map(S3Object::getKey).toList();
assertEquals(List.of(key), listedKeys);
assertEveryFileNameFitsTheByteLimit();
s3Service.deleteObject("bucket", key);
assertEquals("NoSuchKey", assertThrows(AwsException.class,
() -> s3Service.getObject("bucket", key)).getErrorCode());
}
@Test
void theIssuesStreamedReproKeyIsStored() throws IOException {
String key = "k".repeat(249);
byte[] body = "streamed body".getBytes(StandardCharsets.UTF_8);
S3Object streamed = s3Service.putObject("bucket", key, new ByteArrayInputStream(body),
NO_CHECKSUMS, "text/plain", Map.of(), new PutObjectOptions());
assertEquals(body.length, streamed.getSize());
assertArrayEquals(body, s3Service.getObject("bucket", key).getData());
assertEquals(List.of(key), keysListedUnder(null));
assertEveryFileNameFitsTheByteLimit();
}
@Test
void aLastSegmentAtExactlyTheWritableLimitKeepsItsRawFileName() throws IOException {
String key = "k".repeat(MAX_FILE_NAME_BYTES - DATA_SUFFIX.length());
byte[] body = "at the raw limit".getBytes(StandardCharsets.UTF_8);
s3Service.putObject("bucket", key, body, "text/plain", Map.of());
assertTrue(Files.exists(rawObjectFile(key)),
"a key that always fitted stays at its unencoded path");
assertArrayEquals(body, s3Service.getObject("bucket", key).getData());
}
@Test
void aMidSegmentAtExactlyTheByteLimitKeepsItsRawFileName() throws IOException {
String midSegment = "m".repeat(MAX_FILE_NAME_BYTES);
String key = "before/" + midSegment + "/after";
byte[] body = "a mid segment at the limit".getBytes(StandardCharsets.UTF_8);
s3Service.putObject("bucket", key, body, "text/plain", Map.of());
assertTrue(Files.isDirectory(rawObjectFile(key).getParent()),
"a segment that always fitted stays at its unencoded path");
assertArrayEquals(body, s3Service.getObject("bucket", key).getData());
}
@Test
void aLongSegmentAmongShortOnesRoundTrips() throws IOException {
String key = "before/" + "k".repeat(300) + "/after";
byte[] body = "a long segment in the middle".getBytes(StandardCharsets.UTF_8);
s3Service.putObject("bucket", key, body, "text/plain", Map.of());
assertArrayEquals(body, s3Service.getObject("bucket", key).getData());
assertEquals(List.of(key), keysListedUnder(null));
assertEveryFileNameFitsTheByteLimit();
}
@Test
void multiByteCharactersInALongSegmentRoundTripByByteLength() throws IOException {
String longSegment = "é".repeat(150);
assertEquals(300, longSegment.getBytes(StandardCharsets.UTF_8).length,
"test setup: the segment is over the limit only in bytes");
String key = "dossier/" + longSegment + "/résumé";
byte[] body = "multi-byte segment".getBytes(StandardCharsets.UTF_8);
s3Service.putObject("bucket", key, body, "text/plain", Map.of());
assertArrayEquals(body, s3Service.getObject("bucket", key).getData());
assertEquals(List.of(key), keysListedUnder("dossier/"));
assertEveryFileNameFitsTheByteLimit();
}
@Test
void aVersionedBucketKeepsEachVersionOfALongKey() throws IOException {
s3Service.putBucketVersioning("bucket", "Enabled");
String key = "k".repeat(300);
byte[] first = "the first version".getBytes(StandardCharsets.UTF_8);
byte[] second = "the second version".getBytes(StandardCharsets.UTF_8);
S3Object firstStored = s3Service.putObject("bucket", key, first, "text/plain", Map.of());
s3Service.putObject("bucket", key, second, "text/plain", Map.of());
assertArrayEquals(second, s3Service.getObject("bucket", key).getData());
assertArrayEquals(first, s3Service.getObject("bucket", key, firstStored.getVersionId()).getData());
assertEveryFileNameFitsTheByteLimit();
}
@Test
void copyObjectToALongDestKeyRoundTrips() throws IOException {
s3Service.putObject("bucket", "source.txt", "copy me".getBytes(StandardCharsets.UTF_8),
"text/plain", Map.of());
String destKey = "copied/" + "k".repeat(300);
s3Service.copyObject("bucket", "source.txt", "bucket", destKey, new CopyObjectOptions());
assertArrayEquals("copy me".getBytes(StandardCharsets.UTF_8), s3Service.getObject("bucket", destKey).getData());
assertEquals(List.of("copied/" + "k".repeat(300), "source.txt"), keysListedUnder(null));
assertEveryFileNameFitsTheByteLimit();
}
@Test
void aMultipartUploadToALongKeyRoundTrips() throws IOException {
String key = "multipart/" + "k".repeat(300);
byte[] part1 = new byte[5 * 1024 * 1024];
byte[] part2 = "the tail of the object".getBytes(StandardCharsets.UTF_8);
MultipartUpload upload = s3Service.initiateMultipartUpload("bucket", key, null);
s3Service.uploadPart("bucket", key, upload.getUploadId(), 1, part1);
s3Service.uploadPart("bucket", key, upload.getUploadId(), 2, part2);
S3Object stored = s3Service.completeMultipartUpload("bucket", key, upload.getUploadId(),
List.of(1, 2), null, null);
assertTrue(stored.getETag().endsWith("-2\""), "test setup: a multipart ETag " + stored.getETag());
byte[] whole = new byte[part1.length + part2.length];
System.arraycopy(part1, 0, whole, 0, part1.length);
System.arraycopy(part2, 0, whole, part1.length, part2.length);
assertArrayEquals(whole, s3Service.getObject("bucket", key).getData());
assertEquals(List.of(key), keysListedUnder("multipart/"));
assertEveryFileNameFitsTheByteLimit();
}
@Test
void aSegmentShapedLikeAnEncodedOneNeverCollidesWithAnEncodedSegment() throws IOException {
String longSegment = "k".repeat(300);
String craftedRawSegment = "k".repeat(183) + "~" + Digests.sha256Hex(longSegment);
assertTrue(craftedRawSegment.getBytes(StandardCharsets.UTF_8).length <= MAX_FILE_NAME_BYTES - DATA_SUFFIX.length(),
"test setup: the crafted segment fits unencoded");
byte[] longBody = "the long key's body".getBytes(StandardCharsets.UTF_8);
byte[] craftedBody = "the crafted key's body".getBytes(StandardCharsets.UTF_8);
s3Service.putObject("bucket", longSegment, longBody, "text/plain", Map.of());
s3Service.putObject("bucket", craftedRawSegment, craftedBody, "text/plain", Map.of());
assertArrayEquals(longBody, s3Service.getObject("bucket", longSegment).getData());
assertArrayEquals(craftedBody, s3Service.getObject("bucket", craftedRawSegment).getData());
List<String> listedKeys = s3Service.listObjects("bucket", null, null, 1000)
.stream().map(S3Object::getKey).sorted().toList();
assertEquals(List.of(longSegment, craftedRawSegment), listedKeys);
}
@Test
void anEncodedSegmentIsIdempotentAcrossWritesAndReads() {
String key = "k".repeat(300);
byte[] first = "the first body".getBytes(StandardCharsets.UTF_8);
byte[] second = "the second body".getBytes(StandardCharsets.UTF_8);
s3Service.putObject("bucket", key, first, "text/plain", Map.of());
s3Service.putObject("bucket", key, second, "text/plain", Map.of());
assertArrayEquals(second, s3Service.getObject("bucket", key).getData());
s3Service.deleteObject("bucket", key);
s3Service.putObject("bucket", key, first, "text/plain", Map.of());
assertArrayEquals(first, s3Service.getObject("bucket", key).getData());
}
private List<String> keysListedUnder(String prefix) {
return s3Service.listObjects("bucket", prefix, null, 1000)
.stream().map(S3Object::getKey).toList();
}
private Path rawObjectFile(String key) {
return dataRoot.resolve(".accounts").resolve("000000000000").resolve("bucket")
.resolve(key + DATA_SUFFIX);
}
private void assertEveryFileNameFitsTheByteLimit() throws IOException {
try (Stream<Path> paths = Files.walk(dataRoot)) {
for (Path path : paths.toList()) {
String name = path.getFileName().toString();
assertTrue(name.getBytes(StandardCharsets.UTF_8).length <= MAX_FILE_NAME_BYTES,
"file name over the byte limit: " + name);
}
}
}
}