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

@@ -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);
}
}