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,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);
}
}
@@ -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);
}
}
@@ -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 check
boolean 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 index
if (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 -> {
@@ -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;
}
@@ -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 ──