Light, fluffy, and always free - The AWS Local Emulator alternative
fix(dynamodb): validate index access paths (#2278)
Tom Longhurst30f965d0563d
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DynamoDbAccessPathValidationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DynamoDbAccessPathValidationTest.javanew file mode 100644index 0000000000..d7c94bacac--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/DynamoDbAccessPathValidationTest.java@@ -0,0 +1,215 @@+package com.floci.test;++import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+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.ComparisonOperator;+import software.amazon.awssdk.services.dynamodb.model.Condition;+import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;+import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex;+import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;+import software.amazon.awssdk.services.dynamodb.model.KeyType;+import software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex;+import software.amazon.awssdk.services.dynamodb.model.Projection;+import software.amazon.awssdk.services.dynamodb.model.ProjectionType;+import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;+import software.amazon.awssdk.services.dynamodb.model.Select;++import java.util.Map;+import java.util.UUID;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++class DynamoDbAccessPathValidationTest {++ private static final String TABLE = "access-path-" + UUID.randomUUID().toString().substring(0, 8);+ private static DynamoDbClient ddb;++ @BeforeAll+ static void createTable() {+ ddb = TestFixtures.dynamoDbClient();+ ddb.createTable(request -> request+ .tableName(TABLE)+ .keySchema(key("pk", KeyType.HASH), key("sk", KeyType.RANGE))+ .attributeDefinitions(+ attribute("pk"), attribute("sk"), attribute("status"),+ attribute("createdAt"), attribute("alternate"))+ .globalSecondaryIndexes(GlobalSecondaryIndex.builder()+ .indexName("status-index")+ .keySchema(key("status", KeyType.HASH), key("createdAt", KeyType.RANGE))+ .projection(Projection.builder()+ .projectionType(ProjectionType.INCLUDE)+ .nonKeyAttributes("summary")+ .build())+ .build())+ .localSecondaryIndexes(LocalSecondaryIndex.builder()+ .indexName("alternate-index")+ .keySchema(key("pk", KeyType.HASH), key("alternate", KeyType.RANGE))+ .projection(Projection.builder().projectionType(ProjectionType.KEYS_ONLY).build())+ .build())+ .billingMode(BillingMode.PAY_PER_REQUEST));+ }++ @AfterAll+ static void deleteTable() {+ ddb.deleteTable(request -> request.tableName(TABLE));+ ddb.close();+ }++ @Test+ void queryAndScanRejectUnknownIndexOnEmptyTable() {+ assertValidationException(() -> ddb.scan(request -> request+ .tableName(TABLE)+ .indexName("missing-index")));++ assertValidationException(() -> ddb.query(request -> request+ .tableName(TABLE)+ .indexName("missing-index")+ .keyConditionExpression("pk = :pk")+ .expressionAttributeValues(Map.of(":pk", value("p1")))));+ }++ @Test+ void queryRejectsNonKeyConditionOnEmptyTable() {+ assertValidationException(() -> ddb.query(request -> request+ .tableName(TABLE)+ .keyConditionExpression("pk = :pk AND status = :status")+ .expressionAttributeValues(Map.of(+ ":pk", value("p1"),+ ":status", value("open")))));+ }++ @Test+ void acceptsTableKeyConditionsInEitherOrder() {+ var response = ddb.query(request -> request+ .tableName(TABLE)+ .keyConditionExpression("sk >= :sk AND pk = :pk")+ .expressionAttributeValues(Map.of(+ ":pk", value("p1"),+ ":sk", value("a"))));++ assertThat(response.count()).isZero();+ }++ @Test+ void lsiRejectsBaseTableSortKeyCondition() {+ assertValidationException(() -> ddb.query(request -> request+ .tableName(TABLE)+ .indexName("alternate-index")+ .keyConditionExpression("pk = :pk AND sk = :sk")+ .expressionAttributeValues(Map.of(+ ":pk", value("p1"),+ ":sk", value("s1")))));+ }++ @Test+ @SuppressWarnings("deprecation")+ void legacyKeyConditionsUseSelectedGsiSchema() {+ assertValidationException(() -> ddb.query(request -> request+ .tableName(TABLE)+ .indexName("status-index")+ .keyConditions(Map.of(+ "status", condition(ComparisonOperator.EQ, "open"),+ "pk", condition(ComparisonOperator.EQ, "p1")))));+ }++ @Test+ void queryRejectsSelectedKeyInFilterExpression() {+ assertValidationException(() -> ddb.query(request -> request+ .tableName(TABLE)+ .indexName("status-index")+ .keyConditionExpression("#status = :status")+ .filterExpression("createdAt > :cutoff")+ .expressionAttributeNames(Map.of("#status", "status"))+ .expressionAttributeValues(Map.of(+ ":status", value("open"),+ ":cutoff", value("2026-01-01")))));+ }++ @Test+ void queryAndScanRejectNonProjectedGsiAttribute() {+ assertValidationException(() -> ddb.query(request -> request+ .tableName(TABLE)+ .indexName("status-index")+ .keyConditionExpression("#status = :status")+ .expressionAttributeNames(Map.of("#status", "status"))+ .expressionAttributeValues(Map.of(":status", value("open")))+ .projectionExpression("details")));++ assertValidationException(() -> ddb.scan(request -> request+ .tableName(TABLE)+ .indexName("status-index")+ .projectionExpression("details")));+ }++ @Test+ void acceptsProjectedGsiAttributesAndLsiTableFetch() {+ var gsiResponse = ddb.query(request -> request+ .tableName(TABLE)+ .indexName("status-index")+ .keyConditionExpression("#status = :status")+ .expressionAttributeNames(Map.of("#status", "status"))+ .expressionAttributeValues(Map.of(":status", value("open")))+ .projectionExpression("pk, #status, summary"));+ assertThat(gsiResponse.count()).isZero();++ var lsiResponse = ddb.query(request -> request+ .tableName(TABLE)+ .indexName("alternate-index")+ .keyConditionExpression("pk = :pk")+ .expressionAttributeValues(Map.of(":pk", value("p1")))+ .select(Select.ALL_ATTRIBUTES));+ assertThat(lsiResponse.count()).isZero();++ var lsiScanResponse = ddb.scan(request -> request+ .tableName(TABLE)+ .indexName("alternate-index")+ .projectionExpression("details"));+ assertThat(lsiScanResponse.count()).isZero();+ }++ @Test+ void gsiStillRejectsConsistentReads() {+ assertValidationException(() -> ddb.query(request -> request+ .tableName(TABLE)+ .indexName("status-index")+ .consistentRead(true)+ .keyConditionExpression("#status = :status")+ .expressionAttributeNames(Map.of("#status", "status"))+ .expressionAttributeValues(Map.of(":status", value("open")))));+ }++ private static void assertValidationException(org.assertj.core.api.ThrowableAssert.ThrowingCallable call) {+ assertThatThrownBy(call)+ .isInstanceOf(DynamoDbException.class)+ .satisfies(error -> assertThat(((DynamoDbException) error)+ .awsErrorDetails().errorCode()).isEqualTo("ValidationException"));+ }++ private static KeySchemaElement key(String name, KeyType type) {+ return KeySchemaElement.builder().attributeName(name).keyType(type).build();+ }++ private static AttributeDefinition attribute(String name) {+ return AttributeDefinition.builder()+ .attributeName(name)+ .attributeType(ScalarAttributeType.S)+ .build();+ }++ private static AttributeValue value(String value) {+ return AttributeValue.builder().s(value).build();+ }++ private static Condition condition(ComparisonOperator operator, String attributeValue) {+ return Condition.builder()+ .comparisonOperator(operator)+ .attributeValueList(value(attributeValue))+ .build();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPath.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPath.javanew file mode 100644index 0000000000..370fb81291--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPath.java@@ -0,0 +1,88 @@+package io.github.hectorvent.floci.services.dynamodb;++import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;+import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;+import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex;+import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;++import java.util.List;+import java.util.Set;+import java.util.stream.Collectors;++record DynamoDbAccessPath(String indexName, Kind kind, List<KeySchemaElement> keySchema,+ String projectionType, List<String> nonKeyAttributes) {++ enum Kind { TABLE, GLOBAL_SECONDARY_INDEX, LOCAL_SECONDARY_INDEX }++ static DynamoDbAccessPath resolve(TableDefinition table, String indexName) {+ if (indexName == null) {+ return new DynamoDbAccessPath(null, Kind.TABLE, table.getKeySchema(), "ALL", List.of());+ }++ GlobalSecondaryIndex gsi = table.findGsi(indexName).orElse(null);+ if (gsi != null) {+ return new DynamoDbAccessPath(indexName, Kind.GLOBAL_SECONDARY_INDEX,+ gsi.getKeySchema(), gsi.getProjectionType(), gsi.getNonKeyAttributes());+ }++ LocalSecondaryIndex lsi = table.findLsi(indexName).orElse(null);+ if (lsi != null) {+ return new DynamoDbAccessPath(indexName, Kind.LOCAL_SECONDARY_INDEX,+ lsi.getKeySchema(), lsi.getProjectionType(), lsi.getNonKeyAttributes());+ }++ throw new AwsException("ValidationException",+ "The table does not have the specified index: " + indexName, 400);+ }++ DynamoDbAccessPath {+ keySchema = keySchema != null ? List.copyOf(keySchema) : List.of();+ projectionType = projectionType != null ? projectionType : "ALL";+ nonKeyAttributes = nonKeyAttributes != null ? List.copyOf(nonKeyAttributes) : List.of();+ }++ String partitionKeyName() {+ return keySchema.stream()+ .filter(key -> "HASH".equals(key.getKeyType()))+ .map(KeySchemaElement::getAttributeName)+ .findFirst()+ .orElseThrow();+ }++ List<String> sortKeyNames() {+ return keySchema.stream()+ .filter(key -> "RANGE".equals(key.getKeyType()))+ .map(KeySchemaElement::getAttributeName)+ .toList();+ }++ String sortKeyName() {+ return sortKeyNames().stream().findFirst().orElse(null);+ }++ Set<String> keyAttributeNames() {+ return keySchema.stream()+ .map(KeySchemaElement::getAttributeName)+ .collect(Collectors.toUnmodifiableSet());+ }++ boolean isIndex() {+ return kind != Kind.TABLE;+ }++ boolean isGlobalSecondaryIndex() {+ return kind == Kind.GLOBAL_SECONDARY_INDEX;+ }++ Set<String> projectedAttributeNames(TableDefinition table) {+ var projected = table.getKeySchema().stream()+ .map(KeySchemaElement::getAttributeName)+ .collect(Collectors.toSet());+ projected.addAll(keyAttributeNames());+ if ("INCLUDE".equals(projectionType)) {+ projected.addAll(nonKeyAttributes);+ }+ return Set.copyOf(projected);+ }+}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.javanew file mode 100644index 0000000000..3bc8f3152e--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidator.java@@ -0,0 +1,281 @@+package io.github.hectorvent.floci.services.dynamodb;++import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.AndExpr;+import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.BetweenExpr;+import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.CompareExpr;+import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.Expr;+import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.FunctionCallExpr;+import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.FunctionOperand;+import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.InExpr;+import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.NotExpr;+import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.Operand;+import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.OrExpr;+import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.PathOperand;+import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.PlaceholderOperand;+import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.TokenType;+import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;++import java.util.HashSet;+import java.util.List;+import java.util.Set;++final class DynamoDbAccessPathValidator {++ private static final Set<TokenType> SORT_KEY_COMPARATORS = Set.of(+ TokenType.EQ, TokenType.LT, TokenType.LE, TokenType.GT, TokenType.GE);+ private static final Set<String> LEGACY_SORT_KEY_COMPARATORS = Set.of(+ "EQ", "LT", "LE", "GT", "GE", "BETWEEN", "BEGINS_WITH");++ private DynamoDbAccessPathValidator() {}++ static String validateQuery(DynamoDbAccessPath accessPath, JsonNode keyConditions,+ String keyConditionExpression, String filterExpression,+ JsonNode queryFilter, JsonNode expressionAttributeNames) {+ String partitionKeyValuePlaceholder = null;+ if (keyConditionExpression != null) {+ partitionKeyValuePlaceholder = validateKeyConditionExpression(+ accessPath, keyConditionExpression, expressionAttributeNames);+ } else {+ validateLegacyKeyConditions(accessPath, keyConditions);+ }+ validateFilterExpression(accessPath, filterExpression, expressionAttributeNames);+ validateLegacyQueryFilter(accessPath, queryFilter);+ return partitionKeyValuePlaceholder;+ }++ static void validateSelection(TableDefinition table, DynamoDbAccessPath accessPath,+ String select, String projectionExpression,+ JsonNode attributesToGet, JsonNode expressionAttributeNames) {+ if ("ALL_PROJECTED_ATTRIBUTES".equals(select) && !accessPath.isIndex()) {+ throw validationException("Select type ALL_PROJECTED_ATTRIBUTES is not supported for query on a table");+ }+ if (projectionExpression != null && select != null && !"SPECIFIC_ATTRIBUTES".equals(select)) {+ throw validationException("Cannot use both Select and ProjectionExpression unless Select is SPECIFIC_ATTRIBUTES");+ }+ if (attributesToGet != null && select != null && !"SPECIFIC_ATTRIBUTES".equals(select)) {+ throw validationException("Cannot use both Select and AttributesToGet unless Select is SPECIFIC_ATTRIBUTES");+ }+ if (!accessPath.isGlobalSecondaryIndex() || "ALL".equals(accessPath.projectionType())) {+ return;+ }+ if ("ALL_ATTRIBUTES".equals(select)) {+ throw validationException("Select type ALL_ATTRIBUTES is not supported for global secondary index "+ + accessPath.indexName() + " because its projection type is not ALL");+ }++ Set<String> requestedAttributes = new HashSet<>();+ if (projectionExpression != null) {+ requestedAttributes.addAll(ProjectionEvaluator.topLevelAttributes(+ projectionExpression, expressionAttributeNames));+ }+ if (attributesToGet != null) {+ attributesToGet.forEach(attribute -> requestedAttributes.add(attribute.asText()));+ }++ Set<String> projectedAttributes = accessPath.projectedAttributeNames(table);+ requestedAttributes.removeAll(projectedAttributes);+ if (!requestedAttributes.isEmpty()) {+ throw validationException("One or more parameter values were invalid: Global secondary index "+ + accessPath.indexName() + " does not project "+ + String.join(", ", requestedAttributes.stream().sorted().toList()));+ }+ }++ private static String validateKeyConditionExpression(DynamoDbAccessPath accessPath,+ String expression, JsonNode names) {+ Expr root = parseExpression(expression, "KeyConditionExpression");++ List<Expr> conditions = root instanceof AndExpr and+ ? and.operands() : List.of(root);+ String partitionKey = accessPath.partitionKeyName();+ Set<String> sortKeys = Set.copyOf(accessPath.sortKeyNames());+ int partitionConditions = 0;+ String partitionKeyValuePlaceholder = null;+ Set<String> conditionedAttributes = new HashSet<>();++ for (Expr condition : conditions) {+ 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 (partitionKey.equals(attribute)) {+ partitionConditions++;+ if (!isPartitionKeyEquality(condition)) {+ throw new AwsException("ValidationException", "Query key condition not supported", 400);+ }+ partitionKeyValuePlaceholder = ((PlaceholderOperand) ((CompareExpr) condition).right()).name();+ } else if (attribute != null && sortKeys.contains(attribute)) {+ if (!isSupportedSortKeyCondition(condition)) {+ throw new AwsException("ValidationException", "Query key condition not supported", 400);+ }+ } else {+ throw new AwsException("ValidationException", "Query key condition not supported", 400);+ }+ }++ if (partitionConditions == 0) {+ throw new AwsException("ValidationException",+ "Query condition missed key schema element: " + partitionKey, 400);+ }+ if (partitionConditions > 1) {+ throw new AwsException("ValidationException",+ "KeyConditionExpressions must only contain one condition per key", 400);+ }+ return partitionKeyValuePlaceholder;+ }++ private static boolean isPartitionKeyEquality(Expr condition) {+ return condition instanceof CompareExpr compare+ && compare.op() == TokenType.EQ+ && compare.right() instanceof PlaceholderOperand;+ }++ private static boolean isSupportedSortKeyCondition(Expr condition) {+ if (condition instanceof CompareExpr compare) {+ return SORT_KEY_COMPARATORS.contains(compare.op())+ && compare.right() instanceof PlaceholderOperand;+ }+ if (condition instanceof BetweenExpr between) {+ return between.low() instanceof PlaceholderOperand+ && between.high() instanceof PlaceholderOperand;+ }+ if (condition instanceof FunctionCallExpr function) {+ return "begins_with".equals(function.functionName())+ && function.args().size() == 2+ && function.args().get(1) instanceof PlaceholderOperand;+ }+ return false;+ }++ private static String conditionAttribute(Expr condition, JsonNode names) {+ Operand operand = 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) {+ return null;+ }+ return topLevelAttribute(path, names);+ }++ private static void validateLegacyKeyConditions(DynamoDbAccessPath accessPath, JsonNode keyConditions) {+ String partitionKey = accessPath.partitionKeyName();+ if (keyConditions == null || !keyConditions.has(partitionKey)) {+ throw new AwsException("ValidationException",+ "Query condition missed key schema element: " + partitionKey, 400);+ }++ Set<String> sortKeys = Set.copyOf(accessPath.sortKeyNames());+ keyConditions.fields().forEachRemaining(entry -> {+ String attribute = entry.getKey();+ String operator = entry.getValue().path("ComparisonOperator").asText();+ int values = entry.getValue().path("AttributeValueList").size();+ if (partitionKey.equals(attribute)) {+ if (!"EQ".equals(operator) || values != 1) {+ throw new AwsException("ValidationException", "Query key condition not supported", 400);+ }+ } else if (!sortKeys.contains(attribute)+ || !LEGACY_SORT_KEY_COMPARATORS.contains(operator)+ || ("BETWEEN".equals(operator) ? values != 2 : values != 1)) {+ throw new AwsException("ValidationException", "Query key condition not supported", 400);+ }+ });+ }++ private static void validateFilterExpression(DynamoDbAccessPath accessPath,+ String expression, JsonNode names) {+ if (expression == null) {+ return;+ }+ Expr root = parseExpression(expression, "FilterExpression");++ Set<String> referenced = new HashSet<>();+ collectAttributes(root, names, referenced);+ for (String keyAttribute : accessPath.keyAttributeNames()) {+ if (referenced.contains(keyAttribute)) {+ throw validationException("Filter Expression can only contain non-primary key attributes: "+ + "Primary key attribute: " + keyAttribute);+ }+ }+ }++ private static void validateLegacyQueryFilter(DynamoDbAccessPath accessPath, JsonNode queryFilter) {+ if (queryFilter == null) {+ return;+ }+ for (String keyAttribute : accessPath.keyAttributeNames()) {+ if (queryFilter.has(keyAttribute)) {+ throw validationException("QueryFilter can only contain non-primary key attributes: "+ + "Primary key attribute: " + keyAttribute);+ }+ }+ }++ private static void collectAttributes(Expr expression, JsonNode names, Set<String> attributes) {+ switch (expression) {+ case AndExpr and -> and.operands().forEach(item -> collectAttributes(item, names, attributes));+ case OrExpr or -> or.operands().forEach(item -> collectAttributes(item, names, attributes));+ case NotExpr not -> collectAttributes(not.operand(), names, attributes);+ case CompareExpr compare -> {+ collectAttributes(compare.left(), names, attributes);+ collectAttributes(compare.right(), names, attributes);+ }+ case BetweenExpr between -> {+ collectAttributes(between.value(), names, attributes);+ collectAttributes(between.low(), names, attributes);+ collectAttributes(between.high(), names, attributes);+ }+ case InExpr in -> {+ collectAttributes(in.value(), names, attributes);+ in.candidates().forEach(item -> collectAttributes(item, names, attributes));+ }+ case FunctionCallExpr function ->+ function.args().forEach(item -> collectAttributes(item, names, attributes));+ }+ }++ private static void collectAttributes(Operand operand, JsonNode names, Set<String> attributes) {+ if (operand instanceof PathOperand path) {+ String attribute = topLevelAttribute(path, names);+ if (attribute != null) {+ attributes.add(attribute);+ }+ } else if (operand instanceof FunctionOperand function) {+ function.args().forEach(item -> collectAttributes(item, names, attributes));+ }+ }++ private static String topLevelAttribute(Operand operand, JsonNode names) {+ if (!(operand instanceof PathOperand path) || path.segments().isEmpty()) {+ return null;+ }+ String segment = path.segments().getFirst();+ if (segment.startsWith("#") && names != null && names.has(segment)) {+ return names.get(segment).asText();+ }+ return segment;+ }++ private static Expr parseExpression(String expression, String expressionType) {+ try {+ return ExpressionEvaluator.parse(expression);+ } catch (IllegalArgumentException e) {+ String detail = e.getMessage();+ String message = "Invalid " + expressionType + ": Syntax error";+ if (detail != null && detail.startsWith("token:")) {+ message += "; " + detail;+ }+ throw validationException(message);+ }+ }++ private static AwsException validationException(String message) {+ return new AwsException("ValidationException", message, 400);+ }+}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.javaindex bc515bb90c..08b5169caf 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@@ -814,6 +814,7 @@ public class DynamoDbJsonHandler {ExpressionEvaluator.validateExpression(keyConditionExpr, "KeyConditionExpression", exprAttrNames, exprAttrValues);ExpressionEvaluator.validateExpression(filterExpr, "FilterExpression", exprAttrNames, exprAttrValues);+ ProjectionEvaluator.validateExpression(projectionExpression);if (select != null && !VALID_SELECT.contains(select)) {throw new AwsException("ValidationException",@@ -827,10 +828,16 @@ public class DynamoDbJsonHandler {"Select type SPECIFIC_ATTRIBUTES requires the ProjectionExpression to be provided.", 400);}+ TableDefinition queryTable = dynamoDbService.describeTable(tableName, region);+ DynamoDbAccessPath queryAccessPath = DynamoDbAccessPath.resolve(queryTable, indexName);+ DynamoDbAccessPathValidator.validateQuery(queryAccessPath, keyConditions, keyConditionExpr,+ filterExpr, queryFilter, exprAttrNames);+ DynamoDbAccessPathValidator.validateSelection(queryTable, queryAccessPath, select,+ projectionExpression, attributesToGet, exprAttrNames);+// ConsistentRead on GSI checkboolean consistentRead = request.path("ConsistentRead").asBoolean(false);if (consistentRead && indexName != null) {- TableDefinition queryTable = dynamoDbService.describeTable(tableName, region);if (queryTable.findGsi(indexName).isPresent()) {throw new AwsException("ValidationException","Consistent reads are not supported on global secondary indexes", 400);@@ -854,8 +861,7 @@ public class DynamoDbJsonHandler {}if (exclusiveStartKey != null) {- validateExclusiveStartKey(exclusiveStartKey,- dynamoDbService.describeTable(tableName, region), indexName, false);+ validateExclusiveStartKey(exclusiveStartKey, queryTable, indexName, false);}DynamoDbService.QueryResult result = dynamoDbService.query(tableName, keyConditions,@@ -872,8 +878,7 @@ public class DynamoDbJsonHandler {}// Apply index projection (KEYS_ONLY / INCLUDE) when querying a secondary indexif (indexName != null && projectionExpression == null && attributesToGet == null) {- TableDefinition queryTable = dynamoDbService.describeTable(tableName, region);- queryItems = applyIndexProjection(queryItems, indexName, queryTable, select);+ queryItems = applyIndexProjection(queryItems, queryTable, queryAccessPath, select);}if (projectionExpression != null) {queryItems = queryItems.stream()@@ -920,6 +925,9 @@ public class DynamoDbJsonHandler {? request.get("ExclusiveStartKey") : null;String select = request.has("Select") ? request.get("Select").asText() : null;String indexNameScan = request.has("IndexName") ? request.get("IndexName").asText() : null;+ String projectionExpressionScan = request.has("ProjectionExpression")+ ? request.get("ProjectionExpression").asText() : null;+ JsonNode attributesToGetScan = request.has("AttributesToGet") ? request.get("AttributesToGet") : null;Integer segment = request.has("Segment") ? request.get("Segment").asInt() : null;Integer totalSegments = request.has("TotalSegments") ? request.get("TotalSegments").asInt() : null;@@ -950,13 +958,32 @@ public class DynamoDbJsonHandler {}ExpressionEvaluator.validateExpression(filterExpr, "FilterExpression", exprAttrNames, exprAttrValues);+ ProjectionEvaluator.validateExpression(projectionExpressionScan);- String projectionExpressionScan = request.has("ProjectionExpression")- ? request.get("ProjectionExpression").asText() : null;+ if (select != null && !VALID_SELECT.contains(select)) {+ throw new AwsException("ValidationException",+ "1 validation error detected: Value '" + select + "' at 'select' failed to satisfy constraint: "+ + "Member must satisfy enum value set: [SPECIFIC_ATTRIBUTES, COUNT, ALL_ATTRIBUTES, ALL_PROJECTED_ATTRIBUTES]", 400);+ }+ if (projectionExpressionScan != null && attributesToGetScan != null) {+ throw new AwsException("ValidationException",+ "Can not use both expression and non-expression parameters in the same request: "+ + "Non-expression parameters: {AttributesToGet} Expression parameters: {ProjectionExpression}", 400);+ }+ boolean hasAttributesToGetScan = attributesToGetScan != null && attributesToGetScan.size() > 0;+ if ("SPECIFIC_ATTRIBUTES".equals(select)+ && projectionExpressionScan == null && !hasAttributesToGetScan) {+ throw new AwsException("ValidationException",+ "Select type SPECIFIC_ATTRIBUTES requires the ProjectionExpression to be provided.", 400);+ }++ TableDefinition scanTable = dynamoDbService.describeTable(tableName, region);+ DynamoDbAccessPath scanAccessPath = DynamoDbAccessPath.resolve(scanTable, indexNameScan);+ DynamoDbAccessPathValidator.validateSelection(scanTable, scanAccessPath, select,+ projectionExpressionScan, attributesToGetScan, exprAttrNames);if (exclusiveStartKey != null) {- validateExclusiveStartKey(exclusiveStartKey,- dynamoDbService.describeTable(tableName, region), indexNameScan, true);+ validateExclusiveStartKey(exclusiveStartKey, scanTable, indexNameScan, true);}DynamoDbService.ScanResult result = dynamoDbService.scan(@@ -974,11 +1001,9 @@ public class DynamoDbJsonHandler {}}// Apply index projection (KEYS_ONLY / INCLUDE) when scanning a secondary index- if (indexNameScan != null && projectionExpressionScan == null) {- TableDefinition scanTable = dynamoDbService.describeTable(tableName, region);- scanItems = applyIndexProjection(scanItems, indexNameScan, scanTable, select);+ if (indexNameScan != null && projectionExpressionScan == null && attributesToGetScan == null) {+ scanItems = applyIndexProjection(scanItems, scanTable, scanAccessPath, select);}- JsonNode attributesToGetScan = request.has("AttributesToGet") ? request.get("AttributesToGet") : null;if (projectionExpressionScan != null) {scanItems = scanItems.stream().map(i -> (JsonNode) ProjectionEvaluator.project(i, projectionExpressionScan, exprAttrNames))@@ -1825,40 +1850,13 @@ public class DynamoDbJsonHandler {}// Filters items to only include the attributes projected into the given index.- // Returns items unchanged when projectionType is ALL or no matching index is found.- private List<JsonNode> applyIndexProjection(List<JsonNode> items, String indexName,- TableDefinition table, String select) {- if (indexName == null || "ALL_ATTRIBUTES".equals(select)) return items;-- String projectionType = "ALL";- List<String> nonKeyAttributes = new ArrayList<>();- Set<String> indexKeyNames = new HashSet<>();-- for (GlobalSecondaryIndex gsi : table.getGlobalSecondaryIndexes()) {- if (gsi.getIndexName().equals(indexName)) {- projectionType = gsi.getProjectionType() != null ? gsi.getProjectionType() : "ALL";- nonKeyAttributes = gsi.getNonKeyAttributes() != null ? gsi.getNonKeyAttributes() : List.of();- gsi.getKeySchema().forEach(k -> indexKeyNames.add(k.getAttributeName()));- break;- }- }- for (LocalSecondaryIndex lsi : table.getLocalSecondaryIndexes()) {- if (lsi.getIndexName().equals(indexName)) {- projectionType = lsi.getProjectionType() != null ? lsi.getProjectionType() : "ALL";- nonKeyAttributes = lsi.getNonKeyAttributes() != null ? lsi.getNonKeyAttributes() : List.of();- lsi.getKeySchema().forEach(k -> indexKeyNames.add(k.getAttributeName()));- break;- }+ private List<JsonNode> applyIndexProjection(List<JsonNode> items, TableDefinition table,+ DynamoDbAccessPath accessPath, String select) {+ if ("ALL_ATTRIBUTES".equals(select) || "ALL".equals(accessPath.projectionType())) {+ return items;}- if ("ALL".equals(projectionType)) return items;-- Set<String> allowed = new HashSet<>(indexKeyNames);- allowed.add(table.getPartitionKeyName());- String sortKeyName = table.getSortKeyName();- if (sortKeyName != null) allowed.add(sortKeyName);- if ("INCLUDE".equals(projectionType)) allowed.addAll(nonKeyAttributes);-+ Set<String> allowed = accessPath.projectedAttributeNames(table);return items.stream().map(item -> {ObjectNode filtered = objectMapper.createObjectNode();item.fields().forEachRemaining(e -> {diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.javaindex 3bd27955d8..835fa3c775 100644--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java@@ -727,33 +727,16 @@ public class DynamoDbService {TableDefinition table = tableStore.get(storageKey).orElseThrow(() -> resourceNotFoundException(canonicalTableName));+ DynamoDbAccessPath accessPath = DynamoDbAccessPath.resolve(table, indexName);+ String partitionKeyValuePlaceholder = DynamoDbAccessPathValidator.validateQuery(+ accessPath, keyConditions, keyConditionExpression, filterExpression, null, exprAttrNames);+ String pkName = accessPath.partitionKeyName();+ String skName = accessPath.sortKeyName();+ List<String> sortKeyNames = accessPath.sortKeyNames();+var items = itemsByTable.get(scopedItemsKey(storageKey));if (items == null) return new QueryResult(List.of(), 0, null);- // Resolve key names: use GSI or table keys- String pkName;- String skName;- List<String> sortKeyNames;- if (indexName != null) {- var gsi = table.findGsi(indexName);- if (gsi.isPresent()) {- pkName = gsi.get().getPartitionKeyName();- skName = gsi.get().getSortKeyName();- sortKeyNames = gsi.get().getSortKeyNames();- } else {- var lsi = table.findLsi(indexName)- .orElseThrow(() -> new AwsException("ValidationException",- "The table does not have the specified index: " + indexName, 400));- pkName = lsi.getPartitionKeyName();- skName = lsi.getSortKeyName();- sortKeyNames = lsi.getSortKeyNames();- }- } else {- pkName = table.getPartitionKeyName();- skName = table.getSortKeyName();- sortKeyNames = table.getSortKeyNames();- }-List<JsonNode> results = new ArrayList<>();if (keyConditions != null) {@@ -775,19 +758,17 @@ public class DynamoDbService {}}} else if (keyConditionExpression != null) {- // Modern expression format with exprAttrNames support- results = queryWithExpression(items, pkName, skName, keyConditionExpression,- expressionAttrValues, exprAttrNames);+ results = queryWithExpression(items, pkName, partitionKeyValuePlaceholder,+ keyConditionExpression, expressionAttrValues, exprAttrNames);}// Filter out items without GSI key attributes (sparse index behavior).// DynamoDB excludes items from a GSI if any key attribute is null/missing.- if (indexName != null) {- String finalPkName = pkName;- String finalSkName = skName;+ if (accessPath.isIndex()) {+ Set<String> indexKeys = accessPath.keyAttributeNames();results = results.stream()- .filter(item -> item.has(finalPkName) && hasNonNullAttribute(item, finalPkName))- .filter(item -> finalSkName == null || (item.has(finalSkName) && hasNonNullAttribute(item, finalSkName)))+ .filter(item -> indexKeys.stream().allMatch(+ key -> item.has(key) && hasNonNullAttribute(item, key))).toList();}@@ -907,6 +888,8 @@ public class DynamoDbService {TableDefinition table = tableStore.get(storageKey).orElseThrow(() -> resourceNotFoundException(canonicalTableName));+ DynamoDbAccessPath accessPath = DynamoDbAccessPath.resolve(table, indexName);+var items = itemsByTable.get(scopedItemsKey(storageKey));if (items == null) return new ScanResult(List.of(), 0, null);@@ -918,19 +901,12 @@ public class DynamoDbService {// When scanning a secondary index, the LastEvaluatedKey must carry the index key// attributes in addition to the base table key. Cursor navigation still uses the// (unique) base table key, which is a total order even when index sort keys tie.- boolean indexScan = indexName != null;+ boolean indexScan = accessPath.isIndex();String lekPkName = pkName;String lekSkName = skName;if (indexScan) {- var gsi = table.findGsi(indexName);- var lsi = table.findLsi(indexName);- if (gsi.isPresent()) {- lekPkName = gsi.get().getPartitionKeyName();- lekSkName = gsi.get().getSortKeyName();- } else if (lsi.isPresent()) {- lekPkName = lsi.get().getPartitionKeyName();- lekSkName = lsi.get().getSortKeyName();- }+ lekPkName = accessPath.partitionKeyName();+ lekSkName = accessPath.sortKeyName();}var source = exclusiveStartKey != null@@ -2719,61 +2695,24 @@ public class DynamoDbService {}private List<JsonNode> queryWithExpression(ConcurrentSkipListMap<String, JsonNode> items,- String pkName, String skName,+ String partitionKeyName,+ String partitionKeyValuePlaceholder,String expression,JsonNode expressionAttrValues,JsonNode exprAttrNames) {List<JsonNode> results = new ArrayList<>();-- // Use token-based splitting that correctly handles BETWEEN...AND and compact format- String[] keyParts = ExpressionEvaluator.splitKeyCondition(expression);- String pkExpression = keyParts[0];- String skExpression = keyParts[1];-- // Extract pk attr name from expression (may use #alias)- // Strip outer parens for PK extraction (e.g. "(#f0 = :v0)" → "#f0 = :v0")- String pkExprStripped = pkExpression.trim();- while (pkExprStripped.startsWith("(") && pkExprStripped.endsWith(")")) {- pkExprStripped = pkExprStripped.substring(1, pkExprStripped.length() - 1).trim();- }- String pkAttrInExpr = pkExprStripped.split("\\s*=\\s*")[0].trim();- String resolvedPkName = resolveAttributeName(pkAttrInExpr, exprAttrNames);-- // Validate the PK attribute in the expression matches the actual table/index PK- if (!resolvedPkName.equals(pkName)) {- throw new AwsException("ValidationException",- "Query condition missed key schema element: " + pkName, 400);- }-- // Extract pk value placeholder- int colonIdx = pkExprStripped.indexOf(':');- String pkPlaceholder = null;- if (colonIdx >= 0) {- int end = colonIdx + 1;- while (end < pkExprStripped.length() && (Character.isLetterOrDigit(pkExprStripped.charAt(end)) || pkExprStripped.charAt(end) == '_')) {- end++;- }- pkPlaceholder = pkExprStripped.substring(colonIdx, end);- }- String pkValue = pkPlaceholder != null && expressionAttrValues != null- ? extractScalarValue(expressionAttrValues.get(pkPlaceholder))+ String partitionKeyValue = expressionAttrValues != null && partitionKeyValuePlaceholder != null+ ? extractScalarValue(expressionAttrValues.get(partitionKeyValuePlaceholder)): null;-for (JsonNode item : items.values()) {- if (!item.has(resolvedPkName)) continue;- if (pkValue != null && !matchesAttributeValue(item.get(resolvedPkName), pkValue)) {+ if (partitionKeyValue != null+ && !matchesAttributeValue(item.get(partitionKeyName), partitionKeyValue)) {continue;}-- if (skExpression != null && skName != null) {- if (!ExpressionEvaluator.matches(skExpression, item, exprAttrNames, expressionAttrValues)) {- continue;- }+ if (ExpressionEvaluator.matches(expression, item, exprAttrNames, expressionAttrValues)) {+ results.add(item);}-- results.add(item);}-return results;}diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/ProjectionEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/ProjectionEvaluator.javaindex 239d109c3e..e5d890dab9 100644--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/ProjectionEvaluator.java+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/ProjectionEvaluator.java@@ -28,8 +28,7 @@ final class ProjectionEvaluator {if (item == null || projectionExpression == null || projectionExpression.isBlank()) {return (ObjectNode) item;}- validateProjectionExpression(projectionExpression);- DynamoDbReservedWords.check(projectionExpression, "ProjectionExpression");+ validateExpression(projectionExpression);ObjectNode result = MAPPER.createObjectNode();for (String rawPath : splitProjectionPaths(projectionExpression)) {List<String> segments = resolvePath(rawPath.trim(), exprAttrNames);@@ -53,6 +52,17 @@ final class ProjectionEvaluator {return result;}+ static Set<String> topLevelAttributes(String projectionExpression, JsonNode exprAttrNames) {+ var attributes = new java.util.HashSet<String>();+ for (String rawPath : splitProjectionPaths(projectionExpression)) {+ List<String> segments = resolvePath(rawPath.trim(), exprAttrNames);+ if (!segments.isEmpty()) {+ attributes.add(segments.getFirst());+ }+ }+ return Set.copyOf(attributes);+ }+static void validateSyntax(String expression, String expressionType) {if (expression == null || expression.isBlank()) return;char first = expression.charAt(0);@@ -64,8 +74,9 @@ final class ProjectionEvaluator {}}- private static void validateProjectionExpression(String expression) {+ static void validateExpression(String expression) {validateSyntax(expression, "ProjectionExpression");+ DynamoDbReservedWords.check(expression, "ProjectionExpression");}// ── Path splitting ──diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathIntegrationTest.javanew file mode 100644index 0000000000..fcc2e04e14--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathIntegrationTest.java@@ -0,0 +1,272 @@+package io.github.hectorvent.floci.services.dynamodb;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;++@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class DynamoDbAccessPathIntegrationTest {++ private static final String CONTENT_TYPE = "application/x-amz-json-1.0";+ private static final String TABLE = "access-path-validation";++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ @Order(1)+ void createTable() {+ given()+ .header("X-Amz-Target", "DynamoDB_20120810.CreateTable")+ .contentType(CONTENT_TYPE)+ .body("""+ {+ "TableName": "%s",+ "AttributeDefinitions": [+ {"AttributeName":"pk","AttributeType":"S"},+ {"AttributeName":"sk","AttributeType":"S"},+ {"AttributeName":"status","AttributeType":"S"},+ {"AttributeName":"createdAt","AttributeType":"S"},+ {"AttributeName":"alternate","AttributeType":"S"}+ ],+ "KeySchema": [+ {"AttributeName":"pk","KeyType":"HASH"},+ {"AttributeName":"sk","KeyType":"RANGE"}+ ],+ "GlobalSecondaryIndexes": [{+ "IndexName":"status-index",+ "KeySchema": [+ {"AttributeName":"status","KeyType":"HASH"},+ {"AttributeName":"createdAt","KeyType":"RANGE"}+ ],+ "Projection":{"ProjectionType":"INCLUDE","NonKeyAttributes":["summary"]}+ }],+ "LocalSecondaryIndexes": [{+ "IndexName":"alternate-index",+ "KeySchema": [+ {"AttributeName":"pk","KeyType":"HASH"},+ {"AttributeName":"alternate","KeyType":"RANGE"}+ ],+ "Projection":{"ProjectionType":"KEYS_ONLY"}+ }],+ "BillingMode":"PAY_PER_REQUEST"+ }+ """.formatted(TABLE))+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }++ @Test+ @Order(2)+ void queryAndScanRejectUnknownIndexOnEmptyTable() {+ request("DynamoDB_20120810.Scan", """+ {"TableName":"%s","IndexName":"missing-index"}+ """.formatted(TABLE))+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("The table does not have the specified index: missing-index"));++ request("DynamoDB_20120810.Query", """+ {+ "TableName":"%s",+ "IndexName":"missing-index",+ "KeyConditionExpression":"pk = :pk",+ "ExpressionAttributeValues":{":pk":{"S":"p1"}}+ }+ """.formatted(TABLE))+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("The table does not have the specified index: missing-index"));+ }++ @Test+ @Order(3)+ void queryRejectsNonKeyConditionOnEmptyTable() {+ request("DynamoDB_20120810.Query", """+ {+ "TableName":"%s",+ "KeyConditionExpression":"pk = :pk AND status = :status",+ "ExpressionAttributeValues":{+ ":pk":{"S":"p1"},+ ":status":{"S":"open"}+ }+ }+ """.formatted(TABLE))+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("Query key condition not supported"));+ }++ @Test+ @Order(4)+ void tableAndLsiUseTheirSelectedKeySchemas() {+ request("DynamoDB_20120810.Query", """+ {+ "TableName":"%s",+ "KeyConditionExpression":"sk >= :sk AND pk = :pk",+ "ExpressionAttributeValues":{+ ":pk":{"S":"p1"},+ ":sk":{"S":"a"}+ }+ }+ """.formatted(TABLE))+ .statusCode(200)+ .body("Count", equalTo(0));++ request("DynamoDB_20120810.Query", """+ {+ "TableName":"%s",+ "IndexName":"alternate-index",+ "KeyConditionExpression":"pk = :pk AND sk = :sk",+ "ExpressionAttributeValues":{+ ":pk":{"S":"p1"},+ ":sk":{"S":"s1"}+ }+ }+ """.formatted(TABLE))+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));+ }++ @Test+ @Order(5)+ void queryRejectsSelectedKeyInFilterExpression() {+ request("DynamoDB_20120810.Query", """+ {+ "TableName":"%s",+ "IndexName":"status-index",+ "KeyConditionExpression":"#status = :status",+ "FilterExpression":"createdAt > :cutoff",+ "ExpressionAttributeNames":{"#status":"status"},+ "ExpressionAttributeValues":{+ ":status":{"S":"open"},+ ":cutoff":{"S":"2026-01-01"}+ }+ }+ """.formatted(TABLE))+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("Filter Expression can only contain non-primary key attributes: "+ + "Primary key attribute: createdAt"));+ }++ @Test+ @Order(6)+ void queryAndScanRejectNonProjectedGsiAttribute() {+ String query = """+ {+ "TableName":"%s",+ "IndexName":"status-index",+ "KeyConditionExpression":"#status = :status",+ "ExpressionAttributeNames":{"#status":"status"},+ "ExpressionAttributeValues":{":status":{"S":"open"}},+ "ProjectionExpression":"details"+ }+ """.formatted(TABLE);+ request("DynamoDB_20120810.Query", query)+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));++ request("DynamoDB_20120810.Scan", """+ {+ "TableName":"%s",+ "IndexName":"status-index",+ "ProjectionExpression":"details"+ }+ """.formatted(TABLE))+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));+ }++ @Test+ @Order(7)+ void acceptsProjectedGsiAttributesAndLsiTableFetch() {+ request("DynamoDB_20120810.Query", """+ {+ "TableName":"%s",+ "IndexName":"status-index",+ "KeyConditionExpression":"#status = :status",+ "ExpressionAttributeValues":{":status":{"S":"open"}},+ "ProjectionExpression":"pk, #status, summary",+ "ExpressionAttributeNames":{"#status":"status"}+ }+ """.formatted(TABLE))+ .statusCode(200)+ .body("Count", equalTo(0));++ request("DynamoDB_20120810.Query", """+ {+ "TableName":"%s",+ "IndexName":"alternate-index",+ "KeyConditionExpression":"pk = :pk",+ "ExpressionAttributeValues":{":pk":{"S":"p1"}},+ "Select":"ALL_ATTRIBUTES"+ }+ """.formatted(TABLE))+ .statusCode(200)+ .body("Count", equalTo(0));++ request("DynamoDB_20120810.Scan", """+ {+ "TableName":"%s",+ "IndexName":"alternate-index",+ "ProjectionExpression":"details"+ }+ """.formatted(TABLE))+ .statusCode(200)+ .body("Count", equalTo(0));+ }++ @Test+ @Order(8)+ void gsiStillRejectsConsistentReads() {+ request("DynamoDB_20120810.Query", """+ {+ "TableName":"%s",+ "IndexName":"status-index",+ "ConsistentRead":true,+ "KeyConditionExpression":"#status = :status",+ "ExpressionAttributeNames":{"#status":"status"},+ "ExpressionAttributeValues":{":status":{"S":"open"}}+ }+ """.formatted(TABLE))+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("Consistent reads are not supported on global secondary indexes"));+ }++ @Test+ @Order(99)+ void deleteTable() {+ given()+ .header("X-Amz-Target", "DynamoDB_20120810.DeleteTable")+ .contentType(CONTENT_TYPE)+ .body("{\"TableName\":\"" + TABLE + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }++ private static io.restassured.response.ValidatableResponse request(String target, String body) {+ return given()+ .header("X-Amz-Target", target)+ .contentType(CONTENT_TYPE)+ .body(body)+ .when()+ .post("/")+ .then();+ }+}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.javanew file mode 100644index 0000000000..e8c8f85158--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidatorTest.java@@ -0,0 +1,200 @@+package io.github.hectorvent.floci.services.dynamodb;++import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ArrayNode;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.dynamodb.model.GlobalSecondaryIndex;+import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;+import io.github.hectorvent.floci.services.dynamodb.model.LocalSecondaryIndex;+import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.List;++import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;++class DynamoDbAccessPathValidatorTest {++ private final ObjectMapper mapper = new ObjectMapper();+ private TableDefinition table;+ private DynamoDbAccessPath tablePath;+ private DynamoDbAccessPath gsiPath;+ private DynamoDbAccessPath lsiPath;++ @BeforeEach+ void setUp() {+ table = new TableDefinition();+ table.setKeySchema(List.of(+ new KeySchemaElement("pk", "HASH"),+ new KeySchemaElement("sk", "RANGE")));+ table.setGlobalSecondaryIndexes(List.of(new GlobalSecondaryIndex(+ "status-index",+ List.of(new KeySchemaElement("status", "HASH"),+ new KeySchemaElement("createdAt", "RANGE")),+ null, "INCLUDE", List.of("summary"))));+ table.setLocalSecondaryIndexes(List.of(new LocalSecondaryIndex(+ "alternate-index",+ List.of(new KeySchemaElement("pk", "HASH"),+ new KeySchemaElement("alternate", "RANGE")),+ null, "KEYS_ONLY")));++ tablePath = DynamoDbAccessPath.resolve(table, null);+ gsiPath = DynamoDbAccessPath.resolve(table, "status-index");+ lsiPath = DynamoDbAccessPath.resolve(table, "alternate-index");+ }++ @Test+ void rejectsUnknownIndex() {+ AwsException error = assertThrows(AwsException.class,+ () -> DynamoDbAccessPath.resolve(table, "missing-index"));++ assertEquals("ValidationException", error.getErrorCode());+ assertEquals("The table does not have the specified index: missing-index", error.getMessage());+ }++ @Test+ void acceptsTableKeyConditionsInEitherOrder() {+ assertDoesNotThrow(() -> validateExpression(tablePath,+ "pk = :pk AND begins_with(sk, :prefix)"));+ assertDoesNotThrow(() -> validateExpression(tablePath,+ "sk >= :start AND pk = :pk"));+ }++ @Test+ void acceptsAliasedGsiKeyConditions() {+ ObjectNode names = mapper.createObjectNode();+ names.put("#status", "status");++ assertEquals(":status", DynamoDbAccessPathValidator.validateQuery(+ gsiPath, null, "#status = :status AND createdAt BETWEEN :start AND :end",+ null, null, names));+ }++ @Test+ void rejectsMissingPartitionKeyCondition() {+ AwsException error = assertThrows(AwsException.class,+ () -> validateExpression(tablePath, "sk = :sk"));++ assertEquals("Query condition missed key schema element: pk", error.getMessage());+ }++ @Test+ void rejectsNonKeyCondition() {+ AwsException error = assertThrows(AwsException.class,+ () -> validateExpression(tablePath, "pk = :pk AND status = :status"));++ assertEquals("Query key condition not supported", error.getMessage());+ }++ @Test+ void rejectsUnsupportedPartitionAndSortKeyOperators() {+ assertThrows(AwsException.class,+ () -> validateExpression(tablePath, "pk > :pk"));+ assertThrows(AwsException.class,+ () -> 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,+ () -> validateExpression(tablePath, "pk ="));+ assertEquals("Invalid KeyConditionExpression: Syntax error", keyError.getMessage());++ AwsException filterError = assertThrows(AwsException.class,+ () -> DynamoDbAccessPathValidator.validateQuery(+ tablePath, null, "pk = :pk", "status =", null, null));+ assertEquals("Invalid FilterExpression: Syntax error", filterError.getMessage());+ }++ @Test+ void validatesLegacyKeyConditions() {+ ObjectNode valid = mapper.createObjectNode();+ valid.set("pk", legacyCondition("EQ", attributeValues("p1")));+ valid.set("sk", legacyCondition("BETWEEN", attributeValues("a", "z")));+ assertDoesNotThrow(() -> DynamoDbAccessPathValidator.validateQuery(+ tablePath, valid, null, null, null, null));++ ObjectNode nonKey = valid.deepCopy();+ nonKey.set("status", legacyCondition("EQ", attributeValues("open")));+ assertThrows(AwsException.class, () -> DynamoDbAccessPathValidator.validateQuery(+ tablePath, nonKey, null, null, null, null));++ ObjectNode missingPartitionKey = mapper.createObjectNode();+ missingPartitionKey.set("sk", legacyCondition("EQ", attributeValues("a")));+ assertThrows(AwsException.class, () -> DynamoDbAccessPathValidator.validateQuery(+ tablePath, missingPartitionKey, null, null, null, null));+ }++ @Test+ void rejectsSelectedKeysInQueryFilters() {+ assertThrows(AwsException.class, () -> DynamoDbAccessPathValidator.validateQuery(+ gsiPath, null, "status = :status", "createdAt > :cutoff", null, null));++ ObjectNode queryFilter = mapper.createObjectNode();+ queryFilter.set("status", legacyCondition("EQ", attributeValues("open")));+ assertThrows(AwsException.class, () -> DynamoDbAccessPathValidator.validateQuery(+ gsiPath, null, "status = :status", null, queryFilter, null));+ }++ @Test+ void enforcesGsiProjectionButAllowsLsiTableFetches() {+ ObjectNode names = mapper.createObjectNode();+ names.put("#summary", "summary");++ assertDoesNotThrow(() -> DynamoDbAccessPathValidator.validateSelection(+ table, gsiPath, "SPECIFIC_ATTRIBUTES", "pk, status, #summary",+ null, names));+ AwsException projectionError = assertThrows(AwsException.class,+ () -> DynamoDbAccessPathValidator.validateSelection(+ table, gsiPath, "SPECIFIC_ATTRIBUTES", "zeta, details",+ null, null));+ assertEquals("One or more parameter values were invalid: Global secondary index "+ + "status-index does not project details, zeta", projectionError.getMessage());+ assertThrows(AwsException.class, () -> DynamoDbAccessPathValidator.validateSelection(+ table, gsiPath, "ALL_ATTRIBUTES", null, null, null));+ assertDoesNotThrow(() -> DynamoDbAccessPathValidator.validateSelection(+ table, lsiPath, "ALL_ATTRIBUTES", null, null, null));+ }++ @Test+ void rejectsTableAllProjectedAttributesAndInvalidSelectProjectionCombination() {+ assertThrows(AwsException.class, () -> DynamoDbAccessPathValidator.validateSelection(+ table, tablePath, "ALL_PROJECTED_ATTRIBUTES", null, null, null));+ assertThrows(AwsException.class, () -> DynamoDbAccessPathValidator.validateSelection(+ table, tablePath, "COUNT", "pk", null, null));+ }++ private void validateExpression(DynamoDbAccessPath accessPath, String expression) {+ DynamoDbAccessPathValidator.validateQuery(+ accessPath, null, expression, null, null, null);+ }++ private ObjectNode legacyCondition(String operator, ArrayNode values) {+ ObjectNode condition = mapper.createObjectNode();+ condition.put("ComparisonOperator", operator);+ condition.set("AttributeValueList", values);+ return condition;+ }++ private ArrayNode attributeValues(String... values) {+ ArrayNode result = mapper.createArrayNode();+ for (String value : values) {+ ObjectNode attributeValue = mapper.createObjectNode();+ attributeValue.put("S", value);+ result.add(attributeValue);+ }+ return result;+ }+}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.javaindex 44c5209fb5..36f2ae7bed 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@@ -412,21 +412,7 @@ class DynamoDbServiceTest {@Testvoid queryOnCompositeSortKeyGsiRespectsScanIndexForward() {String region = "us-east-1";- GlobalSecondaryIndex gsi = new GlobalSecondaryIndex(- "memberIndex",- List.of(- new KeySchemaElement("memberName", "HASH"),- new KeySchemaElement("state", "RANGE"),- new KeySchemaElement("createdAt", "RANGE")),- null, "ALL", null);- service.createTable("Requests",- List.of(new KeySchemaElement("requestId", "HASH")),- List.of(- new AttributeDefinition("requestId", "S"),- new AttributeDefinition("memberName", "S"),- new AttributeDefinition("state", "S"),- new AttributeDefinition("createdAt", "S")),- 5L, 5L, List.of(gsi), region);+ createRequestsTableWithCompositeSortKeyGsi(region);// Same memberName + state. Deliberately make base-table key order (requestId: a, b, c)// DISAGREE with createdAt order, so a correct result can only come from sorting on the@@ -462,6 +448,44 @@ class DynamoDbServiceTest {.toList());}+ @Test+ void queryOnCompositeSortKeyGsiExcludesItemsMissingTrailingIndexKey() {+ String region = "us-east-1";+ createRequestsTableWithCompositeSortKeyGsi(region);+ service.putItem("Requests", item("requestId", "complete", "memberName", "alice",+ "state", "ACTIVE", "createdAt", "2026-07-14T00:00:01Z"), region);+ service.putItem("Requests", item("requestId", "incomplete", "memberName", "alice",+ "state", "ACTIVE"), region);++ ObjectNode exprValues = mapper.createObjectNode();+ exprValues.set(":pk", attributeValue("S", "alice"));++ DynamoDbService.QueryResult results = service.query("Requests", null, exprValues,+ "memberName = :pk", null, null, true, "memberIndex", null, null, region);++ assertEquals(List.of("complete"), results.items().stream()+ .map(result -> result.get("requestId").get("S").asText())+ .toList());+ }++ private void createRequestsTableWithCompositeSortKeyGsi(String region) {+ GlobalSecondaryIndex gsi = new GlobalSecondaryIndex(+ "memberIndex",+ List.of(+ new KeySchemaElement("memberName", "HASH"),+ new KeySchemaElement("state", "RANGE"),+ new KeySchemaElement("createdAt", "RANGE")),+ null, "ALL", null);+ service.createTable("Requests",+ List.of(new KeySchemaElement("requestId", "HASH")),+ List.of(+ new AttributeDefinition("requestId", "S"),+ new AttributeDefinition("memberName", "S"),+ new AttributeDefinition("state", "S"),+ new AttributeDefinition("createdAt", "S")),+ 5L, 5L, List.of(gsi), region);+ }+@Testvoid queryAppliesFilterExpressionAfterKeyCondition() {String region = "eu-west-1";@@ -611,6 +635,34 @@ class DynamoDbServiceTest {assertThrows(AwsException.class, () -> service.scan("NoTable", null, null, null, null, null, null, region));}+ @Test+ void scanRejectsUnknownIndexOnEmptyTable() {+ String region = "eu-west-1";+ createOrdersTable(region);++ AwsException error = assertThrows(AwsException.class, () -> service.scan(+ "Orders", null, null, null, null, null, null, "missing-index", region));++ assertEquals("ValidationException", error.getErrorCode());+ assertEquals("The table does not have the specified index: missing-index", error.getMessage());+ }++ @Test+ void queryRejectsNonKeyConditionOnEmptyTable() {+ String region = "eu-west-1";+ createOrdersTable(region);+ ObjectNode values = mapper.createObjectNode();+ values.set(":customer", attributeValue("S", "c1"));+ values.set(":total", attributeValue("N", "10"));++ AwsException error = assertThrows(AwsException.class, () -> service.query(+ "Orders", null, values, "customerId = :customer AND total > :total",+ null, null, null, null, null, null, region));++ assertEquals("ValidationException", error.getErrorCode());+ assertEquals("Query key condition not supported", error.getMessage());+ }+@Testvoid updateItemSetIfNotExistsOnNonExistentItemCreatesAttribute() {String region = "eu-west-1";