fix(dynamodb): use the older check order and wording for a PutItem or DeleteItem without Item or Key or nested too deep (#7480)

This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-04 05:57:17 -04:00
1 parent eaefd55980
commit e105843426
5 files changed
+164 -4

No files matched your search

@@ -247,6 +247,23 @@ final class DynamoDbAttributeValueValidator {
return false;
}
static boolean hasUnknownMember(JsonNode value) {
if (value.properties().stream().anyMatch(member -> !TYPES.contains(member.getKey()))) {
return true;
}
for (JsonNode member : value.path("M")) {
if (hasUnknownMember(member)) {
return true;
}
}
for (JsonNode element : value.path("L")) {
if (hasUnknownMember(element)) {
return true;
}
}
return false;
}
private static int depthOf(JsonNode value) {
if (!value.isObject()) {
return 1;
@@ -4,6 +4,8 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
@@ -117,15 +119,22 @@ public final class DynamoDbTableNames {
/** The violation for a short table name, or {@code null} for a valid one. A bad length hides a bad pattern. */
static String nameViolation(String tableName) {
List<String> violations = nameViolations(tableName);
return violations.isEmpty() ? null : violations.getFirst();
}
/** Every violation of a short table name, the length first. */
static List<String> nameViolations(String tableName) {
List<String> violations = new ArrayList<>();
String lengthViolation = SmithyValidationErrors.lengthOutOfRange("tableName", tableName, 3, 255);
if (lengthViolation != null) {
return lengthViolation;
violations.add(lengthViolation);
}
if (!TABLE_NAME_CHARS.matcher(tableName).matches()) {
return "Value '" + tableName
+ "' at 'tableName' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+";
violations.add("Value '" + tableName
+ "' at 'tableName' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+");
}
return null;
return violations;
}
private static AwsException invalid(String message) {
@@ -615,7 +615,88 @@ public class NativeDynamoDbJsonHandler {
throwValidationErrors(validationErrors);
}
// DynamoDB's newer validator gives up on an attribute value with a member it does not know.
// It leaves the other unknown members out when it measures how deep a request nests.
private static boolean readByOlderValidator(JsonNode request, String target) {
if (!request.hasNonNull(target)) {
return true;
}
List<JsonNode> values = new ArrayList<>();
request.path(target).forEach(values::add);
request.path("ExpressionAttributeValues").forEach(values::add);
int deepest = Math.max(jsonDepth(request.path(target)), jsonDepth(request.path("ExpressionAttributeValues")));
for (JsonNode condition : request.path("Expected")) {
values.add(condition.path("Value"));
condition.path("AttributeValueList").forEach(values::add);
int known = Math.max(jsonDepth(condition.path("Value")), jsonDepth(condition.path("AttributeValueList")));
// Expected and the condition hold these members.
deepest = Math.max(deepest, known + 2);
}
// The request holds these members.
return deepest + 1 >= OLDER_VALIDATOR_DEPTH
|| values.stream().anyMatch(DynamoDbAttributeValueValidator::hasUnknownMember);
}
private static final List<String> OLDER_RETURN_VALUES =
List.of("ALL_NEW", "UPDATED_OLD", "ALL_OLD", "NONE", "UPDATED_NEW");
private static final List<String> OLDER_CONDITIONAL_OPERATORS = List.of("OR", "AND");
// The older validator lists the members in this order and leaves out a missing table name.
private void requireValidOlderItemWrite(JsonNode request, String target) {
String tableName = textOrNull(request, "TableName");
String returnValues = textOrNull(request, "ReturnValues");
List<String> validationErrors = new ArrayList<>();
if (returnValues != null && !OLDER_RETURN_VALUES.contains(returnValues)) {
validationErrors.add(SmithyValidationErrors.notInEnum(returnValues, "returnValues", OLDER_RETURN_VALUES));
}
String conditionalOperator = textOrNull(request, "ConditionalOperator");
if (conditionalOperator != null && !OLDER_CONDITIONAL_OPERATORS.contains(conditionalOperator)) {
validationErrors.add(SmithyValidationErrors.notInEnum(conditionalOperator, "conditionalOperator",
OLDER_CONDITIONAL_OPERATORS));
}
if ("Item".equals(target) && !request.hasNonNull(target)) {
validationErrors.add(SmithyValidationErrors.notNull("item"));
}
addPartiQLReturnValuesError(request, "returnValuesOnConditionCheckFailure", validationErrors);
addReturnConsumedCapacityError(request, validationErrors);
addIfPresent(validationErrors, returnItemCollectionMetricsError(request));
if ("Key".equals(target) && !request.hasNonNull(target)) {
validationErrors.add(SmithyValidationErrors.notNull("key"));
}
if ("".equals(tableName)) {
validationErrors.add(SmithyValidationErrors.lengthTooShort("tableName", "", 1));
}
throwValidationErrors(validationErrors);
if (AwsArnUtils.looksLikeArn(tableName)) {
DynamoDbTableNames.resolve(tableName);
} else if (tableName != null) {
throwValidationErrors(DynamoDbTableNames.nameViolations(tableName));
}
if (returnValues != null && !VALID_RETURN_VALUES_ITEM_WRITE.contains(returnValues)) {
throw new AwsException("ValidationException", "ReturnValues can only be ALL_OLD or NONE", 400);
}
rejectMixedParameters(request, List.of("Expected"), List.of("ConditionExpression"));
// Only the ExpressionAttributeValues message names the missing expression.
if (!request.has("ConditionExpression") && request.has("ExpressionAttributeNames")) {
throw new AwsException("ValidationException",
"ExpressionAttributeNames can only be specified when using expressions", 400);
}
rejectExprAttrsWithoutExpression(null, request.get("ExpressionAttributeValues"),
request.has("ConditionExpression"), "ConditionExpression is null");
JsonNode values = request.get(target);
DynamoDbAttributeValueValidator.requireNestingWithinLimit(values, false);
requireReadableValues(values, "");
DynamoDbAttributeValueValidator.requireNonEmptyNames(values);
DynamoDbAttributeValueValidator.requireNonEmptyMemberNames(values);
requireNamedExpressionValues(request.get("ExpressionAttributeValues"));
DynamoDbAttributeValueValidator.requireNestingWithinLimit(legacyValues(request.get("Expected")), false);
}
private Response handlePutItem(JsonNode request, String region) {
if (readByOlderValidator(request, "Item")) {
requireValidOlderItemWrite(request, "Item");
}
String tableName = request.has("TableName") ? request.path("TableName").asText() : null;
requireValidItemWriteMembers(request, tableName);
JsonNode item = request.path("Item");
@@ -722,6 +803,9 @@ public class NativeDynamoDbJsonHandler {
Set.of("NONE", "ALL_OLD", "ALL_NEW", "UPDATED_OLD", "UPDATED_NEW");
private Response handleDeleteItem(JsonNode request, String region) {
if (readByOlderValidator(request, "Key")) {
requireValidOlderItemWrite(request, "Key");
}
String tableName = request.path("TableName").asText();
requireValidItemWriteMembers(request, tableName);
JsonNode key = request.path("Key");
@@ -5882,6 +5882,27 @@ given()
.body("message", equalTo(message));
}
@ParameterizedTest
@CsvSource(delimiter = '|', quoteCharacter = '`', textBlock = """
DeleteItem | {"TableName": "Missing", "ReturnValues": "BOGUS", "ReturnConsumedCapacity": "BOGUS"} | 3 validation errors detected: Value 'BOGUS' at 'returnValues' failed to satisfy constraint: Member must satisfy enum value set: [ALL_NEW, UPDATED_OLD, ALL_OLD, NONE, UPDATED_NEW]; Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]; Value null at 'key' failed to satisfy constraint: Member must not be null
PutItem | {"TableName": "Missing", "Item": {"pk": {"S": "a"}}, "Expected": {"a": {"Value": "DEEP"}, "b": {"Exists": false}}, "ConditionalOperator": "XOR"} | 1 validation error detected: Value 'XOR' at 'conditionalOperator' failed to satisfy constraint: Member must satisfy enum value set: [OR, AND]
DeleteItem | {"TableName": "Missing", "Key": {"pk": "DEEP"}, "ReturnValues": "UPDATED_NEW"} | ReturnValues can only be ALL_OLD or NONE
PutItem | {"TableName": "Missing", "Item": {"pk": {"S": "a"}, "d": {"S": "x", "Foo": "y"}}, "ReturnValues": "BOGUS"} | 1 validation error detected: Value 'BOGUS' at 'returnValues' failed to satisfy constraint: Member must satisfy enum value set: [ALL_NEW, UPDATED_OLD, ALL_OLD, NONE, UPDATED_NEW]
""")
void putAndDeleteItemGetTheOlderChecksWhenTheNewerValidatorGivesUp(String operation, String body,
String message) {
String deep = "{\"M\": {\"n\": ".repeat(63) + "{\"S\": \"leaf\"}" + "}}".repeat(63);
given()
.header("X-Amz-Target", "DynamoDB_20120810." + operation)
.contentType(DYNAMODB_CONTENT_TYPE)
.body(body.replace("\"DEEP\"", deep))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo(message));
}
private void deleteTable(String tableName) {
given()
.header("X-Amz-Target", "DynamoDB_20120810.DeleteTable")
@@ -2375,6 +2375,35 @@ class NativeDynamoDbJsonHandlerTest {
assertEquals(message, ex.getMessage());
}
@ParameterizedTest
@CsvSource(delimiter = '|', quoteCharacter = '`', textBlock = """
DeleteItem | 0 | {"TableName":"Tbl","ReturnValues":"BOGUS","ConditionalOperator":"XOR","ReturnValuesOnConditionCheckFailure":"BOGUS","ReturnConsumedCapacity":"BOGUS","ReturnItemCollectionMetrics":"BOGUS"} | 6 validation errors detected: Value 'BOGUS' at 'returnValues' failed to satisfy constraint: Member must satisfy enum value set: [ALL_NEW, UPDATED_OLD, ALL_OLD, NONE, UPDATED_NEW]; Value 'XOR' at 'conditionalOperator' failed to satisfy constraint: Member must satisfy enum value set: [OR, AND]; Value 'BOGUS' at 'returnValuesOnConditionCheckFailure' failed to satisfy constraint: Member must satisfy enum value set: [ALL_OLD, NONE]; Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]; Value 'BOGUS' at 'returnItemCollectionMetrics' failed to satisfy constraint: Member must satisfy enum value set: [SIZE, NONE]; Value null at 'key' failed to satisfy constraint: Member must not be null
PutItem | 0 | {"TableName":"","ReturnValues":"BOGUS"} | 3 validation errors detected: Value 'BOGUS' at 'returnValues' failed to satisfy constraint: Member must satisfy enum value set: [ALL_NEW, UPDATED_OLD, ALL_OLD, NONE, UPDATED_NEW]; Value null at 'item' failed to satisfy constraint: Member must not be null; Value '' at 'tableName' failed to satisfy constraint: Member must have length greater than or equal to 1
PutItem | 0 | {"TableName":"bad!name","Item":null,"ReturnValues":"ALL_NEW"} | 1 validation error detected: Value null at 'item' failed to satisfy constraint: Member must not be null
PutItem | 63 | {"TableName":"a!","Item":{"pk":{"S":"a"}},"Expected":{"d":{"Value":"DEEP"}},"ReturnValues":"ALL_NEW"} | 2 validation errors detected: Value 'a!' at 'tableName' failed to satisfy constraint: Member must have length greater than or equal to 3; Value 'a!' at 'tableName' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+
DeleteItem | 63 | {"TableName":"Missing","Key":{"pk":"DEEP"},"ReturnValues":"UPDATED_NEW"} | ReturnValues can only be ALL_OLD or NONE
PutItem | 63 | {"TableName":"Missing","Item":{"d":"DEEP"},"ExpressionAttributeValues":{":v":{"S":"x"}}} | ExpressionAttributeValues can only be specified when using expressions: ConditionExpression is null
DeleteItem | 63 | {"TableName":"Missing","Key":{"pk":{"S":"a"}},"Expected":{"d":{"Value":"DEEP"}},"ExpressionAttributeNames":{"#d":"d"},"ExpressionAttributeValues":{":v":{"S":"x"}}} | ExpressionAttributeNames can only be specified when using expressions
PutItem | 63 | {"TableName":"Missing","Item":{"n":{"N":"x"}},"Expected":{"d":{"Value":"DEEP"}}} | The parameter cannot be converted to a numeric value: x
DeleteItem | 63 | {"TableName":"Missing","Key":{"pk":{"S":"a"},"m":{"M":{"":{"S":"x"}}}},"ConditionExpression":"d = :deep","ExpressionAttributeValues":{":deep":"DEEP"}} | Empty attribute name
PutItem | 63 | {"TableName":"Missing","Item":{"d":"DEEP"}} | Nesting Levels have exceeded supported limits: Attributes in the item have nested levels beyond supported limit
DeleteItem | 63 | {"TableName":"Missing","Key":{"pk":{"S":"a"}},"ConditionExpression":"d = :deep","ExpressionAttributeValues":{":deep":"DEEP"}} | ExpressionAttributeValues contains invalid value: Nesting Levels have exceeded supported limits: Attributes in the item have nested levels beyond supported limit for key :deep
DeleteItem | 63 | {"TableName":"Missing","Key":{"pk":{"S":"a"}},"Expected":{"d":{"Value":"DEEP"}},"ConditionalOperator":"AND"} | Nesting Levels have exceeded supported limits: Attributes in the item have nested levels beyond supported limit
DeleteItem | 62 | {"TableName":"Missing","Key":{"pk":{"S":"a"}},"Expected":{"d":{"Value":"DEEP"}},"ReturnValues":"BOGUS"} | 1 validation error detected: Value 'BOGUS' at 'returnValues' failed to satisfy constraint: Member must satisfy enum value set: [ALL_NEW, UPDATED_OLD, ALL_OLD, NONE, UPDATED_NEW]
DeleteItem | 62 | {"TableName":"Missing","Key":{"pk":"DEEP"},"ReturnValues":"BOGUS"} | 1 validation error detected: Failed to satisfy constraint: Member must satisfy enum value set: [ALL_OLD, UPDATED_OLD, ALL_NEW, UPDATE_NEW, NONE]
PutItem | 0 | {"TableName":"Missing","Item":{"pk":{"S":"a"},"d":{"L":[{"S":"x","Foo":"y"}]}},"ReturnValues":"BOGUS"} | 1 validation error detected: Value 'BOGUS' at 'returnValues' failed to satisfy constraint: Member must satisfy enum value set: [ALL_NEW, UPDATED_OLD, ALL_OLD, NONE, UPDATED_NEW]
DeleteItem | 0 | {"TableName":"Missing","Key":{"pk":{"S":"a"}},"Expected":{"d":{"ComparisonOperator":"IN","AttributeValueList":[{"S":"x","Foo":"y"}]}},"ReturnValues":"BOGUS"} | 1 validation error detected: Value 'BOGUS' at 'returnValues' failed to satisfy constraint: Member must satisfy enum value set: [ALL_NEW, UPDATED_OLD, ALL_OLD, NONE, UPDATED_NEW]
DeleteItem | 63 | {"TableName":"Missing","Key":{"pk":{"S":"a"}},"Expected":{"d":{"Value":{"S":"x"},"Foo":"DEEP"}},"ReturnValues":"BOGUS"} | 1 validation error detected: Failed to satisfy constraint: Member must satisfy enum value set: [ALL_OLD, UPDATED_OLD, ALL_NEW, UPDATE_NEW, NONE]
""")
void theOlderValidatorChecksAPutOrDeleteTheNewerOneGivesUpOn(String operation, int levels,
String request, String message) throws Exception {
JsonNode body = mapper.readTree(request.replace("\"DEEP\"", mapper.writeValueAsString(nestedMaps(levels))));
AwsException ex = assertThrows(AwsException.class, () -> handler.handle(operation, body, "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