fix(dynamodb): refuse an UpdateExpression operand that reads an absent attribute (#8266)

DynamoDB refuses the whole update when a path in a SET value reads
nothing. That covers a missing attribute or map key, a path through a
scalar, a list index past the end, and an if_not_exists whose path and
fallback are both absent. It reads the operands of a sum or list_append
one by one, so the first absent operand or the first of the wrong type
gives the error. A sum operand of the wrong type gets the same message
as list_append and ADD. In TransactWriteItems both errors cancel the
transaction with a ValidationError reason.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-14 00:05:22 -04:00
1 parent f087599883
commit 287c44b8f8
3 files changed
+142 -27

No files matched your search

@@ -2310,7 +2310,8 @@ public class DynamoDbService {
try {
validateTransactItem(transactItem, region, staged);
return null;
} catch (KeySchemaMismatchException | ItemNestingExceededException | UpdatedItemTooLargeException e) {
} catch (KeySchemaMismatchException | ItemNestingExceededException | UpdatedItemTooLargeException
| UpdateOperandException e) {
return new TransactionCanceledException.CancellationReason("ValidationError", null, e.getMessage());
}
}
@@ -3635,12 +3636,8 @@ public class DynamoDbService {
String leftExpr = valuePart.substring(0, arithmeticIdx).trim();
char operator = valuePart.charAt(arithmeticIdx);
String rightExpr = valuePart.substring(arithmeticIdx + 1).trim();
JsonNode leftVal = evaluateSetExpr(snapshot, leftExpr, exprAttrNames, exprAttrValues);
JsonNode rightVal = evaluateSetExpr(snapshot, rightExpr, exprAttrNames, exprAttrValues);
if (leftVal == null || rightVal == null || !leftVal.has("N") || !rightVal.has("N")) {
throw new AwsException("ValidationException",
"Invalid UpdateExpression: Incorrect operand type for operator or function", 400);
}
JsonNode leftVal = typedOperand(snapshot, leftExpr, "N", exprAttrNames, exprAttrValues);
JsonNode rightVal = typedOperand(snapshot, rightExpr, "N", exprAttrNames, exprAttrValues);
try {
BigDecimal left = new BigDecimal(leftVal.get("N").asText());
BigDecimal right = new BigDecimal(rightVal.get("N").asText());
@@ -3667,16 +3664,8 @@ public class DynamoDbService {
if (commaPos >= 0) {
String arg1 = inner.substring(0, commaPos).trim();
String arg2 = inner.substring(commaPos + 1).trim();
JsonNode list1 = evaluateSetExpr(snapshot, arg1, exprAttrNames, exprAttrValues);
JsonNode list2 = evaluateSetExpr(snapshot, arg2, exprAttrNames, exprAttrValues);
if (list1 == null || list2 == null) {
throw new AwsException("ValidationException",
"The provided expression refers to an attribute that does not exist in the item", 400);
}
if (!list1.has("L") || !list2.has("L")) {
throw new AwsException("ValidationException",
"An operand in the update expression has an incorrect data type", 400);
}
JsonNode list1 = typedOperand(snapshot, arg1, "L", exprAttrNames, exprAttrValues);
JsonNode list2 = typedOperand(snapshot, arg2, "L", exprAttrNames, exprAttrValues);
ArrayNode merged =
JsonNodeFactory.instance.arrayNode();
list1.get("L").forEach(merged::add);
@@ -3698,12 +3687,8 @@ public class DynamoDbService {
LOG.debugv("applySetClause: value was null for valuePart={0}, NOT setting attribute", valuePart);
}
} else if (!valuePart.isEmpty()) {
// Plain attribute reference: SET a = b or SET a = #alias
String refAttr = resolveAttributeName(valuePart, exprAttrNames);
JsonNode refValue = getValueAtPath(snapshot, refAttr, exprAttrNames);
if (refValue != null) {
setValueAtPath(item, attrPath, refValue, exprAttrNames);
}
setValueAtPath(item, attrPath, evaluateSetExpr(snapshot, valuePart, exprAttrNames, exprAttrValues),
exprAttrNames);
}
clause = rest;
@@ -3743,9 +3728,21 @@ public class DynamoDbService {
return null;
} else if (expr.startsWith(":") && exprAttrValues != null) {
return exprAttrValues.get(expr);
} else {
return getValueAtPath(item, resolveAttributeName(expr, exprAttrNames), exprAttrNames);
}
JsonNode value = getValueAtPath(item, resolveAttributeName(expr, exprAttrNames), exprAttrNames);
if (value == null) {
throw UpdateOperandException.absentAttribute();
}
return value;
}
private JsonNode typedOperand(ObjectNode item, String operand, String type,
JsonNode exprAttrNames, JsonNode exprAttrValues) {
JsonNode value = evaluateSetExpr(item, operand, exprAttrNames, exprAttrValues);
if (value == null || !value.has(type)) {
throw UpdateOperandException.incorrectType();
}
return value;
}
private String applyRemoveClause(ObjectNode item, String clause, JsonNode exprAttrNames,
@@ -3972,8 +3969,7 @@ public class DynamoDbService {
private static void requireSameTypeAsOperand(JsonNode existingValue, JsonNode operand, List<String> types) {
for (String type : types) {
if (operand.has(type) && existingValue != null && !existingValue.has(type)) {
throw new AwsException("ValidationException",
"An operand in the update expression has an incorrect data type", 400);
throw UpdateOperandException.incorrectType();
}
}
}
@@ -0,0 +1,20 @@
package io.floci.aws.services.dynamodb;
import io.floci.aws.core.common.AwsException;
/** An update operand the item cannot serve. A transact member carrying one cancels instead of failing up front. */
public class UpdateOperandException extends AwsException {
private UpdateOperandException(String message) {
super("ValidationException", message, 400);
}
static UpdateOperandException absentAttribute() {
return new UpdateOperandException(
"The provided expression refers to an attribute that does not exist in the item");
}
static UpdateOperandException incorrectType() {
return new UpdateOperandException("An operand in the update expression has an incorrect data type");
}
}
@@ -4075,6 +4075,105 @@ class DynamoDbServiceTest {
assertEquals(mapper.readTree(expected), service.getItem("Users", item("userId", "u1"), region).get(attribute));
}
private static final String ABSENT_ATTRIBUTE =
"The provided expression refers to an attribute that does not exist in the item";
private static final String INCORRECT_TYPE = "An operand in the update expression has an incorrect data type";
private ObjectNode putOperandItem(String region) throws IOException {
createUsersTable(region);
ObjectNode stored = (ObjectNode) mapper.readTree("""
{"userId":{"S":"u1"},"n":{"N":"10"},"k":{"L":[{"N":"4"},{"N":"5"}]},
"m":{"M":{"x":{"N":"1"}}},"s":{"S":"str"}}""");
service.putItem("Users", stored, region);
return stored;
}
private ObjectNode operandValues() throws IOException {
return (ObjectNode) mapper.readTree("""
{":v":{"N":"2"},":l":{"L":[{"S":"x"}]}}""");
}
@ParameterizedTest
@CsvSource(delimiter = '|', textBlock = """
SET a = z | absent
SET a = (z) | absent
SET a = m.y | absent
SET a = m.x.y | absent
SET a = n.x | absent
SET a = k[5] | absent
SET a = m[0] | absent
SET a = if_not_exists(z, y) | absent
SET a = if_not_exists(z, if_not_exists(y, x)) | absent
SET a = if_not_exists(m.y, m.z) | absent
SET a = z + :v | absent
SET a = :v + z | absent
SET a = if_not_exists(z, y) + :v | absent
SET l = list_append(z, :l) | absent
SET l = list_append(if_not_exists(z, y), :l) | absent
SET b = :v, a = z | absent
SET a = z REMOVE n | absent
SET a = z + s | absent
SET a = s + :v | type
SET a = s + z | type
SET l = list_append(s, :l) | type
SET l = list_append(s, z) | type
ADD s :v | type
""")
void updateItemRefusesAnOperandTheItemCannotServe(String expression, String error) throws IOException {
String region = "eu-west-1";
ObjectNode stored = putOperandItem(region);
AwsException ex = assertThrows(AwsException.class, () -> service.updateItem("Users", item("userId", "u1"),
null, expression, null, operandValues(), null, region));
assertEquals("ValidationException", ex.getErrorCode());
assertEquals("absent".equals(error) ? ABSENT_ATTRIBUTE : INCORRECT_TYPE, ex.getMessage());
assertEquals(stored, service.getItem("Users", item("userId", "u1"), region));
}
@Test
void updateItemRefusingAnAbsentOperandCreatesNoItem() {
String region = "eu-west-1";
createUsersTable(region);
AwsException ex = assertThrows(AwsException.class, () -> service.updateItem("Users", item("userId", "new"),
null, "SET a = z", null, null, null, region));
assertEquals(ABSENT_ATTRIBUTE, ex.getMessage());
assertNull(service.getItem("Users", item("userId", "new"), region));
}
@ParameterizedTest
@CsvSource(delimiter = '|', textBlock = """
SET a = z | absent
SET a = if_not_exists(z, y) | absent
SET a = s + :v | type
SET l = list_append(s, :l) | type
ADD s :v | type
""")
void transactWriteItemsCancelsAnUpdateWhoseOperandTheItemCannotServe(String expression, String error)
throws IOException {
String region = "eu-west-1";
ObjectNode stored = putOperandItem(region);
JsonNode put = mapper.readTree("""
{"Put":{"TableName":"Users","Item":{"userId":{"S":"other"}}}}""");
ObjectNode update = mapper.createObjectNode();
ObjectNode member = update.putObject("Update");
member.put("TableName", "Users");
member.set("Key", item("userId", "u1"));
member.put("UpdateExpression", expression);
if (expression.contains(":")) {
member.set("ExpressionAttributeValues", operandValues());
}
TransactionCanceledException ex = assertThrows(TransactionCanceledException.class,
() -> service.transactWriteItems(List.of(put, update), region));
List<TransactionCanceledException.CancellationReason> reasons = ex.getCancellationReasons();
assertEquals("", reasons.get(0).code());
assertEquals("ValidationError", reasons.get(1).code());
assertEquals("absent".equals(error) ? ABSENT_ATTRIBUTE : INCORRECT_TYPE, reasons.get(1).message());
assertEquals(stored, service.getItem("Users", item("userId", "u1"), region));
assertNull(service.getItem("Users", item("userId", "other"), region));
}
@Test
void transactWriteItemsReplayWithSameTokenAndBodyIsNoOp() {
// ClientRequestToken contract: same token + same body → no re-application of writes.