diff --git a/docs/configuration/multi-account.md b/docs/configuration/multi-account.md index 1750464fd1..9590563794 100644 --- a/docs/configuration/multi-account.md +++ b/docs/configuration/multi-account.md @@ -202,6 +202,25 @@ When `validate-signatures` is `false` (the default), S3 signatures are verified Storage keys are namespaced per account at the persistence layer. When using `persistent`, `hybrid`, or `wal` storage modes, each account's data is stored under its own key prefix. Restarting Floci restores each account's resources independently. +When a normal scoped read misses, the storage wrapper can migrate an older unprefixed +record. A supplied key such as `222222222222/resource` already contains an account +prefix, so it is only looked up inside the caller's namespace. It cannot be used as +an alias that reads or moves the raw record belonging to account `222222222222`. +The same prefix-shaped logical key still works when it was explicitly stored in +the caller's namespace. + +This rule also applies to the single-key migration helper that checks a legacy +value's owner. Genuine unprefixed legacy records remain eligible for migration, +including to a nondefault account when its owner is established by the caller's +predicate. The separate migration helper for known older key formats continues +to handle intentional account-prefixed legacy keys. + +S3 handles older objects in twelve-digit bucket names explicitly. On a scoped +miss, it verifies the stored bucket and object key before migrating metadata to +the bucket owner's namespace. Unscoped data belongs to the configured default +account, so another account's same-named bucket cannot claim it. This applies +with either setting of the global bucket namespace; existing scoped data wins. + ## Configuration Reference | Variable | Default | Description | diff --git a/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java b/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java index 9ab4e57045..47fa39e3ec 100644 --- a/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java +++ b/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java @@ -32,7 +32,8 @@ import java.util.stream.Collectors; * *

Backward compatibility: on a {@link #get} miss for the prefixed key, the un-prefixed * key is tried and the entry is migrated on read. This covers existing persistent/WAL data - * created before multi-account support was added. + * created before multi-account support was added. A key already carrying an account prefix + * is only read inside the caller's explicit namespace, never as a raw legacy key. */ public class AccountAwareStorageBackend implements StorageBackend { @@ -98,7 +99,7 @@ public class AccountAwareStorageBackend implements StorageBackend public Optional get(String key) { String prefixedKey = prefixed(key); Optional result = delegate.get(prefixedKey); - if (result.isPresent()) { + if (result.isPresent() || hasAccountPrefix(key)) { return result; } // Backward-compat: try un-prefixed key (pre-multi-account data) and migrate on read. The @@ -349,12 +350,13 @@ public class AccountAwareStorageBackend implements StorageBackend * *

The caller-supplied predicate must establish that the legacy value belongs to the * destination account. This opt-in path avoids {@link #get(String)}'s request-context fallback, - * which cannot validate ownership before migrating old data. + * which cannot validate ownership before migrating old data. Account-prefixed logical + * keys are only eligible for the explicit scoped lookup, not the raw legacy fallback. */ public synchronized Optional getForAccountMigratingLegacy( String accountId, String key, Predicate legacyOwner) { Optional scoped = getForAccount(accountId, key); - if (scoped.isPresent()) { + if (scoped.isPresent() || hasAccountPrefix(key)) { return scoped; } Optional legacy = delegate.get(key).filter(legacyOwner); @@ -661,6 +663,11 @@ public class AccountAwareStorageBackend implements StorageBackend return prefix(); } + /** The configured owner of data written before account namespaces were introduced. */ + public String defaultAccountId() { + return defaultAccountId; + } + private RequestContext requestContext() { return requestContextProxy.get(); } 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 d947b00fc6..4be1e55b57 100644 --- a/src/main/java/io/floci/aws/services/s3/S3Service.java +++ b/src/main/java/io/floci/aws/services/s3/S3Service.java @@ -7773,6 +7773,11 @@ public class S3Service implements Resettable, ResourceProvider { * {@code globalBucketNamespace} is enabled, otherwise account-scoped. */ private Optional resolveObject(String storeKey) { + String numericBucket = numericBucketName(storeKey); + if (numericBucket != null) { + return resolveBucketEntry(numericBucket) + .flatMap(bucket -> resolveObjectForAccount(bucket.account(), storeKey)); + } if (globalBucketNamespace && objectStore instanceof AccountAwareStorageBackend aware) { @SuppressWarnings("unchecked") AccountAwareStorageBackend typed = (AccountAwareStorageBackend) aware; @@ -7786,11 +7791,46 @@ public class S3Service implements Resettable, ResourceProvider { @SuppressWarnings("unchecked") AccountAwareStorageBackend typed = (AccountAwareStorageBackend) aware; return typed.getForAccount(accountId, storeKey) - .or(() -> typed.getLegacyForAccount(accountId, storeKey)); + .or(() -> typed.getLegacyForAccount(accountId, storeKey)) + .or(() -> migrateNumericBucketObject(typed, accountId, storeKey)); } return objectStore.get(storeKey); } + private Optional migrateNumericBucketObject( + AccountAwareStorageBackend objects, String accountId, String storeKey) { + String bucketName = numericBucketName(storeKey); + if (bucketName == null || !accountId.equals(objects.defaultAccountId())) { + return Optional.empty(); + } + AccountAwareStorageBackend.OwnedEntry bucket = resolveBucketEntry(bucketName).orElse(null); + if (bucket == null || !accountId.equals(bucket.account()) + || !bucketName.equals(bucket.value().getName())) { + return Optional.empty(); + } + synchronized (bucket.value()) { + // A numeric bucket can look like an account prefix. Only the stored S3 identity + // distinguishes its legacy object from another account's unrelated scoped entry. + return objects.getForAccountMigratingLegacyKeys(accountId, storeKey, List.of(), + object -> matchesStoredObjectKey(bucketName, storeKey, object)); + } + } + + private static String numericBucketName(String storeKey) { + if (!AccountAwareStorageBackend.hasAccountPrefix(storeKey)) { + return null; + } + return storeKey.substring(0, 12); + } + + private boolean matchesStoredObjectKey(String bucketName, String storeKey, S3Object object) { + if (!bucketName.equals(object.getBucketName()) || object.getKey() == null) { + return false; + } + return storeKey.equals(objectKey(bucketName, object.getKey())) + || storeKey.equals(versionedKey(bucketName, object.getKey(), storedVersionId(object))); + } + private void putObjectForAccount(String accountId, String storeKey, S3Object object) { if (objectStore instanceof AccountAwareStorageBackend aware) { @SuppressWarnings("unchecked") diff --git a/src/test/java/io/floci/aws/core/storage/AccountAwareLegacyKeyIsolationTest.java b/src/test/java/io/floci/aws/core/storage/AccountAwareLegacyKeyIsolationTest.java new file mode 100644 index 0000000000..cc18c9ca0e --- /dev/null +++ b/src/test/java/io/floci/aws/core/storage/AccountAwareLegacyKeyIsolationTest.java @@ -0,0 +1,183 @@ +package io.floci.aws.core.storage; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +class AccountAwareLegacyKeyIsolationTest { + private static final String DEFAULT_ACCOUNT = "111111111111"; + + @ParameterizedTest + @ValueSource(strings = {"111111111111", "222222222222"}) + void ambientPrefixAliasCannotReadOrMoveAnAccountScopedRawRecord(String owner) { + InMemoryStorage raw = spy(new InMemoryStorage<>()); + AccountAwareStorageBackend storage = + new AccountAwareStorageBackend<>(raw, null, DEFAULT_ACCOUNT); + String alias = owner + "/resource"; + OwnedValue value = new OwnedValue(owner, "original"); + raw.put(alias, value); + clearInvocations(raw); + + Optional actual = storage.get(alias); + + assertAll( + () -> assertTrue(actual.isEmpty()), + () -> assertEquals(Set.of(alias), raw.keys()), + () -> assertSame(value, raw.scan(alias::equals).stream().findFirst().orElse(null)), + () -> verify(raw, never()).get(alias)); + } + + @ParameterizedTest + @ValueSource(strings = {"111111111111", "222222222222"}) + void singleKeyMigrationCannotReadOrMoveAnAccountScopedRawRecord(String owner) { + InMemoryStorage raw = spy(new InMemoryStorage<>()); + AccountAwareStorageBackend storage = + new AccountAwareStorageBackend<>(raw, null, DEFAULT_ACCOUNT); + String alias = owner + "/resource"; + OwnedValue value = new OwnedValue(owner, "original"); + raw.put(alias, value); + clearInvocations(raw); + + Optional actual = storage.getForAccountMigratingLegacy( + DEFAULT_ACCOUNT, alias, candidate -> true); + + assertAll( + () -> assertTrue(actual.isEmpty()), + () -> assertEquals(Set.of(alias), raw.keys()), + () -> assertSame(value, raw.scan(alias::equals).stream().findFirst().orElse(null)), + () -> verify(raw, never()).get(alias)); + } + + @ParameterizedTest + @ValueSource(strings = {"111111111111", "222222222222"}) + void ambientLookupPreservesExplicitScopedPrefixShapedLogicalKeys(String prefix) { + InMemoryStorage raw = new InMemoryStorage<>(); + AccountAwareStorageBackend storage = + new AccountAwareStorageBackend<>(raw, null, DEFAULT_ACCOUNT); + String logicalKey = prefix + "/resource"; + OwnedValue scoped = new OwnedValue(DEFAULT_ACCOUNT, "scoped"); + OwnedValue other = new OwnedValue(prefix, "other raw record"); + storage.put(logicalKey, scoped); + raw.put(logicalKey, other); + + assertSame(scoped, storage.get(logicalKey).orElseThrow()); + assertSame(other, raw.get(logicalKey).orElseThrow()); + assertEquals(Set.of(logicalKey, DEFAULT_ACCOUNT + "/" + logicalKey), raw.keys()); + } + + @ParameterizedTest + @ValueSource(strings = {"111111111111", "222222222222"}) + void singleKeyLookupPreservesExplicitScopedPrefixShapedLogicalKeys(String prefix) { + InMemoryStorage raw = new InMemoryStorage<>(); + AccountAwareStorageBackend storage = + new AccountAwareStorageBackend<>(raw, null, DEFAULT_ACCOUNT); + String logicalKey = prefix + "/resource"; + OwnedValue scoped = new OwnedValue(DEFAULT_ACCOUNT, "scoped"); + OwnedValue other = new OwnedValue(prefix, "other raw record"); + storage.putForAccount(DEFAULT_ACCOUNT, logicalKey, scoped); + raw.put(logicalKey, other); + + assertSame(scoped, storage.getForAccountMigratingLegacy( + DEFAULT_ACCOUNT, logicalKey, candidate -> false).orElseThrow()); + assertSame(other, raw.get(logicalKey).orElseThrow()); + assertEquals(Set.of(logicalKey, DEFAULT_ACCOUNT + "/" + logicalKey), raw.keys()); + } + + @Test + void ambientLookupStillMigratesGenuineDefaultAccountLegacyData() { + InMemoryStorage raw = new InMemoryStorage<>(); + AccountAwareStorageBackend storage = + new AccountAwareStorageBackend<>(raw, null, DEFAULT_ACCOUNT); + OwnedValue legacy = new OwnedValue(DEFAULT_ACCOUNT, "legacy"); + raw.put("legacy/path", legacy); + + assertSame(legacy, storage.get("legacy/path").orElseThrow()); + assertEquals(Set.of(DEFAULT_ACCOUNT + "/legacy/path"), raw.keys()); + assertSame(legacy, raw.get(DEFAULT_ACCOUNT + "/legacy/path").orElseThrow()); + } + + @ParameterizedTest + @ValueSource(strings = {"111111111111", "222222222222"}) + void singleKeyMigrationRetainsProvenLegacyOwnersIncludingNondefaultAccounts(String owner) { + InMemoryStorage raw = new InMemoryStorage<>(); + AccountAwareStorageBackend storage = + new AccountAwareStorageBackend<>(raw, null, DEFAULT_ACCOUNT); + OwnedValue legacy = new OwnedValue(owner, "legacy"); + raw.put("legacy/path", legacy); + + assertSame(legacy, storage.getForAccountMigratingLegacy( + owner, "legacy/path", candidate -> owner.equals(candidate.owner())).orElseThrow()); + assertEquals(Set.of(owner + "/legacy/path"), raw.keys()); + assertSame(legacy, raw.get(owner + "/legacy/path").orElseThrow()); + } + + @Test + void singleKeyMigrationPreservesLegacyDataWhenOwnerPredicateRejectsIt() { + InMemoryStorage raw = new InMemoryStorage<>(); + AccountAwareStorageBackend storage = + new AccountAwareStorageBackend<>(raw, null, DEFAULT_ACCOUNT); + OwnedValue legacy = new OwnedValue("222222222222", "legacy"); + raw.put("resource", legacy); + + assertTrue(storage.getForAccountMigratingLegacy(DEFAULT_ACCOUNT, "resource", + candidate -> DEFAULT_ACCOUNT.equals(candidate.owner())).isEmpty()); + assertEquals(Set.of("resource"), raw.keys()); + assertSame(legacy, raw.get("resource").orElseThrow()); + } + + @Test + void pluralMigrationStillAcceptsAnIntentionalKnownAccountScopedLegacyKey() { + InMemoryStorage raw = new InMemoryStorage<>(); + AccountAwareStorageBackend storage = + new AccountAwareStorageBackend<>(raw, null, DEFAULT_ACCOUNT); + OwnedValue legacy = new OwnedValue(DEFAULT_ACCOUNT, "legacy"); + raw.put(DEFAULT_ACCOUNT + "/resource", legacy); + + assertSame(legacy, storage.getForAccountMigratingLegacyKeys( + DEFAULT_ACCOUNT, "us-west-2::resource", List.of("resource"), + candidate -> DEFAULT_ACCOUNT.equals(candidate.owner())).orElseThrow()); + assertEquals(Set.of(DEFAULT_ACCOUNT + "/us-west-2::resource"), raw.keys()); + assertSame(legacy, raw.get(DEFAULT_ACCOUNT + "/us-west-2::resource").orElseThrow()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void rejectedMigrationWritePreservesTheGenuineLegacyRecord(boolean explicitAccount) { + InMemoryStorage raw = spy(new InMemoryStorage<>()); + AccountAwareStorageBackend storage = + new AccountAwareStorageBackend<>(raw, null, DEFAULT_ACCOUNT); + OwnedValue legacy = new OwnedValue(DEFAULT_ACCOUNT, "legacy"); + raw.put("resource", legacy); + doThrow(new IllegalStateException("injected pre-write failure")) + .when(raw).put(DEFAULT_ACCOUNT + "/resource", legacy); + + assertThrows(IllegalStateException.class, () -> { + if (explicitAccount) { + storage.getForAccountMigratingLegacy(DEFAULT_ACCOUNT, "resource", + candidate -> DEFAULT_ACCOUNT.equals(candidate.owner())); + } else { + storage.get("resource"); + } + }); + + assertEquals(Set.of("resource"), raw.keys()); + assertSame(legacy, raw.get("resource").orElseThrow()); + } + + private record OwnedValue(String owner, String marker) {} +} diff --git a/src/test/java/io/floci/aws/services/s3/S3LegacyNumericBucketTest.java b/src/test/java/io/floci/aws/services/s3/S3LegacyNumericBucketTest.java new file mode 100644 index 0000000000..6f3f313e1b --- /dev/null +++ b/src/test/java/io/floci/aws/services/s3/S3LegacyNumericBucketTest.java @@ -0,0 +1,176 @@ +package io.floci.aws.services.s3; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RequestContext; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.core.storage.PersistentStorage; +import io.floci.aws.services.s3.model.Bucket; +import io.floci.aws.services.s3.model.S3Object; +import jakarta.enterprise.inject.Instance; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class S3LegacyNumericBucketTest { + + private static final String OWNER = "111111111111"; + private static final String CALLER = "222222222222"; + private static final String BUCKET = "333333333333"; + private static final String KEY = "orders/report.csv"; + private static final String STORE_KEY = BUCKET + "/" + KEY; + + @TempDir + Path directory; + + private final AtomicReference caller = new AtomicReference<>(OWNER); + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void persistedLegacyObjectIsReadAndMigratedIntoTheBucketOwnersAccount(boolean global) throws Exception { + PersistentStorage raw = persistedObject(BUCKET, KEY); + S3Service service = service(raw, global); + service.createBucket(BUCKET, "us-east-1"); + Path legacyFile = directory.resolve(BUCKET).resolve(KEY + ".s3data"); + Files.createDirectories(legacyFile.getParent()); + Files.writeString(legacyFile, "legacy-body", UTF_8); + if (global) { + caller.set(CALLER); + } + + assertArrayEquals("legacy-body".getBytes(UTF_8), service.getObject(BUCKET, KEY).getData()); + + PersistentStorage reloaded = reload(); + assertFalse(reloaded.get(STORE_KEY).isPresent()); + assertTrue(reloaded.get(OWNER + "/" + STORE_KEY).isPresent()); + assertFalse(reloaded.get(CALLER + "/" + STORE_KEY).isPresent()); + assertArrayEquals("legacy-body".getBytes(UTF_8), + Files.readAllBytes(directory.resolve(".accounts").resolve(OWNER) + .resolve(BUCKET).resolve(KEY + ".s3data"))); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void anAccountScopedObjectAtTheSameRawKeyIsNeitherReadNorMoved(boolean global) { + PersistentStorage raw = persistedObject("orders", "report.csv"); + S3Service service = service(raw, global); + caller.set(BUCKET); + service.createBucket("orders", "us-east-1"); + caller.set(OWNER); + service.createBucket(BUCKET, "us-east-1"); + if (global) { + caller.set(CALLER); + } + + AwsException failure = assertThrows(AwsException.class, () -> service.getObject(BUCKET, KEY)); + + assertEquals("NoSuchKey", failure.getErrorCode()); + assertEquals("orders", raw.get(STORE_KEY).orElseThrow().getBucketName()); + assertFalse(raw.get(OWNER + "/" + STORE_KEY).isPresent()); + assertFalse(raw.get(CALLER + "/" + STORE_KEY).isPresent()); + caller.set(BUCKET); + assertEquals("report.csv", service.headObject("orders", "report.csv").getKey()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void aMismatchedObjectKeyIsNotMigrated(boolean global) { + PersistentStorage raw = persistedObject(BUCKET, "different-key"); + S3Service service = service(raw, global); + service.createBucket(BUCKET, "us-east-1"); + + AwsException failure = assertThrows(AwsException.class, () -> service.getObject(BUCKET, KEY)); + + assertEquals("NoSuchKey", failure.getErrorCode()); + assertEquals("different-key", raw.get(STORE_KEY).orElseThrow().getKey()); + assertFalse(raw.get(OWNER + "/" + STORE_KEY).isPresent()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void anotherAccountsSameNamedBucketCannotClaimLegacyData(boolean global) { + PersistentStorage raw = persistedObject(BUCKET, KEY); + S3Service service = service(raw, global); + caller.set(CALLER); + service.createBucket(BUCKET, "us-east-1"); + + AwsException failure = assertThrows(AwsException.class, () -> service.getObject(BUCKET, KEY)); + + assertEquals("NoSuchKey", failure.getErrorCode()); + assertTrue(raw.get(STORE_KEY).isPresent()); + assertFalse(raw.get(CALLER + "/" + STORE_KEY).isPresent()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void anExistingScopedObjectWinsWithoutRemovingTheLegacyRecord(boolean global) { + PersistentStorage raw = persistedObject(BUCKET, KEY); + S3Service service = service(raw, global); + service.createBucket(BUCKET, "us-east-1"); + service.putObject(BUCKET, KEY, "new-body".getBytes(UTF_8), "text/plain", Map.of()); + raw.put(STORE_KEY, new S3Object(BUCKET, KEY, "legacy-body".getBytes(UTF_8), "text/plain")); + + assertArrayEquals("new-body".getBytes(UTF_8), service.getObject(BUCKET, KEY).getData()); + assertTrue(raw.get(STORE_KEY).isPresent()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void aPersistedLegacyVersionIsMatchedByItsObjectKeyAndVersion(boolean global) { + PersistentStorage raw = reload(); + S3Object version = new S3Object(BUCKET, KEY, "old-version".getBytes(UTF_8), "text/plain"); + version.setVersionId("old-version-id"); + String versionKey = STORE_KEY + "#v#old-version-id"; + raw.put(versionKey, version); + raw = reload(); + S3Service service = service(raw, global); + service.createBucket(BUCKET, "us-east-1"); + if (global) { + caller.set(CALLER); + } + + assertEquals("old-version-id", service.headObject(BUCKET, KEY, "old-version-id").getVersionId()); + assertFalse(raw.get(versionKey).isPresent()); + assertTrue(raw.get(OWNER + "/" + versionKey).isPresent()); + } + + private PersistentStorage persistedObject(String bucket, String key) { + PersistentStorage raw = reload(); + raw.put(STORE_KEY, new S3Object(bucket, key, "legacy-body".getBytes(UTF_8), "text/plain")); + return reload(); + } + + private PersistentStorage reload() { + PersistentStorage raw = new PersistentStorage<>( + directory.resolve("objects.json"), new TypeReference>() { }); + raw.load(); + return raw; + } + + @SuppressWarnings("unchecked") + private S3Service service(PersistentStorage raw, boolean global) { + RequestContext request = mock(RequestContext.class); + when(request.getAccountId()).thenAnswer(ignored -> caller.get()); + Instance context = mock(Instance.class); + when(context.get()).thenReturn(request); + AccountAwareStorageBackend buckets = + new AccountAwareStorageBackend<>(new InMemoryStorage<>(), context, OWNER); + AccountAwareStorageBackend objects = new AccountAwareStorageBackend<>(raw, context, OWNER); + return new S3Service(buckets, objects, directory, false, global); + } +}