fix(dynamodb): refuse an over-limit UpdateItem statement before the condition (#8076)

This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-12 07:27:37 -04:00
1 parent f8e5a883d8
commit 67814c5d21
5 files changed
+201 -12

No files matched your search

@@ -14,6 +14,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.OptionalInt;
import java.util.Set;
import java.util.function.Function;
@@ -62,11 +63,16 @@ final class DynamoDbItemSize {
return calculateItemSize(item) <= MAX_ITEM_SIZE;
}
static boolean updateItemWithinLimit(JsonNode item, int statementSize) {
return calculateItemSize(item) <= MAX_ITEM_SIZE && statementSize <= MAX_ITEM_SIZE;
static boolean updateStatementWithinLimit(int statementSize) {
return statementSize <= MAX_ITEM_SIZE;
}
static int updateStatementSize(String expression, Function<String, List<Object>> paths, JsonNode values) {
/**
* The size of an UpdateExpression statement, or empty when an action lacks the assignment or the
* value its clause needs, or leaves a parenthesis open. The update parser refuses such a statement.
*/
static OptionalInt updateStatementSize(String expression, Function<String, List<Object>> paths,
JsonNode values) {
int size = UPDATE_COST;
PathTree targets = new PathTree();
String remaining = expression.trim().replaceAll("\\s+", " ");
@@ -79,11 +85,38 @@ final class DynamoDbItemSize {
while (!actions.isBlank()) {
int comma = DynamoDbService.findNextComma(actions);
String action = (comma < 0 ? actions : actions.substring(0, comma)).trim();
if (!readable(keyword, action)) {
return OptionalInt.empty();
}
size += actionSize(keyword, action, targets, paths, values);
actions = comma < 0 ? "" : actions.substring(comma + 1);
}
}
return size + targets.size();
return OptionalInt.of(size + targets.size());
}
private static boolean readable(String clause, String action) {
if (leavesParenthesisOpen(action)) {
return false;
}
return switch (clause) {
case "SET" -> action.indexOf('=') >= 0;
case "ADD" -> action.indexOf(' ') >= 0;
default -> true;
};
}
private static boolean leavesParenthesisOpen(String action) {
int open = 0;
for (int i = 0; i < action.length(); i++) {
char c = action.charAt(i);
if (c == '(') {
open++;
} else if (c == ')' && open > 0) {
open--;
}
}
return open > 0;
}
private static int actionSize(String clause, String action, PathTree targets,
@@ -1394,6 +1394,12 @@ public class DynamoDbService {
String itemKey = buildItemKey(table, key, true);
// AWS refuses an over-limit statement before it evaluates the condition.
if (sizeRule == UpdateSizeRule.UPDATE_ITEM && updateExpression != null) {
DynamoDbItemSize.updateStatementSize(updateExpression, path -> parsePath(path, expressionAttrNames),
expressionAttrValues).ifPresent(DynamoDbService::requireUpdateStatementWithinSizeLimit);
}
return withItemLock(storageKey, itemKey, () -> {
ConcurrentSkipListMap<String, JsonNode> items = itemsFor(storageKey, stagedItems, true);
@@ -1503,12 +1509,7 @@ public class DynamoDbService {
// AWS validates index key values against the item the update produces.
validateIndexKeyTypes(table, item, true);
if (sizeRule == UpdateSizeRule.UPDATE_ITEM && updateExpression != null) {
requireUpdateItemWithinSizeLimit(item, DynamoDbItemSize.updateStatementSize(updateExpression,
path -> parsePath(path, expressionAttrNames), expressionAttrValues));
} else {
requireUpdatedItemWithinSizeLimit(item);
}
requireUpdatedItemWithinSizeLimit(item);
if (stagedItems == null) {
pointInTimeRecovery.recordItem(regionResolver.getAccountId(), storageKey, table, itemKey, existing);
@@ -2427,8 +2428,8 @@ public class DynamoDbService {
}
}
private static void requireUpdateItemWithinSizeLimit(JsonNode item, int statementSize) {
if (!DynamoDbItemSize.updateItemWithinLimit(item, statementSize)) {
private static void requireUpdateStatementWithinSizeLimit(int statementSize) {
if (!DynamoDbItemSize.updateStatementWithinLimit(statementSize)) {
throw new UpdatedItemTooLargeException();
}
}
@@ -3463,6 +3464,7 @@ public class DynamoDbService {
throw new AwsException("ValidationException",
"Invalid UpdateExpression: The expression can not be empty;", 400);
}
requireAssignmentAfterSetTarget(expression);
requireClosedParentheses(expression, "");
// AWS tokenizes UpdateExpression whitespace-insensitively, so collapse runs of
// whitespace (newlines, tabs, multiple spaces) so clause-keyword dispatch and the
@@ -4389,6 +4391,54 @@ public class DynamoDbService {
return "()[],.=+-".indexOf(c) >= 0;
}
// DynamoDB reads a SET target path up to "=", so a comma before it fails on the comma.
static void requireAssignmentAfterSetTarget(String expression) {
List<ExpressionEvaluator.Token> tokens = ExpressionEvaluator.tokenize(expression);
boolean inSet = false;
int target = -1;
int depth = 0;
for (int i = 0; i < tokens.size(); i++) {
ExpressionEvaluator.Token token = tokens.get(i);
if (target >= 0) {
switch (token.type()) {
case COMMA -> throw new AwsException("ValidationException",
"Invalid UpdateExpression: Syntax error; token: \",\", near: \""
+ expression.substring(tokens.get(i - 1).pos(), tokens.get(i + 1).end()) + "\"",
400);
case EQ -> {
if (i == target) {
return;
}
target = -1;
}
case IDENTIFIER, NAME_REF, DOT, LBRACKET, NUMBER, RBRACKET -> { }
default -> {
return;
}
}
continue;
}
switch (token.type()) {
case LPAREN -> depth++;
case RPAREN -> depth--;
case COMMA -> target = inSet && depth == 0 ? i + 1 : -1;
case IDENTIFIER -> {
String word = token.value().toUpperCase(Locale.ROOT);
if (depth == 0 && List.of("SET", "REMOVE", "ADD", "DELETE").contains(word)) {
inSet = word.equals("SET");
target = inSet ? i + 1 : -1;
}
}
case UNKNOWN -> {
if (!isUpdatePunctuation(token.value().charAt(0))) {
return;
}
}
default -> { }
}
}
}
static int findNextComma(String s) {
// Find next comma that is not inside a function call
int depth = 0;
@@ -1023,6 +1023,7 @@ public class NativeDynamoDbJsonHandler {
throw new AwsException("ValidationException",
"Invalid UpdateExpression: Syntax error; token: \"" + token + "\", near: \"" + near + "\"", 400);
}
DynamoDbService.requireAssignmentAfterSetTarget(updateExpression);
DynamoDbService.requireClosedParentheses(updateExpression, "1 validation error detected: ");
}
// Undefined tokens, then ConditionExpression's semantic errors, must both be caught