fix(dynamodb): refuse an UpdateExpression whose actions overlap (#9675)

This commit is contained in:
Mahmoud Khalifa authored and GitHub committed 2026-11-28 15:59:01 -04:00
1 parent 92994cbd27
commit 51e887e46c
5 files changed
+181 -19

No files matched your search

@@ -187,7 +187,7 @@ public class DynamoDbService {
private DynamoDbTransactionConflicts transactionConflicts = DynamoDbTransactionConflicts.OFF;
private final int vectorIndexAllocationSeconds;
private final int vectorIndexBackfillSeconds;
private static final long MAX_DYNAMODB_LIST_INDEX = 4_294_967_294L;
static final long MAX_DYNAMODB_LIST_INDEX = 4_294_967_294L;
@Inject
public DynamoDbService(StorageFactory storageFactory, RegionResolver regionResolver,
@@ -6,6 +6,7 @@ import io.floci.aws.services.dynamodb.ExpressionEvaluator.Token;
import io.floci.aws.services.dynamodb.ExpressionEvaluator.TokenType;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -25,7 +26,7 @@ final class DynamoDbUpdateExpressionSyntax {
private sealed interface Operand permits PathOperand, ValueOperand, Call, Sum, Group {}
private record PathOperand(List<Token> names) implements Operand {}
private record PathOperand(List<Token> names, List<Token> elements) implements Operand {}
private record ValueOperand(Token placeholder) implements Operand {}
@@ -40,6 +41,8 @@ final class DynamoDbUpdateExpressionSyntax {
private final String expression;
private final List<Token> tokens;
private final List<Action> actions = new ArrayList<>();
private final Set<String> sectionsSeen = new HashSet<>();
private boolean repeatedSection;
private final JsonNode names;
private final JsonNode values;
private int pos;
@@ -67,6 +70,7 @@ final class DynamoDbUpdateExpressionSyntax {
throw syntaxError();
}
String section = tokens.get(pos++).value().toUpperCase(Locale.ROOT);
repeatedSection |= !sectionsSeen.add(section);
do {
actions.add(readAction(section));
} while (accept(TokenType.COMMA));
@@ -135,15 +139,21 @@ final class DynamoDbUpdateExpressionSyntax {
private PathOperand readPath() {
List<Token> pathNames = new ArrayList<>();
pathNames.add(expectName());
List<Token> elements = new ArrayList<>();
Token first = expectName();
pathNames.add(first);
elements.add(first);
while (true) {
if (accept(TokenType.DOT)) {
pathNames.add(expectName());
Token name = expectName();
pathNames.add(name);
elements.add(name);
} else if (accept(TokenType.LBRACKET)) {
elements.add(peek());
expect(TokenType.NUMBER);
expect(TokenType.RBRACKET);
} else {
return new PathOperand(pathNames);
return new PathOperand(pathNames, elements);
}
}
}
@@ -168,6 +178,14 @@ final class DynamoDbUpdateExpressionSyntax {
default -> { }
}
}
if (repeatedSection) {
return;
}
List<List<Token>> targets = new ArrayList<>();
for (Action action : actions) {
targets.add(action.target().elements());
}
ProjectionEvaluator.requireDisjointPaths(EXPRESSION_TYPE, targets, names);
}
private void checkOperand(Operand operand, boolean nested) {
@@ -105,18 +105,56 @@ final class ProjectionEvaluator {
List<List<PathSegment>> paths = new ArrayList<>();
for (List<Token> path : readPaths(expression)) {
List<PathSegment> segments = resolvePath(path, exprAttrNames, true);
for (List<PathSegment> earlier : paths) {
if (covers(earlier, segments) || covers(segments, earlier)) {
throw new AwsException("ValidationException",
"Invalid ProjectionExpression: Two document paths overlap with each other; "
+ "must remove or rewrite one of these paths; path one: " + render(earlier)
+ ", path two: " + render(segments), 400);
}
}
requireNoOverlap("ProjectionExpression", paths, segments);
paths.add(segments);
}
}
/**
* Rejects a path that equals, contains or sits inside an earlier one, for the target paths of
* an UpdateExpression in written order. Names are resolved per segment and never split. A path
* with an out-of-range list index is skipped, so the update reports the range error instead.
*/
static void requireDisjointPaths(String expressionType, List<List<Token>> paths, JsonNode exprAttrNames) {
List<List<PathSegment>> resolved = new ArrayList<>();
for (List<Token> path : paths) {
List<PathSegment> segments = targetSegments(path, exprAttrNames);
if (segments == null) {
continue;
}
requireNoOverlap(expressionType, resolved, segments);
resolved.add(segments);
}
}
private static List<PathSegment> targetSegments(List<Token> path, JsonNode exprAttrNames) {
List<PathSegment> segments = new ArrayList<>();
for (Token token : path) {
if (token.type() == TokenType.NUMBER) {
String digits = token.value().replaceFirst("^0+(?=.)", "");
if (digits.length() > 10 || Long.parseLong(digits) > DynamoDbService.MAX_DYNAMODB_LIST_INDEX) {
return null;
}
segments.add(PathSegment.index(Long.parseLong(digits)));
} else {
segments.add(PathSegment.name(resolveSegment(token.value(), exprAttrNames, false)));
}
}
return segments;
}
private static void requireNoOverlap(String expressionType, List<List<PathSegment>> earlierPaths,
List<PathSegment> segments) {
for (List<PathSegment> earlier : earlierPaths) {
if (covers(earlier, segments) || covers(segments, earlier)) {
throw new AwsException("ValidationException",
"Invalid " + expressionType + ": Two document paths overlap with each other; "
+ "must remove or rewrite one of these paths; path one: " + render(earlier)
+ ", path two: " + render(segments), 400);
}
}
}
private static boolean covers(List<PathSegment> outer, List<PathSegment> inner) {
return outer.size() <= inner.size() && inner.subList(0, outer.size()).equals(outer);
}
@@ -2452,7 +2452,7 @@ class DynamoDbIntegrationTest {
@Test
@Order(30)
void deleteFromSetWithAddInSameExpression() {
void deleteFromSetWithAddInSameExpressionIsRefused() {
// Create table
given()
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
@@ -2485,7 +2485,7 @@ class DynamoDbIntegrationTest {
.then()
.statusCode(200);
// Combined: ADD "c" then DELETE "a" in the same expression
// ADD and DELETE on the same set overlap, so DynamoDB refuses the whole update
given()
.header("X-Amz-Target", "DynamoDB_20120810.UpdateItem")
.contentType(DYNAMODB_CONTENT_TYPE)
@@ -2503,9 +2503,13 @@ class DynamoDbIntegrationTest {
.when()
.post("/")
.then()
.statusCode(200);
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("1 validation error detected: Invalid UpdateExpression: "
+ "Two document paths overlap with each other; "
+ "must remove or rewrite one of these paths; path one: [tags], path two: [tags]"));
// Verify: should have "b" and "c", not "a"
// The set is unchanged
given()
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
.contentType(DYNAMODB_CONTENT_TYPE)
@@ -2520,8 +2524,7 @@ class DynamoDbIntegrationTest {
.then()
.statusCode(200)
.body("Item.tags.SS.size()", equalTo(2))
.body("Item.tags.SS", hasItems("b", "c"))
.body("Item.tags.SS", not(hasItem("a")));
.body("Item.tags.SS", hasItems("a", "b"));
// Cleanup
given()
@@ -3026,6 +3026,109 @@ class NativeDynamoDbJsonHandlerTest {
assertNull(service.getItem("Users", key, "eu-west-1"));
}
private ObjectNode overlapRequest(String expression) {
ObjectNode request = updateUserRequest();
request.put("UpdateExpression", expression);
request.set("ExpressionAttributeValues", valuesFor(expression));
Map<String, String> aliases = Map.of("#m", "parent", "#k", "child", "#d", "parent.child");
ObjectNode names = mapper.createObjectNode();
aliases.forEach((alias, name) -> {
if (expression.contains(alias)) {
names.put(alias, name);
}
});
if (!names.isEmpty()) {
request.set("ExpressionAttributeNames", names);
}
return request;
}
@ParameterizedTest
@CsvSource(delimiter = '|', textBlock = """
SET a = :v, a = :v | [a] | [a]
SET #m = :m, #m.#k = :v | [parent] | [parent, child]
SET a = :v REMOVE a | [a] | [a]
SET l[0] = :v REMOVE l | [l, [0]] | [l]
ADD s :ss DELETE s :ss | [s] | [s]
SET l[1] = :v, l[1] = :v | [l, [1]] | [l, [1]]
""")
void updateItemOverlappingPaths_rejected(String expression, String pathOne, String pathTwo) throws Exception {
seedUpdateReturnValuesItem();
ObjectNode key = item("userId", "u1");
JsonNode before = service.getItem("Users", key, "eu-west-1").deepCopy();
AwsException ex = expectValidationException("UpdateItem", overlapRequest(expression));
assertEquals(400, ex.getHttpStatus());
assertEquals("1 validation error detected: Invalid UpdateExpression: Two document paths overlap with each "
+ "other; must remove or rewrite one of these paths; path one: " + pathOne
+ ", path two: " + pathTwo, ex.getMessage());
assertEquals(before, service.getItem("Users", key, "eu-west-1"));
}
@Test
void updateItemOverlappingPaths_rejectedBeforeTheTableLookup() {
ObjectNode request = overlapRequest("SET a = :v, a = :v");
request.put("TableName", "Missing");
AwsException ex = expectValidationException("UpdateItem", request);
assertTrue(ex.getMessage().contains("Two document paths overlap with each other"), ex.getMessage());
}
@ParameterizedTest
@ValueSource(strings = {"SET l[0] = :v, l[1] = :v", "SET parent.a = :v, parent.b = :v", "REMOVE l[0], l[2]",
"SET #d = :v, a = :v", "SET #d = :v, parent.child = :v", "SET #d = :v, parent = :m"})
void updateItemDisjointPaths_accepted(String expression) throws Exception {
seedUpdateReturnValuesItem();
Response response = handler.handle("UpdateItem", overlapRequest(expression), "eu-west-1");
assertEquals(200, response.getStatus());
}
@Test
void updateItemAliasWithDot_isOneTopLevelAttribute() throws Exception {
seedUpdateReturnValuesItem();
ObjectNode request = overlapRequest("SET #d = :v, parent.child = :v");
request.put("ReturnValues", "ALL_NEW");
JsonNode body = mapper.convertValue(handler.handle("UpdateItem", request, "eu-west-1").getEntity(),
JsonNode.class);
JsonNode attributes = body.get("Attributes");
assertEquals("x", attributes.get("parent.child").get("S").asText());
assertEquals("x", attributes.get("parent").get("M").get("child").get("S").asText());
}
@Test
void transactWriteItemsOverlappingUpdatePaths_rejected() throws Exception {
seedUpdateReturnValuesItem();
ObjectNode key = item("userId", "u1");
JsonNode before = service.getItem("Users", key, "eu-west-1").deepCopy();
ObjectNode update = mapper.createObjectNode();
update.set("Key", key);
update.put("UpdateExpression", "SET parent = :m, parent.child = :v");
update.set("ExpressionAttributeValues", valuesFor("SET parent = :m, parent.child = :v"));
AwsException ex = expectValidationException("TransactWriteItems", transactWrite("Update", update));
assertEquals(400, ex.getHttpStatus());
assertEquals("Invalid UpdateExpression: Two document paths overlap with each other; must remove or "
+ "rewrite one of these paths; path one: [parent], path two: [parent, child]", ex.getMessage());
assertEquals(before, service.getItem("Users", key, "eu-west-1"));
}
@Test
void updateItemRepeatedSection_reportsTheSectionErrorNotAnOverlap() {
AwsException ex = expectValidationException("UpdateItem", overlapRequest("SET a = :v SET a = :v"));
assertTrue(ex.getMessage().contains("The \"SET\" section can only be used once"), ex.getMessage());
}
@Test
void updateItemOutOfRangeListIndex_reportsTheRangeErrorNotAnOverlap() throws Exception {
seedUpdateReturnValuesItem();
AwsException ex = expectValidationException("UpdateItem",
overlapRequest("SET l[99999999999] = :v, l[99999999998] = :v"));
assertTrue(ex.getMessage().contains("List index is not within the allowable range"), ex.getMessage());
}
private ObjectNode valueAndSet() {
ObjectNode values = singleValue(":v");
values.putObject(":s").putArray("SS").add("x");