fix(dynamodb): give resource-tag conditions the tags of the table a request names (#8623)

The generated request resources give DynamoDB's table, index and stream
types aws:ResourceTag/ keys, but DynamoDB had no StoredResourceArns, so
a condition on a table's tags saw none. DynamoDbStoredResourceArns now
answers from the selected backend: the native one reads the table
stored under the ARN in the account and Region it names, a
pre-multi-account one of the default account in place, matched on the
whole ARN; the DynamoDB Local one reads the tags Floci records for it
while DynamoDB Local still has the table. An index ARN gets its table's
tags when the table holds that index; a stream ARN gets none. Native tag
writes, CreateTable's included, now replace the map whole under one
lock, keeping tags already put, and the field is volatile.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-16 15:02:13 -04:00
1 parent 9de6cd74b8
commit 3d6f59c064
14 files changed
+272 -21

No files matched your search

+3 -2
View File
@@ -3156,8 +3156,9 @@ floci populates:
tags), MicroVM images and network connectors, Glue for its schema registries and schemas and for the jobs,
crawlers, triggers, workflows, connections, databases, tables and other resources it tags, Step Functions for its
state machines, their versions and executions (the state machine's tags) and activities, CodeBuild for its
projects and report groups, Athena for its workgroups and data catalogs, and Redshift Serverless for its
namespaces, workgroups and snapshots. Tag keys differing only in case are one condition key holding every value.
projects and report groups, Athena for its workgroups and data catalogs, Redshift Serverless for its namespaces,
workgroups and snapshots, and DynamoDB for its tables and their indexes (the table's tags). Tag keys differing
only in case are one condition key holding every value.
- EC2 resource keys such as a network interface's `ec2:Vpc`, `ec2:Subnet`, `ec2:AvailabilityZone` and
`ec2:NetworkInterfaceID`: for every action on a resource EC2 holds, the members of the resource the
key names, an ARN for a key the Service Reference types as one. `resourceKeys` in
@@ -33,10 +33,10 @@ import java.util.Optional;
* network connector; Glue, for the tags of a resource it tags; Step Functions, for the tags of a state machine, its
* versions and executions, and an activity; CodeBuild, for the project a build belongs to and the tags of a project or
* a report group; Athena, for the workgroup and the data catalog a request naming none uses and the tags of a
* workgroup or a data catalog; Redshift Serverless, for the tags of a namespace, a workgroup or a snapshot); looked up
* lazily by {@code ResourceArnBuilder} and {@code IamConditionContextResolver} through
* {@code Instance<StoredResourceArns>} for the namespace a request or an ARN is of, so IAM never depends on that
* service directly.</p>
* workgroup or a data catalog; Redshift Serverless, for the tags of a namespace, a workgroup or a snapshot; DynamoDB,
* for the tags of a table and its indexes); looked up lazily by {@code ResourceArnBuilder} and
* {@code IamConditionContextResolver} through {@code Instance<StoredResourceArns>} for the namespace a request or an
* ARN is of, so IAM never depends on that service directly.</p>
*
* <p>Each answer is a lookup of what the service holds, asked for by an entry of the generated table ({@code find},
* {@code through}, a default, {@code forwarded}, a type's {@code resourceTagKeys}): never a fact about what an operation acts on, which the table alone
@@ -138,6 +138,9 @@ public class DynamoDbService {
private final Object capacityLock = new Object();
// Held from a resource policy revision check until the policy it allowed is stored.
private final Object resourcePolicyLock = new Object();
// Held while a table's tags are copied, changed and put in place of the map it held, which is never changed. The
// copy is put one entry at a time, as the map always was, so ListTagsOfResource keeps the order it listed.
private final Object tagLock = new Object();
// ClientRequestToken idempotency for TransactWriteItems. AWS retains tokens for
// ~10 minutes; floci uses the same window. The cache entry stores a hash of the
// request body so a replay with the same token but different parameters can be
@@ -3427,24 +3430,46 @@ public class DynamoDbService {
// --- Tag Operations ---
public void tagResource(String resourceArn, Map<String, String> tags, String region) {
TableDefinition table = findTableByArn(resourceArn, region);
if (table.getTags() == null) {
table.setTags(new HashMap<>());
synchronized (tagLock) {
TableDefinition table = findTableByArn(resourceArn, region);
Map<String, String> updated = new HashMap<>();
if (table.getTags() != null) {
table.getTags().forEach(updated::put);
}
tags.forEach(updated::put);
table.setTags(updated);
String storageKey = regionKey(region, table.getTableName());
tableStore.put(storageKey, table);
}
table.getTags().putAll(tags);
String storageKey = regionKey(region, table.getTableName());
tableStore.put(storageKey, table);
LOG.debugv("Tagged resource: {0}", resourceArn);
}
public void untagResource(String resourceArn, List<String> tagKeys, String region) {
TableDefinition table = findTableByArn(resourceArn, region);
if (table.getTags() != null) {
for (String key : tagKeys) {
table.getTags().remove(key);
/**
* Puts CreateTable's tags on the table it has just stored, under the lock TagResource takes, keeping a tag a
* TagResource already put on it in the meantime, as that came later.
*/
void putCreationTags(TableDefinition table, Map<String, String> tags) {
synchronized (tagLock) {
Map<String, String> created = new HashMap<>();
tags.forEach(created::put);
if (table.getTags() != null) {
table.getTags().forEach(created::put);
}
table.setTags(created);
}
}
public void untagResource(String resourceArn, List<String> tagKeys, String region) {
synchronized (tagLock) {
TableDefinition table = findTableByArn(resourceArn, region);
if (table.getTags() != null) {
Map<String, String> updated = new HashMap<>();
table.getTags().forEach(updated::put);
tagKeys.forEach(updated::remove);
table.setTags(updated);
String storageKey = regionKey(region, table.getTableName());
tableStore.put(storageKey, table);
}
String storageKey = regionKey(region, table.getTableName());
tableStore.put(storageKey, table);
}
LOG.debugv("Untagged resource: {0}", resourceArn);
}
@@ -3454,6 +3479,33 @@ public class DynamoDbService {
return table.getTags() != null ? table.getTags() : Map.of();
}
/**
* The tags of the table {@code arn} names, or of the table whose index it names, as an index inherits its table's
* tags: the table stored under the ARN's name in the account and Region it names, a pre-multi-account one of the
* default account read in place, matched on the whole ARN and, for an index, holding it. Empty for any other ARN,
* a stream's included, whose tags are its own and which Floci holds none of.
*/
public Map<String, String> storedTags(String arn) {
if (!AwsArnUtils.isArnFor(arn, "dynamodb")) {
return Map.of();
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
String[] parts = parsed.resource().split("/", -1);
boolean index = parts.length == 4 && "index".equals(parts[2]);
if (!"table".equals(parts[0]) || parts.length != 2 && !index) {
return Map.of();
}
TableDefinition table = AccountAwareStorageBackend.readInAccount(tableStore, parsed.accountId(),
regionKey(parsed.region(), parts[1])).orElse(null);
if (table == null || table.getTableArn() == null
|| !arn.equals(index ? table.getTableArn() + "/index/" + parts[3] : table.getTableArn())
|| index && !table.holdsIndex(parts[3])) {
return Map.of();
}
Map<String, String> tags = table.getTags();
return tags == null ? Map.of() : tags;
}
/** Result of a successful GetResourcePolicy call: the raw policy document and its revision id. */
public record ResourcePolicyResult(String policy, String revisionId) {}
@@ -0,0 +1,41 @@
package io.floci.aws.services.dynamodb;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.services.dynamodb.backend.DynamoDbTableAccess;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* What IAM asks DynamoDB of the resources a request names: the tags of the table an ARN names, or of the table whose
* index it names, from the selected backend.
*/
@ApplicationScoped
public class DynamoDbStoredResourceArns implements StoredResourceArns {
private final DynamoDbTableAccess tables;
@Inject
public DynamoDbStoredResourceArns(DynamoDbTableAccess tables) {
this.tables = tables;
}
@Override
public String namespace() {
return "dynamodb";
}
/** DynamoDB mints no id into an ARN a request names by its name, so there is nothing to find. */
@Override
public Optional<String> find(String type, List<String> names, String region) {
return Optional.empty();
}
@Override
public Map<String, String> storedTags(String arn) {
return tables.storedTags(arn);
}
}
@@ -155,7 +155,7 @@ public class NativeDynamoDbTableService {
applyOnDemandThroughput(table, settings.onDemandThroughput());
request.tags().forEach(table.getTags()::put);
dynamoDbService.putCreationTags(table, request.tags());
if (Boolean.TRUE.equals(settings.streamEnabled())) {
enableStream(table, settings.streamViewType(), region);
@@ -543,6 +543,36 @@ public class DynamoDbLocalBackend implements DynamoDbBackend {
}
}
/**
* The tags Floci records for the table {@code arn} names in the account and Region it names, matched on the whole
* ARN, or for the table whose index it names, when DynamoDB Local describes that table, and for an index as
* holding it, as ListTagsOfResource asks it; none for a table DynamoDB Local no longer has.
*/
@Override
public Map<String, String> storedTags(String arn) {
if (!AwsArnUtils.isArnFor(arn, "dynamodb")) {
return Map.of();
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
String[] parts = parsed.resource().split("/", -1);
boolean index = parts.length == 4 && "index".equals(parts[2]);
if (!"table".equals(parts[0]) || parts.length != 2 && !index) {
return Map.of();
}
String tableArn = AwsArnUtils.Arn.of("dynamodb", parsed.region(), parsed.accountId(), "table/" + parts[1])
.toString();
if (!arn.equals(index ? tableArn + "/index/" + parts[3] : tableArn)) {
return Map.of();
}
Map<String, String> held = AccountAwareStorageBackend.readInAccount(tags, parsed.accountId(),
key(parsed.region(), parts[1])).orElse(Map.of());
if (held.isEmpty() || !findTable(new Scope(parsed.accountId(), parsed.region()), parts[1])
.map(table -> !index || table.holdsIndex(parts[3])).orElse(false)) {
return Map.of();
}
return held;
}
private String existingTableKey(Scope scope, String resourceArn) {
if (!AwsArnUtils.looksLikeArn(resourceArn)) {
throw new AwsException("ValidationException", "Invalid TableArn", 400);
@@ -61,6 +61,13 @@ public interface DynamoDbTableAccess {
void untagResource(Scope scope, String resourceArn, List<String> tagKeys);
/**
* The tags held for the table {@code arn} names, or for the table whose index it names, as an index inherits its
* table's tags, in the account and Region the ARN names, read without changing anything; empty for an ARN naming
* no table or index held, or any other resource.
*/
Map<String, String> storedTags(String arn);
TableDefinition applyReplicaUpdates(Scope scope, String tableName, List<String> addRegions,
List<String> removeRegions);
@@ -264,6 +264,11 @@ public class NativeDynamoDbBackend implements DynamoDbBackend {
() -> dynamoDbService.untagResource(resourceArn, tagKeys, scope.region()));
}
@Override
public Map<String, String> storedTags(String arn) {
return dynamoDbService.storedTags(arn);
}
@Override
public TableDefinition applyReplicaUpdates(Scope scope, String tableName, List<String> addRegions,
List<String> removeRegions) {
@@ -31,7 +31,7 @@ public class TableDefinition {
private long warmReadUnitsPerSecond;
private long warmWriteUnitsPerSecond;
private String tableArn;
private Map<String, String> tags;
private volatile Map<String, String> tags;
private List<GlobalSecondaryIndex> globalSecondaryIndexes;
private List<LocalSecondaryIndex> localSecondaryIndexes;
private List<VectorIndex> vectorIndexes;
@@ -345,6 +345,12 @@ public class TableDefinition {
.findFirst();
}
/** Whether the table has a global secondary, local secondary or vector index of this name. */
public boolean holdsIndex(String indexName) {
return findGsi(indexName).isPresent() || findLsi(indexName).isPresent()
|| findVectorIndex(indexName).isPresent();
}
@JsonIgnore
public Optional<VectorIndex> findVectorIndex(String indexName) {
if (vectorIndexes == null || vectorIndexes.isEmpty() || indexName == null) {
@@ -169,6 +169,17 @@ class NativeDynamoDbTableServiceTest {
assertNoTableAndNoStream();
}
@Test
void creationTagsKeepATagATagResourceAlreadyPutOnTheStoredTable() {
TableDefinition table = dynamoDbService.createTable(TABLE, List.of(new KeySchemaElement("id", "HASH")),
List.of(new AttributeDefinition("id", "S")), 5L, 5L, REGION);
dynamoDbService.tagResource(table.getTableArn(), Map.of("stage", "prod", "team", "web"), REGION);
dynamoDbService.putCreationTags(table, Map.of("team", "data", "env", "test"));
assertEquals(Map.of("stage", "prod", "team", "web", "env", "test"), table.getTags());
}
@Test
void createSettingsSurviveARestart() {
Map<String, String> tags = new LinkedHashMap<>();
@@ -426,6 +426,31 @@ class DynamoDbLocalBackendTest {
assertEquals(Map.of("env", "dev"), backend.listTagsOfResource(SCOPE, ORDERS_ARN));
}
@Test
void storedTagsAreTheTagsHeldForTheTableTheArnNamesAndForAnIndexItHolds() throws Exception {
answer("DescribeTable", 200, "{\"Table\":{\"TableName\":\"orders\",\"TableArn\":\"" + LOCAL
+ "table/orders\",\"TableStatus\":\"ACTIVE\","
+ "\"GlobalSecondaryIndexes\":[{\"IndexName\":\"byCustomer\"}]}}");
backend.tagResource(SCOPE, ORDERS_ARN, Map.of("team", "data"));
assertEquals(Map.of("team", "data"), backend.storedTags(ORDERS_ARN));
assertEquals(Map.of("team", "data"), backend.storedTags(ORDERS_ARN + "/index/byCustomer"));
assertEquals(Map.of(), backend.storedTags(ORDERS_ARN + "/index/byStatus"));
assertEquals(Map.of(), backend.storedTags(PUBLIC + STREAM_RESOURCE));
assertEquals(Map.of(), backend.storedTags(ORDERS_ARN.replace(ACCOUNT, "111122223333")));
assertEquals(Map.of(), backend.storedTags(ORDERS_ARN.replace(REGION, "us-east-1")));
assertEquals(Map.of(), backend.storedTags("arn:aws-cn:dynamodb:" + REGION + ":" + ACCOUNT + ":table/orders"));
}
@Test
void storedTagsAreNoneForATableDynamoDbLocalNoLongerHas() throws Exception {
tags.putForAccount(ACCOUNT, REGION + "/orders", Map.of("team", "data"));
answer("DescribeTable", 400, "{\"__type\":\"com.amazonaws.dynamodb.v20120810#ResourceNotFoundException\","
+ "\"message\":\"Requested resource not found\"}");
assertEquals(Map.of(), backend.storedTags(ORDERS_ARN));
}
@Test
void deleteTableDropsTags() throws Exception {
tags.putForAccount(ACCOUNT, REGION + "/orders", Map.of("env", "dev"));
@@ -180,6 +180,37 @@ class DynamoDbNativeBackendTest {
assertEquals(json("{\"id\":{\"S\":\"k\"},\"n\":{\"N\":\"5\"}}"), backend.getItem(SCOPE, TABLE, key));
}
@Test
void storedTagsAreTheTablesForItAndItsIndexesInTheArnsAccountAndRegionAndTaggingPutsANewMap() throws Exception {
call(Api.DYNAMODB, "CreateTable", json("""
{"TableName":"%s",
"KeySchema":[{"AttributeName":"id","KeyType":"HASH"}],
"AttributeDefinitions":[{"AttributeName":"id","AttributeType":"S"},
{"AttributeName":"customer","AttributeType":"S"}],
"GlobalSecondaryIndexes":[{"IndexName":"byCustomer",
"KeySchema":[{"AttributeName":"customer","KeyType":"HASH"}],
"Projection":{"ProjectionType":"ALL"}}],
"BillingMode":"PAY_PER_REQUEST",
"Tags":[{"Key":"team","Value":"data"}]}
""".formatted(TABLE)));
String arn = backend.describeTable(SCOPE, TABLE).getTableArn();
Map<String, String> held = backend.listTagsOfResource(SCOPE, arn);
assertEquals(Map.of("team", "data"), backend.storedTags(arn));
assertEquals(Map.of("team", "data"), backend.storedTags(arn + "/index/byCustomer"));
assertEquals(Map.of(), backend.storedTags(arn + "/index/byStatus"));
assertEquals(Map.of(), backend.storedTags(arn + "/stream/2026-11-16T00:00:00.000"));
assertEquals(Map.of(), backend.storedTags(arn.replace(ACCOUNT, "111122223333")));
assertEquals(Map.of(), backend.storedTags(arn.replace(REGION, "us-west-2")));
assertEquals(Map.of(), backend.storedTags(arn.replace("arn:aws:", "arn:aws-cn:")));
backend.tagResource(SCOPE, arn, Map.of("stage", "prod"));
backend.untagResource(SCOPE, arn, List.of("team"));
assertEquals(Map.of("stage", "prod"), backend.storedTags(arn + "/index/byCustomer"));
assertEquals(Map.of("team", "data"), held);
}
@Test
void typedTimeToLiveIsWhatDescribeTimeToLiveReportsUnderTheScopesAccount() throws Exception {
Scope owner = new Scope("111122223333", REGION);
@@ -169,6 +169,12 @@ public final class RecordingDynamoDbBackend implements DynamoDbItemAccess, Dynam
record("untagResource", scope);
}
@Override
public Map<String, String> storedTags(String arn) {
invocations.add(new Invocation("storedTags", null, null));
return Map.of();
}
@Override
public TableDefinition applyReplicaUpdates(Scope scope, String tableName, List<String> addRegions,
List<String> removeRegions) {
@@ -2133,6 +2133,42 @@ class IamRequestResourceEnforcementIntegrationTest {
+ otherRegistry + "\"}}"), "glue:GetRegistry");
}
/**
* An {@code aws:ResourceTag} condition reads the tags DynamoDB holds on the table a request names, as created and
* as tagged later, so an allow on one team's tag lets the caller describe that team's tables and not another's.
*/
@Test
void aDynamoDbResourceTagConditionReadsTheTagsOfTheTable() {
String tagged = dynamoDbTable("res-tag-ddb-" + suffix(), "data");
String other = dynamoDbTable("res-tag-ddb-" + suffix(), "web");
User user = user("res-ddb-tags");
user.policy("{\"Effect\":\"Allow\",\"Action\":\"dynamodb:DescribeTable\",\"Resource\":\"*\","
+ "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}");
send(user, "dynamodb", "DynamoDB_20120810.DescribeTable", "1.0", "{\"TableName\":\"" + tagged + "\"}")
.statusCode(200);
refusedJson(send(user, "dynamodb", "DynamoDB_20120810.DescribeTable", "1.0", "{\"TableName\":\"" + other
+ "\"}"), "dynamodb:DescribeTable");
adminJson("dynamodb", "DynamoDB_20120810.TagResource", "1.0").body("{\"ResourceArn\":\"arn:aws:dynamodb:"
+ REGION + ":" + ACCOUNT + ":table/" + other + "\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"data\"}]}")
.post("/").then().statusCode(200);
send(user, "dynamodb", "DynamoDB_20120810.DescribeTable", "1.0", "{\"TableName\":\"" + other + "\"}")
.statusCode(200);
}
/** A DynamoDB table of the name, keyed on {@code id} and tagged with the team, deleted afterwards. */
private String dynamoDbTable(String name, String team) {
adminJson("dynamodb", "DynamoDB_20120810.CreateTable", "1.0").body("{\"TableName\":\"" + name + "\","
+ "\"KeySchema\":[{\"AttributeName\":\"id\",\"KeyType\":\"HASH\"}],"
+ "\"AttributeDefinitions\":[{\"AttributeName\":\"id\",\"AttributeType\":\"S\"}],"
+ "\"BillingMode\":\"PAY_PER_REQUEST\",\"Tags\":[{\"Key\":\"team\",\"Value\":\"" + team + "\"}]}")
.post("/").then().statusCode(200);
cleanup.register(() -> adminJson("dynamodb", "DynamoDB_20120810.DeleteTable", "1.0")
.body("{\"TableName\":\"" + name + "\"}").post("/"));
return name;
}
/**
* What Glue's batch deletes name, the tables of {@code TablesToDelete} and the connections of
* {@code ConnectionNameList}, is checked one by one, so a deny scoped to one of them holds under an allow on