fix(dynamodb): treat resolved projection aliases as literal names, not list indices (#3633)

This commit is contained in:
Chris Jovanovski authored and GitHub committed 2026-09-15 21:20:25 -04:00
1 parent b8d78c8c9f
commit c707415be7
3 files changed
+210 -15

No files matched your search

@@ -39,7 +39,7 @@ final class ProjectionEvaluator {
validateExpression(projectionExpression);
PathTrie root = new PathTrie();
for (String rawPath : splitProjectionPaths(projectionExpression)) {
List<String> segments = resolvePath(rawPath.trim(), exprAttrNames);
List<PathSegment> segments = resolvePath(rawPath.trim(), exprAttrNames);
if (segments.isEmpty()) {
continue;
}
@@ -66,9 +66,9 @@ final class ProjectionEvaluator {
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);
List<PathSegment> segments = resolvePath(rawPath.trim(), exprAttrNames);
if (!segments.isEmpty()) {
attributes.add(segments.getFirst());
attributes.add(segments.getFirst().name());
}
}
return Set.copyOf(attributes);
@@ -116,8 +116,24 @@ final class ProjectionEvaluator {
// ── Path resolution ──
private static List<String> resolvePath(String path, JsonNode exprAttrNames) {
List<String> segments = new ArrayList<>();
/**
* One step of a document path. The kind is fixed by the raw expression: a name token
* (including a resolved #alias, whatever characters its value contains) addresses a map
* key, and only a [n] suffix written in the expression itself addresses a list index.
*/
private record PathSegment(String name, long index, boolean isIndex) {
static PathSegment name(String name) {
return new PathSegment(name, -1L, false);
}
static PathSegment index(long index) {
return new PathSegment(null, index, true);
}
}
private static List<PathSegment> resolvePath(String path, JsonNode exprAttrNames) {
List<PathSegment> segments = new ArrayList<>();
// Tokenize on dots, preserving [n] bracket indices
String[] parts = path.split("\\.");
for (String part : parts) {
@@ -126,7 +142,7 @@ final class ProjectionEvaluator {
if (bracketIdx >= 0) {
String name = part.substring(0, bracketIdx);
if (!name.isEmpty()) {
segments.add(resolveSegment(name, exprAttrNames));
segments.add(PathSegment.name(resolveSegment(name, exprAttrNames)));
}
// Parse each [n] suffix
String rest = part.substring(bracketIdx);
@@ -134,12 +150,13 @@ final class ProjectionEvaluator {
while (i < rest.length() && rest.charAt(i) == '[') {
int close = rest.indexOf(']', i);
if (close < 0) break;
validateListIndex(rest.substring(i + 1, close));
segments.add(rest.substring(i, close + 1)); // e.g. "[0]"
String content = rest.substring(i + 1, close);
validateListIndex(content);
segments.add(PathSegment.index(Long.parseLong(content)));
i = close + 1;
}
} else {
segments.add(resolveSegment(part, exprAttrNames));
segments.add(PathSegment.name(resolveSegment(part, exprAttrNames)));
}
}
return segments;
@@ -194,14 +211,13 @@ final class ProjectionEvaluator {
// Long keys: the allowable index range (up to 4294967294) exceeds Integer.MAX_VALUE.
private final TreeMap<Long, PathTrie> indices = new TreeMap<>();
void insert(List<String> segments) {
void insert(List<PathSegment> segments) {
PathTrie node = this;
for (String seg : segments) {
if (seg.startsWith("[")) {
long idx = Long.parseLong(seg.substring(1, seg.length() - 1));
node = node.indices.computeIfAbsent(idx, k -> new PathTrie());
for (PathSegment seg : segments) {
if (seg.isIndex()) {
node = node.indices.computeIfAbsent(seg.index(), k -> new PathTrie());
} else {
node = node.names.computeIfAbsent(seg, k -> new PathTrie());
node = node.names.computeIfAbsent(seg.name(), k -> new PathTrie());
}
}
node.terminal = true;
@@ -170,6 +170,83 @@ class DynamoDbProjectionIntegrationTest {
.body("Items[0].data.M.sources", nullValue());
}
@Test
@Order(6)
void putItemWithBracketedMapKey() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
.contentType(CT)
.body("""
{
"TableName": "%s",
"Item": {
"pk": {"S": "item2"},
"data": {"M": {
"settings": {"M": {
"[alpha]": {"L": [{"S": "one"}]},
"[beta]": {"L": [{"S": "three"}]}
}}
}}
}
}
""".formatted(TABLE))
.when()
.post("/")
.then()
.statusCode(200);
}
/**
* An alias that resolves to a bracketed map key such as "[alpha]" is a literal
* attribute name, not a list index. Before the fix this failed with a 500 because
* the bracket was parsed as an index.
*/
@Test
@Order(7)
void getItemWithAliasResolvingToBracketedKeyProjectsThatKey() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
.contentType(CT)
.body("""
{
"TableName": "%s",
"Key": {"pk": {"S": "item2"}},
"ExpressionAttributeNames": {"#data": "data", "#key": "[alpha]"},
"ProjectionExpression": "#data.settings.#key"
}
""".formatted(TABLE))
.when()
.post("/")
.then()
.statusCode(200)
.body("Item.data.M.settings.M.'[alpha]'.L[0].S", equalTo("one"))
.body("Item.data.M.settings.M.'[beta]'", nullValue());
}
@Test
@Order(8)
void queryWithAliasResolvingToBracketedKeyProjectsThatKey() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.Query")
.contentType(CT)
.body("""
{
"TableName": "%s",
"KeyConditionExpression": "pk = :pk",
"ExpressionAttributeValues": {":pk": {"S": "item2"}},
"ExpressionAttributeNames": {"#data": "data", "#key": "[alpha]"},
"ProjectionExpression": "#data.settings.#key"
}
""".formatted(TABLE))
.when()
.post("/")
.then()
.statusCode(200)
.body("Count", equalTo(1))
.body("Items[0].data.M.settings.M.'[alpha]'.L[0].S", equalTo("one"))
.body("Items[0].data.M.settings.M.'[beta]'", nullValue());
}
@AfterAll
static void cleanup() {
given()
@@ -5,6 +5,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.api.Test;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
/**
@@ -183,6 +185,106 @@ class ProjectionEvaluatorTest {
assertNull(result.get("l"), "an in-range index past the list end matches nothing");
}
private static ObjectNode bracketKeyedItem() {
return readValue("""
{
"pk": {"S": "p"},
"data": {"M": {
"settings": {"M": {
"[alpha]": {"L": [{"S": "one"}, {"S": "two"}]},
"[beta]": {"L": [{"S": "three"}]}
}},
"[0]": {"S": "literal-zero-key"},
"a.b": {"S": "dotted-key"},
"a[0]": {"S": "indexed-looking-key"},
"a": {"M": {"b": {"S": "real-nested"}}}
}},
"list": {"L": [{"S": "first"}, {"S": "second"}]}
}
""");
}
@Test
void aliasResolvingToBracketedNameIsALiteralMapKey() {
ObjectNode result = ProjectionEvaluator.project(bracketKeyedItem(), "#data.settings.#key",
readValue("""
{"#data": "data", "#key": "[alpha]"}
"""));
ObjectNode settings = (ObjectNode) result.get("data").get("M").get("settings").get("M");
assertEquals(2, settings.get("[alpha]").get("L").size());
assertEquals("one", settings.get("[alpha]").get("L").get(0).get("S").asText());
assertNull(settings.get("[beta]"), "unprojected sibling bracketed key must be dropped");
}
@Test
void aliasResolvingToBracketZeroIsNotAListIndex() {
ObjectNode result = ProjectionEvaluator.project(bracketKeyedItem(), "#data.#zero",
readValue("""
{"#data": "data", "#zero": "[0]"}
"""));
assertEquals("literal-zero-key", result.get("data").get("M").get("[0]").get("S").asText());
assertNull(result.get("data").get("L"), "a literal [0] alias must not index a list");
}
@Test
void aliasResolvingToDottedNameIsOneSegment() {
ObjectNode result = ProjectionEvaluator.project(bracketKeyedItem(), "#data.#dotted",
readValue("""
{"#data": "data", "#dotted": "a.b"}
"""));
ObjectNode data = (ObjectNode) result.get("data").get("M");
assertEquals("dotted-key", data.get("a.b").get("S").asText());
assertNull(data.get("a"), "a dotted alias must not traverse into the real nested map");
}
@Test
void aliasResolvingToIndexedLookingNameIsOneSegment() {
ObjectNode result = ProjectionEvaluator.project(bracketKeyedItem(), "#data.#indexed",
readValue("""
{"#data": "data", "#indexed": "a[0]"}
"""));
ObjectNode data = (ObjectNode) result.get("data").get("M");
assertEquals("indexed-looking-key", data.get("a[0]").get("S").asText());
assertNull(data.get("a"), "an indexed-looking alias must not index the real attribute");
}
@Test
void bracketedAliasFollowedByListIndexIndexesItsValue() {
ObjectNode result = ProjectionEvaluator.project(bracketKeyedItem(), "#data.settings.#key[1]",
readValue("""
{"#data": "data", "#key": "[alpha]"}
"""));
ObjectNode settings = (ObjectNode) result.get("data").get("M").get("settings").get("M");
assertEquals(1, settings.get("[alpha]").get("L").size());
assertEquals("two", settings.get("[alpha]").get("L").get(0).get("S").asText());
}
@Test
void realIndexSuffixOnAliasedListStillIndexes() {
ObjectNode result = ProjectionEvaluator.project(bracketKeyedItem(), "#list[0]",
readValue("""
{"#list": "list"}
"""));
assertEquals(1, result.get("list").get("L").size());
assertEquals("first", result.get("list").get("L").get(0).get("S").asText());
}
@Test
void topLevelAttributesKeepsBracketedAliasLiteral() {
Set<String> attributes = ProjectionEvaluator.topLevelAttributes("#key.x, #list[0]",
readValue("""
{"#key": "[alpha]", "#list": "list"}
"""));
assertEquals(Set.of("[alpha]", "list"), attributes);
}
private static ObjectNode readValue(String json) {
try {
return (ObjectNode) mapper.readTree(json);