Files
floci/src/main/java/io/github
Dmitriy Polomoshnov cdb2c36dfe 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.
2026-08-12 17:05:55 -04:00
..