mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix(s3): isolate object byte storage between accounts (#2241)
* fix(s3): isolate object byte storage between accounts
Object bytes (S3Service.memoryDataStore in memory mode, or files
under dataRoot on disk) were keyed only by "bucketName/key", with no
account component — unlike bucketStore/objectStore, which get
automatic account prefixing from AccountAwareStorageBackend.
bucketStore only enforces name uniqueness within an account, so two
accounts can each own a bucket with the same name (real S3 disallows
this globally, which is a separate, pre-existing behavior difference
not addressed here); when they did, their object bytes collided:
- PutObject in one account's bucket could overwrite the bytes read
back by GetObject in another account's identically-named bucket.
- DeleteBucket in one account deleted the *shared* memoryDataStore
entries / on-disk directory, corrupting another account's
same-named bucket (surfaced as a 500 "S3 object data is missing").
Scope the physical key/path by the resolved account ID at the four
byte-storage entry points (writeFile/readFile/deleteFile and their
versioned counterparts) plus deleteBucket's cleanup and
openObjectStream's direct memoryDataStore lookups, which bypassed
those helpers. objectKey()/versionedKey() themselves are unchanged,
since they're also used as objectStore's own storage keys, which are
already correctly account-scoped via AccountAwareStorageBackend.
Added S3AccountIsolationIntegrationTest, reproducing both leaks
end-to-end (fails without this fix). Updated S3ServiceTest /
S3VersioningServiceTest disk-path assertions for the new
<accountId>/ path segment (these unit tests construct S3Service
directly with no RegionResolver, so paths fall back to the default
account "000000000000").
* fix(s3): migrate pre-existing objects from the legacy unscoped disk layout
Before this fix, every disk-mode S3 object lived at
dataRoot/bucketName/key.s3data, with no account segment — object
metadata (objectStore) was already account-scoped and unaffected by
an upgrade, but the physical bytes were not. Resolving only the new
account-scoped path meant an existing Floci installation upgrading
past the account-isolation fix would 404 on every object already on
disk.
resolveObjectPath()/resolveVersionedPath() now transparently relocate
a legacy-layout file to its new, account-scoped location on first
access, mirroring how AccountAwareStorageBackend.get() already
migrates a pre-multi-account storage key on read. Memory-mode storage
needs no equivalent fix: memoryDataStore is never persisted across a
restart, so there's no pre-existing state to migrate. Found by review.
* fix(s3): confine legacy-layout migration to reads, guarded and bounded correctly
The previous commit's naive migrateLegacyFileIfPresent() ran on every
path resolution — including writes and deletes — and MOVED the legacy
file into place. Review (Greptile + @pgermosen) surfaced several real
correctness gaps in that design, all addressed here in the final form:
- A legacy object predates any account concept, so it isn't actually
known to belong to whichever account happens to touch it first —
and two different accounts can legitimately own a same-named bucket
in Floci (bucket-name uniqueness is only enforced per account here).
Migrating on a write/delete let one account's operation destroy
another account's still-unmigrated data: the same cross-account
corruption this whole fix exists to prevent, introduced a different
way. Legacy fallback is now confined to resolveObjectPathForRead/
resolveVersionedPathForRead, used only by the read call sites
(readFile, readVersionedFile, openObjectStream); writeFile/
deleteFile/writeVersionedFile/deleteVersionedFile use the plain
scoped-path resolvers with no legacy involvement at all. The legacy
source is copied, never moved, so every account that reads it
independently gets its own copy instead of racing to claim it.
- Migration and a write/delete of the same path could still race each
other: a read could copy legacy bytes in, a concurrent write could
land its real content, and the read's install step could clobber
that write with the stale legacy content — a completed PutObject's
data silently reverting. A per-path ReentrantLock, striped across a
fixed-size (256) array rather than one lock per Path in an
unboundedly growing map, now guards copyLegacyFileIfPresent and
every write/delete of the same resolved path, making "does the
destination already exist" and "install it" one atomic step with
respect to every other disk operation on that path. This also made
an earlier temp-file + ATOMIC_MOVE approach unnecessary — with the
lock guaranteeing no concurrent writer, a plain, portable Files.copy
is sufficient, sidestepping both ATOMIC_MOVE's lack of universal
filesystem support and a temp filename that could exceed filesystem
component limits.
- Files.copy can still throw partway through (disk full, transient
I/O error) after already creating the destination with truncated
content. Left in place, that file would satisfy the exists-check on
every later attempt, permanently shadowing the still-intact legacy
source. The catch block now deletes the destination (best-effort,
logged per AGENTS.md) before rethrowing, still holding the lock.
Tests added: anotherAccountsWriteMustNotDestroyThisAccountsUnmigratedLegacyObject
(the cross-account corruption scenario), concurrentOverwriteNeverLosesToARacingLegacyMigration
(a completed write must never be clobbered by a racing migration),
concurrentFirstReadsOfTheSameLegacyObjectBothSucceed (concurrent reads
of a never-yet-migrated file), and migrationFailureIsNotPermanentAndDoesNotLeaveAFileBehind
(a retry after a transient failure recovers the intact legacy content —
note this last test's specific fault, permission denied on the source,
happens to fail before Files.copy ever creates a destination on this
JVM, so it doesn't reproduce a genuinely partial/truncated write; that
scenario isn't reliably forceable through portable java.nio.file APIs
for a file this small, so the cleanup's correctness there rests on the
delete being unconditional on any IOException, not on this test).
* fix(s3): reserve a namespace for account-scoped storage disjoint from bucket names
A 12-digit bucket name is valid on S3, so dataRoot/<accountId>/
<bucket>/<key>.s3data was not disjoint from the legacy
dataRoot/<bucket>/<key>.s3data layout: a legacy bucket literally named
e.g. "000000000000" with key "orders/report.csv" resolved to the exact
same path as account "000000000000"'s own, unrelated "orders" bucket,
key "report.csv". After upgrading, reading one could silently return
the other's bytes, and a write or DeleteBucket("orders") could
overwrite or delete the legacy object entirely — the same class of
cross-account corruption this whole fix exists to prevent, reintroduced
by the specific path-scoping scheme it chose. Found by review.
Account-scoped storage now lives under a reserved ACCOUNT_STORAGE_ROOT
(".accounts") segment: dataRoot/.accounts/<accountId>/<bucket>/...
A leading "." makes this namespace unreachable by any bucket name real
S3 accepts (bucket names must begin with a letter or number); since
Floci doesn't otherwise validate bucket name format at all,
createBucket() additionally rejects the one bucket name that would
collide with the root of this namespace itself (".accounts" exactly).
Added bucketNamedLikeTheDefaultAccountIdDoesNotCollideWithAccountScopedStorage
(the exact scenario above; confirmed it reproduces the corruption
without this fix by temporarily reverting it) and
bucketNamedLikeTheReservedAccountStorageRootIsRejected. Updated
existing S3ServiceTest/S3VersioningServiceTest/S3LegacyDiskLayoutIntegrationTest
path assertions for the new segment.
* style(s3): tighten comments to be concise and scoped to their code
No behavior change. Several comments introduced across this fix had grown into
paragraph-length essays restating context better left to the commit history;
trimmed them down to the non-obvious 'why' at the point they're placed.
This commit is contained in:
1 parent
bc21367cc4
commit
cdb2c36dfe
5 files changed
+540
-33
No files matched your search
@@ -40,6 +40,7 @@ import java.time.Instant;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -71,6 +72,19 @@ public class S3Service implements Resettable {
|
||||
private final Path dataRoot;
|
||||
private final boolean inMemory;
|
||||
private final ConcurrentHashMap<String, byte[]> memoryDataStore = new ConcurrentHashMap<>();
|
||||
// Guards disk writes/deletes against a racing legacy migration for the same path (see
|
||||
// copyLegacyFileIfPresent()). Fixed-size stripes keep memory bounded, unlike a per-path
|
||||
// map that would need reference counting to ever shrink safely.
|
||||
private static final int DISK_FILE_LOCK_STRIPES = 256;
|
||||
private final ReentrantLock[] diskFileLocks = newLockStripes(DISK_FILE_LOCK_STRIPES);
|
||||
|
||||
private static ReentrantLock[] newLockStripes(int count) {
|
||||
ReentrantLock[] locks = new ReentrantLock[count];
|
||||
for (int i = 0; i < count; i++) {
|
||||
locks[i] = new ReentrantLock();
|
||||
}
|
||||
return locks;
|
||||
}
|
||||
private final ConcurrentHashMap<String, Map<Integer, byte[]>> memoryMultipartStore = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, MultipartUpload> multipartUploads = new ConcurrentHashMap<>();
|
||||
|
||||
@@ -183,6 +197,12 @@ public class S3Service implements Resettable {
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
var existing = bucketStore.get(bucketName);
|
||||
if (existing.isPresent()) {
|
||||
Bucket bucket = existing.get();
|
||||
@@ -217,10 +237,10 @@ public class S3Service implements Resettable {
|
||||
|
||||
bucketStore.delete(bucketName);
|
||||
if (inMemory) {
|
||||
String prefix = bucketName + "/";
|
||||
String prefix = ownerId() + "/" + bucketName + "/";
|
||||
memoryDataStore.keySet().removeIf(k -> k.startsWith(prefix));
|
||||
} else {
|
||||
deleteDirectory(dataRoot.resolve(bucketName));
|
||||
deleteDirectory(dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(ownerId()).resolve(bucketName));
|
||||
}
|
||||
LOG.infov("Deleted bucket: {0}", bucketName);
|
||||
}
|
||||
@@ -659,8 +679,8 @@ public class S3Service implements Resettable {
|
||||
getObjectMetadata(bucketName, key, versionId);
|
||||
if (inMemory) {
|
||||
byte[] data = versionId != null
|
||||
? memoryDataStore.get(versionedKey(bucketName, key, versionId))
|
||||
: memoryDataStore.get(objectKey(bucketName, key));
|
||||
? memoryDataStore.get(physicalVersionedKey(bucketName, key, versionId))
|
||||
: memoryDataStore.get(physicalKey(bucketName, key));
|
||||
if (data == null) {
|
||||
throw new IllegalStateException("S3 object data is missing for " + bucketName + "/" + key);
|
||||
}
|
||||
@@ -668,8 +688,8 @@ public class S3Service implements Resettable {
|
||||
}
|
||||
try {
|
||||
Path path = versionId != null
|
||||
? resolveVersionedPath(bucketName, key, versionId)
|
||||
: resolveObjectPath(bucketName, key);
|
||||
? resolveVersionedPathForRead(bucketName, key, versionId)
|
||||
: resolveObjectPathForRead(bucketName, key);
|
||||
return Files.newInputStream(path);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Failed to open S3 object stream", e);
|
||||
@@ -2564,14 +2584,29 @@ public class S3Service implements Resettable {
|
||||
|
||||
private static final String DATA_SUFFIX = ".s3data";
|
||||
|
||||
// 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.
|
||||
private static final String ACCOUNT_STORAGE_ROOT = ".accounts";
|
||||
|
||||
// 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) {
|
||||
return ownerId() + "/" + objectKey(bucketName, key);
|
||||
}
|
||||
|
||||
private String physicalVersionedKey(String bucketName, String key, String versionId) {
|
||||
return ownerId() + "/" + versionedKey(bucketName, key, versionId);
|
||||
}
|
||||
|
||||
private Path resolveObjectPath(String bucketName, String key) {
|
||||
Path bucketDir = dataRoot.resolve(bucketName).normalize();
|
||||
|
||||
Path bucketDir = dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(ownerId()).resolve(bucketName).normalize();
|
||||
|
||||
String safeKey = key;
|
||||
while (safeKey.startsWith("/")) {
|
||||
safeKey = safeKey.substring(1);
|
||||
}
|
||||
|
||||
|
||||
Path resolved = bucketDir.resolve(safeKey + DATA_SUFFIX).normalize();
|
||||
if (!resolved.startsWith(bucketDir)) {
|
||||
throw new AwsException("InvalidKey", "The specified key is invalid.", 400);
|
||||
@@ -2579,14 +2614,35 @@ public class S3Service implements Resettable {
|
||||
return resolved;
|
||||
}
|
||||
|
||||
private Path resolveVersionedPath(String bucketName, String key, String versionId) {
|
||||
Path baseDir = dataRoot.resolve(".versions").resolve(bucketName).normalize();
|
||||
|
||||
private Path legacyObjectPath(String bucketName, String key) {
|
||||
String safeKey = key;
|
||||
while (safeKey.startsWith("/")) {
|
||||
safeKey = safeKey.substring(1);
|
||||
}
|
||||
|
||||
return dataRoot.resolve(bucketName).normalize().resolve(safeKey + DATA_SUFFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the path for a read, copying in a legacy-layout file if present. Reads only —
|
||||
* a write/delete ({@link #resolveObjectPath}) must never touch legacy data, since it isn't
|
||||
* known to belong to any one account and two accounts can share a bucket name. Copying
|
||||
* (not moving) leaves the ambiguous source in place so every account that reads it gets
|
||||
* its own copy.
|
||||
*/
|
||||
private Path resolveObjectPathForRead(String bucketName, String key) {
|
||||
Path resolved = resolveObjectPath(bucketName, key);
|
||||
copyLegacyFileIfPresent(legacyObjectPath(bucketName, key), resolved);
|
||||
return resolved;
|
||||
}
|
||||
|
||||
private Path resolveVersionedPath(String bucketName, String key, String versionId) {
|
||||
Path baseDir = dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(ownerId()).resolve(".versions").resolve(bucketName).normalize();
|
||||
|
||||
String safeKey = key;
|
||||
while (safeKey.startsWith("/")) {
|
||||
safeKey = safeKey.substring(1);
|
||||
}
|
||||
|
||||
Path resolved = baseDir.resolve(safeKey).resolve(versionId + DATA_SUFFIX).normalize();
|
||||
if (!resolved.startsWith(baseDir)) {
|
||||
throw new AwsException("InvalidKey", "The specified key is invalid.", 400);
|
||||
@@ -2594,26 +2650,86 @@ public class S3Service implements Resettable {
|
||||
return resolved;
|
||||
}
|
||||
|
||||
private void writeVersionedFile(String bucketName, String key, String versionId, byte[] data) {
|
||||
if (inMemory) {
|
||||
memoryDataStore.put(versionedKey(bucketName, key, versionId), data);
|
||||
private Path legacyVersionedPath(String bucketName, String key, String versionId) {
|
||||
String safeKey = key;
|
||||
while (safeKey.startsWith("/")) {
|
||||
safeKey = safeKey.substring(1);
|
||||
}
|
||||
return dataRoot.resolve(".versions").resolve(bucketName).normalize()
|
||||
.resolve(safeKey).resolve(versionId + DATA_SUFFIX);
|
||||
}
|
||||
|
||||
/** Read-only counterpart of {@link #resolveObjectPathForRead} for versioned objects. */
|
||||
private Path resolveVersionedPathForRead(String bucketName, String key, String versionId) {
|
||||
Path resolved = resolveVersionedPath(bucketName, key, versionId);
|
||||
copyLegacyFileIfPresent(legacyVersionedPath(bucketName, key, versionId), resolved);
|
||||
return resolved;
|
||||
}
|
||||
|
||||
private ReentrantLock diskFileLock(Path path) {
|
||||
// A stripe collision just serializes unrelated paths — safe, unlike a map entry.
|
||||
return diskFileLocks[Math.floorMod(path.hashCode(), diskFileLocks.length)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies in a legacy file for {@code newPath}, under the same lock {@link #writeFile}/
|
||||
* {@link #deleteFile} hold for that path — otherwise a concurrent write could land its
|
||||
* real content and then be silently clobbered by a racing legacy copy.
|
||||
*/
|
||||
private void copyLegacyFileIfPresent(Path legacyPath, Path newPath) {
|
||||
if (!Files.exists(legacyPath)) {
|
||||
return;
|
||||
}
|
||||
ReentrantLock lock = diskFileLock(newPath);
|
||||
lock.lock();
|
||||
try {
|
||||
if (Files.exists(newPath)) {
|
||||
return;
|
||||
}
|
||||
Files.createDirectories(newPath.getParent());
|
||||
Files.copy(legacyPath, newPath);
|
||||
} catch (IOException e) {
|
||||
// A failed copy can leave newPath truncated, which would wrongly look
|
||||
// "already migrated" on a later retry — clean it up before rethrowing.
|
||||
deleteQuietly(newPath, "partially-copied legacy S3 object file, so a later read can retry migration");
|
||||
throw new UncheckedIOException("Failed to copy legacy S3 object file to account-scoped layout", e);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteQuietly(Path path, String reason) {
|
||||
try {
|
||||
Files.deleteIfExists(path);
|
||||
} catch (IOException e) {
|
||||
LOG.warnv(e, "Failed to delete {0} ({1})", path, reason);
|
||||
}
|
||||
}
|
||||
|
||||
private void writeVersionedFile(String bucketName, String key, String versionId, byte[] data) {
|
||||
if (inMemory) {
|
||||
memoryDataStore.put(physicalVersionedKey(bucketName, key, versionId), data);
|
||||
return;
|
||||
}
|
||||
Path filePath = resolveVersionedPath(bucketName, key, versionId);
|
||||
ReentrantLock lock = diskFileLock(filePath);
|
||||
lock.lock();
|
||||
try {
|
||||
Path filePath = resolveVersionedPath(bucketName, key, versionId);
|
||||
Files.createDirectories(filePath.getParent());
|
||||
Files.write(filePath, data);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Failed to write versioned S3 object file", e);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] readVersionedFile(String bucketName, String key, String versionId) {
|
||||
if (inMemory) {
|
||||
return memoryDataStore.get(versionedKey(bucketName, key, versionId));
|
||||
return memoryDataStore.get(physicalVersionedKey(bucketName, key, versionId));
|
||||
}
|
||||
try {
|
||||
return Files.readAllBytes(resolveVersionedPath(bucketName, key, versionId));
|
||||
return Files.readAllBytes(resolveVersionedPathForRead(bucketName, key, versionId));
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Failed to read versioned S3 object file", e);
|
||||
}
|
||||
@@ -2621,24 +2737,28 @@ public class S3Service implements Resettable {
|
||||
|
||||
private void writeFile(String bucketName, String key, byte[] data) {
|
||||
if (inMemory) {
|
||||
memoryDataStore.put(objectKey(bucketName, key), data);
|
||||
memoryDataStore.put(physicalKey(bucketName, key), data);
|
||||
return;
|
||||
}
|
||||
Path filePath = resolveObjectPath(bucketName, key);
|
||||
ReentrantLock lock = diskFileLock(filePath);
|
||||
lock.lock();
|
||||
try {
|
||||
Path filePath = resolveObjectPath(bucketName, key);
|
||||
Files.createDirectories(filePath.getParent());
|
||||
Files.write(filePath, data);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Failed to write S3 object file", e);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] readFile(String bucketName, String key) {
|
||||
if (inMemory) {
|
||||
return memoryDataStore.get(objectKey(bucketName, key));
|
||||
return memoryDataStore.get(physicalKey(bucketName, key));
|
||||
}
|
||||
try {
|
||||
return Files.readAllBytes(resolveObjectPath(bucketName, key));
|
||||
return Files.readAllBytes(resolveObjectPathForRead(bucketName, key));
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Failed to read S3 object file", e);
|
||||
}
|
||||
@@ -2646,25 +2766,35 @@ public class S3Service implements Resettable {
|
||||
|
||||
private void deleteFile(String bucketName, String key) {
|
||||
if (inMemory) {
|
||||
memoryDataStore.remove(objectKey(bucketName, key));
|
||||
memoryDataStore.remove(physicalKey(bucketName, key));
|
||||
return;
|
||||
}
|
||||
Path filePath = resolveObjectPath(bucketName, key);
|
||||
ReentrantLock lock = diskFileLock(filePath);
|
||||
lock.lock();
|
||||
try {
|
||||
Files.deleteIfExists(resolveObjectPath(bucketName, key));
|
||||
Files.deleteIfExists(filePath);
|
||||
} catch (IOException e) {
|
||||
LOG.errorv(e, "Failed to delete S3 object file: {0}/{1}", bucketName, key);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteVersionedFile(String bucketName, String key, String versionId) {
|
||||
if (inMemory) {
|
||||
memoryDataStore.remove(versionedKey(bucketName, key, versionId));
|
||||
memoryDataStore.remove(physicalVersionedKey(bucketName, key, versionId));
|
||||
return;
|
||||
}
|
||||
Path filePath = resolveVersionedPath(bucketName, key, versionId);
|
||||
ReentrantLock lock = diskFileLock(filePath);
|
||||
lock.lock();
|
||||
try {
|
||||
Files.deleteIfExists(resolveVersionedPath(bucketName, key, versionId));
|
||||
Files.deleteIfExists(filePath);
|
||||
} catch (IOException e) {
|
||||
LOG.errorv(e, "Failed to delete versioned S3 object file: {0}/{1} v={2}", bucketName, key, versionId);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user