fix(dynamodb): accept full ARN for TableName across operations (#575) (#580)

Real AWS DynamoDB accepts both short table names and full table ARNs for
TableName inputs. Floci only accepted short names, which broke OpenSearch
Data Prepper's dynamodb source plugin (requires table_arn) and any
Terraform flow that feeds aws_dynamodb_table.x.arn into the SDK.

- Add DynamoDbTableNames resolver: canonicalizes TableName input,
  rejects ARNs targeting index/stream resources, and rejects ARNs whose
  region does not match the request region (400 InvalidParameterValue,
  matching the #450 Lambda ARN precedent).
- Normalize at every DynamoDbService lookup boundary, including
  transaction condition paths and batch RequestItems map keys, so
  internal callers handling request-derived input cannot bypass the
  resolver.
- CreateTable explicitly rejects ARN-form TableName via requireShortName
  so ARN input cannot be persisted as the canonical table identity
  (which would produce nested ARN-on-ARN TableArn values).
- UpdateTable stream enable/disable now use the canonical
  table.getTableName() instead of the raw request TableName. Without
  this, calling UpdateTable via ARN keyed stream state under the ARN
  while reads canonicalize, stranding the stream.
- Covers DescribeTable, Scan, Query, GetItem, PutItem, UpdateItem,
  DeleteItem, BatchGetItem, BatchWriteItem, TransactGetItems,
  TransactWriteItems, UpdateTable, DeleteTable, DescribeTimeToLive,
  UpdateTimeToLive, DescribeContinuousBackups, UpdateContinuousBackups,
  Enable/DisableKinesisStreamingDestination.
- Tests: 32 resolver unit tests, 7 integration tests (item/batch/
  transact/TTL/backups/streaming/validation), 1 awscli bats case.
This commit is contained in:
TiM authored and GitHub committed 2026-04-23 22:32:40 -05:00
1 parent 3d6d6b17cc
commit df58c71d8b
7 files changed
+844 -49

No files matched your search

@@ -71,7 +71,7 @@ public class DynamoDbJsonHandler {
}
private Response handleCreateTable(JsonNode request, String region) {
String tableName = request.path("TableName").asText();
String tableName = DynamoDbTableNames.requireShortName(request.path("TableName").asText());
List<KeySchemaElement> keySchema = new ArrayList<>();
request.path("KeySchema").forEach(ks ->
@@ -523,12 +523,12 @@ public class DynamoDbJsonHandler {
if (streamEnabled) {
String viewType = streamSpec.path("StreamViewType").asText("NEW_AND_OLD_IMAGES");
StreamDescription sd = dynamoDbStreamService.enableStream(
tableName, table.getTableArn(), viewType, region);
table.getTableName(), table.getTableArn(), viewType, region);
table.setStreamEnabled(true);
table.setStreamArn(sd.getStreamArn());
table.setStreamViewType(viewType);
} else {
dynamoDbStreamService.disableStream(tableName, region);
dynamoDbStreamService.disableStream(table.getTableName(), region);
table.setStreamEnabled(false);
}
}
@@ -693,6 +693,7 @@ public class DynamoDbJsonHandler {
String streamArn = request.path("StreamArn").asText();
TableDefinition table = dynamoDbService.describeTable(tableName, region);
String resolvedTableName = table.getTableName();
String streamName = streamArn.substring(streamArn.lastIndexOf('/') + 1);
try {
@@ -717,16 +718,16 @@ public class DynamoDbJsonHandler {
if (!table.isStreamEnabled()) {
StreamDescription sd = dynamoDbStreamService.enableStream(
tableName, table.getTableArn(), "NEW_AND_OLD_IMAGES", region);
resolvedTableName, table.getTableArn(), "NEW_AND_OLD_IMAGES", region);
table.setStreamEnabled(true);
table.setStreamArn(sd.getStreamArn());
table.setStreamViewType("NEW_AND_OLD_IMAGES");
}
dynamoDbService.persistTable(tableName, table, region);
dynamoDbService.persistTable(resolvedTableName, table, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("TableName", tableName);
response.put("TableName", resolvedTableName);
response.put("StreamArn", streamArn);
response.put("DestinationStatus", "ACTIVE");
response.put("DestinationStatusDescription", "Kinesis streaming is enabled for this table");
@@ -738,6 +739,7 @@ public class DynamoDbJsonHandler {
String streamArn = request.path("StreamArn").asText();
TableDefinition table = dynamoDbService.describeTable(tableName, region);
String resolvedTableName = table.getTableName();
Optional<KinesisStreamingDestination> existing = table.findKinesisStreamingDestination(streamArn);
if (existing.isEmpty()) {
@@ -752,10 +754,10 @@ public class DynamoDbJsonHandler {
existing.get().setDestinationStatus("DISABLED");
existing.get().setDestinationStatusDescription("Kinesis streaming is disabled for this table");
dynamoDbService.persistTable(tableName, table, region);
dynamoDbService.persistTable(resolvedTableName, table, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("TableName", tableName);
response.put("TableName", resolvedTableName);
response.put("StreamArn", streamArn);
response.put("DestinationStatus", "DISABLED");
response.put("DestinationStatusDescription", "Kinesis streaming is disabled for this table");
@@ -767,7 +769,7 @@ public class DynamoDbJsonHandler {
TableDefinition table = dynamoDbService.describeTable(tableName, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("TableName", tableName);
response.put("TableName", table.getTableName());
ArrayNode destinations = objectMapper.createArrayNode();
for (KinesisStreamingDestination dest : table.getKinesisStreamingDestinations()) {
@@ -795,7 +797,7 @@ public class DynamoDbJsonHandler {
double cu = isWrite ? Math.max(1.0, itemCount) : Math.max(0.5, itemCount * 0.5);
ObjectNode cc = objectMapper.createObjectNode();
cc.put("TableName", tableName);
cc.put("TableName", DynamoDbTableNames.resolve(tableName));
cc.put("CapacityUnits", cu);
if ("INDEXES".equals(returnCC)) {
@@ -829,7 +831,7 @@ public class DynamoDbJsonHandler {
ArrayNode ccArray = objectMapper.createArrayNode();
for (String tableName : tableItems.keySet()) {
ObjectNode cc = objectMapper.createObjectNode();
cc.put("TableName", tableName);
cc.put("TableName", DynamoDbTableNames.resolve(tableName));
cc.put("CapacityUnits", isWrite ? 1.0 : 0.5);
if ("INDEXES".equals(returnCC)) {
ObjectNode tableCap = objectMapper.createObjectNode();
@@ -130,6 +130,11 @@ public class DynamoDbService {
List<GlobalSecondaryIndex> gsis,
List<LocalSecondaryIndex> lsis,
String region) {
// Enforce at the service boundary: CreateTable persists its input as the
// canonical table name and derives TableArn from it. An ARN-form input
// would produce ARN-on-ARN TableArn values. Handler-layer rejection alone
// would leave non-HTTP callers able to bypass the guard.
DynamoDbTableNames.requireShortName(tableName);
String storageKey = regionKey(region, tableName);
if (tableStore.get(storageKey).isPresent()) {
throw new AwsException("ResourceInUseException",
@@ -174,9 +179,10 @@ public class DynamoDbService {
}
public TableDefinition describeTable(String tableName, String region) {
String storageKey = regionKey(region, tableName);
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(tableName));
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
// Update dynamic counts
var items = itemsByTable.get(storageKey);
@@ -187,7 +193,8 @@ public class DynamoDbService {
}
public void persistTable(String tableName, TableDefinition table, String region) {
tableStore.put(regionKey(region, tableName), table);
String canonicalTableName = canonicalTableName(region, tableName);
tableStore.put(regionKey(region, canonicalTableName), table);
}
public void deleteTable(String tableName) {
@@ -195,9 +202,10 @@ public class DynamoDbService {
}
public void deleteTable(String tableName, String region) {
String storageKey = regionKey(region, tableName);
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
if (tableStore.get(storageKey).isEmpty()) {
throw resourceNotFoundException(tableName);
throw resourceNotFoundException(canonicalTableName);
}
tableStore.delete(storageKey);
itemsByTable.remove(storageKey);
@@ -205,9 +213,9 @@ public class DynamoDbService {
itemStore.delete(storageKey);
}
if (streamService != null) {
streamService.deleteStream(tableName, region);
streamService.deleteStream(canonicalTableName, region);
}
LOG.infov("Deleted table: {0}", tableName);
LOG.infov("Deleted table: {0}", canonicalTableName);
}
public List<String> listTables() {
@@ -233,9 +241,10 @@ public class DynamoDbService {
String conditionExpression,
JsonNode exprAttrNames, JsonNode exprAttrValues,
String region, String returnValuesOnConditionCheckFailure) {
String storageKey = regionKey(region, tableName);
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(tableName));
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
String itemKey = buildItemKey(table, item);
var tableItems = itemsByTable.computeIfAbsent(storageKey, k -> new ConcurrentSkipListMap<>());
@@ -248,11 +257,11 @@ public class DynamoDbService {
tableItems.put(itemKey, item);
persistItems(storageKey);
LOG.debugv("Put item in {0}: key={1}", tableName, itemKey);
LOG.debugv("Put item in {0}: key={1}", canonicalTableName, itemKey);
String eventName = existing == null ? "INSERT" : "MODIFY";
if (streamService != null) {
streamService.captureEvent(tableName, eventName, existing, item, table, region);
streamService.captureEvent(canonicalTableName, eventName, existing, item, table, region);
}
if (kinesisForwarder != null) {
kinesisForwarder.forward(eventName, existing, item, table, region);
@@ -264,9 +273,10 @@ public class DynamoDbService {
}
public JsonNode getItem(String tableName, JsonNode key, String region) {
String storageKey = regionKey(region, tableName);
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(tableName));
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
String itemKey = buildItemKey(table, key);
var items = itemsByTable.get(storageKey);
@@ -288,9 +298,10 @@ public class DynamoDbService {
String conditionExpression,
JsonNode exprAttrNames, JsonNode exprAttrValues,
String region, String returnValuesOnConditionCheckFailure) {
String storageKey = regionKey(region, tableName);
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(tableName));
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
String itemKey = buildItemKey(table, key);
var items = itemsByTable.get(storageKey);
@@ -303,11 +314,11 @@ public class DynamoDbService {
JsonNode removed = items.remove(itemKey);
persistItems(storageKey);
LOG.debugv("Deleted item from {0}: key={1}", tableName, itemKey);
LOG.debugv("Deleted item from {0}: key={1}", canonicalTableName, itemKey);
if (removed != null) {
if (streamService != null) {
streamService.captureEvent(tableName, "REMOVE", removed, null, table, region);
streamService.captureEvent(canonicalTableName, "REMOVE", removed, null, table, region);
}
if (kinesisForwarder != null) {
kinesisForwarder.forward("REMOVE", removed, null, table, region);
@@ -338,9 +349,10 @@ public class DynamoDbService {
JsonNode expressionAttrNames, JsonNode expressionAttrValues,
String returnValues, String conditionExpression, String region,
String returnValuesOnConditionCheckFailure) {
String storageKey = regionKey(region, tableName);
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(tableName));
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
String itemKey = buildItemKey(table, key);
var items = itemsByTable.computeIfAbsent(storageKey, k -> new ConcurrentSkipListMap<>());
@@ -388,7 +400,7 @@ public class DynamoDbService {
persistItems(storageKey);
if (streamService != null) {
streamService.captureEvent(tableName, "MODIFY", existing, item, table, region);
streamService.captureEvent(canonicalTableName, "MODIFY", existing, item, table, region);
}
if (kinesisForwarder != null) {
kinesisForwarder.forward("MODIFY", existing, item, table, region);
@@ -415,9 +427,10 @@ public class DynamoDbService {
JsonNode expressionAttrValues, String keyConditionExpression,
String filterExpression, Integer limit, Boolean scanIndexForward, String indexName,
JsonNode exclusiveStartKey, JsonNode exprAttrNames, String region) {
String storageKey = regionKey(region, tableName);
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(tableName));
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
var items = itemsByTable.get(storageKey);
if (items == null) return new QueryResult(List.of(), 0, null);
@@ -547,9 +560,10 @@ public class DynamoDbService {
public ScanResult scan(String tableName, String filterExpression,
JsonNode expressionAttrNames, JsonNode expressionAttrValues,
JsonNode scanFilter, Integer limit, JsonNode exclusiveStartKey, String region) {
String storageKey = regionKey(region, tableName);
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(tableName));
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
var items = itemsByTable.get(storageKey);
if (items == null) return new ScanResult(List.of(), 0, null);
@@ -610,7 +624,7 @@ public class DynamoDbService {
public BatchWriteResult batchWriteItem(Map<String, List<JsonNode>> requestItems, String region) {
for (Map.Entry<String, List<JsonNode>> entry : requestItems.entrySet()) {
String tableName = entry.getKey();
String tableName = canonicalTableName(region, entry.getKey());
for (JsonNode writeRequest : entry.getValue()) {
if (writeRequest.has("PutRequest")) {
JsonNode item = writeRequest.get("PutRequest").get("Item");
@@ -629,7 +643,8 @@ public class DynamoDbService {
public BatchGetResult batchGetItem(Map<String, JsonNode> requestItems, String region) {
Map<String, List<JsonNode>> responses = new HashMap<>();
for (Map.Entry<String, JsonNode> entry : requestItems.entrySet()) {
String tableName = entry.getKey();
String tableNameOrArn = entry.getKey();
String tableName = canonicalTableName(region, tableNameOrArn);
JsonNode tableRequest = entry.getValue();
JsonNode keys = tableRequest.get("Keys");
List<JsonNode> tableItems = new ArrayList<>();
@@ -641,7 +656,7 @@ public class DynamoDbService {
}
}
}
responses.put(tableName, tableItems);
responses.put(tableNameOrArn, tableItems);
}
return new BatchGetResult(responses, Map.of());
}
@@ -717,13 +732,14 @@ public class DynamoDbService {
? target.get("ReturnValuesOnConditionCheckFailure").asText() : null;
String tableName = target.path("TableName").asText();
String canonicalTableName = canonicalTableName(region, tableName);
JsonNode key = transactItem.has("Put") ? target.get("Item") : target.get("Key");
JsonNode exprAttrNames = target.has("ExpressionAttributeNames") ? target.get("ExpressionAttributeNames") : null;
JsonNode exprAttrValues = target.has("ExpressionAttributeValues") ? target.get("ExpressionAttributeValues") : null;
String storageKey = regionKey(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(tableName));
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
String itemKey = buildItemKey(table, key);
var tableItems = itemsByTable.get(storageKey);
@@ -761,9 +777,10 @@ public class DynamoDbService {
public TableDefinition updateTable(String tableName, Long readCapacity, Long writeCapacity,
List<GlobalSecondaryIndex> gsiCreates, List<String> gsiDeletes,
List<AttributeDefinition> newAttrDefs, String region) {
String storageKey = regionKey(region, tableName);
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(tableName));
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
if (readCapacity != null) {
table.getProvisionedThroughput().setReadCapacityUnits(readCapacity);
@@ -793,33 +810,35 @@ public class DynamoDbService {
}
tableStore.put(storageKey, table);
LOG.infov("Updated table: {0} in region {1}", tableName, region);
LOG.infov("Updated table: {0} in region {1}", canonicalTableName, region);
return table;
}
// --- TTL ---
public void updateTimeToLive(String tableName, String ttlAttributeName, boolean enabled, String region) {
String storageKey = regionKey(region, tableName);
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(tableName));
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
table.setTtlAttributeName(ttlAttributeName);
table.setTtlEnabled(enabled);
tableStore.put(storageKey, table);
LOG.infov("Updated TTL for table {0}: enabled={1}, attr={2}", tableName, enabled, ttlAttributeName);
LOG.infov("Updated TTL for table {0}: enabled={1}, attr={2}", canonicalTableName, enabled, ttlAttributeName);
}
public TableDefinition updateContinuousBackups(String tableName, boolean enabled,
Integer recoveryPeriodInDays, String region) {
String storageKey = regionKey(region, tableName);
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
TableDefinition table = tableStore.get(storageKey)
.orElseThrow(() -> resourceNotFoundException(tableName));
.orElseThrow(() -> resourceNotFoundException(canonicalTableName));
table.setPointInTimeRecoveryEnabled(enabled);
table.setPointInTimeRecoveryRecoveryPeriodInDays(
recoveryPeriodInDays != null ? recoveryPeriodInDays : table.getPointInTimeRecoveryRecoveryPeriodInDays());
tableStore.put(storageKey, table);
LOG.infov("Updated PITR for table {0}: enabled={1}, recoveryPeriodInDays={2}",
tableName, enabled, table.getPointInTimeRecoveryRecoveryPeriodInDays());
canonicalTableName, enabled, table.getPointInTimeRecoveryRecoveryPeriodInDays());
return table;
}
@@ -910,6 +929,10 @@ public class DynamoDbService {
"Requested resource not found: " + arn, 400));
}
private String canonicalTableName(String region, String tableName) {
return DynamoDbTableNames.resolveWithRegion(tableName, region).name();
}
// --- Condition expression evaluation ---
private void evaluateCondition(JsonNode existingItem, String conditionExpression,
@@ -0,0 +1,107 @@
package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.core.common.AwsException;
import java.util.regex.Pattern;
/**
* Resolves DynamoDB {@code TableName} inputs that may be either a short table
* name or a full table ARN.
*/
public final class DynamoDbTableNames {
private static final Pattern TABLE_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9_.-]{3,255}");
private static final Pattern ACCOUNT_PATTERN = Pattern.compile("\\d{12}");
private DynamoDbTableNames() {}
public record ResolvedTableRef(String name, String region) {}
public static String resolve(String input) {
return resolveInternal(input).name();
}
/**
* Validates a short table name. Rejects ARN-form input: callers (e.g. CreateTable)
* must persist a canonical short name, not an ARN that would produce ARN-on-ARN
* values when derived into {@code TableArn}.
*/
public static String requireShortName(String input) {
if (input == null || input.isBlank()) {
throw invalid("TableName must not be blank");
}
if (input.startsWith("arn:")) {
throw invalid("TableName must be a short name, not an ARN: " + input);
}
validateTableName(input);
return input;
}
public static ResolvedTableRef resolveWithRegion(String input, String requestRegion) {
ResolvedTableRef ref = resolveInternal(input);
if (ref.region() != null && !ref.region().equals(requestRegion)) {
throw invalid("Region '" + ref.region() + "' in ARN does not match request region '" + requestRegion + "'");
}
return ref;
}
private static ResolvedTableRef resolveInternal(String input) {
if (input == null || input.isBlank()) {
throw invalid("TableName must not be blank");
}
if (input.startsWith("arn:")) {
return parseArn(input);
}
validateTableName(input);
return new ResolvedTableRef(input, null);
}
private static ResolvedTableRef parseArn(String input) {
String[] parts = input.split(":", 6);
if (parts.length != 6) {
throw invalid("Invalid table ARN: " + input);
}
if (!"arn".equals(parts[0]) || !"aws".equals(parts[1]) || !"dynamodb".equals(parts[2])) {
throw invalid("Invalid table ARN: " + input);
}
String region = parts[3];
String account = parts[4];
String resource = parts[5];
if (region.isBlank()) {
throw invalid("Table ARN missing region: " + input);
}
if (!ACCOUNT_PATTERN.matcher(account).matches()) {
throw invalid("Table ARN has invalid account id: " + input);
}
if (!resource.startsWith("table/")) {
throw invalid("Table ARN resource must start with 'table/': " + input);
}
String tableResource = resource.substring("table/".length());
int slash = tableResource.indexOf('/');
String tableName = slash >= 0 ? tableResource.substring(0, slash) : tableResource;
if (tableName.isEmpty()) {
throw invalid("Table ARN is missing table name: " + input);
}
if (slash >= 0) {
String suffix = tableResource.substring(slash + 1);
if (suffix.startsWith("index/") || suffix.startsWith("stream/")) {
throw invalid("TableName does not accept index or stream ARNs: " + input);
}
throw invalid("Invalid table ARN: " + input);
}
validateTableName(tableName);
return new ResolvedTableRef(tableName, region);
}
private static void validateTableName(String tableName) {
if (!TABLE_NAME_PATTERN.matcher(tableName).matches()) {
throw invalid("Invalid TableName: " + tableName);
}
}
private static AwsException invalid(String message) {
return new AwsException("InvalidParameterValue", message, 400);
}
}