fix(dynamodb): refuse a nested or repeated key condition attribute before the table lookup (#7883)

* fix(dynamodb): refuse a nested or repeated key condition attribute before the table lookup

DynamoDB reports a KeyConditionExpression condition on a nested attribute,
or a second condition on the same attribute, with the
"Invalid KeyConditionExpression: " prefix. It checks both after the
expression walk and before the Select enum, the table lookup and the key
schema checks.

* fix(dynamodb): read key conditions grouped in parentheses as one list

DynamoDB reads AND groups in parentheses in a KeyConditionExpression as
if the parentheses were not there. This holds for the nested and
repeated attribute checks and for the key schema checks.

* fix(dynamodb): read grouped key conditions as one list for dynamodb:LeadingKeys

The IAM condition key reader now flattens AND groups the same way as the
key condition checks. A grouped condition like
"(h1 = :a AND h2 = :b) AND r1 = :c" on a multi-attribute index gave no
leading key, and a ForAllValues condition passes when that key is absent.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-10 09:33:07 -04:00
1 parent 4512de1402
commit 2e158f7d1d
6 files changed
+113 -33

No files matched your search

@@ -116,35 +116,46 @@ final class DynamoDbAccessPathValidator {
}
}
// DynamoDB checks these before it looks up the table.
static void validateKeyConditionAttributes(String expression, JsonNode names) {
if (expression == null) {
return;
}
Set<String> conditionedAttributes = new HashSet<>();
for (Expr rawCondition : keyConditions(expression)) {
Expr condition = normalizeOperandOrder(rawCondition);
if (conditionOperand(condition) instanceof PathOperand(List<String> segments) && segments.size() > 1) {
throw validationException("Invalid KeyConditionExpression: "
+ "KeyConditionExpressions cannot have conditions on nested attributes");
}
String attribute = conditionAttribute(condition, names);
if (attribute != null && !conditionedAttributes.add(attribute)) {
throw validationException("Invalid KeyConditionExpression: "
+ "KeyConditionExpressions must only contain one condition per key");
}
}
}
private static List<Expr> keyConditions(String expression) {
return DynamoDbKeyConditionParser.conditions(parseExpression(expression, "KeyConditionExpression"));
}
private static String validateKeyConditionExpression(TableDefinition table,
DynamoDbAccessPath accessPath,
String expression, JsonNode names,
JsonNode values) {
Expr root = parseExpression(expression, "KeyConditionExpression");
List<Expr> conditions = root instanceof AndExpr and
? and.operands() : List.of(root);
List<String> partitionKeys = accessPath.partitionKeyNames();
Set<String> partitionKeySet = Set.copyOf(partitionKeys);
List<String> sortKeys = accessPath.sortKeyNames();
Set<String> conditionedPartitionKeys = new HashSet<>();
String partitionKeyValuePlaceholder = null;
Set<String> conditionedAttributes = new HashSet<>();
Map<String, Boolean> sortKeyEqualities = new HashMap<>();
boolean conditionOnNonKeyAttribute = false;
for (Expr rawCondition : conditions) {
for (Expr rawCondition : keyConditions(expression)) {
Expr condition = normalizeOperandOrder(rawCondition);
if (conditionOperand(condition) instanceof PathOperand(List<String> segments) && segments.size() > 1) {
throw new AwsException("ValidationException",
"KeyConditionExpressions cannot have conditions on nested attributes", 400);
}
String attribute = conditionAttribute(condition, names);
if (attribute != null && !conditionedAttributes.add(attribute)) {
throw new AwsException("ValidationException",
"KeyConditionExpressions must only contain one condition per key", 400);
}
if (attribute != null && partitionKeySet.contains(attribute)) {
if (!isPartitionKeyEquality(condition)) {
throw new AwsException("ValidationException", "Query key condition not supported", 400);
@@ -8,6 +8,7 @@ import io.floci.aws.services.dynamodb.ExpressionEvaluator.PathOperand;
import io.floci.aws.services.dynamodb.ExpressionEvaluator.PlaceholderOperand;
import io.floci.aws.services.dynamodb.ExpressionEvaluator.TokenType;
import java.util.ArrayList;
import java.util.List;
/**
@@ -49,8 +50,7 @@ final class DynamoDbKeyConditionParser {
if (root == null) {
return null;
}
List<Expr> conditions = root instanceof AndExpr and ? and.operands() : List.of(root);
for (Expr condition : conditions) {
for (Expr condition : conditions(root)) {
if (!(condition instanceof CompareExpr compare) || compare.op() != TokenType.EQ) {
continue;
}
@@ -66,6 +66,21 @@ final class DynamoDbKeyConditionParser {
return null;
}
// DynamoDB reads AND groups in parentheses as one list of key conditions.
static List<Expr> conditions(Expr root) {
List<Expr> conditions = new ArrayList<>();
addConditions(root, conditions);
return conditions;
}
private static void addConditions(Expr expression, List<Expr> conditions) {
if (expression instanceof AndExpr and) {
and.operands().forEach(operand -> addConditions(operand, conditions));
} else {
conditions.add(expression);
}
}
/** Resolves a single-segment path operand, following a {@code #alias} when one is used. */
private static String topLevelAttribute(Object operand, JsonNode exprAttrNames) {
if (!(operand instanceof PathOperand path) || path.segments().size() != 1) {
@@ -1330,6 +1330,7 @@ public class NativeDynamoDbJsonHandler {
// 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);
if (select != null && !VALID_SELECT.contains(select)) {
throw SmithyValidationErrors.validationException(
@@ -12,6 +12,7 @@ import org.junit.jupiter.api.TestMethodOrder;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static io.restassured.RestAssured.given;
@@ -118,6 +119,27 @@ class DynamoDbAccessPathIntegrationTest {
.body("message", equalTo("Query key condition not supported"));
}
@Test
@Order(12)
void queryRefusesANestedOrRepeatedKeyConditionAttributeBeforeTheTableLookup() {
Map<String, String> errors = Map.of(
"pk = :pk AND sk > :a AND sk < :b", "must only contain one condition per key",
"pk = :pk AND (sk > :a AND sk < :b)", "must only contain one condition per key",
"pk = :pk AND x.y = :a", "cannot have conditions on nested attributes",
"(pk = :pk AND sk > :a) AND x.y = :b", "cannot have conditions on nested attributes");
for (String table : List.of(TABLE, "access-path-validation-missing")) {
errors.forEach((expression, error) -> request("DynamoDB_20120810.Query", """
{
"TableName":"%s",
"KeyConditionExpression":"%s",
"ExpressionAttributeValues":{":pk":{"S":"p1"},":a":{"S":"a"},":b":{"S":"b"}}
}
""".formatted(table, expression))
.statusCode(400)
.body("message", equalTo("Invalid KeyConditionExpression: KeyConditionExpressions " + error)));
}
}
@Test
@Order(4)
void tableAndLsiUseTheirSelectedKeySchemas() {
@@ -12,6 +12,8 @@ import io.floci.aws.services.dynamodb.model.LocalSecondaryIndex;
import io.floci.aws.services.dynamodb.model.TableDefinition;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.List;
import java.util.regex.MatchResult;
@@ -78,6 +80,14 @@ class DynamoDbAccessPathValidatorTest {
"region = :r AND tenantId = :t"));
}
@Test
void acceptsKeyConditionsGroupedInParentheses() {
assertDoesNotThrow(() -> validateExpression(compositePkGsiPath,
"tenantId = :t AND (region = :r AND createdAt > :c)"));
assertDoesNotThrow(() -> validateExpression(compositePkGsiPath,
"(tenantId = :t AND region = :r) AND (createdAt > :c)"));
}
@Test
void rejectsCompositePartitionKeyQueryMissingOneHashAttribute() {
AwsException error = assertThrows(AwsException.class,
@@ -186,14 +196,6 @@ class DynamoDbAccessPathValidatorTest {
() -> validateExpression(tablePath, "pk = :pk AND sk <> :sk"));
}
@Test
void rejectsDuplicateAndNestedKeyConditions() {
assertThrows(AwsException.class, () -> validateExpression(
tablePath, "pk = :pk AND sk > :start AND sk < :end"));
assertThrows(AwsException.class, () -> validateExpression(
tablePath, "pk.value = :pk"));
}
@Test
void rejectsMalformedKeyAndFilterExpressions() {
AwsException keyError = assertThrows(AwsException.class,
@@ -375,19 +377,41 @@ class DynamoDbAccessPathValidatorTest {
assertDoesNotThrow(() -> validateExpression(tablePath, "pk = :pk AND :hi > sk"));
}
@Test
void rejectsANestedPathOnAKeyAttribute() {
@ParameterizedTest
@CsvSource(delimiter = '|', textBlock = """
pk.value = :pk | cannot have conditions on nested attributes
pk = :pk AND #sk.foo = :v | cannot have conditions on nested attributes
pk = :pk AND x[0] = :v | cannot have conditions on nested attributes
pk = :pk AND x.y BETWEEN :a AND :b | cannot have conditions on nested attributes
pk = :pk AND begins_with(x.y, :v) | cannot have conditions on nested attributes
pk = :pk AND x.y = :v AND sk > :a AND sk < :b | cannot have conditions on nested attributes
pk = :pk AND sk > :a AND sk < :b AND x.y = :v | must only contain one condition per key
pk = :pk AND #sk > :a AND sk < :b | must only contain one condition per key
pk = :pk AND :a < sk AND sk < :b | must only contain one condition per key
x = :a AND x = :b AND pk = :pk | must only contain one condition per key
pk = :pk AND pk = :pk | must only contain one condition per key
pk = :pk AND (sk > :a AND x.y = :v) | cannot have conditions on nested attributes
pk = :pk AND (sk > :a AND sk < :b) | must only contain one condition per key
(pk = :pk AND sk > :a) AND sk < :b | must only contain one condition per key
pk = :pk AND (sk > :a AND (sk < :b)) | must only contain one condition per key
""")
void refusesANestedOrRepeatedAttributeInAKeyCondition(String expression, String error) {
ObjectNode names = mapper.createObjectNode();
names.put("#sk", "sk");
ObjectNode values = expressionValues(":pk", ":v");
AwsException error = assertThrows(AwsException.class,
() -> DynamoDbAccessPathValidator.validateQuery(
table, tablePath, null, "pk = :pk AND #sk.foo = :v",
null, null, names, values));
AwsException thrown = assertThrows(AwsException.class,
() -> DynamoDbAccessPathValidator.validateKeyConditionAttributes(expression, names));
assertEquals("KeyConditionExpressions cannot have conditions on nested attributes",
error.getMessage());
assertEquals("Invalid KeyConditionExpression: KeyConditionExpressions " + error, thrown.getMessage());
}
@Test
void acceptsANameThatHoldsADotInAKeyCondition() {
ObjectNode names = mapper.createObjectNode();
names.put("#a", "x.y");
assertDoesNotThrow(() -> DynamoDbAccessPathValidator.validateKeyConditionAttributes(
"pk = :pk AND #a = :v", names));
}
@Test
@@ -32,6 +32,13 @@ class DynamoDbKeyConditionParserTest {
json("{\":v\":{\"S\":\"USER_alice\"},\":s\":{\"S\":\"2020\"}}"), "pk"));
}
@Test
void resolvesPartitionKeyEqualityInsideAGroupedCondition() {
assertEquals("USER_alice", DynamoDbKeyConditionParser.partitionKeyEqualityValue(
"(h1 = :a AND h2 = :b) AND r1 = :c", null,
json("{\":a\":{\"S\":\"USER_alice\"},\":b\":{\"S\":\"x\"},\":c\":{\"S\":\"y\"}}"), "h1"));
}
@Test
void resolvesAnAliasedPartitionKeyThroughExpressionAttributeNames() {
assertEquals("USER_alice", DynamoDbKeyConditionParser.partitionKeyEqualityValue(