mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(dynamodb): refuse empty or unused transaction expressions and an unknown ReturnValuesOnConditionCheckFailure (#7319)
This commit is contained in:
1 parent
c79db010ea
commit
b821dcd718
4 files changed
+96
-43
No files matched your search
+1
-1
@@ -6,7 +6,7 @@ import java.nio.charset.StandardCharsets;
|
||||
|
||||
// AWS counts the raw expression text, before placeholders are resolved. Single-item write
|
||||
// APIs wrap the error in the validation envelope, the others do not, and only the Scan
|
||||
// FilterExpression and TransactWriteItems conditions report the size.
|
||||
// FilterExpression and the conditions of a deeply nested TransactWriteItems request report the size.
|
||||
final class DynamoDbExpressionSize {
|
||||
|
||||
static final int MAX_BYTES = 4096;
|
||||
|
||||
+60
-35
@@ -2427,39 +2427,11 @@ public class NativeDynamoDbJsonHandler {
|
||||
}
|
||||
|
||||
private Response handleTransactWriteItems(JsonNode request, String region) {
|
||||
JsonNode transactItemsNode = requireValidTransactRequest(request, true);
|
||||
TransactRequest checked = requireValidTransactRequest(request, true);
|
||||
JsonNode transactItemsNode = checked.items();
|
||||
|
||||
for (JsonNode txItem : transactItemsNode) {
|
||||
for (Map.Entry<String, JsonNode> action : txItem.properties()) {
|
||||
JsonNode op = action.getValue();
|
||||
String conditionExpression = op.has("ConditionExpression")
|
||||
? op.get("ConditionExpression").asText() : null;
|
||||
String updateExpression = op.has("UpdateExpression")
|
||||
? op.get("UpdateExpression").asText() : null;
|
||||
JsonNode opExprAttrNames = op.get("ExpressionAttributeNames");
|
||||
JsonNode opExprAttrValues = op.get("ExpressionAttributeValues");
|
||||
// AWS checks the depth of every value of a member before anything else,
|
||||
// so even an unused or condition-only value fails the request.
|
||||
DynamoDbAttributeValueValidator.requireNestingWithinLimit(op.get("Item"), false);
|
||||
DynamoDbAttributeValueValidator.requireNestingWithinLimit(op.get("Key"), false);
|
||||
DynamoDbAttributeValueValidator.requireNestingWithinLimit(opExprAttrValues, false);
|
||||
requireReadableValues(op.get("Put".equals(action.getKey()) ? "Item" : "Key"), "");
|
||||
// An action without an expression ignores its ExpressionAttributeValues.
|
||||
if (conditionExpression != null || updateExpression != null) {
|
||||
requireReadableValues(opExprAttrValues, "");
|
||||
}
|
||||
DynamoDbExpressionSize.checkRead(op.path("UpdateExpression").textValue(), "UpdateExpression");
|
||||
DynamoDbExpressionSize.checkReadWithSize(conditionExpression, "ConditionExpression");
|
||||
ExpressionEvaluator.validateSyntax(conditionExpression, "ConditionExpression");
|
||||
// Undefined tokens must fail here as a ValidationException, never a
|
||||
// TransactionCanceledException with a false ConditionalCheckFailed reason.
|
||||
requireDefinedTokens(updateExpression, "UpdateExpression", opExprAttrNames, opExprAttrValues);
|
||||
requireDefinedTokens(conditionExpression, "ConditionExpression", opExprAttrNames, opExprAttrValues);
|
||||
ExpressionEvaluator.validateSemantics(conditionExpression, "ConditionExpression",
|
||||
opExprAttrNames, opExprAttrValues);
|
||||
dynamoDbService.requireAddOrDeleteOperandTypes(op.path("UpdateExpression").textValue(),
|
||||
opExprAttrValues, false);
|
||||
}
|
||||
for (TransactAction action : checked.actions()) {
|
||||
requireValidTransactAction(action, checked.older());
|
||||
}
|
||||
|
||||
// Check 4MB total item size limit
|
||||
@@ -2546,9 +2518,11 @@ public class NativeDynamoDbJsonHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private record TransactRequest(JsonNode items, List<TransactAction> actions, boolean older) {}
|
||||
|
||||
// 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) {
|
||||
private static TransactRequest requireValidTransactRequest(JsonNode request, boolean write) {
|
||||
String token = write ? request.path("ClientRequestToken").textValue() : null;
|
||||
List<String> memberErrors = new ArrayList<>();
|
||||
if (token != null) {
|
||||
@@ -2638,7 +2612,7 @@ public class NativeDynamoDbJsonHandler {
|
||||
throw new AwsException("ValidationException",
|
||||
"TransactItems can only contain one of Check, Put, Update or Delete", 400);
|
||||
}
|
||||
return transactItems;
|
||||
return new TransactRequest(transactItems, actions, older);
|
||||
}
|
||||
|
||||
// The newer validator names a member by its 0-based position and leaves the value out.
|
||||
@@ -2659,6 +2633,57 @@ public class NativeDynamoDbJsonHandler {
|
||||
throwValidationErrors(validationErrors);
|
||||
}
|
||||
|
||||
// DynamoDB checks an action's ConditionExpression in full before its UpdateExpression.
|
||||
private void requireValidTransactAction(TransactAction action, boolean older) {
|
||||
JsonNode op = action.op();
|
||||
String conditionExpression = textOrNull(op, "ConditionExpression");
|
||||
String updateExpression = textOrNull(op, "UpdateExpression");
|
||||
JsonNode exprAttrNames = op.get("ExpressionAttributeNames");
|
||||
JsonNode exprAttrValues = op.get("ExpressionAttributeValues");
|
||||
DynamoDbAttributeValueValidator.requireNestingWithinLimit(op.get("Item"), false);
|
||||
DynamoDbAttributeValueValidator.requireNestingWithinLimit(op.get("Key"), false);
|
||||
requireReadableValues(op.get("Put".equals(action.type()) ? "Item" : "Key"), "");
|
||||
List<String> onFailureErrors = new ArrayList<>();
|
||||
addPartiQLReturnValuesError(op, action.path("ReturnValuesOnConditionCheckFailure"), onFailureErrors);
|
||||
throwValidationErrors(onFailureErrors);
|
||||
// AWS checks the depth of every value, so even an unused or condition-only value fails the request.
|
||||
DynamoDbAttributeValueValidator.requireNestingWithinLimit(exprAttrValues, false);
|
||||
// An action without an expression ignores its ExpressionAttributeNames and ExpressionAttributeValues.
|
||||
if (conditionExpression == null && updateExpression == null) {
|
||||
return;
|
||||
}
|
||||
requireReadableValues(exprAttrValues, "");
|
||||
|
||||
requireNonEmptyExpression(conditionExpression, "ConditionExpression");
|
||||
// Only a request too deep for the newer validator reports the condition's size.
|
||||
if (older) {
|
||||
DynamoDbExpressionSize.checkReadWithSize(conditionExpression, "ConditionExpression");
|
||||
} else {
|
||||
DynamoDbExpressionSize.checkRead(conditionExpression, "ConditionExpression");
|
||||
}
|
||||
ExpressionEvaluator.validateSyntax(conditionExpression, "ConditionExpression");
|
||||
// Undefined tokens must fail here as a ValidationException, never a
|
||||
// TransactionCanceledException with a false ConditionalCheckFailed reason.
|
||||
requireDefinedTokens(conditionExpression, "ConditionExpression", exprAttrNames, exprAttrValues);
|
||||
ExpressionEvaluator.validateSemantics(conditionExpression, "ConditionExpression",
|
||||
exprAttrNames, exprAttrValues);
|
||||
|
||||
requireNonEmptyExpression(updateExpression, "UpdateExpression");
|
||||
DynamoDbExpressionSize.checkRead(updateExpression, "UpdateExpression");
|
||||
requireDefinedTokens(updateExpression, "UpdateExpression", exprAttrNames, exprAttrValues);
|
||||
dynamoDbService.requireAddOrDeleteOperandTypes(updateExpression, exprAttrValues, false);
|
||||
|
||||
checkUnusedEan(exprAttrNames, extractHashTokens(conditionExpression, updateExpression));
|
||||
checkUnusedEav(exprAttrValues, extractColonTokens(conditionExpression, updateExpression));
|
||||
}
|
||||
|
||||
private static void requireNonEmptyExpression(String expression, String exprType) {
|
||||
if (expression != null && expression.isEmpty()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Invalid " + exprType + ": The expression can not be empty;", 400);
|
||||
}
|
||||
}
|
||||
|
||||
// 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;
|
||||
@@ -2743,7 +2768,7 @@ public class NativeDynamoDbJsonHandler {
|
||||
}
|
||||
|
||||
private Response handleTransactGetItems(JsonNode request, String region) {
|
||||
JsonNode transactItemsNode = requireValidTransactRequest(request, false);
|
||||
JsonNode transactItemsNode = requireValidTransactRequest(request, false).items();
|
||||
transactItemsNode.forEach(txItem -> requireReadableValues(txItem.path("Get").path("Key"), ""));
|
||||
|
||||
for (JsonNode txItem : transactItemsNode) {
|
||||
|
||||
+3
-3
@@ -5748,7 +5748,7 @@ given()
|
||||
.body("message", equalTo("Invalid UpdateExpression: An expression attribute name "
|
||||
+ "used in the document path is not defined; attribute name: #n"));
|
||||
|
||||
// Both undefined; UpdateExpression's own token is reported first.
|
||||
// Both undefined; ConditionExpression's token is reported first.
|
||||
given()
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.TransactWriteItems")
|
||||
.contentType(DYNAMODB_CONTENT_TYPE)
|
||||
@@ -5768,8 +5768,8 @@ given()
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", containsString("ValidationException"))
|
||||
.body("message", equalTo("Invalid UpdateExpression: An expression attribute value "
|
||||
+ "used in expression is not defined; attribute value: :d"));
|
||||
.body("message", equalTo("Invalid ConditionExpression: An expression attribute value "
|
||||
+ "used in expression is not defined; attribute value: :v"));
|
||||
|
||||
// Control: a fully-defined transaction is still accepted; seed the item first.
|
||||
given()
|
||||
|
||||
+32
-4
@@ -1856,19 +1856,24 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
return request;
|
||||
}
|
||||
|
||||
@Test
|
||||
void transactWriteItemsRejectsAConditionExpressionOver4096BytesWithTheSizeBeforeTheTableLookup() {
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', textBlock = """
|
||||
60 | Invalid ConditionExpression: Expression size has exceeded the maximum allowed size;
|
||||
61 | Invalid ConditionExpression: Expression size has exceeded the maximum allowed size; expression size: 4097
|
||||
""")
|
||||
void transactWriteItemsRejectsAConditionExpressionOver4096BytesBeforeTheTableLookup(int levels, String message) {
|
||||
ObjectNode put = mapper.createObjectNode();
|
||||
put.set("Item", item("userId", "u1"));
|
||||
put.put("ConditionExpression", "attribute_not_exists(" + nameOfBytes(4075) + ")");
|
||||
ObjectNode request = transactWrite("Put", put);
|
||||
((ObjectNode) request.get("TransactItems").get(0).get("Put")).put("TableName", "Missing");
|
||||
((ArrayNode) request.get("TransactItems")).add(transactMember("Put", "Missing", "Item",
|
||||
mapper.createObjectNode().set("d", nestedMaps(levels))));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("TransactWriteItems", request, "eu-west-1"));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("Invalid ConditionExpression: Expression size has exceeded the maximum allowed size; "
|
||||
+ "expression size: 4097", ex.getMessage());
|
||||
assertEquals(message, ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -2393,6 +2398,29 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
assertEquals(message, ex.getMessage());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', quoteCharacter = '`', textBlock = """
|
||||
[{"Update":{"TableName":"Missing","Key":{},"UpdateExpression":"SET a = :a","ExpressionAttributeValues":{":a":{"S":"x"}},"ReturnValuesOnConditionCheckFailure":"BOGUS"}}] | 1 validation error detected: Value 'BOGUS' at 'transactItems.1.member.update.returnValuesOnConditionCheckFailure' failed to satisfy constraint: Member must satisfy enum value set: [ALL_OLD, NONE]
|
||||
[{"Put":{"TableName":"Missing","Item":{},"ConditionExpression":"a = :n","ExpressionAttributeValues":{":n":{"N":"abc"}},"ReturnValuesOnConditionCheckFailure":"all_old"}}] | 1 validation error detected: Value 'all_old' at 'transactItems.1.member.put.returnValuesOnConditionCheckFailure' failed to satisfy constraint: Member must satisfy enum value set: [ALL_OLD, NONE]
|
||||
[{"Put":{"TableName":"Missing","Item":{},"ConditionExpression":""}}] | Invalid ConditionExpression: The expression can not be empty;
|
||||
[{"Update":{"TableName":"Missing","Key":{},"UpdateExpression":"","ConditionExpression":""}}] | Invalid ConditionExpression: The expression can not be empty;
|
||||
[{"Update":{"TableName":"Missing","Key":{},"UpdateExpression":""}}] | Invalid UpdateExpression: The expression can not be empty;
|
||||
[{"Update":{"TableName":"Missing","Key":{},"UpdateExpression":"SET a = :zz","ConditionExpression":"a = :yy"}}] | Invalid ConditionExpression: An expression attribute value used in expression is not defined; attribute value: :yy
|
||||
[{"Update":{"TableName":"Missing","Key":{},"UpdateExpression":"SET a = :zz","ConditionExpression":"contains(a, a)"}}] | Invalid ConditionExpression: The first operand must be distinct from the remaining operands for this operator or function; operator: contains, first operand: [a]
|
||||
[{"Put":{"TableName":"Missing","Item":{},"ConditionExpression":"attribute_not_exists(a)","ExpressionAttributeNames":{"#n":"n"},"ExpressionAttributeValues":{":v":{"S":"x"}}}}] | Value provided in ExpressionAttributeNames unused in expressions: keys: {#n}
|
||||
[{"Update":{"TableName":"Missing","Key":{},"UpdateExpression":"SET a = :a","ConditionExpression":"b = :b","ExpressionAttributeValues":{":a":{"S":"x"},":b":{"S":"y"},":v":{"S":"z"}}}}] | Value provided in ExpressionAttributeValues unused in expressions: keys: {:v}
|
||||
[{"Put":{"TableName":"Missing","Item":{}}},{"Delete":{"TableName":"Missing","Key":{},"ConditionExpression":"attribute_exists(a)","ExpressionAttributeValues":{":v":{"S":"x"}}}}] | Value provided in ExpressionAttributeValues unused in expressions: keys: {:v}
|
||||
[{"Put":{"TableName":"Missing","Item":{},"ExpressionAttributeNames":{"#n":"n"}}}] | Requested resource not found
|
||||
""")
|
||||
void aTransactionChecksEachActionBeforeAnyTable(String items, String message) throws Exception {
|
||||
ObjectNode request = mapper.createObjectNode();
|
||||
request.set("TransactItems", mapper.readTree(items));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("TransactWriteItems", request, "eu-west-1"));
|
||||
assertEquals(message, ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateItemRejectsAnAttributeUpdatesValueWithALeafAtLevel33BeforeTheTableLookup() {
|
||||
ObjectNode request = updateUserRequest();
|
||||
|
||||
Reference in new issue
Block a user