fix(dynamodb): refuse a reserved attribute name in written order before the table lookup (#8274)

This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-14 09:34:59 -04:00
1 parent 869a5fcb59
commit c5e7c3d84e
8 files changed
+131 -35

No files matched your search

@@ -17,8 +17,7 @@ final class DynamoDbReservedWords {
// and should not be treated as attribute name tokens.
private static final Set<String> CLAUSE_KEYWORDS = Set.of(
"SET", "REMOVE", "ADD", "DELETE",
"AND", "OR", "NOT", "BETWEEN", "IN",
"TRUE", "FALSE"
"AND", "OR", "NOT", "BETWEEN", "IN"
);
// DynamoDB reserved words list (uppercase). DynamoDB documents SIZE too, but accepts it as an attribute name.
@@ -128,7 +127,7 @@ final class DynamoDbReservedWords {
static AwsException reservedWord(String expressionType, String ident) {
return new AwsException("ValidationException",
"Invalid " + expressionType + ": Attribute name is a reserved keyword; "
+ "reserved word: " + ident, 400);
+ "reserved keyword: " + ident, 400);
}
private static List<String> extractBareIdentifiers(String expr) {
@@ -537,6 +537,9 @@ final class ExpressionEvaluator {
if (segment.startsWith("#") && (names == null || !names.has(segment))) {
throw undefinedName(exprType, segment);
}
if (DynamoDbReservedWords.isReserved(segment)) {
throw DynamoDbReservedWords.reservedWord(exprType, segment);
}
}
}
case PlaceholderOperand placeholder -> {
@@ -1388,13 +1388,13 @@ public class NativeDynamoDbJsonHandler {
DynamoDbAttributeValueValidator.requireNestingWithinLimit(legacyValues(queryFilter), false);
ExpressionEvaluator.validateSyntax(keyConditionExpr, "KeyConditionExpression");
ExpressionEvaluator.validateSyntax(filterExpr, "FilterExpression");
// DynamoDB reports filter errors before projection errors, and projection before key-condition.
// DynamoDB reports filter errors first, then key-condition errors, then projection errors.
ExpressionEvaluator.validateSemantics(filterExpr, "FilterExpression", exprAttrNames, exprAttrValues);
ProjectionEvaluator.validateExpression(projectionExpression, exprAttrNames);
// Must run before DynamoDbAccessPathValidator below: an unresolved #name there falls
// through to "Query condition missed key schema element" instead of the real cause.
ExpressionEvaluator.validateSemantics(keyConditionExpr, "KeyConditionExpression", exprAttrNames, exprAttrValues);
DynamoDbAccessPathValidator.validateKeyConditionAttributes(keyConditionExpr, exprAttrNames);
ProjectionEvaluator.validateExpression(projectionExpression, exprAttrNames);
if (select != null && !VALID_SELECT.contains(select)) {
throw SmithyValidationErrors.validationException(
@@ -3279,6 +3279,18 @@ public class NativeDynamoDbJsonHandler {
"ProjectionExpression");
}
// DynamoDB checks every ProjectionExpression before the table lookup.
for (JsonNode txItem : transactItemsNode) {
JsonNode get = txItem.has("Get") ? txItem.get("Get") : null;
if (get == null) {
continue;
}
String pe = get.has("ProjectionExpression") ? get.get("ProjectionExpression").asText() : null;
if (pe != null) {
ProjectionEvaluator.validateExpression(pe, get.get("ExpressionAttributeNames"));
}
}
Map<String, TableDefinition> tableCache = new HashMap<>();
Set<String> seenGet = new HashSet<>();
for (JsonNode txItem : transactItemsNode) {
@@ -3303,16 +3315,6 @@ public class NativeDynamoDbJsonHandler {
}
}
// Validate the ProjectionExpression in each Get action before executing
for (JsonNode txItem : transactItemsNode) {
JsonNode get = txItem.has("Get") ? txItem.get("Get") : null;
if (get == null) continue;
String pe = get.has("ProjectionExpression") ? get.get("ProjectionExpression").asText() : null;
if (pe != null) {
ProjectionEvaluator.validateExpression(pe, get.get("ExpressionAttributeNames"));
}
}
List<JsonNode> transactItems = new ArrayList<>();
transactItemsNode.forEach(transactItems::add);
@@ -101,13 +101,13 @@ final class ProjectionEvaluator {
static void validateExpression(String expression, JsonNode exprAttrNames) {
validateSyntax(expression, "ProjectionExpression");
DynamoDbReservedWords.check(expression, "ProjectionExpression");
validatePaths(expression, exprAttrNames);
}
/**
* Rejects an undefined #alias, and any two paths where one covers the other.
* DynamoDB applies both before the read, so a request that matches nothing still fails.
* Rejects an undefined #alias, a reserved word, and a path that overlaps an earlier one.
* DynamoDB checks each path in written order before the read, so a request that matches
* nothing still fails.
*/
static void validatePaths(String expression, JsonNode exprAttrNames) {
if (expression == null || expression.isBlank()) {
@@ -116,21 +116,18 @@ final class ProjectionEvaluator {
List<List<PathSegment>> paths = new ArrayList<>();
for (String rawPath : splitProjectionPaths(expression)) {
List<PathSegment> segments = resolvePath(rawPath.trim(), exprAttrNames, true);
if (!segments.isEmpty()) {
paths.add(segments);
if (segments.isEmpty()) {
continue;
}
}
for (int i = 0; i < paths.size(); i++) {
List<PathSegment> first = paths.get(i);
for (int j = i + 1; j < paths.size(); j++) {
List<PathSegment> second = paths.get(j);
if (covers(first, second) || covers(second, first)) {
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(first)
+ ", path two: " + render(second), 400);
+ "must remove or rewrite one of these paths; path one: " + render(earlier)
+ ", path two: " + render(segments), 400);
}
}
paths.add(segments);
}
}
@@ -255,6 +252,9 @@ final class ProjectionEvaluator {
private static String resolveSegment(String seg, JsonNode exprAttrNames, boolean requireDefinedNames) {
if (!seg.startsWith("#")) {
if (requireDefinedNames && DynamoDbReservedWords.isReserved(seg)) {
throw DynamoDbReservedWords.reservedWord("ProjectionExpression", seg);
}
return seg;
}
JsonNode resolved = exprAttrNames != null ? exprAttrNames.get(seg) : null;
@@ -107,7 +107,8 @@ class DynamoDbAccessPathIntegrationTest {
request("DynamoDB_20120810.Query", """
{
"TableName":"%s",
"KeyConditionExpression":"pk = :pk AND status = :status",
"KeyConditionExpression":"pk = :pk AND #status = :status",
"ExpressionAttributeNames":{"#status":"status"},
"ExpressionAttributeValues":{
":pk":{"S":"p1"},
":status":{"S":"open"}
@@ -1490,7 +1490,8 @@ class DynamoDbIntegrationTest {
{
"TableName": "TestTable",
"KeyConditionExpression": "pk = :pk",
"FilterExpression": "total >= :min",
"FilterExpression": "#total >= :min",
"ExpressionAttributeNames": {"#total": "total"},
"ExpressionAttributeValues": {
":pk": {"S": "user-1"},
":min": {"N": "50"}
@@ -1516,7 +1517,8 @@ class DynamoDbIntegrationTest {
{
"TableName": "TestTable",
"KeyConditionExpression": "pk = :pk",
"FilterExpression": "total >= :min",
"FilterExpression": "#total >= :min",
"ExpressionAttributeNames": {"#total": "total"},
"Limit": 2,
"ExpressionAttributeValues": {
":pk": {"S": "user-1"},
@@ -6006,7 +6008,7 @@ given()
"UpdateExpression": "SET q = :w", "ExpressionAttributeValues": {":w": {"S": "w"}, ":z": {"S": "z"}} | Value provided in ExpressionAttributeValues unused in expressions: keys: {:z}
"UpdateExpression": "" | Invalid UpdateExpression: The expression can not be empty;
"UpdateExpression": "", "ConditionExpression": "a = :missing" | Invalid ConditionExpression: An expression attribute value used in expression is not defined; attribute value: :missing
"UpdateExpression": "SET name = :w", "ExpressionAttributeValues": {":w": {"S": "w"}} | Invalid UpdateExpression: Attribute name is a reserved keyword; reserved word: name
"UpdateExpression": "SET name = :w", "ExpressionAttributeValues": {":w": {"S": "w"}} | Invalid UpdateExpression: Attribute name is a reserved keyword; reserved keyword: name
"UpdateExpression": "SET q = :w", "AttributeUpdates": {"q": {"Action": "PUT", "Value": {"S": "w"}}} | Can not use both expression and non-expression parameters in the same request: Non-expression parameters: {AttributeUpdates} Expression parameters: {UpdateExpression}
""")
void updateItemPutsExpressionErrorsInTheValidationEnvelope(String members, String message) {
@@ -2440,13 +2440,16 @@ class NativeDynamoDbJsonHandlerTest {
SET a = if_not_exists(:n, :u) | An expression attribute value used in expression is not defined; attribute value: :u
SET a = list_append(:l, :l) + :u | The function is not allowed to be used this way in an expression; function: list_append
SET a = :s + :u | An expression attribute value used in expression is not defined; attribute value: :u
SET out = foo(:n) | Attribute name is a reserved keyword; reserved word: out
SET out = foo(:n) | Attribute name is a reserved keyword; reserved keyword: out
SET a = foo(:n), out = :n | Invalid function name; function: foo
SET out = :u | Attribute name is a reserved keyword; reserved word: out
SET out = :u | Attribute name is a reserved keyword; reserved keyword: out
ADD c :u SET a = foo(:n) | An expression attribute value used in expression is not defined; attribute value: :u
ADD b :s SET a = foo(:n) | Incorrect operand type for operator or function; operator: ADD, operand type: STRING, typeSet: ALLOWED_FOR_ADD_OPERAND
SET a = foo(:n) ADD b :s | Invalid function name; function: foo
SET a = foo(:n) SET b = :n | Invalid function name; function: foo
SET a = true | Attribute name is a reserved keyword; reserved keyword: true
ADD true :s | Attribute name is a reserved keyword; reserved keyword: true
REMOVE false | Attribute name is a reserved keyword; reserved keyword: false
""")
void updateItemChecksNamesValuesAndCallsInWrittenOrder(String expression, String message) {
ObjectNode request = updateUserRequest();
@@ -2478,7 +2481,7 @@ class NativeDynamoDbJsonHandlerTest {
@ParameterizedTest
@CsvSource(delimiter = '|', textBlock = """
SET a = foo(:n) | Invalid function name; function: foo
SET out = :n | Attribute name is a reserved keyword; reserved word: out
SET out = :n | Attribute name is a reserved keyword; reserved keyword: out
SET a = foo(:n), out = :n | Invalid function name; function: foo
DELETE a :n | Incorrect operand type for operator or function; operator: DELETE, operand type: NUMBER, typeSet: ALLOWED_FOR_DELETE_OPERAND
""")
@@ -2497,6 +2500,72 @@ class NativeDynamoDbJsonHandlerTest {
assertEquals("Invalid UpdateExpression: " + message, ex.getMessage());
}
@ParameterizedTest
@CsvSource(delimiter = '|', textBlock = """
Scan | {"TableName":"Missing","FilterExpression":"name = :w","ExpressionAttributeValues":{":w":{"S":"w"}}} | Invalid FilterExpression
Scan | {"TableName":"Missing","ProjectionExpression":"name"} | Invalid ProjectionExpression
Query | {"TableName":"Missing","KeyConditionExpression":"userId = :w AND name = :w","ExpressionAttributeValues":{":w":{"S":"w"}}} | Invalid KeyConditionExpression
Query | {"TableName":"Missing","KeyConditionExpression":"userId = :w","FilterExpression":"name = :w","ExpressionAttributeValues":{":w":{"S":"w"}}} | Invalid FilterExpression
GetItem | {"TableName":"Missing","Key":{"userId":{"S":"u1"}},"ProjectionExpression":"a.name"} | Invalid ProjectionExpression
TransactGetItems | {"TransactItems":[{"Get":{"TableName":"Missing","Key":{"userId":{"S":"u1"}},"ProjectionExpression":"a"}},{"Get":{"TableName":"Missing","Key":{"userId":{"S":"u1"}},"ProjectionExpression":"name"}}]} | Invalid ProjectionExpression
PutItem | {"TableName":"Missing","Item":{"userId":{"S":"u1"}},"ConditionExpression":"attribute_exists(name)"} | 1 validation error detected: Invalid ConditionExpression
DeleteItem | {"TableName":"Missing","Key":{"userId":{"S":"u1"}},"ConditionExpression":"a[0].name = :w","ExpressionAttributeValues":{":w":{"S":"w"}}} | 1 validation error detected: Invalid ConditionExpression
UpdateItem | {"TableName":"Missing","Key":{"userId":{"S":"u1"}},"UpdateExpression":"SET status = :w","ConditionExpression":"name = :w","ExpressionAttributeValues":{":w":{"S":"w"}}} | 1 validation error detected: Invalid ConditionExpression
UpdateItem | {"TableName":"Missing","Key":{"userId":{"S":"u1"}},"UpdateExpression":"SET name = :w","ExpressionAttributeValues":{":w":{"S":"w"}}} | 1 validation error detected: Invalid UpdateExpression
TransactWriteItems | {"TransactItems":[{"ConditionCheck":{"TableName":"Missing","Key":{"userId":{"S":"u1"}},"ConditionExpression":"NOT name = :w","ExpressionAttributeValues":{":w":{"S":"w"}}}}]} | Invalid ConditionExpression
""")
void everyExpressionRefusesAReservedWordBeforeTheTableLookup(String operation, String request, String prefix)
throws Exception {
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle(operation, mapper.readTree(request), "eu-west-1"));
assertEquals("ValidationException", ex.getErrorCode());
assertEquals(prefix + ": Attribute name is a reserved keyword; reserved keyword: name", ex.getMessage());
}
@ParameterizedTest
@CsvSource(delimiter = '|', textBlock = """
name = :missing | Attribute name is a reserved keyword; reserved keyword: name
:missing = name | An expression attribute value used in expression is not defined; attribute value: :missing
name.#u = :w | Attribute name is a reserved keyword; reserved keyword: name
'#u.name = :w' | An expression attribute name used in the document path is not defined; attribute name: #u
name < :b | Attribute name is a reserved keyword; reserved keyword: name
a < :b AND name = :w | Incorrect operand type for operator or function; operator or function: <, operand type: BOOL
name = :w AND a < :b | Attribute name is a reserved keyword; reserved keyword: name
contains(name, name) | Attribute name is a reserved keyword; reserved keyword: name
status = :w AND name = :w | Attribute name is a reserved keyword; reserved keyword: status
NaMe = :w | Attribute name is a reserved keyword; reserved keyword: NaMe
true = :w | Attribute name is a reserved keyword; reserved keyword: true
attribute_exists(false) | Attribute name is a reserved keyword; reserved keyword: false
""")
void conditionExpressionChecksReservedWordsInWrittenOrder(String expression, String message) throws Exception {
ObjectNode request = (ObjectNode) mapper.readTree("""
{"TableName":"Missing","Item":{"userId":{"S":"u1"}},
"ExpressionAttributeValues":{":w":{"S":"w"},":b":{"BOOL":true},":z":{"S":"z"}}}
""");
request.put("ConditionExpression", expression);
AwsException ex = assertThrows(AwsException.class, () -> handler.handle("PutItem", request, "eu-west-1"));
assertEquals("1 validation error detected: Invalid ConditionExpression: " + message, ex.getMessage());
}
@ParameterizedTest
@CsvSource(delimiter = '|', textBlock = """
userId = :w AND name = :w | status | Invalid KeyConditionExpression: Attribute name is a reserved keyword; reserved keyword: name
userId = :w AND sk > :w AND sk < :w | a, a | Invalid KeyConditionExpression: KeyConditionExpressions must only contain one condition per key
userId = :w | status | Invalid ProjectionExpression: Attribute name is a reserved keyword; reserved keyword: status
""")
void queryChecksTheKeyConditionBeforeTheProjection(String keyCondition, String projection, String message)
throws Exception {
ObjectNode request = (ObjectNode) mapper.readTree("""
{"TableName":"Missing","ExpressionAttributeValues":{":w":{"S":"w"}}}
""");
request.put("KeyConditionExpression", keyCondition);
request.put("ProjectionExpression", projection);
AwsException ex = assertThrows(AwsException.class, () -> handler.handle("Query", request, "eu-west-1"));
assertEquals(message, ex.getMessage());
}
@ParameterizedTest
@CsvSource(delimiter = '|', textBlock = """
SET a = :v SET b = :v | SET
@@ -5,6 +5,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.Set;
@@ -330,6 +332,24 @@ class ProjectionEvaluatorTest {
ex.getMessage());
}
@ParameterizedTest
@CsvSource(delimiter = '|', textBlock = """
'#u, name' | An expression attribute name used in the document path is not defined; attribute name: #u
name, #u | Attribute name is a reserved keyword; reserved keyword: name
a[0].name | Attribute name is a reserved keyword; reserved keyword: name
STATUS | Attribute name is a reserved keyword; reserved keyword: STATUS
true | Attribute name is a reserved keyword; reserved keyword: true
a, a.b, name | Two document paths overlap with each other; must remove or rewrite one of these paths; path one: [a], path two: [a, b]
a, name, a.b | Attribute name is a reserved keyword; reserved keyword: name
a, a.b, #u | Two document paths overlap with each other; must remove or rewrite one of these paths; path one: [a], path two: [a, b]
a.b, c.d, c, a | Two document paths overlap with each other; must remove or rewrite one of these paths; path one: [c, d], path two: [c]
""")
void checksEachPathInWrittenOrder(String expression, String message) {
AwsException ex = assertThrows(AwsException.class,
() -> ProjectionEvaluator.validateExpression(expression, null));
assertEquals("Invalid ProjectionExpression: " + message, ex.getMessage());
}
@Test
void rejectsAListAndOneOfItsElements() {
AwsException ex = assertThrows(AwsException.class,