diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java b/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java index 35bbe31fec..56e0515e8c 100644 --- a/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java +++ b/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java @@ -4,6 +4,7 @@ import io.github.hectorvent.floci.core.common.RequestContext; import jakarta.enterprise.context.ContextNotActiveException; import jakarta.enterprise.inject.Instance; +import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -121,6 +122,43 @@ public class AccountAwareStorageBackend implements StorageBackend return result; } + /** + * Returns all entries across every account, keyed by the raw {@code accountId/logicalKey} + * storage key rather than the stripped logical key {@link #scanAllAccountsAsMap()} returns, + * so entries sharing a logical key across accounts stay distinguishable. + * + *

A key with no account segment (pre-multi-account data) is attributed to + * {@code defaultAccountId} rather than skipped, and migrated in place — unlike {@link #get}'s + * per-key migration, this bulk scan has no caller-supplied key to migrate later, so it acts + * immediately: already-prefixed keys load first so a legacy key can never win a collision + * against one already written under its proper prefix, and a superseded legacy key is + * deleted rather than left to collide again on a later restart. + */ + public Map scanAllAccountsRaw() { + Map result = new LinkedHashMap<>(); + List legacyKeys = new ArrayList<>(); + for (String rawKey : delegate.keys()) { + if (rawKey.indexOf('/') < 0) { + legacyKeys.add(rawKey); + continue; + } + delegate.get(rawKey).ifPresent(v -> result.put(rawKey, v)); + } + for (String rawKey : legacyKeys) { + String effectiveKey = defaultAccountId + "/" + rawKey; + if (result.containsKey(effectiveKey)) { + delegate.delete(rawKey); + continue; + } + delegate.get(rawKey).ifPresent(v -> { + delegate.put(effectiveKey, v); + delegate.delete(rawKey); + result.put(effectiveKey, v); + }); + } + return result; + } + public Optional getForAccount(String accountId, String key) { return delegate.get(accountId + "/" + key); } diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java index 729b37551a..632e2057e2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java @@ -138,15 +138,23 @@ public class DynamoDbService { private void loadPersistedItems() { if (itemStore == null) return; + // No request scope at startup, so itemStore.keys() would only see the default account. + // scanAllAccountsRaw() returns every account's items already in the "accountId/ + // region::tableName" key format itemsByTable expects. + if (itemStore instanceof AccountAwareStorageBackend> aware) { + aware.scanAllAccountsRaw().forEach((rawKey, items) -> + itemsByTable.put(rawKey, new ConcurrentSkipListMap<>(items))); + return; + } for (String key : itemStore.keys()) { itemStore.get(key).ifPresent(items -> - itemsByTable.put(key, new ConcurrentSkipListMap<>(items))); + itemsByTable.put(scopedItemsKey(key), new ConcurrentSkipListMap<>(items))); } } private void persistItems(String storageKey) { if (itemStore == null) return; - var items = itemsByTable.get(storageKey); + var items = itemsByTable.get(scopedItemsKey(storageKey)); if (items != null) { itemStore.put(storageKey, new HashMap<>(items)); } else { @@ -309,7 +317,7 @@ public class DynamoDbService { } tableStore.put(storageKey, table); - itemsByTable.put(storageKey, new ConcurrentSkipListMap<>()); + itemsByTable.put(scopedItemsKey(storageKey), new ConcurrentSkipListMap<>()); LOG.infov("Created table: {0} in region {1}", tableName, region); return table; } @@ -321,7 +329,7 @@ public class DynamoDbService { .orElseThrow(() -> resourceNotFoundException(canonicalTableName)); // Update dynamic counts - var items = itemsByTable.get(storageKey); + var items = itemsByTable.get(scopedItemsKey(storageKey)); if (items != null) { table.setItemCount(items.size()); } @@ -340,8 +348,8 @@ public class DynamoDbService { throw resourceNotFoundException(canonicalTableName); } tableStore.delete(storageKey); - itemsByTable.remove(storageKey); - itemLocks.remove(storageKey); + itemsByTable.remove(scopedItemsKey(storageKey)); + itemLocks.remove(scopedItemsKey(storageKey)); if (itemStore != null) { itemStore.delete(storageKey); } @@ -402,7 +410,7 @@ public class DynamoDbService { String itemKey = buildItemKey(table, normalizedItem); withItemLock(storageKey, itemKey, () -> { - var tableItems = itemsByTable.computeIfAbsent(storageKey, k -> new ConcurrentSkipListMap<>()); + var tableItems = itemsByTable.computeIfAbsent(scopedItemsKey(storageKey), k -> new ConcurrentSkipListMap<>()); JsonNode existing = tableItems.get(itemKey); @@ -432,7 +440,7 @@ public class DynamoDbService { .orElseThrow(() -> resourceNotFoundException(canonicalTableName)); String itemKey = buildItemKey(table, key, true); - var items = itemsByTable.get(storageKey); + var items = itemsByTable.get(scopedItemsKey(storageKey)); if (items == null) { LOG.tracev("Got item from {0}: key={1} item=", canonicalTableName, itemKey); return null; @@ -462,7 +470,7 @@ public class DynamoDbService { String itemKey = buildItemKey(table, key, true); return withItemLock(storageKey, itemKey, () -> { - var items = itemsByTable.get(storageKey); + var items = itemsByTable.get(scopedItemsKey(storageKey)); if (items == null) return null; if (conditionExpression != null) { @@ -509,7 +517,7 @@ public class DynamoDbService { String itemKey = buildItemKey(table, key, true); return withItemLock(storageKey, itemKey, () -> { - var items = itemsByTable.computeIfAbsent(storageKey, k -> new ConcurrentSkipListMap<>()); + var items = itemsByTable.computeIfAbsent(scopedItemsKey(storageKey), k -> new ConcurrentSkipListMap<>()); // Get existing item or create new one from key JsonNode existing = items.get(itemKey); @@ -653,7 +661,7 @@ public class DynamoDbService { TableDefinition table = tableStore.get(storageKey) .orElseThrow(() -> resourceNotFoundException(canonicalTableName)); - var items = itemsByTable.get(storageKey); + var items = itemsByTable.get(scopedItemsKey(storageKey)); if (items == null) return new QueryResult(List.of(), 0, null); // Resolve key names: use GSI or table keys @@ -826,7 +834,7 @@ public class DynamoDbService { TableDefinition table = tableStore.get(storageKey) .orElseThrow(() -> resourceNotFoundException(canonicalTableName)); - var items = itemsByTable.get(storageKey); + var items = itemsByTable.get(scopedItemsKey(storageKey)); if (items == null) return new ScanResult(List.of(), 0, null); // ConcurrentSkipListMap keeps items sorted by base item key — no sort needed. @@ -982,7 +990,7 @@ public class DynamoDbService { // * Same token + different request body → IdempotentParameterMismatchException. // * No token, or expired token → proceed normally. if (clientRequestToken != null && !clientRequestToken.isEmpty() && rawRequest != null) { - String cacheKey = region + "::" + clientRequestToken; + String cacheKey = regionResolver.getAccountId() + "::" + region + "::" + clientRequestToken; String requestHash = sha256(rawRequest.toString()); long nowNanos = System.nanoTime(); @@ -1161,7 +1169,7 @@ public class DynamoDbService { .orElseThrow(() -> resourceNotFoundException(canonicalTableName)); String itemKey = buildItemKey(table, key); - var tableItems = itemsByTable.get(storageKey); + var tableItems = itemsByTable.get(scopedItemsKey(storageKey)); JsonNode existing = tableItems != null ? tableItems.get(itemKey) : null; try { @@ -1340,20 +1348,22 @@ public class DynamoDbService { void deleteExpiredItems() { int totalDeleted = 0; + // Runs with no request scope and must sweep every account's tables, not just the + // default one — scanAllAccountsRaw()'s key matches itemsByTable's directly. Map allTables; if (tableStore instanceof AccountAwareStorageBackend aware) { - allTables = aware.scanAllAccountsAsMap(); + allTables = aware.scanAllAccountsRaw(); } else { allTables = new HashMap<>(); - tableStore.keys().forEach(k -> tableStore.get(k).ifPresent(v -> allTables.put(k, v))); + tableStore.keys().forEach(k -> tableStore.get(k).ifPresent(v -> allTables.put(scopedItemsKey(k), v))); } for (Map.Entry entry : allTables.entrySet()) { - String storageKey = entry.getKey(); + String rawKey = entry.getKey(); TableDefinition table = entry.getValue(); if (!table.isTtlEnabled() || table.getTtlAttributeName() == null) { continue; } - var items = itemsByTable.get(storageKey); + var items = itemsByTable.get(rawKey); if (items == null) continue; List expiredKeys = items.entrySet().stream() @@ -1363,6 +1373,9 @@ public class DynamoDbService { if (expiredKeys.isEmpty()) continue; + int slash = rawKey.indexOf('/'); + String accountId = slash >= 0 ? rawKey.substring(0, slash) : null; + String storageKey = slash >= 0 ? rawKey.substring(slash + 1) : rawKey; String region = storageKey.split("::", 2)[0]; for (String itemKey : expiredKeys) { JsonNode removed = items.remove(itemKey); @@ -1375,7 +1388,7 @@ public class DynamoDbService { } } } - persistItems(storageKey); + persistItemsForAccount(accountId, storageKey, items); totalDeleted += expiredKeys.size(); } if (totalDeleted > 0) { @@ -1383,6 +1396,16 @@ public class DynamoDbService { } } + /** Like {@link #persistItems}, but for callers with no ambient request account to rely on. */ + private void persistItemsForAccount(String accountId, String storageKey, Map items) { + if (itemStore == null) return; + if (accountId != null && itemStore instanceof AccountAwareStorageBackend> aware) { + aware.putForAccount(accountId, storageKey, new HashMap<>(items)); + } else { + itemStore.put(storageKey, new HashMap<>(items)); + } + } + // --- Tag Operations --- public void tagResource(String resourceArn, Map tags, String region) { @@ -2291,9 +2314,17 @@ public class DynamoDbService { return region + "::" + tableName; } + // itemsByTable/itemLocks are plain fields, unlike tableStore/itemStore, so they get no + // automatic account prefixing — without this, two accounts with a same-named table would + // share one item map. Matches scanAllAccountsRaw()'s key format, so a raw key from there + // can be used directly as an itemsByTable/itemLocks key. + private String scopedItemsKey(String storageKey) { + return regionResolver.getAccountId() + "/" + storageKey; + } + private ReentrantLock lockFor(String storageKey, String itemKey) { return itemLocks - .computeIfAbsent(storageKey, k -> new ConcurrentHashMap<>()) + .computeIfAbsent(scopedItemsKey(storageKey), k -> new ConcurrentHashMap<>()) .computeIfAbsent(itemKey, k -> new ReentrantLock()); } @@ -2647,7 +2678,7 @@ public class DynamoDbService { } ExportDescription finalDesc = desc; - ConcurrentSkipListMap tableItems = itemsByTable.get(storageKey); + ConcurrentSkipListMap tableItems = itemsByTable.get(scopedItemsKey(storageKey)); List snapshot = tableItems != null ? List.copyOf(tableItems.values()) : List.of(); diff --git a/src/test/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackendTest.java b/src/test/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackendTest.java new file mode 100644 index 0000000000..f23e166de2 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackendTest.java @@ -0,0 +1,62 @@ +package io.github.hectorvent.floci.core.storage; + +import org.junit.jupiter.api.Test; + +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class AccountAwareStorageBackendTest { + + @Test + void scanAllAccountsRawAttributesLegacyUnprefixedKeysToDefaultAccount() { + InMemoryStorage raw = new InMemoryStorage<>(); + // Simulates data persisted before multi-account support existed: no account + // segment at all, unlike every key AccountAwareStorageBackend itself writes. + raw.put("us-east-1::LegacyTable", "legacy-value"); + raw.put("111111111111/us-east-1::NewTable", "new-value"); + + AccountAwareStorageBackend aware = new AccountAwareStorageBackend<>(raw, null, "000000000000"); + + Map result = aware.scanAllAccountsRaw(); + + assertEquals(2, result.size()); + assertEquals("legacy-value", result.get("000000000000/us-east-1::LegacyTable"), + "a pre-multi-account key must be attributed to the default account, not dropped"); + assertEquals("new-value", result.get("111111111111/us-east-1::NewTable")); + assertTrue(result.keySet().stream().allMatch(k -> k.indexOf('/') >= 0), + "every returned key must carry an account segment"); + } + + @Test + void scanAllAccountsRawMigratesLegacyKeyIntoUnderlyingStorage() { + InMemoryStorage raw = new InMemoryStorage<>(); + raw.put("us-east-1::LegacyTable", "legacy-value"); + + AccountAwareStorageBackend aware = new AccountAwareStorageBackend<>(raw, null, "000000000000"); + aware.scanAllAccountsRaw(); + + assertEquals(Optional.empty(), raw.get("us-east-1::LegacyTable"), + "the bare legacy key must not be left sitting in storage after being migrated"); + assertEquals(Optional.of("legacy-value"), raw.get("000000000000/us-east-1::LegacyTable")); + } + + @Test + void scanAllAccountsRawPrefersAlreadyPrefixedEntryOverStaleLegacyKeyAndDeletesTheStaleOne() { + InMemoryStorage raw = new InMemoryStorage<>(); + // A legacy key already superseded by a real write under its proper prefix. + raw.put("us-east-1::Orders", "stale-legacy-value"); + raw.put("000000000000/us-east-1::Orders", "current-value"); + + AccountAwareStorageBackend aware = new AccountAwareStorageBackend<>(raw, null, "000000000000"); + Map result = aware.scanAllAccountsRaw(); + + assertEquals(1, result.size()); + assertEquals("current-value", result.get("000000000000/us-east-1::Orders"), + "the already-prefixed, current entry must win over a stale legacy duplicate"); + assertEquals(Optional.empty(), raw.get("us-east-1::Orders"), + "the superseded legacy key must be deleted, not left to collide again later"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccountIsolationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccountIsolationIntegrationTest.java new file mode 100644 index 0000000000..2bd2e74f58 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccountIsolationIntegrationTest.java @@ -0,0 +1,98 @@ +package io.github.hectorvent.floci.services.dynamodb; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +/** + * Verifies DynamoDB item data is isolated between accounts, mirroring + * {@link io.github.hectorvent.floci.core.common.AccountIsolationIntegrationTest}'s SQS coverage. + * Two accounts can each create a table with the same name; their items must not collide. + */ +@QuarkusTest +class DynamoDbAccountIsolationIntegrationTest { + + private static final String DYNAMODB_CONTENT_TYPE = "application/x-amz-json-1.0"; + + private static final String AUTH_ACCOUNT_1 = + "AWS4-HMAC-SHA256 Credential=000000000001/20260215/us-east-1/dynamodb/aws4_request, SignedHeaders=host, Signature=abc"; + private static final String AUTH_ACCOUNT_2 = + "AWS4-HMAC-SHA256 Credential=000000000002/20260215/us-east-1/dynamodb/aws4_request, SignedHeaders=host, Signature=abc"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void itemsInSameNamedTableAreIsolatedBetweenAccounts() { + String tableName = "account-isolation-shared-table"; + + createTable(AUTH_ACCOUNT_1, tableName); + createTable(AUTH_ACCOUNT_2, tableName); + + // Account 1 writes an item into its own table. + given() + .header("X-Amz-Target", "DynamoDB_20120810.PutItem") + .header("Authorization", AUTH_ACCOUNT_1) + .contentType(DYNAMODB_CONTENT_TYPE) + .body(""" + { + "TableName": "%s", + "Item": {"pk": {"S": "item-from-account-1"}, "secret": {"S": "account-1-data"}} + } + """.formatted(tableName)) + .when().post("/") + .then().statusCode(200); + + // Account 2's same-named table must NOT see account 1's item. + given() + .header("X-Amz-Target", "DynamoDB_20120810.GetItem") + .header("Authorization", AUTH_ACCOUNT_2) + .contentType(DYNAMODB_CONTENT_TYPE) + .body(""" + { + "TableName": "%s", + "Key": {"pk": {"S": "item-from-account-1"}} + } + """.formatted(tableName)) + .when().post("/") + .then() + .statusCode(200) + .body("Item", equalTo(null)); + + // Account 2 scanning its own table must be empty too (not just GetItem). + given() + .header("X-Amz-Target", "DynamoDB_20120810.Scan") + .header("Authorization", AUTH_ACCOUNT_2) + .contentType(DYNAMODB_CONTENT_TYPE) + .body(""" + {"TableName": "%s"} + """.formatted(tableName)) + .when().post("/") + .then() + .statusCode(200) + .body("Count", equalTo(0)); + } + + private static void createTable(String auth, String tableName) { + given() + .header("X-Amz-Target", "DynamoDB_20120810.CreateTable") + .header("Authorization", auth) + .contentType(DYNAMODB_CONTENT_TYPE) + .body(""" + { + "TableName": "%s", + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}], + "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5} + } + """.formatted(tableName)) + .when().post("/") + .then().statusCode(200); + } +}