fix(dynamodb): isolate item storage and locks between accounts (#2240)

* fix(dynamodb): isolate item storage and locks between accounts

DynamoDbService kept item data (itemsByTable), per-item locks
(itemLocks), and TransactWriteItems idempotency tokens in raw maps
keyed only by "region::tableName" / "region::token", with no account
component — unlike tableStore/itemStore, which get automatic account
prefixing from AccountAwareStorageBackend. Two AWS accounts creating a
same-named table in the same region therefore shared one underlying
item map: PutItem in one account's table was visible via GetItem/Scan
in another account's identically-named table.

Scope every itemsByTable/itemLocks access by the resolved account ID.
Also fixes two related gaps surfaced by the same code path:
loadPersistedItems() only reloaded the default account's items after a
restart (AccountAwareStorageBackend.keys() is request-scoped, and
startup has no request), and the TTL sweeper's use of
scanAllAccountsAsMap() collapsed same-named tables from different
accounts into one map entry, silently skipping one account's expired
items. Both are fixed via a new AccountAwareStorageBackend
.scanAllAccountsRaw(), which preserves the account segment instead of
stripping it.

Added DynamoDbAccountIsolationIntegrationTest, reproducing the leak
end-to-end (fails without this fix).

* fix(dynamodb): scope item keys in non-account-aware fallback branches too

loadPersistedItems() and deleteExpiredItems() call scopedItemsKey()
for every access except their fallback branch (used when tableStore/
itemStore isn't an AccountAwareStorageBackend, e.g. some test-only
constructors) — that branch stored/looked up itemsByTable entries
under the bare, unscoped key, inconsistent with every other accessor
in the class. Not reachable in production (StorageFactory always
wraps backends in AccountAwareStorageBackend), but would silently
orphan reloaded items / disable TTL sweeping for any future test using
the plain-backend constructors. Caught in review.

* fix(dynamodb): recover pre-multi-account data in scanAllAccountsRaw

scanAllAccountsRaw() silently dropped any key with no account segment
— data persisted before multi-account support existed. Unlike a
per-key AccountAwareStorageBackend.get() call, which falls back to the
bare unprefixed key and migrates it on read, a bulk startup reload via
scanAllAccountsRaw() has no per-key caller to trigger that path, so
loadPersistedItems() would silently lose such items on upgrade instead
of surfacing them under the default account.

Attribute slash-less keys to defaultAccountId instead of skipping
them, consistent with how get() already treats them. Found by review.

* fix(dynamodb): migrate legacy keys in scanAllAccountsRaw instead of leaving them stale

scanAllAccountsRaw() attributed a bare legacy key to defaultAccountId
but never migrated it in the underlying storage the way get()'s
per-key migrate-on-read does. Concretely: after a restart, a legacy
item loads and gets attributed to defaultAccountId in memory; a
subsequent write to that table then persists under the properly
prefixed key, but the original bare key is left untouched in storage.
On a second restart, both the stale bare key and the fresh prefixed
key map to the same effective key, and whichever the scan's iteration
happens to visit last silently wins — reviving stale data with no
deterministic outcome.

Already-prefixed keys are now loaded first, so a legacy key can never
win a collision against one that's since been written under its proper
prefix; a superseded bare key is deleted outright instead of lingering
to collide again later, and a genuinely-still-legacy key is migrated
(written under its prefix, bare key deleted) rather than left in place.
Found by review (Greptile + @pgermosen).

* style(dynamodb): tighten comments to be concise and scoped to their code

No behavior change. Trimmed comments introduced across this fix down to the
non-obvious 'why' at the point they're placed.
This commit is contained in:
Dmitriy Polomoshnov authored and GitHub committed 2026-08-12 09:22:17 -04:00
1 parent 19a32ab51d
commit a803626c17
4 files changed
+250 -21

No files matched your search

@@ -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<V> implements StorageBackend<String, V>
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.
*
* <p>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<String, V> scanAllAccountsRaw() {
Map<String, V> result = new LinkedHashMap<>();
List<String> 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<V> getForAccount(String accountId, String key) {
return delegate.get(accountId + "/" + key);
}
@@ -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<Map<String, JsonNode>> 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=<not found>", 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<String, TableDefinition> allTables;
if (tableStore instanceof AccountAwareStorageBackend<TableDefinition> 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<String, TableDefinition> 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<String> 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<String, JsonNode> items) {
if (itemStore == null) return;
if (accountId != null && itemStore instanceof AccountAwareStorageBackend<Map<String, JsonNode>> aware) {
aware.putForAccount(accountId, storageKey, new HashMap<>(items));
} else {
itemStore.put(storageKey, new HashMap<>(items));
}
}
// --- Tag Operations ---
public void tagResource(String resourceArn, Map<String, String> 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<String, JsonNode> tableItems = itemsByTable.get(storageKey);
ConcurrentSkipListMap<String, JsonNode> tableItems = itemsByTable.get(scopedItemsKey(storageKey));
List<JsonNode> snapshot = tableItems != null
? List.copyOf(tableItems.values())
: List.of();
@@ -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<String, String> 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<String> aware = new AccountAwareStorageBackend<>(raw, null, "000000000000");
Map<String, String> 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<String, String> raw = new InMemoryStorage<>();
raw.put("us-east-1::LegacyTable", "legacy-value");
AccountAwareStorageBackend<String> 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<String, String> 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<String> aware = new AccountAwareStorageBackend<>(raw, null, "000000000000");
Map<String, String> 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");
}
}
@@ -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);
}
}