Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(dynamodb): more request validations in Query and Scan (#3360)

TATSUNO “Taz” Yasuhirofbe92aa41102
diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidator.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidator.java
index 511945f027..d24be78779 100644
--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidator.java
@@ -106,7 +106,14 @@ final class DynamoDbAccessPathValidator {
Set<String> conditionedAttributes = new HashSet<>();
Map<String, Boolean> sortKeyEqualities = new HashMap<>();
- for (Expr condition : conditions) {
+ boolean conditionOnNonKeyAttribute = false;
+
+ for (var rawCondition : conditions) {
+ 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",
@@ -126,7 +133,8 @@ final class DynamoDbAccessPathValidator {
}
sortKeyEqualities.put(attribute, isEqualityCondition(condition));
} else {
- throw new AwsException("ValidationException", "Query key condition not supported", 400);
+ conditionOnNonKeyAttribute = true;
+ continue;
}
validateConditionValueTypes(table, attribute, condition, values);
}
@@ -138,6 +146,9 @@ final class DynamoDbAccessPathValidator {
throw new AwsException("ValidationException",
"Query condition missed key schema element: " + missing, 400);
}
+ if (conditionOnNonKeyAttribute) {
+ throw new AwsException("ValidationException", "Query key condition not supported", 400);
+ }
validateCompositeSortKeyConditions(sortKeys, sortKeyEqualities);
return partitionKeyValuePlaceholder;
}
@@ -187,15 +198,39 @@ final class DynamoDbAccessPathValidator {
return false;
}
- private static String conditionAttribute(Expr condition, JsonNode names) {
- Operand operand = switch (condition) {
+ // AWS accepts the value on the left of a sort-key comparison (":lo <= #sk"), which means
+ // the same as "#sk >= :lo".
+ private static Expr normalizeOperandOrder(Expr condition) {
+ if (condition instanceof CompareExpr(Operand left, TokenType op, Operand right)
+ && left instanceof PlaceholderOperand
+ && right instanceof PathOperand) {
+ return new CompareExpr(right, flipComparator(op), left);
+ }
+ return condition;
+ }
+
+ private static TokenType flipComparator(TokenType op) {
+ return switch (op) {
+ case LT -> TokenType.GT;
+ case LE -> TokenType.GE;
+ case GT -> TokenType.LT;
+ case GE -> TokenType.LE;
+ default -> op;
+ };
+ }
+
+ private static Operand conditionOperand(Expr condition) {
+ return switch (condition) {
case CompareExpr compare -> compare.left();
case BetweenExpr between -> between.value();
case FunctionCallExpr function when "begins_with".equals(function.functionName())
&& !function.args().isEmpty() -> function.args().getFirst();
default -> null;
};
- if (!(operand instanceof PathOperand path) || path.segments().size() != 1) {
+ }
+
+ private static String conditionAttribute(Expr condition, JsonNode names) {
+ if (!(conditionOperand(condition) instanceof PathOperand path) || path.segments().size() != 1) {
return null;
}
return topLevelAttribute(path, names);
diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java
index c47bb60510..3b44e52589 100644
--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java
@@ -833,6 +833,8 @@ public class DynamoDbJsonHandler {
return changedAttributes;
}
+ private static final int MAX_TOTAL_SEGMENTS = 1_000_000;
+
private static final Set<String> VALID_SELECT = Set.of(
"ALL_ATTRIBUTES", "ALL_PROJECTED_ATTRIBUTES", "SPECIFIC_ATTRIBUTES", "COUNT");
@@ -1038,6 +1040,28 @@ public class DynamoDbJsonHandler {
+ "Member must have value greater than or equal to 1", 400);
}
+ var segmentErrors = new ArrayList<String>();
+ if (totalSegments != null) {
+ if (totalSegments < 1) {
+ segmentErrors.add("Value '" + totalSegments + "' at 'totalSegments' failed to satisfy constraint: "
+ + "Member must have value greater than or equal to 1");
+ }
+ if (MAX_TOTAL_SEGMENTS < totalSegments) {
+ segmentErrors.add("Value '" + totalSegments + "' at 'totalSegments' failed to satisfy constraint: "
+ + "Member must have value less than or equal to " + MAX_TOTAL_SEGMENTS);
+ }
+ }
+ if (segment != null && segment < 0) {
+ segmentErrors.add("Value '" + segment + "' at 'segment' failed to satisfy constraint: "
+ + "Member must have value greater than or equal to 0");
+ }
+ if (!segmentErrors.isEmpty()) {
+ var n = segmentErrors.size();
+ throw new AwsException("ValidationException",
+ n + " validation error" + (n > 1 ? "s" : "") + " detected: "
+ + String.join("; ", segmentErrors), 400);
+ }
+
if (segment != null && totalSegments == null) {
throw new AwsException("ValidationException",
"The TotalSegments parameter is required but was not present in the request when Segment parameter is present", 400);
@@ -1046,12 +1070,6 @@ public class DynamoDbJsonHandler {
throw new AwsException("ValidationException",
"The Segment parameter is required but was not present in the request when parameter TotalSegments is present", 400);
}
- if (totalSegments != null && totalSegments > 1_000_000) {
- throw new AwsException("ValidationException",
- "1 validation error detected: Value '" + totalSegments
- + "' at 'totalSegments' failed to satisfy constraint: "
- + "Member must have value less than or equal to 1000000", 400);
- }
if (segment != null && totalSegments != null && segment >= totalSegments) {
throw new AwsException("ValidationException",
"The Segment parameter is zero-based and must be less than parameter TotalSegments: "
diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidatorTest.java
index 681692d5c7..8c4a4bcfc5 100644
--- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidatorTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidatorTest.java
@@ -350,6 +350,43 @@ class DynamoDbAccessPathValidatorTest {
table, tablePath, "COUNT", "pk", null, null));
}
+ @Test
+ void acceptsAKeyConditionWithTheValueOnTheLeft() {
+ assertDoesNotThrow(() -> validateExpression(tablePath, "pk = :pk AND :lo <= sk"));
+ assertDoesNotThrow(() -> validateExpression(tablePath, "pk = :pk AND :hi > sk"));
+ }
+
+ @Test
+ void rejectsANestedPathOnAKeyAttribute() {
+ var names = mapper.createObjectNode();
+ names.put("#sk", "sk");
+ var values = expressionValues(":pk", ":v");
+
+ var error = assertThrows(AwsException.class,
+ () -> DynamoDbAccessPathValidator.validateQuery(
+ table, tablePath, null, "pk = :pk AND #sk.foo = :v",
+ null, null, names, values));
+
+ assertEquals("KeyConditionExpressions cannot have conditions on nested attributes",
+ error.getMessage());
+ }
+
+ @Test
+ void reportsTheMissingKeySchemaElementForANonKeyAttribute() {
+ var error = assertThrows(AwsException.class,
+ () -> validateExpression(tablePath, "attr1 = :v"));
+
+ assertEquals("Query condition missed key schema element: pk", error.getMessage());
+ }
+
+ @Test
+ void stillRejectsANonKeyAttributeAlongsideTheFullKey() {
+ var error = assertThrows(AwsException.class,
+ () -> validateExpression(tablePath, "pk = :pk AND attr1 = :v"));
+
+ assertEquals("Query key condition not supported", error.getMessage());
+ }
+
private void validateExpression(DynamoDbAccessPath accessPath, String expression) {
DynamoDbAccessPathValidator.validateQuery(
table, accessPath, null, expression, null, null, null,
diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandlerTest.java
index 7cabf8ef77..f578d9a5d7 100644
--- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandlerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandlerTest.java
@@ -914,4 +914,44 @@ class DynamoDbJsonHandlerTest {
assertEquals("ExpressionAttributeNames can only be specified when using expressions: "
+ "UpdateExpression is null, ConditionExpression is null", ex.getMessage());
}
+
+ @Test
+ void scanRejectsANegativeSegment() {
+ var ex = expectValidationException("Scan", json("""
+ {"TableName": "Users", "Segment": -1, "TotalSegments": 4}
+ """));
+ assertEquals("1 validation error detected: Value '-1' at 'segment' failed to satisfy constraint: "
+ + "Member must have value greater than or equal to 0", ex.getMessage());
+ }
+
+ @Test
+ void scanRejectsTotalSegmentsBelowOne() {
+ var ex = expectValidationException("Scan", json("""
+ {"TableName": "Users", "Segment": 0, "TotalSegments": 0}
+ """));
+ assertEquals("1 validation error detected: Value '0' at 'totalSegments' failed to satisfy constraint: "
+ + "Member must have value greater than or equal to 1", ex.getMessage());
+ }
+
+ @Test
+ void scanReportsTotalSegmentsBeforeSegmentWhenBothAreOutOfRange() {
+ var ex = expectValidationException("Scan", json("""
+ {"TableName": "Users", "Segment": -1, "TotalSegments": 0}
+ """));
+ assertEquals("2 validation errors detected: "
+ + "Value '0' at 'totalSegments' failed to satisfy constraint: "
+ + "Member must have value greater than or equal to 1; "
+ + "Value '-1' at 'segment' failed to satisfy constraint: "
+ + "Member must have value greater than or equal to 0", ex.getMessage());
+ }
+
+ @Test
+ void scanAcceptsSegmentsAtTheBounds() throws Exception {
+ createUsersTable("eu-west-1");
+
+ var response = handler.handle("Scan", json("""
+ {"TableName": "Users", "Segment": 0, "TotalSegments": 1000000}
+ """), "eu-west-1");
+ assertEquals(200, response.getStatus());
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbServiceTest.java
index 99839dd32b..75e51c8429 100644
--- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbServiceTest.java
@@ -624,6 +624,23 @@ class DynamoDbServiceTest {
assertEquals(2, results.items().size());
}
+ @Test
+ void queryWithTheSortKeyValueOnTheLeft() {
+ var region = "eu-west-1";
+ createOrdersTable(region);
+ service.putItem("Orders", item("customerId", "c1", "orderId", "o1"), region);
+ service.putItem("Orders", item("customerId", "c1", "orderId", "o3"), region);
+
+ var exprValues = mapper.createObjectNode();
+ exprValues.set(":pk", mapper.createObjectNode().put("S", "c1"));
+ exprValues.set(":lo", mapper.createObjectNode().put("S", "o2"));
+
+ DynamoDbService.QueryResult results = service.query("Orders", null, exprValues,
+ "customerId = :pk AND :lo <= orderId", null, null, region);
+ assertEquals(1, results.items().size());
+ assertEquals("o3", results.items().getFirst().get("orderId").get("S").asText());
+ }
+
@Test
void queryWithBeginsWith() {
String region = "eu-west-1";