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

@@ -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 {