fix(dynamodb): validate index access paths (#2278)

* fix(dynamodb): validate index access paths

* fix(dynamodb): address review feedback

* test(dynamodb): cover composite sparse index
This commit is contained in:
Tom Longhurst authored and GitHub committed 2026-08-22 00:13:46 -04:00
1 parent f3029ee251
commit 30f965d056
9 files changed
+1206 -150

No files matched your search

@@ -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();
}
}
@@ -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;
}
}
@@ -412,21 +412,7 @@ class DynamoDbServiceTest {
@Test
void 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);
}
@Test
void 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());
}
@Test
void updateItemSetIfNotExistsOnNonExistentItemCreatesAttribute() {
String region = "eu-west-1";