feat(dynamodb): index-qualified PartiQL SELECT with ConsistentRead validation (#2953)

* feat(dynamodb): index-qualified PartiQL SELECT with ConsistentRead validation

ExecuteStatement parsed FROM "Table" only — a dot aborted the lexer
with 'Unexpected character', so PartiQL could not read through a
secondary index at all. Lex the qualifier, resolve it to an access
path, and route the read the way AWS does (characterised on real AWS,
eu-west-1, 2026-09-02):

- equality on the selected source's partition key queries it; any
  other WHERE shape becomes a full scan of the table or index with the
  remaining conditions as a filter
- ConsistentRead on a GSI-qualified statement is rejected with
  'Strongly consistent read is not supported on Global Secondary
  Indexes' — PartiQL's own wording, distinct from Query/Scan
- an unknown index omits the index name from the message, again
  unlike Query/Scan; index resolution also precedes the consistent-
  read check
- SELECT over an index surfaces only projected attributes, and an
  explicitly selected non-projected column is rejected
- BatchExecuteStatement SELECT statements must resolve through the
  table's primary key; index-qualified or partial-key statements get
  a per-statement ValidationError slot

Consistent reads on base tables and LSIs stay legal, NextToken/Limit
now paginate both read branches, and GetItem stays a base-table-only
shortcut.

Reproduced with paritysuite/dynamodb-conformance (new
tests/tier2/partiql/executeStatementIndex.test.ts plus ExecuteStatement
cases in tier3/error-messages/indexReads.test.ts): the qualified-read
and message cases fail against main and pass with this change.

Signed-off-by: Kévin Dehoux <dehoux.kevin@gmail.com>

* fix(dynamodb): bind the PartiQL NextToken to its issuing statement

A PartiQL NextToken carried only the last evaluated key, so replaying a
token against another table or access path with identical key names and
scalar types was accepted: Scan continued from the foreign key and
skipped items, Query restarted and duplicated them. Real AWS binds the
opaque token to the request: replaying it against any other statement,
table or access path is rejected with 'NextToken does not match request',
while a changed Limit or a dropped ConsistentRead is accepted and an
older token replays idempotently (characterised on real AWS, eu-west-1,
2026-09-03).

The token now embeds a SHA-256 digest of the statement text and
parameter values alongside the key, and decoding verifies it against the
current request. Wire integration tests cover statement, parameter,
index-qualified and cross-table replay plus the accepted Limit change;
the SDK twin asserts the exact message; the conformance suite gains the
base-table-to-index replay case.

Signed-off-by: Kévin Dehoux <dehoux.kevin@gmail.com>

---------

Signed-off-by: Kévin Dehoux <dehoux.kevin@gmail.com>
This commit is contained in:
Kévin Dehoux authored and GitHub committed 2026-09-04 09:25:46 -04:00
1 parent 7fdd145c0c
commit 84ec8ae8e7
8 files changed
+738 -97

No files matched your search

@@ -15,6 +15,7 @@ class DynamoDbPartiQLTest {
private static DynamoDbClient ddb;
private static final String TABLE = "partiql-test-table";
private static final String INDEX_TABLE = "partiql-index-table";
@BeforeAll
static void setup() {
@@ -34,6 +35,59 @@ class DynamoDbPartiQLTest {
)
.billingMode(BillingMode.PAY_PER_REQUEST)
.build());
try {
ddb.deleteTable(DeleteTableRequest.builder().tableName(INDEX_TABLE).build());
} catch (Exception ignored) {}
ddb.createTable(CreateTableRequest.builder()
.tableName(INDEX_TABLE)
.keySchema(
KeySchemaElement.builder().attributeName("pk").keyType(KeyType.HASH).build(),
KeySchemaElement.builder().attributeName("sk").keyType(KeyType.RANGE).build()
)
.attributeDefinitions(
AttributeDefinition.builder().attributeName("pk").attributeType(ScalarAttributeType.S).build(),
AttributeDefinition.builder().attributeName("sk").attributeType(ScalarAttributeType.S).build(),
AttributeDefinition.builder().attributeName("status").attributeType(ScalarAttributeType.S).build(),
AttributeDefinition.builder().attributeName("createdAt").attributeType(ScalarAttributeType.S).build(),
AttributeDefinition.builder().attributeName("alternate").attributeType(ScalarAttributeType.S).build()
)
.globalSecondaryIndexes(GlobalSecondaryIndex.builder()
.indexName("status-index")
.keySchema(
KeySchemaElement.builder().attributeName("status").keyType(KeyType.HASH).build(),
KeySchemaElement.builder().attributeName("createdAt").keyType(KeyType.RANGE).build()
)
.projection(Projection.builder().projectionType(ProjectionType.ALL).build())
.build())
.localSecondaryIndexes(LocalSecondaryIndex.builder()
.indexName("alternate-index")
.keySchema(
KeySchemaElement.builder().attributeName("pk").keyType(KeyType.HASH).build(),
KeySchemaElement.builder().attributeName("alternate").keyType(KeyType.RANGE).build()
)
.projection(Projection.builder().projectionType(ProjectionType.ALL).build())
.build())
.billingMode(BillingMode.PAY_PER_REQUEST)
.build());
ddb.putItem(PutItemRequest.builder()
.tableName(INDEX_TABLE)
.item(Map.of(
"pk", AttributeValue.builder().s("idxpk").build(),
"sk", AttributeValue.builder().s("s1").build(),
"status", AttributeValue.builder().s("active").build(),
"createdAt", AttributeValue.builder().s("2026-01-01").build(),
"alternate", AttributeValue.builder().s("alt-1").build()))
.build());
ddb.putItem(PutItemRequest.builder()
.tableName(INDEX_TABLE)
.item(Map.of(
"pk", AttributeValue.builder().s("idxpk").build(),
"sk", AttributeValue.builder().s("s2").build(),
"status", AttributeValue.builder().s("active").build(),
"createdAt", AttributeValue.builder().s("2026-01-02").build(),
"alternate", AttributeValue.builder().s("alt-2").build()))
.build());
}
@AfterAll
@@ -42,6 +96,9 @@ class DynamoDbPartiQLTest {
try {
ddb.deleteTable(DeleteTableRequest.builder().tableName(TABLE).build());
} catch (Exception ignored) {}
try {
ddb.deleteTable(DeleteTableRequest.builder().tableName(INDEX_TABLE).build());
} catch (Exception ignored) {}
ddb.close();
}
}
@@ -205,4 +262,91 @@ class DynamoDbPartiQLTest {
assertThat(resp.responses().get(0).item()).containsKey("hit");
assertThat(resp.responses().get(1).item()).isEmpty();
}
@Test
@Order(14)
void executeStatementOnGsiRejectsConsistentRead() {
assertThatThrownBy(() -> ddb.executeStatement(r -> r
.statement("SELECT * FROM \"" + INDEX_TABLE + "\".\"status-index\"")
.consistentRead(true)))
.isInstanceOf(DynamoDbException.class)
.hasMessageContaining("Strongly consistent read is not supported on Global Secondary Indexes");
}
@Test
@Order(15)
void executeStatementReadsThroughGsi() {
// Equality on the index partition key routes through an index query.
ExecuteStatementResponse resp = ddb.executeStatement(r -> r
.statement("SELECT * FROM \"" + INDEX_TABLE + "\".\"status-index\" WHERE status = 'active'"));
assertThat(resp.items()).hasSize(2);
// Without equality on the index partition key, the statement performs
// a full index scan and applies the remaining conditions as a filter.
ExecuteStatementResponse filtered = ddb.executeStatement(r -> r
.statement("SELECT * FROM \"" + INDEX_TABLE + "\".\"status-index\" WHERE sk = 's2'"));
assertThat(filtered.items()).hasSize(1);
assertThat(filtered.items().get(0).get("sk").s()).isEqualTo("s2");
}
@Test
@Order(16)
void executeStatementOnLsiAcceptsConsistentRead() {
ExecuteStatementResponse resp = ddb.executeStatement(r -> r
.statement("SELECT * FROM \"" + INDEX_TABLE + "\".\"alternate-index\" WHERE pk = 'idxpk'")
.consistentRead(true));
assertThat(resp.items()).hasSize(2);
}
@Test
@Order(17)
void executeStatementOnUnknownIndexFailsWithoutIndexName() {
// ExecuteStatement omits the index name from this message, unlike
// Query/Scan (characterised on real AWS, eu-west-1, 2026-09-02).
assertThatThrownBy(() -> ddb.executeStatement(r -> r
.statement("SELECT * FROM \"" + INDEX_TABLE + "\".\"no-such-index\"")))
.isInstanceOfSatisfying(DynamoDbException.class, e -> {
assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationException");
// ExecuteStatement omits the index name from this message,
// unlike Query/Scan (characterised on real AWS, eu-west-1,
// 2026-09-02).
assertThat(e.awsErrorDetails().errorMessage())
.isEqualTo("The table does not have the specified index");
});
}
@Test
@Order(18)
void batchExecuteStatementRejectsIndexQualifiedSelectPerSlot() {
BatchExecuteStatementResponse resp = ddb.batchExecuteStatement(r -> r
.statements(BatchStatementRequest.builder()
.statement("SELECT * FROM \"" + INDEX_TABLE + "\".\"status-index\" WHERE status = 'active'")
.build()));
assertThat(resp.responses()).hasSize(1);
assertThat(resp.responses().get(0).error().codeAsString()).isEqualTo("ValidationError");
assertThat(resp.responses().get(0).error().message()).isEqualTo(
"Select statements within BatchExecuteStatement must specify the primary key in the where clause.");
}
@Test
@Order(19)
void executeStatementRejectsForeignNextToken() {
ExecuteStatementResponse page = ddb.executeStatement(r -> r
.statement("SELECT * FROM \"" + INDEX_TABLE + "\" WHERE pk = 'idxpk'")
.limit(1));
assertThat(page.nextToken()).isNotBlank();
// Characterised on real AWS (eu-west-1, 2026-09-03): the token is bound
// to the issuing statement, so replaying it on another statement or
// access path is rejected even when the target key schema matches.
assertThatThrownBy(() -> ddb.executeStatement(r -> r
.statement("SELECT * FROM \"" + INDEX_TABLE + "\".\"status-index\" WHERE status = 'active'")
.limit(1)
.nextToken(page.nextToken())))
.isInstanceOfSatisfying(DynamoDbException.class, e -> {
assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationException");
assertThat(e.awsErrorDetails().errorMessage())
.isEqualTo("NextToken does not match request");
});
}
}
@@ -16,6 +16,14 @@ record DynamoDbAccessPath(String indexName, Kind kind, List<KeySchemaElement> ke
enum Kind { TABLE, GLOBAL_SECONDARY_INDEX, LOCAL_SECONDARY_INDEX }
static DynamoDbAccessPath resolve(TableDefinition table, String indexName) {
return resolve(table, indexName,
"The table does not have the specified index: " + indexName);
}
// Callers that phrase the missing-index error differently supply their own
// wording: ExecuteStatement omits the index name, unlike Query/Scan
// (characterised on real AWS, eu-west-1, 2026-09-02).
static DynamoDbAccessPath resolve(TableDefinition table, String indexName, String missingIndexMessage) {
if (indexName == null) {
return new DynamoDbAccessPath(null, Kind.TABLE, table.getKeySchema(), "ALL", List.of());
}
@@ -32,8 +40,7 @@ record DynamoDbAccessPath(String indexName, Kind kind, List<KeySchemaElement> ke
lsi.getKeySchema(), lsi.getProjectionType(), lsi.getNonKeyAttributes());
}
throw new AwsException("ValidationException",
"The table does not have the specified index: " + indexName, 400);
throw new AwsException("ValidationException", missingIndexMessage, 400);
}
DynamoDbAccessPath {
@@ -390,4 +390,66 @@ final class DynamoDbAccessPathValidator {
private static AwsException validationException(String message) {
return new AwsException("ValidationException", message, 400);
}
// DynamoDB requires an ExclusiveStartKey to exactly match the paged key schema's
// attribute names and scalar types. Query and Scan report different messages for faults.
static void validateExclusiveStartKey(JsonNode exclusiveStartKey, TableDefinition table,
DynamoDbAccessPath accessPath, boolean isScan) {
if (exclusiveStartKey == null || exclusiveStartKey.isNull()) return;
Set<String> expected = new HashSet<>();
expected.add(table.getPartitionKeyName());
String sortKey = table.getSortKeyName();
if (sortKey != null) {
expected.add(sortKey);
}
if (accessPath.isIndex()) {
expected.addAll(accessPath.keyAttributeNames());
}
Set<String> actual = new HashSet<>();
exclusiveStartKey.fieldNames().forEachRemaining(actual::add);
if (!actual.equals(expected) || hasInvalidKeyValue(exclusiveStartKey, table, expected)) {
throw invalidStartingKey(isScan);
}
}
private static boolean hasInvalidKeyValue(JsonNode exclusiveStartKey, TableDefinition table,
Set<String> expected) {
if (table.getAttributeDefinitions() == null) {
return true;
}
for (String attribute : expected) {
String expectedType = table.getAttributeDefinitions().stream()
.filter(definition -> attribute.equals(definition.getAttributeName()))
.map(AttributeDefinition::getAttributeType)
.findFirst()
.orElse(null);
if (expectedType == null || hasInvalidScalarValue(exclusiveStartKey.get(attribute), expectedType)) {
return true;
}
}
return false;
}
private static boolean hasInvalidScalarValue(JsonNode value, String expectedType) {
if (value == null || !value.isObject() || value.size() != 1 || !value.has(expectedType)) {
return true;
}
JsonNode payload = value.get(expectedType);
if (payload == null || !payload.isTextual() || payload.textValue().isEmpty()) {
return true;
}
if ("N".equals(expectedType)) {
DynamoDbNumberUtils.validateAndNormalize(payload.textValue());
}
if ("B".equals(expectedType)) {
return !payload.textValue().matches(
"(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?");
}
return false;
}
private static AwsException invalidStartingKey(boolean isScan) {
return new AwsException("ValidationException", isScan
? "The provided starting key is invalid: The provided key element does not match the schema"
: "The provided starting key is invalid", 400);
}
}
@@ -743,67 +743,6 @@ public class DynamoDbJsonHandler {
return changedAttributes;
}
// DynamoDB requires an ExclusiveStartKey to exactly match the paged key schema's
// attribute names and scalar types. Query and Scan report different messages for faults.
private void validateExclusiveStartKey(JsonNode exclusiveStartKey, TableDefinition table,
DynamoDbAccessPath accessPath, boolean isScan) {
if (exclusiveStartKey == null || exclusiveStartKey.isNull()) return;
Set<String> expected = new HashSet<>();
expected.add(table.getPartitionKeyName());
String sortKey = table.getSortKeyName();
if (sortKey != null) expected.add(sortKey);
if (accessPath.isIndex()) {
expected.addAll(accessPath.keyAttributeNames());
}
Set<String> actual = new HashSet<>();
exclusiveStartKey.fieldNames().forEachRemaining(actual::add);
if (!actual.equals(expected) || hasInvalidKeyValue(exclusiveStartKey, table, expected)) {
throw invalidStartingKey(isScan);
}
}
private boolean hasInvalidKeyValue(JsonNode exclusiveStartKey, TableDefinition table,
Set<String> expected) {
if (table.getAttributeDefinitions() == null) {
return true;
}
for (String attribute : expected) {
String expectedType = table.getAttributeDefinitions().stream()
.filter(definition -> attribute.equals(definition.getAttributeName()))
.map(AttributeDefinition::getAttributeType)
.findFirst()
.orElse(null);
if (expectedType == null || hasInvalidScalarValue(exclusiveStartKey.get(attribute), expectedType)) {
return true;
}
}
return false;
}
private boolean hasInvalidScalarValue(JsonNode value, String expectedType) {
if (value == null || !value.isObject() || value.size() != 1 || !value.has(expectedType)) {
return true;
}
JsonNode payload = value.get(expectedType);
if (payload == null || !payload.isTextual() || payload.textValue().isEmpty()) {
return true;
}
if ("N".equals(expectedType)) {
DynamoDbNumberUtils.validateAndNormalize(payload.textValue());
}
if ("B".equals(expectedType)) {
return !payload.textValue().matches(
"(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?");
}
return false;
}
private AwsException invalidStartingKey(boolean isScan) {
return new AwsException("ValidationException", isScan
? "The provided starting key is invalid: The provided key element does not match the schema"
: "The provided starting key is invalid", 400);
}
private static final Set<String> VALID_SELECT = Set.of(
"ALL_ATTRIBUTES", "ALL_PROJECTED_ATTRIBUTES", "SPECIFIC_ATTRIBUTES", "COUNT");
@@ -918,9 +857,8 @@ public class DynamoDbJsonHandler {
Set<String> hashTokens = extractHashTokens(keyConditionExpr, filterExpr, projectionExpression);
checkUnusedEan(exprAttrNames, hashTokens);
checkUnusedEav(exprAttrValues, extractColonTokens(keyConditionExpr, filterExpr));
if (exclusiveStartKey != null) {
validateExclusiveStartKey(exclusiveStartKey, queryTable, queryAccessPath, false);
DynamoDbAccessPathValidator.validateExclusiveStartKey(exclusiveStartKey, queryTable, queryAccessPath, false);
}
DynamoDbService.QueryResult result = dynamoDbService.query(tableName, keyConditions,
@@ -1054,7 +992,7 @@ public class DynamoDbJsonHandler {
rejectConsistentReadOnGsi(request, scanAccessPath);
if (exclusiveStartKey != null) {
validateExclusiveStartKey(exclusiveStartKey, scanTable, scanAccessPath, true);
DynamoDbAccessPathValidator.validateExclusiveStartKey(exclusiveStartKey, scanTable, scanAccessPath, true);
}
DynamoDbService.ScanResult result = dynamoDbService.scan(
@@ -2012,13 +1950,9 @@ public class DynamoDbJsonHandler {
}
Set<String> allowed = accessPath.projectedAttributeNames(table);
return items.stream().map(item -> {
ObjectNode filtered = objectMapper.createObjectNode();
item.fields().forEachRemaining(e -> {
if (allowed.contains(e.getKey())) filtered.set(e.getKey(), e.getValue());
});
return (JsonNode) filtered;
}).toList();
return items.stream()
.map(item -> (JsonNode) ProjectionEvaluator.trimToAttributes((ObjectNode) item, allowed))
.toList();
}
private void addConsumedCapacity(ObjectNode response, JsonNode request, String tableName,
@@ -2336,7 +2270,9 @@ public class DynamoDbJsonHandler {
DynamoDbPartiQLParser.Stmt stmt = DynamoDbPartiQLParser.parse(statement, parameters);
PartiQLExecuteContext ctx = PartiQLExecuteContext.builder()
.limit(request.has("Limit") ? request.get("Limit").asInt() : null)
.nextToken(request.has("NextToken") ? request.get("NextToken").asText() : null);
.nextToken(request.has("NextToken") ? request.get("NextToken").asText() : null)
.consistentRead(request.path("ConsistentRead").asBoolean(false))
.tokenBinding(partiQLHandler.tokenBinding(statement, parameters));
JsonNode result = partiQLHandler.execute(stmt, ctx, region);
return Response.ok(result).build();
}
@@ -2385,7 +2321,14 @@ public class DynamoDbJsonHandler {
try {
DynamoDbPartiQLParser.Stmt stmt = DynamoDbPartiQLParser.parse(
s.path("Statement").asText(), toPartiQLParams(s.path("Parameters")));
JsonNode result = partiQLHandler.execute(stmt, PartiQLExecuteContext.builder(), region);
if (stmt instanceof DynamoDbPartiQLParser.Stmt.Select select
&& !batchSelectResolvesThroughPrimaryKey(select, region)) {
throw new AwsException("ValidationError",
"Select statements within BatchExecuteStatement must specify the primary key "
+ "in the where clause.", 400);
}
JsonNode result = partiQLHandler.execute(stmt, PartiQLExecuteContext.builder()
.consistentRead(s.path("ConsistentRead").asBoolean(false)), region);
ObjectNode slot = objectMapper.createObjectNode();
JsonNode firstItem = result.path("Items").path(0);
if (!firstItem.isMissingNode()) {
@@ -2406,6 +2349,31 @@ public class DynamoDbJsonHandler {
return Response.ok(resp).build();
}
// BatchExecuteStatement only runs SELECT statements that resolve through
// the table's primary key: index-qualified statements and partial-key
// WHERE clauses are rejected per statement (characterised on real AWS,
// eu-west-1, 2026-09-02).
private boolean batchSelectResolvesThroughPrimaryKey(DynamoDbPartiQLParser.Stmt.Select select, String region) {
if (select.index() != null) {
return false;
}
TableDefinition table = dynamoDbService.describeTable(select.table(), region);
String pkName = table.getPartitionKeyName();
String skName = table.getSortKeyName();
boolean pkEq = false;
boolean skEq = skName == null;
for (DynamoDbPartiQLParser.Cond c : select.where()) {
if (c instanceof DynamoDbPartiQLParser.Cond.Eq eq) {
if (eq.attr().equals(pkName)) {
pkEq = true;
} else if (skName != null && eq.attr().equals(skName)) {
skEq = true;
}
}
}
return pkEq && skEq;
}
private List<JsonNode> toPartiQLParams(JsonNode node) {
if (node == null || node.isMissingNode() || !node.isArray()) {
return Collections.emptyList();
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
@@ -9,6 +10,9 @@ import io.github.hectorvent.floci.services.dynamodb.DynamoDbPartiQLParser.*;
import io.github.hectorvent.floci.services.dynamodb.model.ConditionalCheckFailedException;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.Base64;
@@ -35,8 +39,39 @@ class DynamoDbPartiQLHandler {
private JsonNode executeSelect(Stmt.Select stmt, PartiQLExecuteContext ctx, String region) {
TableDefinition table = service.describeTable(stmt.table(), region);
String pkName = table.getPartitionKeyName();
String skName = table.getSortKeyName();
// ExecuteStatement omits the index name from the missing-index message,
// unlike Query/Scan (characterised on real AWS, eu-west-1, 2026-09-02).
DynamoDbAccessPath accessPath = DynamoDbAccessPath.resolve(table, stmt.index(),
"The table does not have the specified index");
// Consistent reads are rejected on statements qualified with a GSI.
// Characterised on real AWS (eu-west-1, 2026-09-02): the wording
// differs from the Query/Scan rejection.
if (ctx.consistentRead() && accessPath.isGlobalSecondaryIndex()) {
throw new AwsException("ValidationException",
"Strongly consistent read is not supported on Global Secondary Indexes", 400);
}
// A GSI-qualified statement can only select attributes the index
// projects; the message preserves statement order (characterised on
// real AWS, eu-west-1, 2026-09-02). An LSI read reaches the co-located
// base item, so non-projected columns stay legal there.
if (accessPath.isGlobalSecondaryIndex()) {
Set<String> projected = accessPath.projectedAttributeNames(table);
List<String> unprojected = stmt.columns().stream()
.filter(c -> !"*".equals(c))
.filter(c -> !projected.contains(c))
.toList();
if (!unprojected.isEmpty()) {
throw new AwsException("ValidationException",
"One or more parameter values were invalid: Global secondary index "
+ accessPath.indexName() + " does not project ["
+ String.join(", ", unprojected) + "]", 400);
}
}
String pkName = accessPath.partitionKeyName();
String skName = accessPath.sortKeyName();
Cond.Eq pkEq = null;
Cond skCond = null;
@@ -60,13 +95,28 @@ class DynamoDbPartiQLHandler {
List<JsonNode> items;
JsonNode lastEvaluatedKey = null;
if (stmt.where().isEmpty()) {
JsonNode exclusiveStartKey = decodeNextToken(ctx.nextToken());
DynamoDbService.ScanResult result = service.scan(
stmt.table(), null, null, null, null, ctx.limit(), exclusiveStartKey, region);
if (pkEq == null) {
// No equality on the selected source's partition key: AWS performs
// a full scan of the table or index and applies the remaining
// conditions as a filter (characterised on real AWS, eu-west-1,
// 2026-09-02).
ExprAttrBuilder eav = new ExprAttrBuilder();
ExprAttrNameBuilder ean = new ExprAttrNameBuilder();
List<Cond> scanFilters = new ArrayList<>(filterConds);
if (skCond != null) {
scanFilters.add(skCond);
}
String fe = buildFe(scanFilters, eav, ean);
JsonNode exclusiveStartKey = decodeNextToken(ctx.nextToken(), ctx.tokenBinding());
DynamoDbAccessPathValidator.validateExclusiveStartKey(exclusiveStartKey, table, accessPath, true);
DynamoDbService.ScanResult result = service.scan(stmt.table(), fe,
ean.isEmpty() ? null : ean.toNode(mapper),
eav.isEmpty() ? null : eav.toNode(mapper),
null, ctx.limit(), exclusiveStartKey, accessPath.indexName(), region);
items = result.items();
lastEvaluatedKey = result.lastEvaluatedKey();
} else if (pkEq != null && skName == null && skCond == null && filterConds.isEmpty()) {
} else if (accessPath.kind() == DynamoDbAccessPath.Kind.TABLE && skName == null
&& skCond == null && filterConds.isEmpty()) {
ObjectNode key = mapper.createObjectNode();
key.set(pkName, toTypedNode(pkEq.val()));
JsonNode item = service.getItem(stmt.table(), key, region);
@@ -76,13 +126,19 @@ class DynamoDbPartiQLHandler {
ExprAttrNameBuilder ean = new ExprAttrNameBuilder();
String kce = buildKce(pkEq, skCond, pkName, skName, eav, ean);
String fe = buildFe(filterConds, eav, ean);
JsonNode exclusiveStartKey = decodeNextToken(ctx.nextToken(), ctx.tokenBinding());
DynamoDbAccessPathValidator.validateExclusiveStartKey(exclusiveStartKey, table, accessPath, false);
DynamoDbService.QueryResult result = service.query(
stmt.table(), null, eav.toNode(mapper), kce, fe,
null, null, null, null, ean.isEmpty() ? null : ean.toNode(mapper), region);
ctx.limit(), null, accessPath.indexName(), exclusiveStartKey,
ean.isEmpty() ? null : ean.toNode(mapper), region);
items = result.items();
lastEvaluatedKey = result.lastEvaluatedKey();
}
// Apply column projection for non-* SELECT
// Apply column projection for non-* SELECT. Projects against the full
// item: an LSI read can reach attributes outside the index projection
// (characterised on real AWS, eu-west-1, 2026-09-02).
if (!stmt.columns().isEmpty()) {
ExprAttrNameBuilder projEan = new ExprAttrNameBuilder();
String proj = stmt.columns().stream()
@@ -95,39 +151,75 @@ class DynamoDbPartiQLHandler {
.toList();
}
// SELECT * over an index reads the projection, not the whole item.
if (stmt.columns().isEmpty() && accessPath.isIndex()) {
Set<String> projected = accessPath.projectedAttributeNames(table);
items = items.stream()
.map(item -> (JsonNode) ProjectionEvaluator.trimToAttributes((ObjectNode) item, projected))
.toList();
}
ArrayNode arr = mapper.createArrayNode();
items.forEach(arr::add);
ObjectNode resp = mapper.createObjectNode();
resp.set("Items", arr);
if (lastEvaluatedKey != null) {
resp.put("NextToken", encodeNextToken(lastEvaluatedKey));
resp.put("NextToken", encodeNextToken(lastEvaluatedKey, ctx.tokenBinding()));
}
return resp;
}
private String encodeNextToken(JsonNode lastEvaluatedKey) {
// NextToken is opaque to the client, so it carries a digest binding it to
// the statement text and parameter values that minted it. Real AWS rejects
// a token replayed against any other statement, table or access path with
// "NextToken does not match request", while a changed Limit or a dropped
// ConsistentRead is accepted (characterised on real AWS, eu-west-1,
// 2026-09-03).
String tokenBinding(String statement, List<JsonNode> parameters) {
try {
return Base64.getEncoder().encodeToString(mapper.writeValueAsBytes(lastEvaluatedKey));
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(statement.getBytes(StandardCharsets.UTF_8));
digest.update((byte) 0);
for (JsonNode parameter : parameters) {
digest.update(mapper.writeValueAsBytes(parameter));
digest.update((byte) 0);
}
return HexFormat.of().formatHex(digest.digest());
} catch (NoSuchAlgorithmException | JsonProcessingException e) {
throw new IllegalStateException("Failed to bind the PartiQL NextToken to its statement", e);
}
}
private String encodeNextToken(JsonNode lastEvaluatedKey, String tokenBinding) {
try {
ObjectNode payload = mapper.createObjectNode();
payload.set("k", lastEvaluatedKey);
payload.put("b", tokenBinding);
return Base64.getEncoder().encodeToString(mapper.writeValueAsBytes(payload));
} catch (Exception e) {
throw new AwsException("InternalServerError", "Failed to encode NextToken", 500);
}
}
private JsonNode decodeNextToken(String nextToken) {
private JsonNode decodeNextToken(String nextToken, String tokenBinding) {
if (nextToken == null) return null;
JsonNode payload;
try {
return mapper.readTree(Base64.getDecoder().decode(nextToken));
payload = mapper.readTree(Base64.getDecoder().decode(nextToken));
} catch (Exception e) {
throw new AwsException("ValidationException", "Invalid NextToken", 400);
}
if (!payload.isObject() || !payload.hasNonNull("k")
|| !tokenBinding.equals(payload.path("b").asText())) {
throw new AwsException("ValidationException", "NextToken does not match request", 400);
}
return payload.get("k");
}
private String buildKce(Cond.Eq pkEq, Cond skCond, String pkName, String skName,
ExprAttrBuilder eav, ExprAttrNameBuilder ean) {
if (pkEq == null) {
throw new AwsException("ValidationException",
"WHERE clause of a SELECT must include an equality condition on the partition key", 400);
}
// Query branch: callers only reach this with a partition-key equality
// in the WHERE clause; every other shape routes to the scan branch.
String pkAlias = ean.alias(pkName);
String pkPlaceholder = eav.add(toTypedNode(pkEq.val()));
StringBuilder kce = new StringBuilder(pkAlias).append(" = ").append(pkPlaceholder);
@@ -12,7 +12,7 @@ public class DynamoDbPartiQLParser {
UPDATE, SET, REMOVE, DELETE, AND, BETWEEN,
IDENT, STRING, NUMBER, BOOL, NULL, QUESTION,
EQ, NE, LT, LE, GT, GE,
LPAREN, RPAREN, LBRACE, RBRACE, COMMA, COLON,
LPAREN, RPAREN, LBRACE, RBRACE, COMMA, COLON, DOT,
EOF
}
@@ -22,7 +22,7 @@ public class DynamoDbPartiQLParser {
public sealed interface Stmt permits Stmt.Select, Stmt.Insert, Stmt.Update, Stmt.Delete {
String table();
record Select(String table, List<String> columns, List<Cond> where) implements Stmt {}
record Select(String table, String index, List<String> columns, List<Cond> where) implements Stmt {}
record Insert(String table, Map<String, PVal> item) implements Stmt {}
record Update(String table, List<Assign> sets, List<String> removes, List<Cond> where) implements Stmt {}
record Delete(String table, List<Cond> where) implements Stmt {}
@@ -116,6 +116,7 @@ public class DynamoDbPartiQLParser {
if (c == '}') { tokens.add(new Token(TType.RBRACE, "}")); i++; continue; }
if (c == ',') { tokens.add(new Token(TType.COMMA, ",")); i++; continue; }
if (c == ':') { tokens.add(new Token(TType.COLON, ":")); i++; continue; }
if (c == '.') { tokens.add(new Token(TType.DOT, ".")); i++; continue; }
if (Character.isDigit(c) || (c == '-' && i + 1 < n && Character.isDigit(input.charAt(i + 1)))) {
int start = i;
if (c == '-') i++;
@@ -179,7 +180,7 @@ public class DynamoDbPartiQLParser {
};
}
// SELECT col [, col …] | * FROM "Table" [WHERE cond [AND cond …]]
// SELECT col [, col …] | * FROM "Table"["." "Index"] [WHERE cond [AND cond …]]
private Stmt.Select parseSelect() {
consume(TType.SELECT);
List<String> cols = new ArrayList<>();
@@ -191,9 +192,14 @@ public class DynamoDbPartiQLParser {
}
consume(TType.FROM);
String table = expectIdent();
String index = null;
if (peek().type() == TType.DOT) {
advance();
index = expectIdent();
}
List<Cond> where = new ArrayList<>();
if (peek().type() == TType.WHERE) { advance(); where = parseConditions(); }
return new Stmt.Select(table, cols, where);
return new Stmt.Select(table, index, cols, where);
}
// INSERT INTO "Table" VALUE {'key': val, …}
@@ -4,6 +4,8 @@ class PartiQLExecuteContext {
private Integer limit;
private String nextToken;
private String tokenBinding;
private boolean consistentRead;
private PartiQLExecuteContext() {
}
@@ -22,6 +24,20 @@ class PartiQLExecuteContext {
return this;
}
PartiQLExecuteContext tokenBinding(String tokenBinding) {
this.tokenBinding = tokenBinding;
return this;
}
PartiQLExecuteContext consistentRead(boolean consistentRead) {
this.consistentRead = consistentRead;
return this;
}
boolean consistentRead() {
return consistentRead;
}
Integer limit() {
return limit;
}
@@ -29,4 +45,8 @@ class PartiQLExecuteContext {
String nextToken() {
return nextToken;
}
String tokenBinding() {
return tokenBinding;
}
}
@@ -8,8 +8,13 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@@ -17,6 +22,7 @@ class DynamoDbAccessPathIntegrationTest {
private static final String CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String TABLE = "access-path-validation";
private static final String SIBLING_TABLE = "access-path-validation-sibling";
@BeforeAll
static void configureRestAssured() {
@@ -413,6 +419,342 @@ class DynamoDbAccessPathIntegrationTest {
.body("message", equalTo("The provided starting key is invalid"));
}
@Test
@Order(20)
void executeStatementRejectsConsistentReadOnQualifiedGsi() {
request("DynamoDB_20120810.ExecuteStatement", """
{
"Statement":"SELECT * FROM \\"%s\\".\\"status-index\\"",
"ConsistentRead":true
}
""".formatted(TABLE))
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("Strongly consistent read is not supported on Global Secondary Indexes"));
}
@Test
@Order(21)
void executeStatementReadsThroughQualifiedGsi() {
request("DynamoDB_20120810.PutItem", """
{
"TableName":"%s",
"Item":{"pk":{"S":"partiql-gsi"},"sk":{"S":"s1"},
"status":{"S":"partiql-status"},"createdAt":{"S":"2026-01-01"},
"alternate":{"S":"alt-1"},"summary":{"S":"first"}}
}
""".formatted(TABLE))
.statusCode(200);
request("DynamoDB_20120810.PutItem", """
{
"TableName":"%s",
"Item":{"pk":{"S":"partiql-gsi"},"sk":{"S":"s2"},
"status":{"S":"partiql-status"},"createdAt":{"S":"2026-01-02"},
"alternate":{"S":"alt-2"},"summary":{"S":"second"}}
}
""".formatted(TABLE))
.statusCode(200);
// A row matching the base-table predicate but absent from the index:
// it must stay invisible to the qualified read.
request("DynamoDB_20120810.PutItem", """
{
"TableName":"%s",
"Item":{"pk":{"S":"partiql-sparse"},"sk":{"S":"s2"},
"alternate":{"S":"alt-9"}}
}
""".formatted(TABLE))
.statusCode(200);
// Equality on the index partition key routes through an index query.
// status-index projects INCLUDE summary, so non-projected attributes
// stay out of the result (SELECT * reads the projection).
request("DynamoDB_20120810.ExecuteStatement", """
{
"Statement":"SELECT * FROM \\"%s\\".\\"status-index\\" WHERE status = 'partiql-status'"
}
""".formatted(TABLE))
.statusCode(200)
.body("Items.size()", equalTo(2))
.body("Items[0].summary.S", equalTo("first"))
.body("Items[0].alternate", equalTo(null));
// Without equality on the index partition key, the statement performs
// a full index scan and applies the remaining conditions as a filter.
request("DynamoDB_20120810.ExecuteStatement", """
{
"Statement":"SELECT * FROM \\"%s\\".\\"status-index\\" WHERE sk = 's2'"
}
""".formatted(TABLE))
.statusCode(200)
.body("Items.size()", equalTo(1))
.body("Items[0].sk.S", equalTo("s2"));
}
@Test
@Order(22)
void executeStatementQualifiedLsiAcceptsConsistentReads() {
request("DynamoDB_20120810.ExecuteStatement", """
{
"Statement":"SELECT * FROM \\"%s\\".\\"alternate-index\\" WHERE pk = 'partiql-gsi'",
"ConsistentRead":true
}
""".formatted(TABLE))
.statusCode(200)
.body("Items.size()", equalTo(2))
.body("Items[0].alternate.S", equalTo("alt-1"))
.body("Items[0].summary", equalTo(null));
// An unqualified statement stays legal with ConsistentRead, even when
// its WHERE clause names a GSI attribute.
request("DynamoDB_20120810.ExecuteStatement", """
{
"Statement":"SELECT * FROM \\"%s\\" WHERE status = 'partiql-status'",
"ConsistentRead":true
}
""".formatted(TABLE))
.statusCode(200)
.body("Items.size()", equalTo(2));
// An LSI read reaches the co-located base item, so an explicit column
// outside the index projection still returns (characterised on real
// AWS, eu-west-1, 2026-09-02). alternate-index is KEYS_ONLY.
request("DynamoDB_20120810.ExecuteStatement", """
{
"Statement":"SELECT summary FROM \\"%s\\".\\"alternate-index\\" WHERE pk = 'partiql-gsi'"
}
""".formatted(TABLE))
.statusCode(200)
.body("Items.size()", equalTo(2))
.body("Items[0].summary.S", equalTo("first"));
}
@Test
@Order(26)
void executeStatementRejectsUnprojectedGsiColumnsInStatementOrder() {
request("DynamoDB_20120810.ExecuteStatement", """
{
"Statement":"SELECT zdrop, adrop FROM \\"%s\\".\\"status-index\\" WHERE status = 'partiql-status'"
}
""".formatted(TABLE))
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo(
"One or more parameter values were invalid: Global secondary index status-index "
+ "does not project [zdrop, adrop]"));
}
@Test
@Order(23)
void executeStatementRejectsUnknownQualifiedIndex() {
request("DynamoDB_20120810.ExecuteStatement", """
{
"Statement":"SELECT * FROM \\"%s\\".\\"no-such-index\\""
}
""".formatted(TABLE))
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("The table does not have the specified index"));
}
@Test
@Order(24)
void executeStatementScanAndQueryBranchesPaginate() {
request("DynamoDB_20120810.PutItem", """
{
"TableName":"%s",
"Item":{"pk":{"S":"partiql-page-1"},"sk":{"S":"a"},
"status":{"S":"partiql-page"},"createdAt":{"S":"2026-02-01"},
"alternate":{"S":"page-1"},"summary":{"S":"one"}}
}
""".formatted(TABLE))
.statusCode(200);
request("DynamoDB_20120810.PutItem", """
{
"TableName":"%s",
"Item":{"pk":{"S":"partiql-page-2"},"sk":{"S":"b"},
"status":{"S":"partiql-page"},"createdAt":{"S":"2026-02-02"},
"alternate":{"S":"page-2"},"summary":{"S":"two"}}
}
""".formatted(TABLE))
.statusCode(200);
// Filter scan (no partition-key equality): Limit caps scanned items, so
// a page may come back empty while the cursor still advances. Page
// until the cursor is exhausted and collect both matches.
Set<String> scannedPks = new HashSet<>();
String scanToken = null;
int scanPages = 0;
do {
String pageBody = """
{"Statement":"SELECT * FROM \\"%s\\" WHERE status = 'partiql-page'",
"Limit":1%s}
""".formatted(TABLE, scanToken == null ? "" : ",\"NextToken\":\"" + scanToken + "\"");
io.restassured.response.ValidatableResponse page =
request("DynamoDB_20120810.ExecuteStatement", pageBody).statusCode(200);
page.body("Items.size()", lessThanOrEqualTo(1));
List<String> pagePks = page.extract().jsonPath().getList("Items.pk.S");
if (pagePks != null) scannedPks.addAll(pagePks);
scanToken = page.extract().jsonPath().getString("NextToken");
scanPages++;
} while (scanToken != null && scanPages < 10);
org.junit.jupiter.api.Assertions.assertEquals(Set.of("partiql-page-1", "partiql-page-2"), scannedPks);
// Query branch (partition-key equality): same pagination contract.
String queryToken = request("DynamoDB_20120810.ExecuteStatement", """
{
"Statement":"SELECT * FROM \\"%s\\" WHERE pk = 'partiql-gsi' AND begins_with(sk, 's')",
"Limit":1
}
""".formatted(TABLE))
.statusCode(200)
.body("Items.size()", equalTo(1))
.extract().jsonPath().getString("NextToken");
request("DynamoDB_20120810.ExecuteStatement", """
{
"Statement":"SELECT * FROM \\"%s\\" WHERE pk = 'partiql-gsi' AND begins_with(sk, 's')",
"Limit":1,
"NextToken":"%s"
}
""".formatted(TABLE, queryToken))
.statusCode(200)
.body("Items.size()", equalTo(1));
}
@Test
@Order(25)
void batchExecuteStatementRejectsSelectsOutsideThePrimaryKey() {
request("DynamoDB_20120810.BatchExecuteStatement", """
{
"Statements":[
{"Statement":"SELECT * FROM \\"%s\\".\\"status-index\\" WHERE status = 'partiql-status'"},
{"Statement":"SELECT * FROM \\"%s\\" WHERE pk = 'partiql-page-1'"}
]
}
""".formatted(TABLE, TABLE))
.statusCode(200)
.body("Responses[0].Error.Code", equalTo("ValidationError"))
.body("Responses[0].Error.Message", equalTo(
"Select statements within BatchExecuteStatement must specify the primary key in the where clause."))
.body("Responses[1].Error.Code", equalTo("ValidationError"))
.body("Responses[1].Error.Message", equalTo(
"Select statements within BatchExecuteStatement must specify the primary key in the where clause."));
}
@Test
@Order(27)
void executeStatementRejectsForeignNextTokens() {
// The NextToken is opaque and bound to the issuing statement text and
// parameters (characterised on real AWS, eu-west-1, 2026-09-03):
// replaying one against a different statement, parameter set or access
// path is rejected, while a different Limit is accepted.
String scanToken = request("DynamoDB_20120810.ExecuteStatement", """
{"Statement":"SELECT * FROM \\"%s\\" WHERE status = 'partiql-page'","Limit":1}
""".formatted(TABLE))
.statusCode(200)
.body("Items.size()", lessThanOrEqualTo(1))
.extract().jsonPath().getString("NextToken");
// Different statement over the same table.
request("DynamoDB_20120810.ExecuteStatement", """
{"Statement":"SELECT * FROM \\"%s\\"","Limit":1,"NextToken":"%s"}
""".formatted(TABLE, scanToken))
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("NextToken does not match request"));
// Base-table token replayed on an index-qualified statement.
request("DynamoDB_20120810.ExecuteStatement", """
{"Statement":"SELECT * FROM \\"%s\\".\\"status-index\\" WHERE status = 'partiql-page'","Limit":1,"NextToken":"%s"}
""".formatted(TABLE, scanToken))
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("NextToken does not match request"));
// Index-qualified token replayed on the base table.
String gsiToken = request("DynamoDB_20120810.ExecuteStatement", """
{"Statement":"SELECT * FROM \\"%s\\".\\"status-index\\" WHERE status = 'partiql-page'","Limit":1}
""".formatted(TABLE))
.statusCode(200)
.extract().jsonPath().getString("NextToken");
request("DynamoDB_20120810.ExecuteStatement", """
{"Statement":"SELECT * FROM \\"%s\\" WHERE status = 'partiql-page'","Limit":1,"NextToken":"%s"}
""".formatted(TABLE, gsiToken))
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("NextToken does not match request"));
// Same statement text with different parameters.
String parameterToken = request("DynamoDB_20120810.ExecuteStatement", """
{"Statement":"SELECT * FROM \\"%s\\" WHERE pk = ?","Limit":1,"Parameters":[{"S":"partiql-gsi"}]}
""".formatted(TABLE))
.statusCode(200)
.extract().jsonPath().getString("NextToken");
request("DynamoDB_20120810.ExecuteStatement", """
{"Statement":"SELECT * FROM \\"%s\\" WHERE pk = ?","Limit":1,"Parameters":[{"S":"partiql-page-1"}],"NextToken":"%s"}
""".formatted(TABLE, parameterToken))
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("NextToken does not match request"));
// A different Limit is not part of the binding.
request("DynamoDB_20120810.ExecuteStatement", """
{"Statement":"SELECT * FROM \\"%s\\" WHERE pk = ?","Limit":2,"Parameters":[{"S":"partiql-gsi"}],"NextToken":"%s"}
""".formatted(TABLE, parameterToken))
.statusCode(200);
}
@Test
@Order(28)
void executeStatementRejectsNextTokenFromAnotherTable() {
// Even with an identical key schema, a token minted against one table
// is rejected on another (characterised on real AWS, eu-west-1,
// 2026-09-03).
given()
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
.contentType(CONTENT_TYPE)
.body("""
{
"TableName":"%s",
"AttributeDefinitions":[
{"AttributeName":"pk","AttributeType":"S"},
{"AttributeName":"sk","AttributeType":"S"}
],
"KeySchema":[
{"AttributeName":"pk","KeyType":"HASH"},
{"AttributeName":"sk","KeyType":"RANGE"}
],
"BillingMode":"PAY_PER_REQUEST"
}
""".formatted(SIBLING_TABLE))
.when()
.post("/")
.then()
.statusCode(200);
try {
String token = request("DynamoDB_20120810.ExecuteStatement", """
{"Statement":"SELECT * FROM \\"%s\\" WHERE pk = 'partiql-gsi' AND begins_with(sk, 's')","Limit":1}
""".formatted(TABLE))
.statusCode(200)
.extract().jsonPath().getString("NextToken");
request("DynamoDB_20120810.ExecuteStatement", """
{"Statement":"SELECT * FROM \\"%s\\"","Limit":1,"NextToken":"%s"}
""".formatted(SIBLING_TABLE, token))
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("NextToken does not match request"));
} finally {
given()
.header("X-Amz-Target", "DynamoDB_20120810.DeleteTable")
.contentType(CONTENT_TYPE)
.body("{\"TableName\":\"" + SIBLING_TABLE + "\"}")
.when()
.post("/")
.then()
.statusCode(200);
}
}
@Test
@Order(99)
void deleteTable() {