mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
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:
1 parent
7fdd145c0c
commit
84ec8ae8e7
8 files changed
+738
-97
No files matched your search
@@ -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 {
|
||||
|
||||
+62
@@ -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);
|
||||
}
|
||||
}
|
||||
+41
-73
@@ -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();
|
||||
|
||||
+110
-18
@@ -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);
|
||||
|
||||
+10
-4
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user