fix(dynamodb): refuse transaction requests whose members break their constraints (#7279)

This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-02 07:43:53 -04:00
1 parent 1b87483483
commit cf582c21be
3 files changed
+243 -21

No files matched your search

@@ -572,6 +572,15 @@ public class NativeDynamoDbJsonHandler {
+ "Member must satisfy enum value set: [INDEXES, TOTAL, NONE]";
}
private static String returnItemCollectionMetricsError(JsonNode request) {
JsonNode value = request.get("ReturnItemCollectionMetrics");
if (value == null || value.isNull() || VALID_RETURN_ITEM_COLLECTION_METRICS.contains(value.asText())) {
return null;
}
return "Value '" + value.asText() + "' at 'returnItemCollectionMetrics' failed to satisfy constraint: "
+ "Member must satisfy enum value set: [SIZE, NONE]";
}
private Response handlePutItem(JsonNode request, String region) {
String tableName = request.has("TableName") ? request.path("TableName").asText() : null;
DynamoDbTableNames.resolve(tableName); // validate tableName before other params
@@ -2418,7 +2427,7 @@ public class NativeDynamoDbJsonHandler {
}
private Response handleTransactWriteItems(JsonNode request, String region) {
JsonNode transactItemsNode = requireValidTransactRequest(request);
JsonNode transactItemsNode = requireValidTransactRequest(request, true);
for (JsonNode txItem : transactItemsNode) {
for (Map.Entry<String, JsonNode> action : txItem.properties()) {
@@ -2515,24 +2524,173 @@ public class NativeDynamoDbJsonHandler {
}
}
private static JsonNode requireValidTransactRequest(JsonNode request) {
JsonNode transactItems = request.path("TransactItems");
List<String> validationErrors = new ArrayList<>();
if (transactItems.isMissingNode() || transactItems.isNull() || !transactItems.isArray()) {
validationErrors.add("Value null at 'transactItems' failed to satisfy constraint: "
+ "Member must have length greater than or equal to 1");
} else if (transactItems.isEmpty()) {
validationErrors.add("Value '[]' at 'transactItems' failed to satisfy constraint: "
+ "Member must have length greater than or equal to 1");
} else if (transactItems.size() > 100) {
validationErrors.add("Value '" + transactItems + "' at 'transactItems' failed to satisfy constraint: "
+ "Member must have length less than or equal to 100");
// DynamoDB reads an action with more than one operation as the first one in this order.
private static final List<String> TRANSACT_WRITE_OPS = List.of("ConditionCheck", "Put", "Delete", "Update");
private static final int MAX_TRANSACT_ITEMS = 100;
// DynamoDB names the required members of an action in this order.
private static final Map<String, List<String>> TRANSACT_REQUIRED_MEMBERS = Map.of(
"Put", List.of("Item", "TableName"),
"Delete", List.of("Key", "TableName"),
"Update", List.of("UpdateExpression", "Key", "TableName"),
"ConditionCheck", List.of("ConditionExpression", "Key", "TableName"),
"Get", List.of("Key", "TableName"));
// DynamoDB's newer validator gives up on a request nested this deep, and the older one answers.
private static final int OLDER_VALIDATOR_DEPTH = 128;
private record TransactAction(int index, String type, JsonNode op) {
String path(String member) {
return "transactItems." + (index + 1) + ".member." + decapitalize(type) + "." + decapitalize(member);
}
}
// DynamoDB checks the lengths with its newer validator first. It skips that validator when a
// required member is missing or the request is nested too deep, and the older one checks the rest.
private static JsonNode requireValidTransactRequest(JsonNode request, boolean write) {
String token = write ? request.path("ClientRequestToken").textValue() : null;
List<String> memberErrors = new ArrayList<>();
if (token != null) {
addIfPresent(memberErrors, SmithyValidationErrors.lengthOutOfRange("clientRequestToken", token, 1,
MAX_CLIENT_REQUEST_TOKEN_LENGTH));
}
addReturnConsumedCapacityError(request, memberErrors);
if (write) {
addIfPresent(memberErrors, returnItemCollectionMetricsError(request));
}
JsonNode transactItems = request.path("TransactItems");
if (transactItems.isMissingNode() || transactItems.isNull() || !transactItems.isArray()) {
List<String> validationErrors = new ArrayList<>();
validationErrors.add(SmithyValidationErrors.notNull("transactItems"));
validationErrors.addAll(memberErrors);
throwValidationErrors(validationErrors);
}
List<String> ops = write ? TRANSACT_WRITE_OPS : List.of("Get");
List<TransactAction> actions = new ArrayList<>();
List<String> required = new ArrayList<>();
boolean missing = false;
boolean noOperation = false;
boolean manyOperations = false;
for (int i = 0; i < transactItems.size(); i++) {
JsonNode txItem = transactItems.get(i);
List<String> types = ops.stream().filter(txItem::hasNonNull).toList();
noOperation |= types.isEmpty();
manyOperations |= types.size() > 1;
if (!write && types.isEmpty()) {
required.add(SmithyValidationErrors.notNull("transactItems." + (i + 1) + ".member.get"));
missing = true;
}
if (types.isEmpty()) {
continue;
}
TransactAction action = new TransactAction(i, types.getFirst(), txItem.get(types.getFirst()));
actions.add(action);
for (String member : TRANSACT_REQUIRED_MEMBERS.get(action.type())) {
JsonNode value = action.op().get(member);
if (value == null || value.isNull()) {
required.add(SmithyValidationErrors.notNull(action.path(member)));
missing = true;
} else if ("TableName".equals(member) && value.asText().isEmpty()) {
required.add(SmithyValidationErrors.lengthTooShort(action.path(member), "", 1));
}
}
}
boolean older = transactDepth(transactItems, ops) >= OLDER_VALIDATOR_DEPTH;
if (!missing && !older) {
requireTransactLengths(transactItems.size(), actions, token);
}
if (transactItems.size() > MAX_TRANSACT_ITEMS) {
required.addFirst("Value '" + transactItems + "' at 'transactItems' failed to satisfy constraint: "
+ "Member must have length less than or equal to " + MAX_TRANSACT_ITEMS);
}
// The older validator stops at a missing member, before the operation and name checks.
if (!required.isEmpty()) {
required.addAll(memberErrors);
throwValidationErrors(required);
}
List<String> tableNames = new ArrayList<>();
for (TransactAction action : actions) {
String name = action.op().get("TableName").asText();
if (!AwsArnUtils.looksLikeArn(name)) {
tableNames.addAll(nameViolations(name, action.path("TableName")));
}
}
boolean refuseNoOperation = write && noOperation;
// A request too deep for the newer validator also gets an older answer for an empty action.
if (older) {
throwValidationErrors(memberErrors);
if (refuseNoOperation) {
throw new AwsException("ValidationException",
"Invalid Request: TransactWriteRequest should contain Delete or Put or Update request", 400);
}
throwValidationErrors(tableNames);
} else {
List<String> listed = refuseNoOperation
? new ArrayList<>(List.of("Value '' at 'transactItems' failed to satisfy constraint: "
+ "TransactWriteRequest should contain Delete or Put or Update or ConditionCheck"))
: tableNames;
listed.addAll(memberErrors);
throwValidationErrors(listed);
}
if (manyOperations) {
throw new AwsException("ValidationException",
"TransactItems can only contain one of Check, Put, Update or Delete", 400);
}
addReturnConsumedCapacityError(request, validationErrors);
throwValidationErrors(validationErrors);
return transactItems;
}
// The newer validator names a member by its 0-based position and leaves the value out.
private static void requireTransactLengths(int count, List<TransactAction> actions, String token) {
SmithyValidationErrors.Violations unquoted = SmithyValidationErrors.Violations.WITHOUT_VALUES;
List<String> validationErrors = new ArrayList<>();
if (token != null) {
addIfPresent(validationErrors, unquoted.lengthOutOfRange("ClientRequestToken", token, 1,
MAX_CLIENT_REQUEST_TOKEN_LENGTH));
}
addIfPresent(validationErrors, SmithyValidationErrors.sizeOutOfRange("TransactItems", count, 1,
MAX_TRANSACT_ITEMS));
for (TransactAction action : actions) {
addIfPresent(validationErrors, unquoted.lengthOutOfRange(
"TransactItems." + action.index() + ".member." + action.type() + ".TableName",
action.op().get("TableName").asText(), 1, 1024));
}
throwValidationErrors(validationErrors);
}
// DynamoDB leaves unknown members out when it measures how deep a request nests.
private static int transactDepth(JsonNode transactItems, List<String> ops) {
int deepest = 0;
for (JsonNode txItem : transactItems) {
for (String op : ops) {
for (String member : List.of("Item", "Key", "ExpressionAttributeValues")) {
deepest = Math.max(deepest, jsonDepth(txItem.path(op).path(member)));
}
}
}
// The request, TransactItems, the action and the operation hold these members.
return deepest + 4;
}
private static int jsonDepth(JsonNode node) {
int deepest = 0;
for (JsonNode child : node) {
deepest = Math.max(deepest, jsonDepth(child));
}
return node.isContainerNode() ? deepest + 1 : 0;
}
private static String decapitalize(String name) {
return Character.toLowerCase(name.charAt(0)) + name.substring(1);
}
private static void addIfPresent(List<String> validationErrors, String error) {
if (error != null) {
validationErrors.add(error);
}
}
private static void addReturnConsumedCapacityError(JsonNode request, List<String> validationErrors) {
String error = returnConsumedCapacityError(request);
if (error != null) {
@@ -2585,7 +2743,7 @@ public class NativeDynamoDbJsonHandler {
}
private Response handleTransactGetItems(JsonNode request, String region) {
JsonNode transactItemsNode = requireValidTransactRequest(request);
JsonNode transactItemsNode = requireValidTransactRequest(request, false);
transactItemsNode.forEach(txItem -> requireReadableValues(txItem.path("Get").path("Key"), ""));
for (JsonNode txItem : transactItemsNode) {
@@ -601,8 +601,8 @@ class DynamoDbConsumedCapacityIntegrationTest {
rejected("TransactWriteItems", """
{"TransactItems": [], "ReturnConsumedCapacity": "INVALID"}
""")
.body("message", equalTo("2 validation errors detected: Value '[]' at 'transactItems' failed to "
+ "satisfy constraint: Member must have length greater than or equal to 1; " + invalid));
.body("message", equalTo("1 validation error detected: Value at 'TransactItems' failed to "
+ "satisfy constraint: Member must have length greater than or equal to 1"));
send("TransactGetItems", """
{
@@ -2330,6 +2330,69 @@ class NativeDynamoDbJsonHandlerTest {
assertEquals(message, ex.getMessage());
}
@ParameterizedTest
@CsvSource(delimiter = '|', quoteCharacter = '`', textBlock = """
TransactWriteItems | {"TransactItems":[{"Put":{"TableName":"Tbl","Item":{}}},{"Update":{"TableName":"bad!name","Key":{},"UpdateExpression":"SET a = :a"}}]} | 1 validation error detected: Value 'bad!name' at 'transactItems.2.member.update.tableName' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+
TransactWriteItems | {"TransactItems":[{"ConditionCheck":{"TableName":"a!","Key":{},"ConditionExpression":"x"}}],"ReturnConsumedCapacity":"BOGUS","ReturnItemCollectionMetrics":"BOGUS2"} | 4 validation errors detected: Value 'a!' at 'transactItems.1.member.conditionCheck.tableName' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+; Value 'a!' at 'transactItems.1.member.conditionCheck.tableName' failed to satisfy constraint: Member must have length greater than or equal to 3; Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]; Value 'BOGUS2' at 'returnItemCollectionMetrics' failed to satisfy constraint: Member must satisfy enum value set: [SIZE, NONE]
TransactWriteItems | {"TransactItems":[],"ClientRequestToken":"0123456789012345678901234567890123456"} | 2 validation errors detected: Value at 'ClientRequestToken' failed to satisfy constraint: Member must have length less than or equal to 36; Value at 'TransactItems' failed to satisfy constraint: Member must have length greater than or equal to 1
TransactWriteItems | {"TransactItems":[{"Put":{"TableName":"bad!name","Item":{}}},{"Delete":{"TableName":"","Key":{}}}],"ReturnConsumedCapacity":"BOGUS"} | 1 validation error detected: Value at 'TransactItems.1.member.Delete.TableName' failed to satisfy constraint: Member must have length greater than or equal to 1
TransactWriteItems | {"TransactItems":[{"Put":{"TableName":""}}],"ClientRequestToken":"0123456789012345678901234567890123456","ReturnConsumedCapacity":"BOGUS"} | 4 validation errors detected: Value null at 'transactItems.1.member.put.item' failed to satisfy constraint: Member must not be null; Value '' at 'transactItems.1.member.put.tableName' failed to satisfy constraint: Member must have length greater than or equal to 1; Value '0123456789012345678901234567890123456' at 'clientRequestToken' failed to satisfy constraint: Member must have length less than or equal to 36; Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]
TransactWriteItems | {"TransactItems":[{"Update":{}},{"Put":{"TableName":"bad!name","Item":{}}}]} | 3 validation errors detected: Value null at 'transactItems.1.member.update.updateExpression' failed to satisfy constraint: Member must not be null; Value null at 'transactItems.1.member.update.key' failed to satisfy constraint: Member must not be null; Value null at 'transactItems.1.member.update.tableName' failed to satisfy constraint: Member must not be null
TransactWriteItems | {"TransactItems":[{"Put":{"TableName":"bad!name","Item":{}}},{"Foo":{}}],"ReturnConsumedCapacity":"BOGUS"} | 2 validation errors detected: Value '' at 'transactItems' failed to satisfy constraint: TransactWriteRequest should contain Delete or Put or Update or ConditionCheck; Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]
TransactWriteItems | {"TransactItems":[{"Put":{"TableName":"Tbl"}},{"Put":null}]} | 1 validation error detected: Value null at 'transactItems.1.member.put.item' failed to satisfy constraint: Member must not be null
TransactWriteItems | {"TransactItems":[{"Put":{"TableName":"Tbl","Item":{}},"Delete":{"TableName":"bad!name","Key":{}}}],"ReturnItemCollectionMetrics":"BOGUS2"} | 1 validation error detected: Value 'BOGUS2' at 'returnItemCollectionMetrics' failed to satisfy constraint: Member must satisfy enum value set: [SIZE, NONE]
TransactWriteItems | {"TransactItems":[{"Put":{"TableName":"Tbl","Item":{}},"Delete":{"TableName":"bad!name","Key":{}}}]} | TransactItems can only contain one of Check, Put, Update or Delete
TransactGetItems | {"TransactItems":[{"Get":{"TableName":"Tbl","Key":{}}},{"Get":{"TableName":"bad!name","Key":{}}}]} | 1 validation error detected: Value 'bad!name' at 'transactItems.2.member.get.tableName' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+
TransactGetItems | {"TransactItems":[{"Get":{"TableName":""}},{"Put":{}}],"ReturnConsumedCapacity":"BOGUS"} | 4 validation errors detected: Value null at 'transactItems.1.member.get.key' failed to satisfy constraint: Member must not be null; Value '' at 'transactItems.1.member.get.tableName' failed to satisfy constraint: Member must have length greater than or equal to 1; Value null at 'transactItems.2.member.get' failed to satisfy constraint: Member must not be null; Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]
TransactWriteItems | {"TransactItems":null,"ClientRequestToken":"0123456789012345678901234567890123456","ReturnConsumedCapacity":"BOGUS","ReturnItemCollectionMetrics":"BOGUS2"} | 4 validation errors detected: Value null at 'transactItems' failed to satisfy constraint: Member must not be null; Value '0123456789012345678901234567890123456' at 'clientRequestToken' failed to satisfy constraint: Member must have length less than or equal to 36; Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]; Value 'BOGUS2' at 'returnItemCollectionMetrics' failed to satisfy constraint: Member must satisfy enum value set: [SIZE, NONE]
TransactGetItems | {"ReturnConsumedCapacity":"BOGUS"} | 2 validation errors detected: Value null at 'transactItems' failed to satisfy constraint: Member must not be null; Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]
""")
void aTransactionReportsItsMemberErrorsTogether(String operation, String request, String message) throws Exception {
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle(operation, mapper.readTree(request), "eu-west-1"));
assertEquals("ValidationException", ex.getErrorCode());
assertEquals(message, ex.getMessage());
}
@ParameterizedTest
@CsvSource(delimiter = '|', quoteCharacter = '`', textBlock = """
61 | {"TransactItems":[{},{"Delete":{"TableName":"bad!name","Key":{}}}]} | Invalid Request: TransactWriteRequest should contain Delete or Put or Update request
61 | {"TransactItems":[{}],"ReturnConsumedCapacity":"BOGUS"} | 1 validation error detected: Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]
61 | {"TransactItems":[{"Put":{"TableName":"","Item":{}}}]} | 1 validation error detected: Value '' at 'transactItems.1.member.put.tableName' failed to satisfy constraint: Member must have length greater than or equal to 1
60 | {"TransactItems":[{"Put":{"TableName":"","Item":{}}}]} | 1 validation error detected: Value at 'TransactItems.0.member.Put.TableName' failed to satisfy constraint: Member must have length greater than or equal to 1
60 | {"TransactItems":[{}],"ReturnConsumedCapacity":"BOGUS"} | 2 validation errors detected: Value '' at 'transactItems' failed to satisfy constraint: TransactWriteRequest should contain Delete or Put or Update or ConditionCheck; Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]
""")
void aTransactionNestedTooDeepForTheNewerValidatorIsCheckedByTheOlderOne(int levels, String request,
String message) throws Exception {
ObjectNode body = (ObjectNode) mapper.readTree(request);
ObjectNode put = mapper.createObjectNode().put("TableName", "Tbl");
put.set("Item", mapper.createObjectNode().set("d", nestedMaps(levels)));
((ArrayNode) body.get("TransactItems")).add(mapper.createObjectNode().set("Put", put));
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("TransactWriteItems", body, "eu-west-1"));
assertEquals(message, ex.getMessage());
}
@ParameterizedTest
@CsvSource(delimiter = '|', textBlock = """
TransactWriteItems | {"TransactItems":[]} | 1 validation error detected: Value at 'TransactItems' failed to satisfy constraint: Member must have length greater than or equal to 1
TransactGetItems | {"TransactItems":[]} | 1 validation error detected: Value at 'TransactItems' failed to satisfy constraint: Member must have length greater than or equal to 1
TransactWriteItems | {"TransactItems":[{"Put":{"TableName":"","Item":{}}}]} | 1 validation error detected: Value at 'TransactItems.0.member.Put.TableName' failed to satisfy constraint: Member must have length greater than or equal to 1
""")
void aTransactionNestedDeepInUnknownMembersIsCheckedByTheNewerValidator(String operation, String request,
String message) throws Exception {
ObjectNode body = (ObjectNode) mapper.readTree(request);
body.set("Foo", nestedMaps(63));
for (JsonNode action : body.get("TransactItems")) {
action.forEach(op -> ((ObjectNode) op).set("Foo", nestedMaps(63)));
((ObjectNode) action).set("Foo", nestedMaps(63));
}
AwsException ex = assertThrows(AwsException.class, () -> handler.handle(operation, body, "eu-west-1"));
assertEquals(message, ex.getMessage());
}
@Test
void updateItemRejectsAnAttributeUpdatesValueWithALeafAtLevel33BeforeTheTableLookup() {
ObjectNode request = updateUserRequest();
@@ -2752,9 +2815,10 @@ class NativeDynamoDbJsonHandlerTest {
void transactWriteItemsCancelsOnAConditionCheckKeyMissingItsAttribute() throws Exception {
createUsersTable("eu-west-1");
Response response = handler.handle("TransactWriteItems",
transactWriteOf(transactMember("ConditionCheck", "Users", "Key", mapper.createObjectNode())),
"eu-west-1");
ObjectNode check = transactMember("ConditionCheck", "Users", "Key", mapper.createObjectNode());
((ObjectNode) check.get("ConditionCheck")).put("ConditionExpression", "attribute_exists(userId)");
Response response = handler.handle("TransactWriteItems", transactWriteOf(check), "eu-west-1");
assertEquals("The provided key element does not match the schema", onlyValidationErrorMessage(response));
}