Light, fluffy, and always free - The AWS Local Emulator alternative
fix(dynamodb): reject a BETWEEN with reversed bounds at parse time (#3183)
TATSUNO “Taz” Yasuhirodf0bf82e1232
diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/ExpressionEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/ExpressionEvaluator.javaindex b7c5eb20d7..6ceb31e8dc 100644--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/ExpressionEvaluator.java+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/ExpressionEvaluator.java@@ -6,7 +6,9 @@ import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.core.common.AwsException;import java.math.BigDecimal;+import java.nio.charset.StandardCharsets;import java.util.ArrayList;+import java.util.Arrays;import java.util.Base64;import java.util.List;@@ -451,10 +453,72 @@ final class ExpressionEvaluator {case OrExpr o -> o.operands().forEach(x -> validateSemantics(x, exprType, names, values));case NotExpr n -> validateSemantics(n.operand(), exprType, names, values);case FunctionCallExpr f -> validateFunction(f, exprType, names, values);+ case BetweenExpr b -> validateBetween(b, exprType, values);default -> {}}}+ // AWS rejects a BETWEEN whose bounds are the wrong way round when it parses the+ // expression, rather than letting the condition fail at evaluation time.+ private static void validateBetween(BetweenExpr between, String exprType, JsonNode values) {+ var low = placeholderValue(between.low(), values);+ var high = placeholderValue(between.high(), values);+ if (low == null || high == null) {+ return;+ }+ var lowType = low.fieldNames().next();+ if (!lowType.equals(high.fieldNames().next()) || compareBoundValues(low, high) <= 0) {+ return;+ }+ // AWS wraps the ConditionExpression form in its validation-error envelope, but reports+ // the FilterExpression and KeyConditionExpression forms on their own.+ String envelope = "ConditionExpression".equals(exprType) ? "1 validation error detected: " : "";+ throw new AwsException("ValidationException", envelope+ + "Invalid " + exprType + ": The BETWEEN operator requires upper bound to be greater than "+ + "or equal to lower bound; lower bound operand: " + displayAttributeValue(low)+ + ", upper bound operand: " + displayAttributeValue(high), 400);+ }++ // DynamoDB orders strings by their UTF-8 bytes, which differs from Java's UTF-16+ // ordering above the basic plane: U+E000 sorts before U+10000 on AWS but after it here.+ private static int compareBoundValues(JsonNode low, JsonNode high) {+ if (low.has("S") && high.has("S")) {+ return Arrays.compareUnsigned(+ low.get("S").asText().getBytes(StandardCharsets.UTF_8),+ high.get("S").asText().getBytes(StandardCharsets.UTF_8));+ }+ if (low.has("B") && high.has("B")) {+ return Arrays.compareUnsigned(decodeBinaryBound(low), decodeBinaryBound(high));+ }+ return compareAttributeValues(low, high);+ }++ // A binary value that is not valid base64 never reaches a comparison on AWS: the request+ // fails to deserialize first, with a 400 SerializationException.+ private static byte[] decodeBinaryBound(JsonNode bound) {+ try {+ return Base64.getDecoder().decode(bound.get("B").asText());+ } catch (IllegalArgumentException e) {+ throw new AwsException("SerializationException",+ "Unexpected value type in payload", 400);+ }+ }++ private static JsonNode placeholderValue(Operand operand, JsonNode values) {+ if (operand instanceof PlaceholderOperand(String name) && values != null) {+ var value = values.get(name);+ if (value != null && value.isObject() && value.fieldNames().hasNext()) {+ return value;+ }+ }+ return null;+ }++ private static String displayAttributeValue(JsonNode value) {+ var type = value.fieldNames().next();+ return "AttributeValue: {" + type + ":" + value.get(type).asText() + "}";+ }+private static void validateFunction(FunctionCallExpr f, String exprType,JsonNode names, JsonNode values) {String name = f.functionName().toLowerCase();diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbIntegrationTest.javaindex 877f97e2f6..262144ad1b 100644--- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbIntegrationTest.java@@ -440,6 +440,35 @@ class DynamoDbIntegrationTest {.body("Items[0].total", nullValue());}+ // Checked against real DynamoDB (us-east-1, 2026-09-07). A reversed BETWEEN in a+ // ConditionExpression is a 400 ValidationException, not a ConditionalCheckFailedException,+ // and AWS wraps the ConditionExpression form in its validation-error envelope.+ @Test+ @Order(10)+ void putItemWithReversedBetweenBoundsReturnsValidationException() {+ given()+ .header("X-Amz-Target", "DynamoDB_20120810.PutItem")+ .contentType(DYNAMODB_CONTENT_TYPE)+ .body("""+ {+ "TableName": "TestTable",+ "Item": {"pk": {"S": "between-1"}, "sk": {"S": "a"}},+ "ConditionExpression": "#n BETWEEN :hi AND :lo",+ "ExpressionAttributeNames": {"#n": "n"},+ "ExpressionAttributeValues": {":hi": {"N": "10"}, ":lo": {"N": "1"}}+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("1 validation error detected: Invalid ConditionExpression: "+ + "The BETWEEN operator requires upper bound to be greater than or equal to lower "+ + "bound; lower bound operand: AttributeValue: {N:10}, upper bound operand: "+ + "AttributeValue: {N:1}"));+ }+@Test@Order(10)void queryWithSelectSpecificAttributesRequiresProjectionParameters() {diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/ExpressionEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/ExpressionEvaluatorTest.javaindex 218bf14bab..be8b9230c0 100644--- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/ExpressionEvaluatorTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/ExpressionEvaluatorTest.java@@ -2,7 +2,6 @@ package io.github.hectorvent.floci.services.dynamodb;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;-import com.fasterxml.jackson.databind.node.ObjectNode;import org.junit.jupiter.api.Nested;import org.junit.jupiter.api.Test;@@ -596,6 +595,98 @@ class ExpressionEvaluatorTest {}}+ @Test+ void reversedBetweenBoundsAreRejectedAtParseTime() {+ var mapper = new ObjectMapper();+ var values = mapper.createObjectNode();+ values.set(":hi", mapper.createObjectNode().put("N", "10"));+ values.set(":lo", mapper.createObjectNode().put("N", "1"));++ var e = assertThrows(AwsException.class, () ->+ ExpressionEvaluator.validateExpression("n BETWEEN :hi AND :lo",+ "ConditionExpression", null, values));+ assertEquals("ValidationException", e.getErrorCode());+ assertEquals("1 validation error detected: Invalid ConditionExpression: The BETWEEN operator "+ + "requires upper bound to be greater than or equal to lower bound; lower bound operand: "+ + "AttributeValue: {N:10}, upper bound operand: AttributeValue: {N:1}", e.getMessage());+ }++ // Checked against real DynamoDB (us-east-1, 2026-09-07): U+E000 as the lower bound+ // and U+10000 as the upper bound is accepted, because DynamoDB orders strings by+ // their UTF-8 bytes. Java's UTF-16 ordering puts them the other way round.+ @Test+ void stringBoundsAreOrderedByUtf8Bytes() {+ var mapper = new ObjectMapper();+ var values = mapper.createObjectNode();+ values.set(":lo", mapper.createObjectNode().put("S", "\uE000"));+ values.set(":hi", mapper.createObjectNode().put("S", "\uD800\uDC00"));++ assertDoesNotThrow(() -> ExpressionEvaluator.validateExpression("n BETWEEN :lo AND :hi",+ "ConditionExpression", null, values));++ var reversed = mapper.createObjectNode();+ reversed.set(":lo", mapper.createObjectNode().put("S", "\uD800\uDC00"));+ reversed.set(":hi", mapper.createObjectNode().put("S", "\uE000"));++ var e = assertThrows(AwsException.class, () ->+ ExpressionEvaluator.validateExpression("n BETWEEN :lo AND :hi",+ "ConditionExpression", null, reversed));+ assertEquals("ValidationException", e.getErrorCode());+ }++ // Checked against real DynamoDB (us-east-1, 2026-09-07): binary bounds compare by+ // unsigned bytes, and a bound that is not valid base64 fails the request with a 400+ // SerializationException before any comparison happens.+ @Test+ void binaryBoundsCompareByBytesAndRejectMalformedBase64() {+ var mapper = new ObjectMapper();+ var reversed = mapper.createObjectNode();+ reversed.set(":lo", mapper.createObjectNode().put("B", "/w=="));+ reversed.set(":hi", mapper.createObjectNode().put("B", "AA=="));++ var e = assertThrows(AwsException.class, () ->+ ExpressionEvaluator.validateExpression("n BETWEEN :lo AND :hi",+ "ConditionExpression", null, reversed));+ assertEquals("ValidationException", e.getErrorCode());++ var malformed = mapper.createObjectNode();+ malformed.set(":lo", mapper.createObjectNode().put("B", "!!!not-base64!!!"));+ malformed.set(":hi", mapper.createObjectNode().put("B", "@@@@"));++ var serialization = assertThrows(AwsException.class, () ->+ ExpressionEvaluator.validateExpression("n BETWEEN :lo AND :hi",+ "ConditionExpression", null, malformed));+ assertEquals("SerializationException", serialization.getErrorCode());+ assertEquals(400, serialization.getHttpStatus());+ }++ // A FilterExpression carries the same text without the envelope on AWS.+ @Test+ void filterExpressionReportsTheReversedBoundsWithoutTheEnvelope() {+ var mapper = new ObjectMapper();+ var values = mapper.createObjectNode();+ values.set(":hi", mapper.createObjectNode().put("N", "10"));+ values.set(":lo", mapper.createObjectNode().put("N", "1"));++ var e = assertThrows(AwsException.class, () ->+ ExpressionEvaluator.validateExpression("n BETWEEN :hi AND :lo",+ "FilterExpression", null, values));+ assertEquals("Invalid FilterExpression: The BETWEEN operator requires upper bound to be "+ + "greater than or equal to lower bound; lower bound operand: AttributeValue: {N:10}, "+ + "upper bound operand: AttributeValue: {N:1}", e.getMessage());+ }++ @Test+ void orderedBetweenBoundsAreAccepted() {+ var mapper = new ObjectMapper();+ var values = mapper.createObjectNode();+ values.set(":lo", mapper.createObjectNode().put("N", "1"));+ values.set(":hi", mapper.createObjectNode().put("N", "10"));++ assertDoesNotThrow(() -> ExpressionEvaluator.validateExpression("n BETWEEN :lo AND :hi",+ "ConditionExpression", null, values));+ }+@Testvoid missingOperandThrowsSyntaxError() {AwsException e = assertThrows(AwsException.class, () ->