From 8d9ab570cd7351887c388deb23f7ca3576980f32 Mon Sep 17 00:00:00 2001 From: Andrew Barnes <169967362+Bortlesboat@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:21:46 -0500 Subject: [PATCH] fix(s3): store Windows-incompatible keys without filename collisions (#7925) --- docs/services/s3.md | 21 +- .../io/floci/aws/services/s3/S3Service.java | 133 ++++++++-- .../services/s3/S3WindowsFileNameKeyTest.java | 227 ++++++++++++++++++ 3 files changed, 360 insertions(+), 21 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/s3/S3WindowsFileNameKeyTest.java diff --git a/docs/services/s3.md b/docs/services/s3.md index 3bcb372aaa..57d5a2f97a 100644 --- a/docs/services/s3.md +++ b/docs/services/s3.md @@ -329,12 +329,27 @@ owning account's directory or collides with object version and annotation data. 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 `.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 +stored on disk as a readable prefix followed by the SHA-256 of the whole segment. A segment that +fits and can be represented as written keeps its raw path, unless it already looks like an +encoded name. Those names are encoded too, so they cannot overwrite an encoded object's body. +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. +When Floci runs on Windows, a segment Windows cannot hold as a file name is stored the same way: +one containing a character Windows refuses (`<>:"|?*`, `\` or a control character), one ending in +a dot or a space, which Windows drops, and one naming a device that Microsoft's file naming rules +reserve, such as `CON`, `NUL.txt` or `COM1`. For an unversioned body, the last segment is judged +with `.s3data` appended, the name it is stored under, so a key such as `logs/report.` keeps its +earlier path. Versioned bodies use the key as a directory path, so its last segment is judged +without that suffix. + +Older Windows releases of Floci could fold keys such as `dir./file` and `dir\file` onto another +key's path. Bodies at those ambiguous paths are not migrated automatically, because their intended +key cannot be determined safely. Existing raw filenames that now match the encoded-name pattern +are also not migrated automatically. Their metadata can remain while a read of the new encoded +path fails; these objects need to be rewritten from a known copy of their contents. + A key keeps the slashes it is sent with: `PUT /bucket//file.txt` writes `/file.txt`, and a key made only of slashes is an object too, so `PUT /bucket//` writes the key `/` rather than creating the bucket. One trailing slash after the bucket, `/bucket/`, is still the bucket. The key is read from diff --git a/src/main/java/io/floci/aws/services/s3/S3Service.java b/src/main/java/io/floci/aws/services/s3/S3Service.java index 23bb6bb67a..5ed2da50d3 100644 --- a/src/main/java/io/floci/aws/services/s3/S3Service.java +++ b/src/main/java/io/floci/aws/services/s3/S3Service.java @@ -7973,6 +7973,23 @@ public class S3Service implements Resettable, ResourceProvider { private static final char ENCODED_SEGMENT_SEPARATOR = '~'; private static final int SHA256_HEX_CHARS = 64; + // Windows refuses these characters in a file name, treats '\' as a separator, strips a + // trailing dot and reserves device names such as NUL, all of which S3 accepts in a key, so + // there such a segment is encoded as well. + private static final boolean WINDOWS_FILE_NAMES = + System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows"); + private static final String WINDOWS_RESERVED_CHARS = "<>:\"|?*\\"; + // Microsoft's file naming rules reserve these names with any extension too (NUL.txt is NUL), + // and count the superscript digits ¹, ² and ³ as digits in COM and LPT names. Windows + // versions differ in which of these still open a device, so following the documented rules + // keeps a key on the same file whichever version runs Floci. + private static final Set WINDOWS_DEVICE_NAMES = Set.of( + "CON", "PRN", "AUX", "NUL", + "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", + "COM¹", "COM²", "COM³", + "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", + "LPT¹", "LPT²", "LPT³"); + // A 12-digit bucket name is valid on S3 and would otherwise collide with an account ID, // making dataRoot//... indistinguishable from the legacy dataRoot//... // layout. A leading "." keeps this namespace unreachable by any real bucket name. @@ -8015,27 +8032,82 @@ public class S3Service implements Resettable, ResourceProvider { /** * 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. + * A segment within its byte budget that the filesystem can hold as written is kept, unless + * it has the encoded-name shape. A longer one, one Windows cannot hold when running there, 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 + * encoded segments distinct; recognizing the encoded-name shape prevents raw segments from + * aliasing them. Listing reads keys from the object store, never from these names, so the encoding + * never needs reversing. The last segment is stored with {@code lastSegmentSuffix} appended, + * so the suffix counts toward its byte budget and is part of the name Windows has to hold. */ - private static String encodePathSegments(String key, int lastSegmentBudget, int segmentBudget) { + private static String encodePathSegments(String key, String lastSegmentSuffix) { String[] segments = key.split("/", -1); for (int i = 0; i < segments.length; i++) { - segments[i] = encodePathSegment(segments[i], i == segments.length - 1 ? lastSegmentBudget : segmentBudget); + segments[i] = encodePathSegment(segments[i], i == segments.length - 1 ? lastSegmentSuffix : ""); } return String.join("/", segments); } - private static String encodePathSegment(String segment, int budget) { - if (utf8Length(segment) <= budget && !hasEncodedShape(segment, budget)) { + private static String encodePathSegment(String segment, String suffix) { + int budget = MAX_FILE_NAME_BYTES - suffix.length(); + boolean representable = !WINDOWS_FILE_NAMES || isWindowsFileName(segment + suffix); + if (representable && utf8Length(segment) <= budget && !hasEncodedShape(segment, budget)) { return segment; } - return truncateUtf8(segment, budget - 1 - SHA256_HEX_CHARS) - + ENCODED_SEGMENT_SEPARATOR + Digests.sha256Hex(segment); + String prefix = truncateUtf8(segment, budget - 1 - SHA256_HEX_CHARS); + if (WINDOWS_FILE_NAMES) { + prefix = windowsSafePrefix(prefix); + } + return prefix + ENCODED_SEGMENT_SEPARATOR + Digests.sha256Hex(segment); + } + + /** Whether Windows stores a file or directory named {@code name} exactly as written. */ + static boolean isWindowsFileName(String name) { + if (name.equals(".") || name.equals("..")) { + return true; + } + for (int i = 0; i < name.length(); i++) { + if (isWindowsReservedChar(name.charAt(i))) { + return false; + } + } + return !name.endsWith(".") && !name.endsWith(" ") && !namesWindowsDevice(name); + } + + /** Whether the part of {@code name} before its first dot, less trailing spaces, is a Windows device. */ + private static boolean namesWindowsDevice(String name) { + int end = name.indexOf('.'); + if (end < 0) { + end = name.length(); + } + while (end > 0 && name.charAt(end - 1) == ' ') { + end--; + } + return WINDOWS_DEVICE_NAMES.contains(name.substring(0, end).toUpperCase(Locale.ROOT)); + } + + /** + * The readable prefix of an encoded name, made safe for Windows: each character Windows refuses + * becomes '_', and so does the first dot when the part before it names a device, because + * Microsoft's naming rules still read NUL.txt~digest as NUL. Each swapped character is one + * UTF-8 byte, as '_' is. + */ + static String windowsSafePrefix(String prefix) { + StringBuilder safe = new StringBuilder(prefix.length()); + for (int i = 0; i < prefix.length(); i++) { + char c = prefix.charAt(i); + safe.append(isWindowsReservedChar(c) ? '_' : c); + } + int dot = safe.indexOf("."); + if (dot >= 0 && namesWindowsDevice(safe.substring(0, dot))) { + safe.setCharAt(dot, '_'); + } + return safe.toString(); + } + + private static boolean isWindowsReservedChar(char c) { + return c < 0x20 || WINDOWS_RESERVED_CHARS.indexOf(c) >= 0; } /** Whether {@code segment} could itself be the output of {@link #encodePathSegment}. */ @@ -8048,7 +8120,8 @@ public class S3Service implements Resettable, ResourceProvider { } 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')) { + if ((c < '0' || c > '9') && (c < 'a' || c > 'f') + && (!WINDOWS_FILE_NAMES || c < 'A' || c > 'F')) { return false; } } @@ -8106,8 +8179,7 @@ public class S3Service implements Resettable, ResourceProvider { safeKey = safeKey.substring(1); } - String encodedKey = encodePathSegments(safeKey, - MAX_FILE_NAME_BYTES - DATA_SUFFIX.length(), MAX_FILE_NAME_BYTES); + String encodedKey = encodePathSegments(safeKey, DATA_SUFFIX); Path resolved = bucketDir.resolve(encodedKey + DATA_SUFFIX).normalize(); if (!resolved.startsWith(bucketDir)) { throw new AwsException("InvalidKey", "The specified key is invalid.", 400); @@ -8115,6 +8187,27 @@ public class S3Service implements Resettable, ResourceProvider { return resolved; } + /** + * Whether the legacy layout, which used the raw key as the path with {@code lastSegmentSuffix} + * appended, can represent {@code key} without Windows folding or rejecting a component. + * On Windows it cannot hold a name Windows refuses, + * and probing for one would throw, open a device, or find the file of a different key that + * Windows folds onto the same name. + */ + private static boolean hasLegacyPath(String key, String lastSegmentSuffix) { + if (!WINDOWS_FILE_NAMES) { + return true; + } + String[] segments = key.split("/", -1); + for (int i = 0; i < segments.length; i++) { + String name = i == segments.length - 1 ? segments[i] + lastSegmentSuffix : segments[i]; + if (!isWindowsFileName(name)) { + return false; + } + } + return true; + } + private Path legacyObjectPath(String bucketName, String key) { String safeKey = key; while (safeKey.startsWith("/")) { @@ -8136,7 +8229,9 @@ public class S3Service implements Resettable, ResourceProvider { private Path resolveObjectPathForRead(String accountId, String bucketName, String key) { Path resolved = resolveObjectPath(accountId, bucketName, key); - copyLegacyFileIfPresent(legacyObjectPath(bucketName, key), resolved); + if (hasLegacyPath(key, DATA_SUFFIX)) { + copyLegacyFileIfPresent(legacyObjectPath(bucketName, key), resolved); + } return resolved; } @@ -8153,7 +8248,7 @@ public class S3Service implements Resettable, ResourceProvider { safeKey = safeKey.substring(1); } - Path resolved = baseDir.resolve(encodePathSegments(safeKey, MAX_FILE_NAME_BYTES, MAX_FILE_NAME_BYTES)) + Path resolved = baseDir.resolve(encodePathSegments(safeKey, "")) .resolve(versionId + DATA_SUFFIX).normalize(); if (!resolved.startsWith(baseDir)) { throw new AwsException("InvalidKey", "The specified key is invalid.", 400); @@ -8177,7 +8272,9 @@ public class S3Service implements Resettable, ResourceProvider { private Path resolveVersionedPathForRead(String accountId, String bucketName, String key, String versionId) { Path resolved = resolveVersionedPath(accountId, bucketName, key, versionId); - copyLegacyFileIfPresent(legacyVersionedPath(bucketName, key, versionId), resolved); + if (hasLegacyPath(key, "")) { + copyLegacyFileIfPresent(legacyVersionedPath(bucketName, key, versionId), resolved); + } return resolved; } diff --git a/src/test/java/io/floci/aws/services/s3/S3WindowsFileNameKeyTest.java b/src/test/java/io/floci/aws/services/s3/S3WindowsFileNameKeyTest.java new file mode 100644 index 0000000000..0a32e81ed8 --- /dev/null +++ b/src/test/java/io/floci/aws/services/s3/S3WindowsFileNameKeyTest.java @@ -0,0 +1,227 @@ +package io.floci.aws.services.s3; + +import io.floci.aws.core.common.Digests; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.services.s3.model.S3Object; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +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.Locale; +import java.util.Map; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Object keys whose segments Windows cannot hold as file names (a colon from a timestamp, a + * backslash, a trailing dot or space, a device name such as NUL), in disk-storage mode. S3 + * accepts all of them, so the body file gets an encoded name there while the object store keeps + * the key. + */ +class S3WindowsFileNameKeyTest { + + private static final String DATA_SUFFIX = ".s3data"; + + @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 keysWithCharactersWindowsRejectsRoundTrip() { + assertKeysRoundTrip(List.of( + "logs/2026-11-05T10:00:00Z.json", + "ac|d?e*f\"g", + "tab\there", + "trailing-dot./x", + "trailing-space /x")); + } + + @Test + void keysNamingAWindowsDeviceRoundTrip() { + assertKeysRoundTrip(List.of( + "CON", + "NUL.txt", + "PRN.log", + "COM1", + "com¹", + "NUL/report.json", + "LPT²/x", + "lpt³.log", + "Aux .tar.gz")); + } + + @ParameterizedTest + @ValueSource(strings = {"nul", "NUL.txt", "COM¹.log", "LPT²/x", "Aux .tar.gz"}) + void aVersionedKeyNamingAWindowsDeviceKeepsEachVersion(String key) { + s3Service.putBucketVersioning("bucket", "Enabled"); + String firstVersion = s3Service.putObject("bucket", key, bytes("first"), "text/plain", Map.of()) + .getVersionId(); + s3Service.putObject("bucket", key, bytes("second"), "text/plain", Map.of()); + + assertArrayEquals(bytes("second"), s3Service.getObject("bucket", key).getData()); + assertArrayEquals(bytes("first"), s3Service.getObject("bucket", key, firstVersion).getData()); + } + + @Test + @EnabledOnOs(OS.WINDOWS) + void everyStoredNameIsOneWindowsHoldsAsWritten() throws IOException { + for (String key : List.of("NUL.txt", "con.tar.gz/x", "AUX .txt", "COM¹.log", "logs/10:00:00Z.json")) { + s3Service.putObject("bucket", key, bytes(key), "text/plain", Map.of()); + } + + assertTrue(Files.exists(objectFile("NUL_txt~" + Digests.sha256Hex("NUL.txt"))), + "NUL.txt is stored under a prefix that no longer reads as NUL"); + try (Stream paths = Files.walk(dataRoot)) { + for (Path path : paths.toList()) { + String name = path.getFileName().toString(); + assertTrue(S3Service.isWindowsFileName(name), "a name Windows does not hold as written: " + name); + } + } + } + + @Test + void keysWindowsWouldFoldOntoOneFileStayDistinct() { + s3Service.putObject("bucket", "dir/file", bytes("slash"), "text/plain", Map.of()); + s3Service.putObject("bucket", "dir\\file", bytes("backslash"), "text/plain", Map.of()); + s3Service.putObject("bucket", "dir./file", bytes("trailing dot"), "text/plain", Map.of()); + + assertArrayEquals(bytes("slash"), s3Service.getObject("bucket", "dir/file").getData()); + assertArrayEquals(bytes("backslash"), s3Service.getObject("bucket", "dir\\file").getData()); + assertArrayEquals(bytes("trailing dot"), s3Service.getObject("bucket", "dir./file").getData()); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + @EnabledOnOs(OS.WINDOWS) + void aRawUppercaseDigestNameCannotOverwriteAnEncodedKey(boolean invalidFirst) { + String invalidKey = "x:"; + String craftedKey = "x_~" + Digests.sha256Hex(invalidKey).toUpperCase(Locale.ROOT); + List keys = invalidFirst ? List.of(invalidKey, craftedKey) : List.of(craftedKey, invalidKey); + for (String key : keys) { + s3Service.putObject("bucket", key, bytes("body of " + key), "text/plain", Map.of()); + } + + for (String key : keys) { + assertArrayEquals(bytes("body of " + key), s3Service.getObject("bucket", key).getData(), key); + } + } + + @Test + void aLastSegmentEndingInADotOrSpaceKeepsItsUnencodedPath() { + for (String key : List.of("logs/report.", "logs/report ")) { + s3Service.putObject("bucket", key, bytes(key), "text/plain", Map.of()); + + assertTrue(Files.exists(objectFile(key)), + "with .s3data appended Windows holds the name, so it stays where earlier versions put it: " + key); + assertArrayEquals(bytes(key), s3Service.getObject("bucket", key).getData(), key); + } + } + + @Test + void aLegacyLayoutObjectWhoseLastSegmentEndsInADotOrSpaceIsStillCopiedIn() throws IOException { + for (String key : List.of("logs/report.", "logs/report ")) { + byte[] body = bytes("body of " + key); + s3Service.putObject("bucket", key, body, "text/plain", Map.of()); + Path legacy = dataRoot.resolve("bucket").resolve(key + DATA_SUFFIX); + Files.createDirectories(legacy.getParent()); + Files.move(objectFile(key), legacy); + + assertArrayEquals(body, s3Service.getObject("bucket", key).getData(), key); + assertArrayEquals(body, Files.readAllBytes(objectFile(key)), "copied account-scoped body: " + key); + assertArrayEquals(body, Files.readAllBytes(legacy), "preserved legacy body: " + key); + } + } + + @ParameterizedTest + @ValueSource(strings = {"logs/report.", "logs/report "}) + void aVersionedKeyEndingInADotOrSpaceKeepsItsOwnNullVersion(String key) { + s3Service.putObject("bucket", "logs/report", bytes("plain"), "text/plain", Map.of()); + s3Service.putObject("bucket", key, bytes("trailing character"), "text/plain", Map.of()); + s3Service.putBucketVersioning("bucket", "Enabled"); + s3Service.putObject("bucket", "logs/report", bytes("plain, versioned"), "text/plain", Map.of()); + s3Service.putObject("bucket", key, bytes("trailing character, versioned"), "text/plain", Map.of()); + + assertArrayEquals(bytes("plain"), s3Service.getObject("bucket", "logs/report", "null").getData()); + assertArrayEquals(bytes("trailing character"), s3Service.getObject("bucket", key, "null").getData()); + assertArrayEquals(bytes("plain, versioned"), s3Service.getObject("bucket", "logs/report").getData()); + assertArrayEquals(bytes("trailing character, versioned"), s3Service.getObject("bucket", key).getData()); + } + + @Test + void windowsFileNameRulesMatchTheFileSystem() { + assertTrue(S3Service.isWindowsFileName("report.json")); + assertTrue(S3Service.isWindowsFileName(".")); + assertTrue(S3Service.isWindowsFileName("..")); + assertTrue(S3Service.isWindowsFileName("")); + assertTrue(S3Service.isWindowsFileName("report..s3data")); + assertTrue(S3Service.isWindowsFileName("report .s3data")); + + assertFalse(S3Service.isWindowsFileName("10:00:00Z")); + assertFalse(S3Service.isWindowsFileName("a\\b")); + assertFalse(S3Service.isWindowsFileName("q?")); + assertFalse(S3Service.isWindowsFileName("bell\u0007")); + assertFalse(S3Service.isWindowsFileName("dir.")); + assertFalse(S3Service.isWindowsFileName("dir ")); + } + + @ParameterizedTest + @ValueSource(strings = {"CON", "con", "NUL.txt", "nul.tar.gz", "AUX .txt", "PRN.s3data", + "COM1", "lpt9", "COM¹", "com¹", "LPT³.log"}) + void aWindowsDeviceNameIsNotAFileNameWithOrWithoutAnExtension(String name) { + assertFalse(S3Service.isWindowsFileName(name)); + } + + @ParameterizedTest + @ValueSource(strings = {"CONSOLE", "NULL.txt", "COM10", "LPT", "report.con"}) + void aNameThatOnlyLooksLikeADeviceIsAFileName(String name) { + assertTrue(S3Service.isWindowsFileName(name)); + } + + @ParameterizedTest + @CsvSource({"NUL.txt, NUL_txt", "'Aux .tar.gz', 'Aux _tar.gz'", "COM¹.log, COM¹_log", + "a:b.json, a_b.json", "NULL.txt, NULL.txt", "nul, nul"}) + void anEncodedPrefixDropsTheDotAfterADeviceName(String prefix, String safePrefix) { + assertEquals(safePrefix, S3Service.windowsSafePrefix(prefix)); + } + + private void assertKeysRoundTrip(List keys) { + for (String key : keys) { + byte[] body = bytes("body of " + key); + s3Service.putObject("bucket", key, body, "text/plain", Map.of()); + assertArrayEquals(body, s3Service.getObject("bucket", key).getData(), key); + } + + List listed = s3Service.listObjects("bucket", null, null, 1000) + .stream().map(S3Object::getKey).sorted().toList(); + assertEquals(keys.stream().sorted().toList(), listed); + } + + private Path objectFile(String storedPath) { + return dataRoot.resolve(".accounts").resolve("000000000000").resolve("bucket") + .resolve(storedPath + DATA_SUFFIX); + } + + private static byte[] bytes(String text) { + return text.getBytes(StandardCharsets.UTF_8); + } +}