fix(dynamodb): honor OR in legacy Query and Scan filters (#8031)

* fix(dynamodb): honor OR in legacy Query and Scan filters

Pass ConditionalOperator to the shared legacy read-filter evaluator while retaining default AND behavior and read-before-filter pagination. Reuse one nested-map fixture builder for the four existing expressions. Separate follow-up requested in upstream #8023.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(dynamodb): validate legacy binary filters before matching

Validate every legacy QueryFilter and ScanFilter binary operand through the existing attribute validator before evaluating items. Keep ConditionalOperator validation first and retain valid-filter short circuit behavior. Add actual JSON wire invalid and valid binary controls.

Signed-off-by: Andre Kurait <akurait@amazon.com>

---------

Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-11 12:46:45 -04:00
1 parent aea5c9ad05
commit b954b4fb87
8 files changed
+213 -14

No files matched your search

+4
View File
@@ -102,6 +102,10 @@ use a `dynamodb:Select` condition when the policy must require specific attribut
## Legacy conditional requests
Legacy `QueryFilter` and `ScanFilter` honor `ConditionalOperator`: `OR` retains an
item when any condition matches; `AND`, including the omitted default, requires
every condition. Read limits and scanned counts apply before filtering.
The native backend accepts `KeyConditions` together with `FilterExpression`.
For legacy `Expected` conditions it also accepts `ComparisonOperator` with a single
`Value`, including EQ and NE, just as the live AWS service does. Supplying both
@@ -1707,6 +1707,15 @@ public class DynamoDbService {
JsonNode expressionAttrNames, JsonNode expressionAttrValues,
JsonNode scanFilter, Integer limit, JsonNode exclusiveStartKey,
String indexName, Integer segment, Integer totalSegments, String region) {
return scan(tableName, filterExpression, expressionAttrNames, expressionAttrValues,
scanFilter, limit, exclusiveStartKey, indexName, segment, totalSegments, "AND", region);
}
public ScanResult scan(String tableName, String filterExpression,
JsonNode expressionAttrNames, JsonNode expressionAttrValues,
JsonNode scanFilter, Integer limit, JsonNode exclusiveStartKey,
String indexName, Integer segment, Integer totalSegments,
String conditionalOperator, String region) {
DynamoDbReservedWords.check(filterExpression, "FilterExpression");
String canonicalTableName = canonicalTableName(region, tableName);
String storageKey = regionKey(region, canonicalTableName);
@@ -1779,7 +1788,7 @@ public class DynamoDbService {
lastScanned = item;
boolean matched = (filterExpression == null
|| matchesFilterExpression(item, filterExpression, expressionAttrNames, expressionAttrValues))
&& (scanFilter == null || matchesScanFilter(item, scanFilter));
&& (scanFilter == null || matchesScanFilterPublic(item, scanFilter, conditionalOperator));
if (matched) {
results.add(item);
}
@@ -1818,25 +1827,27 @@ public class DynamoDbService {
}
public boolean matchesScanFilterPublic(JsonNode item, JsonNode scanFilter) {
return matchesScanFilter(item, scanFilter);
return matchesScanFilterPublic(item, scanFilter, "AND");
}
public boolean matchesKeyConditionPublic(JsonNode attrValue, JsonNode condition) {
return matchesKeyCondition(attrValue, condition);
}
private boolean matchesScanFilter(JsonNode item, JsonNode scanFilter) {
public boolean matchesScanFilterPublic(JsonNode item, JsonNode scanFilter, String conditionalOperator) {
boolean useOr = "OR".equals(conditionalOperator);
Iterator<Map.Entry<String, JsonNode>> fields = scanFilter.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> entry = fields.next();
String attrName = entry.getKey();
JsonNode condition = entry.getValue();
JsonNode attrValue = item.get(attrName);
if (!matchesKeyCondition(attrValue, condition)) {
return false;
boolean matched = matchesKeyCondition(attrValue, condition);
if (matched == useOr) {
return useOr;
}
}
return true;
return !useOr;
}
// --- Batch Operations ---
@@ -1270,6 +1270,12 @@ public class NativeDynamoDbJsonHandler {
}
}
private void requireReadableFilterValues(JsonNode filter) {
ObjectNode values = legacyValues(filter);
values.forEach(DynamoDbAttributeValueValidator::requireBase64);
requireReadableValues(values, "");
}
private static final List<String> CONDITIONAL_OPERATORS = List.of("AND", "OR");
private static void requireValidConditionalOperator(JsonNode request, String filterMember) {
@@ -1345,7 +1351,7 @@ public class NativeDynamoDbJsonHandler {
requireReadableValues(exprAttrValues, "");
requireReadableValues(exclusiveStartKey, "");
requireReadableValues(legacyValues(keyConditions), "");
requireReadableValues(legacyValues(queryFilter), "");
requireReadableFilterValues(queryFilter);
if (keyConditionExpr == null && keyConditions == null) {
throw new AwsException("ValidationException",
@@ -1416,7 +1422,7 @@ public class NativeDynamoDbJsonHandler {
if (queryFilter != null) {
final JsonNode qf = queryFilter;
queryItems = queryItems.stream()
.filter(i -> dynamoDbService.matchesScanFilterPublic(i, qf))
.filter(i -> dynamoDbService.matchesScanFilterPublic(i, qf, textOrNull(request, "ConditionalOperator")))
.toList();
}
// Apply index projection (KEYS_ONLY / INCLUDE) when querying a secondary index
@@ -1513,7 +1519,7 @@ public class NativeDynamoDbJsonHandler {
requireValidConditionalOperator(request, "ScanFilter");
requireReadableValues(exprAttrValues, "");
requireReadableValues(exclusiveStartKey, "");
requireReadableValues(legacyValues(scanFilter), "");
requireReadableFilterValues(scanFilter);
DynamoDbExpressionSize.checkReadWithSize(filterExpr, "FilterExpression");
DynamoDbExpressionSize.checkRead(projectionExpressionScan, "ProjectionExpression");
@@ -1565,7 +1571,8 @@ public class NativeDynamoDbJsonHandler {
DynamoDbService.ScanResult result = dynamoDbService.scan(
tableName, filterExpr, exprAttrNames, exprAttrValues, scanFilter, limit,
exclusiveStartKey, indexNameScan, segment, totalSegments, region);
exclusiveStartKey, indexNameScan, segment, totalSegments,
textOrNull(request, "ConditionalOperator"), region);
List<JsonNode> scanItems = result.items();
// Apply index projection (KEYS_ONLY / INCLUDE) when scanning a secondary index
@@ -0,0 +1,166 @@
package io.floci.aws.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import io.floci.aws.testing.AwsTestClients;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.BillingMode;
import software.amazon.awssdk.services.dynamodb.model.Condition;
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
import software.amazon.awssdk.services.dynamodb.model.KeyType;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
import software.amazon.awssdk.services.dynamodb.model.ScanResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class DynamoDbConditionalOperatorIntegrationTest {
private static final ObjectMapper JSON = new ObjectMapper();
private static final ObjectMapper CBOR = new ObjectMapper(new CBORFactory());
@ParameterizedTest
@CsvSource({"Query,OR,3", "Scan,OR,3", "Query,AND,1", "Scan,AND,1", "Query,DEFAULT,1", "Scan,DEFAULT,1"})
void legacyFiltersCombineConditionsWithoutChangingReadPages(String action, String operator, int expected) throws Exception {
try (DynamoDbClient client = AwsTestClients.create(DynamoDbClient.builder(), "test", Region.US_EAST_1)) {
String table = "conditional-" + UUID.randomUUID();
client.createTable(r -> r.tableName(table).billingMode(BillingMode.PAY_PER_REQUEST)
.keySchema(KeySchemaElement.builder().attributeName("pk").keyType(KeyType.HASH).build(),
KeySchemaElement.builder().attributeName("sk").keyType(KeyType.RANGE).build())
.attributeDefinitions(AttributeDefinition.builder().attributeName("pk")
.attributeType(ScalarAttributeType.S).build(),
AttributeDefinition.builder().attributeName("sk").attributeType(ScalarAttributeType.S).build()));
try {
for (int index = 0; index < 4; index++) {
int value = index;
client.putItem(r -> r.tableName(table).item(Map.of("pk", text("group"),
"sk", text(Integer.toString(value)), "left", text(value < 2 ? "yes" : "no"),
"right", text(value % 2 == 0 ? "yes" : "no"))));
}
Map<String, Condition> filter = Map.of("left", equalToYes(), "right", equalToYes());
String conditionalOperator = "DEFAULT".equals(operator) ? null : operator;
Map<String, AttributeValue> cursor = null;
List<Map<String, AttributeValue>> items = new ArrayList<>();
int scanned = 0;
int pages = 0;
do {
if ("Query".equals(action)) {
QueryResponse response = client.query(QueryRequest.builder().tableName(table)
.keyConditions(Map.of("pk", Condition.builder().comparisonOperator("EQ")
.attributeValueList(text("group")).build()))
.queryFilter(filter).conditionalOperator(conditionalOperator).limit(1)
.exclusiveStartKey(cursor).build());
items.addAll(response.items());
scanned += response.scannedCount();
cursor = response.lastEvaluatedKey();
} else {
ScanResponse response = client.scan(ScanRequest.builder().tableName(table)
.scanFilter(filter).conditionalOperator(conditionalOperator).limit(1)
.exclusiveStartKey(cursor).build());
items.addAll(response.items());
scanned += response.scannedCount();
cursor = response.lastEvaluatedKey();
}
pages++;
if (pages > 5) {
throw new AssertionError("Pagination did not terminate");
}
} while (cursor != null && !cursor.isEmpty());
assertEquals(4, scanned);
assertEquals(expected, items.size());
assertEquals("OR".equals(operator) ? List.of("0", "1", "2") : List.of("0"),
items.stream().map(i -> i.get("sk").s()).sorted().toList());
assertCborCount(table, action, operator, expected);
} finally {
client.deleteTable(r -> r.tableName(table));
}
}
}
@ParameterizedTest
@CsvSource({"Query,OR,!!!!,400", "Scan,OR,!!!!,400", "Query,AND,!!!!,400", "Scan,AND,!!!!,400",
"Query,OR,Yg==,200", "Scan,OR,Yg==,200", "Query,AND,Yg==,200", "Scan,AND,Yg==,200"})
void binaryFilterOperandsAreValidatedBeforeCombination(String action, String operator,
String encoded, int status) throws Exception {
try (DynamoDbClient client = AwsTestClients.create(DynamoDbClient.builder(), "test", Region.US_EAST_1)) {
String table = "binary-filter-" + UUID.randomUUID();
client.createTable(r -> r.tableName(table).billingMode(BillingMode.PAY_PER_REQUEST)
.keySchema(KeySchemaElement.builder().attributeName("pk").keyType(KeyType.HASH).build())
.attributeDefinitions(AttributeDefinition.builder().attributeName("pk")
.attributeType(ScalarAttributeType.S).build()));
try {
client.putItem(r -> r.tableName(table).item(Map.of("pk", text("group"), "left", text("yes"),
"right", AttributeValue.builder().b(SdkBytes.fromUtf8String("a")).build())));
ObjectNode request = JSON.createObjectNode().put("TableName", table).put("ConditionalOperator", operator);
request.set("Query".equals(action) ? "QueryFilter" : "ScanFilter", JSON.readTree("""
{"left":{"ComparisonOperator":"EQ","AttributeValueList":[{"S":"yes"}]},
"right":{"ComparisonOperator":"LT","AttributeValueList":[{"B":"%s"}]}}
""".formatted(encoded)));
if ("Query".equals(action)) {
request.set("KeyConditions", JSON.readTree("""
{"pk":{"ComparisonOperator":"EQ","AttributeValueList":[{"S":"group"}]}}
"""));
}
String response = given().contentType("application/x-amz-json-1.0")
.header("X-Amz-Target", "DynamoDB_20120810." + action)
.body(JSON.writeValueAsBytes(request)).post("/").then().statusCode(status).extract().asString();
if (status == 400) {
assertEquals("SerializationException", JSON.readTree(response).path("__type").asText()
.replace("com.amazonaws.dynamodb.v20120810#", ""));
} else {
assertEquals(1, JSON.readTree(response).path("Count").asInt());
}
} finally {
client.deleteTable(r -> r.tableName(table));
}
}
}
private static void assertCborCount(String table, String action, String operator, int expected) throws Exception {
ObjectNode request = JSON.createObjectNode().put("TableName", table).put("Select", "COUNT");
if (!"DEFAULT".equals(operator)) {
request.put("ConditionalOperator", operator);
}
request.set("Query".equals(action) ? "QueryFilter" : "ScanFilter", JSON.readTree("""
{"left":{"ComparisonOperator":"EQ","AttributeValueList":[{"S":"yes"}]},
"right":{"ComparisonOperator":"EQ","AttributeValueList":[{"S":"yes"}]}}
"""));
if ("Query".equals(action)) {
request.set("KeyConditions", JSON.readTree("""
{"pk":{"ComparisonOperator":"EQ","AttributeValueList":[{"S":"group"}]}}
"""));
}
byte[] response = given().contentType("application/cbor").accept("application/cbor")
.body(CBOR.writeValueAsBytes(request)).post("/service/DynamoDB_20120810/operation/" + action)
.then().statusCode(200).extract().asByteArray();
JsonNode result = CBOR.readTree(response);
assertEquals(expected, result.path("Count").asInt());
assertEquals(4, result.path("ScannedCount").asInt());
}
private static Condition equalToYes() {
return Condition.builder().comparisonOperator("EQ").attributeValueList(text("yes")).build();
}
private static AttributeValue text(String value) {
return AttributeValue.builder().s(value).build();
}
}
@@ -23,6 +23,7 @@ import java.util.zip.CRC32;
import static io.floci.aws.testing.DynamoDbRequests.assertEpochMillisBetween;
import static io.floci.aws.testing.DynamoDbRequests.decimalAt;
import static io.floci.aws.testing.DynamoDbRequests.nestedMap;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -6004,7 +6005,7 @@ given()
""")
void itemWritesGetTheOlderChecksWhenTheNewerValidatorGivesUp(String operation, String body,
String message) {
String deep = "{\"M\": {\"n\": ".repeat(63) + "{\"S\": \"leaf\"}" + "}}".repeat(63);
String deep = nestedMap(63, "n", "{\"S\": \"leaf\"}");
given()
.header("X-Amz-Target", "DynamoDB_20120810." + operation)
.contentType(DYNAMODB_CONTENT_TYPE)
@@ -6024,7 +6025,7 @@ given()
""")
void queryAndScanCheckTheConditionalOperatorBeforeTheTableLookup(String operation, String body,
String message) {
String deep = "{\"M\": {\"n\": ".repeat(40) + "{\"S\": \"leaf\"}" + "}}".repeat(40);
String deep = nestedMap(40, "n", "{\"S\": \"leaf\"}");
given()
.header("X-Amz-Target", "DynamoDB_20120810." + operation)
.contentType(DYNAMODB_CONTENT_TYPE)
@@ -14,6 +14,7 @@ import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static io.floci.aws.testing.DynamoDbRequests.nestedMap;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
@@ -615,7 +616,7 @@ class DynamoDbPartiQLEdgeCaseIntegrationTest {
void refusesAWriteThatLeavesTheItemTooDeep() {
putItem("deep-path", "\"m\":{\"M\":{}}");
String update = "UPDATE " + QUOTED_TABLE + " SET m.deep = ? WHERE pk='deep-path' AND sk='1'";
String parameters = "[" + "{\"M\":{\"a\":".repeat(31) + "{\"S\":\"x\"}" + "}}".repeat(31) + "]";
String parameters = "[" + nestedMap(31, "a", "{\"S\":\"x\"}") + "]";
String tooDeep = "Nesting Levels have exceeded supported limits";
statement(update, parameters)
@@ -15,6 +15,7 @@ import org.junit.jupiter.params.provider.ValueSource;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static io.floci.aws.testing.DynamoDbRequests.nestedMap;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
@@ -652,7 +653,7 @@ class DynamoDbPartiQLIntegrationTest {
[{"S":"a","N":null},{"N":"abc"}] | The parameter cannot be converted to a numeric value: abc
""")
void aParameterIsRefusedAtTheFirstValueThatCannotBeRead(String parameters, String message) {
String deep = "{\"M\":{\"n\":".repeat(40) + "{\"S\":\"leaf\"}" + "}}".repeat(40);
String deep = nestedMap(40, "n", "{\"S\":\"leaf\"}");
request("DynamoDB_20120810.ExecuteStatement", """
{"Statement":"SELECT * FROM \\"%s\\" WHERE pk = 'x' AND x = ? AND y = ?","Parameters":%s}
@@ -26,6 +26,14 @@ public final class DynamoDbRequests {
.then();
}
public static String nestedMap(int depth, String member, String leaf) {
String value = leaf;
for (int level = 0; level < depth; level++) {
value = "{\"M\":{" + EXACT.getNodeFactory().textNode(member) + ":" + value + "}}";
}
return value;
}
public static BigDecimal decimalAt(ValidatableResponse response, String pointer) throws Exception {
return EXACT.readTree(response.extract().asString()).at(pointer).decimalValue();
}