fix(dynamodb): refuse a Key that holds non-key attributes (#9677)

DynamoDB refuses a Key argument that holds any attribute outside the
table's key schema with "The provided key element does not match the
schema". Floci only checked that the key attributes were present and
well typed, so passing a whole item as the Key of GetItem, DeleteItem or
UpdateItem succeeded.

- check the attribute names of every Key argument in buildItemKey:
  GetItem, DeleteItem, UpdateItem, BatchGetItem keys, BatchWriteItem
  DeleteRequest keys, TransactGetItems and the TransactWriteItems
  Update, Delete and ConditionCheck keys
- split BatchWriteItem DeleteRequest keys (new BATCH_DELETE surface) from
  PutRequest items, which still accept whole items, as PutItem and the
  TransactWriteItems Put do
- look up the previous item for BatchWriteItem write capacity by its key
  attributes only, instead of passing the whole PutRequest item as a Key
- one DynamoDbKeyAttributes.of helper replaces the key extraction copies
  in DynamoDbStreamService, KinesisStreamingForwarder and the
  BatchWriteItem capacity lookup

Closes #9676
This commit is contained in:
Mahmoud Khalifa authored and GitHub committed 2026-11-29 12:31:23 -04:00
1 parent a5a4489ce1
commit 85a2c03434
7 files changed
+258 -36

No files matched your search

@@ -0,0 +1,27 @@
package io.floci.aws.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.services.dynamodb.model.KeySchemaElement;
import io.floci.aws.services.dynamodb.model.TableDefinition;
final class DynamoDbKeyAttributes {
private DynamoDbKeyAttributes() {}
/** The table's key attributes that the item holds, in key schema order; empty for a null item. */
static ObjectNode of(JsonNode item, TableDefinition table) {
ObjectNode keys = JsonNodeFactory.instance.objectNode();
if (item == null) {
return keys;
}
for (KeySchemaElement element : table.getKeySchema()) {
String name = element.getAttributeName();
if (item.has(name)) {
keys.set(name, item.get(name));
}
}
return keys;
}
}
@@ -2037,7 +2037,7 @@ public class DynamoDbService {
if (key == null) {
throw new AwsException("ValidationException", "Key is required for DeleteRequest", 400);
}
itemKey = buildItemKey(table, key, KeySurface.BATCH_WRITE);
itemKey = buildItemKey(table, key, KeySurface.BATCH_DELETE);
} else {
continue;
}
@@ -4868,7 +4868,8 @@ public class DynamoDbService {
// AWS words a key rejection by the surface the key arrived on. A PutItem item body
// names the mismatched types, a Key argument and a BatchWriteItem entry report a
// schema mismatch instead. An empty key value is worded the same on every surface.
enum KeySurface { ITEM_BODY, KEY_ARGUMENT, BATCH_WRITE }
// A Key argument and a BatchWriteItem DeleteRequest key may hold only the key attributes.
enum KeySurface { ITEM_BODY, KEY_ARGUMENT, BATCH_WRITE, BATCH_DELETE }
String buildItemKey(TableDefinition table, JsonNode item) {
return buildItemKey(table, item, KeySurface.ITEM_BODY);
@@ -4879,6 +4880,24 @@ public class DynamoDbService {
}
String buildItemKey(TableDefinition table, JsonNode item, KeySurface surface) {
String itemKey = buildItemKeyValues(table, item, surface);
if (surface == KeySurface.KEY_ARGUMENT || surface == KeySurface.BATCH_DELETE) {
requireKeyElementsOnly(table, item);
}
return itemKey;
}
void requireKeyElementsOnly(TableDefinition table, JsonNode key) {
String pkName = table.getPartitionKeyName();
String skName = table.getSortKeyName();
for (String name : (Iterable<String>) key::fieldNames) {
if (!name.equals(pkName) && !name.equals(skName)) {
throw new KeySchemaMismatchException("The provided key element does not match the schema");
}
}
}
private String buildItemKeyValues(TableDefinition table, JsonNode item, KeySurface surface) {
String pkName = table.getPartitionKeyName();
JsonNode pkAttr = item.get(pkName);
if (pkAttr == null) {
@@ -250,7 +250,7 @@ public class DynamoDbStreamService {
}
JsonNode sourceItem = newItem != null ? newItem : oldItem;
ObjectNode keys = buildKeys(sourceItem, table);
ObjectNode keys = DynamoDbKeyAttributes.of(sourceItem, table);
String viewType = sd.getStreamViewType();
JsonNode newImage = buildImage(newItem, viewType, true);
@@ -308,20 +308,6 @@ public class DynamoDbStreamService {
return 0;
}
private ObjectNode buildKeys(JsonNode item, TableDefinition table) {
ObjectNode keys = objectMapper.createObjectNode();
if (item == null) {
return keys;
}
for (KeySchemaElement ks : table.getKeySchema()) {
String attrName = ks.getAttributeName();
if (item.has(attrName)) {
keys.set(attrName, item.get(attrName));
}
}
return keys;
}
private JsonNode buildImage(JsonNode item, String viewType, boolean isNewImage) {
if (item == null) {
return null;
@@ -5,7 +5,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.DelayedTaskScheduler;
import io.floci.aws.services.dynamodb.model.KeySchemaElement;
import io.floci.aws.services.dynamodb.model.KinesisStreamingDestination;
import io.floci.aws.services.dynamodb.model.TableDefinition;
import io.floci.aws.services.kinesis.KinesisService;
@@ -158,7 +157,7 @@ public class KinesisStreamingForwarder {
Instant now = Instant.now();
JsonNode sourceItem = newItem != null ? newItem : oldItem;
ObjectNode keys = buildKeys(sourceItem, table);
ObjectNode keys = DynamoDbKeyAttributes.of(sourceItem, table);
// One serialized payload per precision in use: every destination sees the same event (same eventID),
// stamped at the resolution its ApproximateCreationDateTimePrecision asks for.
@@ -482,20 +481,6 @@ public class KinesisStreamingForwarder {
return timestamp.toEpochMilli();
}
private ObjectNode buildKeys(JsonNode item, TableDefinition table) {
ObjectNode keys = objectMapper.createObjectNode();
if (item == null) {
return keys;
}
for (KeySchemaElement ks : table.getKeySchema()) {
String attrName = ks.getAttributeName();
if (item.has(attrName)) {
keys.set(attrName, item.get(attrName));
}
}
return keys;
}
private String extractPartitionKey(JsonNode keys, TableDefinition table) {
if (keys == null || keys.isEmpty()) {
return "default";
@@ -1809,8 +1809,8 @@ public class NativeDynamoDbJsonHandler {
JsonNode keyNode = writeReq.has("PutRequest")
? writeReq.get("PutRequest").get("Item")
: writeReq.get("DeleteRequest").get("Key");
String key = dynamoDbService.buildItemKey(bwTable, keyNode,
DynamoDbService.KeySurface.BATCH_WRITE);
String key = dynamoDbService.buildItemKey(bwTable, keyNode, writeReq.has("PutRequest")
? DynamoDbService.KeySurface.BATCH_WRITE : DynamoDbService.KeySurface.BATCH_DELETE);
if (!seen.add(key)) {
throw new AwsException("ValidationException",
"Provided list of item keys contains duplicates", 400);
@@ -1833,7 +1833,8 @@ public class NativeDynamoDbJsonHandler {
JsonNode keyNode = writeReq.has("PutRequest")
? writeReq.get("PutRequest").get("Item")
: writeReq.get("DeleteRequest").get("Key");
JsonNode previous = dynamoDbService.getItem(entry.getKey(), keyNode, region);
JsonNode previous = dynamoDbService.getItem(entry.getKey(),
DynamoDbKeyAttributes.of(keyNode, costTable), region);
cost = cost.plus(DynamoDbWriteCapacity.forWrite(costTable, previous, newItem));
}
costs.put(entry.getKey(), cost);
@@ -1929,6 +1930,7 @@ public class NativeDynamoDbJsonHandler {
Set<String> seen = new HashSet<>();
for (JsonNode key : keys) {
String itemKey = dynamoDbService.buildItemKey(bgTable, key);
dynamoDbService.requireKeyElementsOnly(bgTable, key);
if (!seen.add(itemKey)) {
throw new AwsException("ValidationException",
"Provided list of item keys contains duplicates", 400);
@@ -31,6 +31,7 @@ import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import java.io.ByteArrayInputStream;
@@ -5439,6 +5440,158 @@ class DynamoDbServiceTest {
latestRestorableLagSeconds, clock);
}
private static final String KEY_MISMATCH = "The provided key element does not match the schema";
private static String keyMismatchTable(boolean hashRange) {
return hashRange ? "Orders" : "Users";
}
private ObjectNode keyOnly(boolean hashRange) {
return hashRange ? item("customerId", "c1", "orderId", "o1") : item("userId", "u1");
}
// Seeds one item with a non-key "note" attribute and returns that whole item.
private ObjectNode seedKeyMismatchItem(boolean hashRange, String region) {
ObjectNode whole = keyOnly(hashRange);
whole.set("note", attributeValue("S", "kept"));
if (hashRange) {
createOrdersTable(region);
} else {
createUsersTable(region);
}
service.putItem(keyMismatchTable(hashRange), whole, region);
return whole;
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void getItem_keyWithNonKeyAttribute_rejected(boolean hashRange) {
String region = "eu-west-1";
ObjectNode whole = seedKeyMismatchItem(hashRange, region);
AwsException error = assertThrows(AwsException.class, () ->
service.getItem(keyMismatchTable(hashRange), whole, region));
assertEquals("ValidationException", error.getErrorCode());
assertEquals(KEY_MISMATCH, error.getMessage());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void deleteItem_keyWithNonKeyAttribute_rejectedAndItemKept(boolean hashRange) {
String region = "eu-west-1";
ObjectNode whole = seedKeyMismatchItem(hashRange, region);
AwsException error = assertThrows(AwsException.class, () ->
service.deleteItem(keyMismatchTable(hashRange), whole, region));
assertEquals(KEY_MISMATCH, error.getMessage());
assertNotNull(service.getItem(keyMismatchTable(hashRange), keyOnly(hashRange), region));
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void updateItem_keyWithNonKeyAttribute_rejectedAndItemUnchanged(boolean hashRange) {
String region = "eu-west-1";
ObjectNode whole = seedKeyMismatchItem(hashRange, region);
ObjectNode values = mapper.createObjectNode();
values.set(":n", attributeValue("S", "changed"));
AwsException error = assertThrows(AwsException.class, () ->
service.updateItem(keyMismatchTable(hashRange), whole, null, "SET #n = :n",
mapper.createObjectNode().put("#n", "note"), values, null, region));
assertEquals(KEY_MISMATCH, error.getMessage());
assertEquals("kept", service.getItem(keyMismatchTable(hashRange), keyOnly(hashRange), region)
.path("note").path("S").asText());
}
@Test
void batchGetItem_keyWithNonKeyAttribute_rejected() {
createUsersTable("us-east-1");
service.putItem("Users", item("userId", "u1", "name", "Alice"), "us-east-1");
ObjectNode request = mapper.createObjectNode();
request.set("Keys", mapper.createArrayNode().add(item("userId", "u1", "name", "Alice")));
AwsException error = assertThrows(AwsException.class, () ->
service.batchGetItem(Map.of("Users", request), "us-east-1"));
assertEquals(KEY_MISMATCH, error.getMessage());
}
@Test
void batchWriteItem_deleteRequestKeyWithNonKeyAttribute_rejected() {
createUsersTable("us-east-1");
service.putItem("Users", item("userId", "u1", "name", "Alice"), "us-east-1");
AwsException error = assertThrows(AwsException.class, () -> service.batchWriteItem(
Map.of("Users", List.of(deleteRequest(item("userId", "u1", "name", "Alice")))), "us-east-1"));
assertEquals(KEY_MISMATCH, error.getMessage());
assertNotNull(service.getItem("Users", item("userId", "u1"), "us-east-1"));
}
@Test
void batchWriteItem_putRequestFullItem_stillAccepted() {
createUsersTable("us-east-1");
service.batchWriteItem(
Map.of("Users", List.of(putRequest(item("userId", "u1", "name", "Alice")))), "us-east-1");
assertEquals("Alice", service.getItem("Users", item("userId", "u1"), "us-east-1")
.path("name").path("S").asText());
}
@Test
void transactGetItems_keyWithNonKeyAttribute_rejected() throws Exception {
String region = "eu-west-1";
createUsersTable(region);
service.putItem("Users", item("userId", "u1", "name", "Alice"), region);
JsonNode get = mapper.readTree("""
{"Get":{"TableName":"Users","Key":{"userId":{"S":"u1"},"name":{"S":"Alice"}}}}
""");
assertThrows(TransactionCanceledException.class, () -> service.transactGetItems(List.of(get), region));
}
@Test
void transactWriteItems_updateKeyWithNonKeyAttribute_rejected() throws Exception {
String region = "eu-west-1";
createUsersTable(region);
service.putItem("Users", item("userId", "u1", "name", "Alice"), region);
JsonNode update = mapper.readTree("""
{"Update":{"TableName":"Users","Key":{"userId":{"S":"u1"},"name":{"S":"Alice"}},
"UpdateExpression":"SET #n = :n",
"ExpressionAttributeNames":{"#n":"name"},
"ExpressionAttributeValues":{":n":{"S":"Bob"}}}}
""");
assertThrows(TransactionCanceledException.class, () -> service.transactWriteItems(List.of(update), region));
assertEquals("Alice", service.getItem("Users", item("userId", "u1"), region).path("name").path("S").asText());
}
@Test
void transactWriteItems_deleteKeyWithNonKeyAttribute_rejected() throws Exception {
String region = "eu-west-1";
createUsersTable(region);
service.putItem("Users", item("userId", "u1", "name", "Alice"), region);
JsonNode delete = mapper.readTree("""
{"Delete":{"TableName":"Users","Key":{"userId":{"S":"u1"},"name":{"S":"Alice"}}}}
""");
assertThrows(TransactionCanceledException.class, () -> service.transactWriteItems(List.of(delete), region));
assertNotNull(service.getItem("Users", item("userId", "u1"), region));
}
@Test
void validateTransactMemberKeys_conditionCheckKeyWithNonKeyAttribute_rejected() throws Exception {
String region = "eu-west-1";
createUsersTable(region);
service.putItem("Users", item("userId", "u1", "name", "Alice"), region);
JsonNode check = mapper.readTree("""
{"ConditionCheck":{"TableName":"Users","Key":{"userId":{"S":"u1"},"name":{"S":"Alice"}},
"ConditionExpression":"attribute_exists(userId)"}}
""");
assertThrows(TransactionCanceledException.class,
() -> service.validateTransactMemberKeysAndSizes(List.of(check), region));
}
private static List<String> userIds(DynamoDbService.PointInTimeState state) {
return state.items().stream().map(i -> i.path("userId").path("S").asText()).sorted().toList();
}
@@ -4869,4 +4869,54 @@ class NativeDynamoDbJsonHandlerTest {
assertEquals(type, ex.getErrorCode());
assertEquals(message, ex.getMessage());
}
@Test
void getItem_keyWithNonKeyAttribute_rejected() {
createUsersTable("eu-west-1");
ObjectNode request = mapper.createObjectNode();
request.put("TableName", "Users");
request.set("Key", item("userId", "u1", "name", "Alice"));
AwsException ex = assertThrows(AwsException.class, () -> handler.handle("GetItem", request, "eu-west-1"));
assertEquals("ValidationException", ex.getErrorCode());
assertEquals("The provided key element does not match the schema", ex.getMessage());
}
@Test
void batchGetItem_keyWithNonKeyAttribute_rejected() {
createUsersTable("eu-west-1");
ObjectNode request = mapper.createObjectNode();
request.set("RequestItems", mapper.createObjectNode().set("Users", mapper.createObjectNode()
.set("Keys", mapper.createArrayNode().add(item("userId", "u1", "name", "Alice")))));
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("BatchGetItem", request, "eu-west-1"));
assertEquals("ValidationException", ex.getErrorCode());
assertEquals("The provided key element does not match the schema", ex.getMessage());
}
@Test
void batchWriteItem_deleteRequestKeyWithNonKeyAttribute_rejected() {
createUsersTable("eu-west-1");
ObjectNode deleteRequest = mapper.createObjectNode();
deleteRequest.set("DeleteRequest", mapper.createObjectNode().set("Key", item("userId", "u1", "name", "Alice")));
ObjectNode request = mapper.createObjectNode();
request.set("RequestItems", mapper.createObjectNode().set("Users", mapper.createArrayNode().add(deleteRequest)));
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("BatchWriteItem", request, "eu-west-1"));
assertEquals("ValidationException", ex.getErrorCode());
assertEquals("The provided key element does not match the schema", ex.getMessage());
}
@Test
void batchWriteItem_putRequestFullItem_stillAccepted() {
createUsersTable("eu-west-1");
ObjectNode putRequest = mapper.createObjectNode();
putRequest.set("PutRequest", mapper.createObjectNode().set("Item", item("userId", "u1", "name", "Alice")));
ObjectNode request = mapper.createObjectNode();
request.set("RequestItems", mapper.createObjectNode().set("Users", mapper.createArrayNode().add(putRequest)));
assertDoesNotThrow(() -> handler.handle("BatchWriteItem", request, "eu-west-1"));
}
}