fix(dynamodb): reject a BETWEEN with reversed bounds at parse time (#3183)

* fix(dynamodb): reject a BETWEEN with reversed bounds at parse time

A BETWEEN whose lower bound exceeds its upper bound parsed cleanly and
then failed the condition at evaluation, so PutItem answered with a
ConditionalCheckFailedException. AWS rejects the expression itself with a
ValidationException.

The bounds are compared during expression validation, when both resolve
to values of the same type.

Closes 1 TIER 1 case in the dynamodb-conformance suite.

* fix(dynamodb): order BETWEEN string bounds by UTF-8 bytes like DynamoDB

* fix(dynamodb): answer a 400 SerializationException for a malformed binary BETWEEN bound

* fix(dynamodb): wrap the ConditionExpression BETWEEN error in the AWS validation envelope
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-09-07 17:16:30 -04:00
1 parent 8142457f9b
commit df0bf82e12
3 files changed
+185 -1

No files matched your search

@@ -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();
@@ -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() {
@@ -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));
}
@Test
void missingOperandThrowsSyntaxError() {
AwsException e = assertThrows(AwsException.class, () ->