fix(dynamodb): match AWS error messages for item calls and projections (#4315)

* fix(dynamodb): drop the table name from ResourceNotFound on item calls

AWS answers a data-plane call on a missing table with the bare message
"Requested resource not found". Floci named the table there, which only
control-plane calls such as DescribeTable do.

* fix(dynamodb): reject overlapping and undefined ProjectionExpression paths

AWS rejects a read whose ProjectionExpression names the same document path
twice, or names a path that covers another one, and it does so before the
read, so a request that matches nothing still fails. An undefined #alias in
a projection path is rejected the same way. Floci accepted both and only
trimmed the item afterwards.

The check runs on GetItem, Query, Scan, BatchGetItem and TransactGetItems.

* test(dynamodb): pin the ResourceNotFound message every item call returns

Covers the missing-table half next to the existing CREATING-table case, and
records that DescribeTable still names the table.

* fix(dynamodb): reject BatchGetItem mixing AttributesToGet and ProjectionExpression

AWS weighs the two projection styles across the whole request. One table
entry carrying both, or one entry naming AttributesToGet while another names
ProjectionExpression, fails with the expression conflict message. Floci
accepted both shapes.

* fix(dynamodb): reject DeleteItem carrying both Expected and ConditionExpression

PutItem and UpdateItem already rejected the mix. DeleteItem ran the legacy
Expected block alongside the condition instead.

* fix(dynamodb): answer an empty BatchGetItem RequestItems the way AWS does

AWS moved BatchGetItem to the validation framework message for an empty
RequestItems map. BatchWriteItem still answers with its own sentence, so
only the read side changes.

* fix(dynamodb): match AWS wording for a StreamViewType with streams disabled

CreateTable answers "Table is being created with a stream disabled,
UpdateViewType should not be specified".

* fix(dynamodb): name the set type when a binary set has duplicates

AWS answers a BS duplicate with "Input collection [, ]of type BS contains
duplicates.", with no space before "of". String and number sets keep the
plain wording.

* refactor(dynamodb): read each projection path once per loop in validatePaths

* refactor(dynamodb): compare projection path prefixes with subList

* fix(dynamodb): reject overlapping and undefined ProjectionExpression paths on SearchVectors

* refactor(dynamodb): declare the BatchWriteItem cost table with its type

* test(dynamodb): pin the overlapping projection rejection on reads that match nothing
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-09-24 21:13:18 -04:00
1 parent 922402210f
commit 8f606c3587
10 files changed
+473 -56

No files matched your search

@@ -856,6 +856,135 @@ class DynamoDbIntegrationTest {
+ "Non-expression parameters: {AttributesToGet} Expression parameters: {ProjectionExpression}"));
}
@Test
@Order(10)
void batchGetItemWithEmptyRequestItemsFails() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.BatchGetItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"RequestItems": {}}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("1 validation error detected: Value at 'RequestItems' failed to satisfy "
+ "constraint: Member must have length greater than or equal to 1"));
}
@Test
@Order(10)
void batchWriteItemWithEmptyRequestItemsFails() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.BatchWriteItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{"RequestItems": {}}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("The requestItems parameter is required for BatchWriteItem"));
}
@Test
@Order(10)
void deleteItemWithExpectedAndConditionExpressionFails() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.DeleteItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "TestTable",
"Key": {"pk": {"S": "user-1"}, "sk": {"S": "profile"}},
"Expected": {"pk": {"Exists": false}},
"ConditionExpression": "attribute_not_exists(pk)"
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("Can not use both expression and non-expression parameters in the same request: "
+ "Non-expression parameters: {Expected} Expression parameters: {ConditionExpression}"));
}
@Test
@Order(10)
void batchGetItemWithProjectionExpressionAndAttributesToGetFails() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.BatchGetItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"RequestItems": {
"TestTable": {
"Keys": [{"pk": {"S": "user-1"}, "sk": {"S": "profile"}}],
"ProjectionExpression": "pk",
"AttributesToGet": ["pk"]
}
}
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("Can not use both expression and non-expression parameters in the same request: "
+ "Non-expression parameters: {AttributesToGet} Expression parameters: {ProjectionExpression}"));
}
@Test
@Order(10)
void batchGetItemMixingProjectionStylesAcrossTablesFails() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "BatchGetMixTable",
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
"BillingMode": "PAY_PER_REQUEST"
}
""")
.when()
.post("/")
.then()
.statusCode(200);
given()
.header("X-Amz-Target", "DynamoDB_20120810.BatchGetItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"RequestItems": {
"TestTable": {
"Keys": [{"pk": {"S": "user-1"}, "sk": {"S": "profile"}}],
"ProjectionExpression": "pk"
},
"BatchGetMixTable": {
"Keys": [{"pk": {"S": "user-1"}}],
"AttributesToGet": ["pk"]
}
}
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("Can not use both expression and non-expression parameters in the same request: "
+ "Non-expression parameters: {AttributesToGet} Expression parameters: {ProjectionExpression}"));
}
@Test
@Order(10)
void queryWithQueryFilterAndKeyConditionExpressionFails() {
@@ -1034,8 +1034,8 @@ class DynamoDbJsonHandlerTest {
"StreamSpecification": {"StreamEnabled": false, "StreamViewType": "NEW_AND_OLD_IMAGES"}
}
"""));
assertEquals("One or more parameter values were invalid: "
+ "StreamViewType cannot be specified when StreamEnabled is false", ex.getMessage());
assertEquals("One or more parameter values were invalid: Table is being created with a stream "
+ "disabled, UpdateViewType should not be specified", ex.getMessage());
}
@Test
@@ -1350,6 +1350,23 @@ class DynamoDbJsonHandlerTest {
assertEquals(200, response.getStatus());
}
@Test
void putItemNamesTheSetTypeWhenABinarySetHasDuplicates() {
createUsersTable("eu-west-1");
ObjectNode request = mapper.createObjectNode();
request.put("TableName", "Users");
ObjectNode item = item("userId", "u1");
ObjectNode binarySet = mapper.createObjectNode();
binarySet.putArray("BS").add("").add("");
item.set("bad", binarySet);
request.set("Item", item);
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("PutItem", request, "eu-west-1"));
assertEquals("One or more parameter values were invalid: "
+ "Input collection [, ]of type BS contains duplicates.", ex.getMessage());
}
@Test
void putItemRejectsAConditionExpressionOver4096Bytes() {
createUsersTable("eu-west-1");
@@ -12,6 +12,8 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
@@ -247,6 +249,62 @@ class DynamoDbProjectionIntegrationTest {
.body("Items[0].data.M.settings.M.'[beta]'", nullValue());
}
@Test
@Order(9)
void getItemRejectsOverlappingPathsBeforeReadingTheItem() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
.contentType(CT)
.body("""
{
"TableName": "%s",
"Key": {"pk": {"S": "no-such-item"}},
"ProjectionExpression": "a, a.b"
}
""".formatted(TABLE))
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("Invalid ProjectionExpression: Two document paths overlap with each other; "
+ "must remove or rewrite one of these paths; path one: [a], path two: [a, b]"));
}
@Test
@Order(11)
void otherReadsRejectOverlappingPathsWhenNothingMatches() {
String missingKey = "{\"pk\": {\"S\": \"no-such-item\"}}";
Map<String, String> requests = Map.of(
"Query", """
{"TableName": "%s", "KeyConditionExpression": "pk = :p",
"ExpressionAttributeValues": {":p": {"S": "no-such-item"}}, "ProjectionExpression": "a, a.b"}
""".formatted(TABLE),
"Scan", """
{"TableName": "%s", "FilterExpression": "pk = :p",
"ExpressionAttributeValues": {":p": {"S": "no-such-item"}}, "ProjectionExpression": "a, a.b"}
""".formatted(TABLE),
"BatchGetItem", """
{"RequestItems": {"%s": {"Keys": [%s], "ProjectionExpression": "a, a.b"}}}
""".formatted(TABLE, missingKey),
"TransactGetItems", """
{"TransactItems": [
{"Get": {"TableName": "%1$s", "Key": {"pk": {"S": "other"}}}},
{"Get": {"TableName": "%1$s", "Key": %2$s, "ProjectionExpression": "a, a.b"}}]}
""".formatted(TABLE, missingKey));
requests.forEach((action, body) -> given()
.header("X-Amz-Target", "DynamoDB_20120810." + action)
.contentType(CT)
.body(body)
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("Invalid ProjectionExpression: Two document paths overlap with each other; "
+ "must remove or rewrite one of these paths; path one: [a], path two: [a, b]")));
}
@AfterAll
static void cleanup() {
given()
@@ -20,6 +20,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -4121,6 +4122,42 @@ class DynamoDbServiceTest {
return s3;
}
/** DescribeTable names the missing table, an item call does not. */
@Test
void itemCalls_missingTable_returnResourceNotFoundWithoutTableName() {
DynamoDbService svc = serviceWithS3(mock(S3Service.class), new InMemoryStorage<>());
String region = "us-east-1";
ObjectNode key = item("userId", "u1");
ObjectNode keys = mapper.createObjectNode();
keys.set("Keys", mapper.createArrayNode().add(key));
ObjectNode putRequest = mapper.createObjectNode();
putRequest.putObject("PutRequest").set("Item", key);
ObjectNode transactPut = mapper.createObjectNode();
transactPut.putObject("Put").put("TableName", "Users").set("Item", key);
ObjectNode transactGet = mapper.createObjectNode();
transactGet.putObject("Get").put("TableName", "Users").set("Key", key);
List<Executable> itemCalls = List.of(
() -> svc.getItem("Users", key, region),
() -> svc.putItem("Users", key, null, null, null, region, "NONE"),
() -> svc.updateItem("Users", key, null, "SET x = :v", null, item("v", "1"), "NONE", region),
() -> svc.deleteItem("Users", key, region),
() -> svc.query("Users", null, item("pk", "u1"), "userId = :pk", null, null, region),
() -> svc.scan("Users", null, null, null, null, null, null, null, region),
() -> svc.batchGetItem(Map.of("Users", keys), region),
() -> svc.batchWriteItem(Map.of("Users", List.of(putRequest)), region),
() -> svc.transactWriteItems(List.of(transactPut), region, null, null),
() -> svc.transactGetItems(List.of(transactGet), region));
for (Executable call : itemCalls) {
AwsException e = assertThrows(AwsException.class, call);
assertEquals("ResourceNotFoundException", e.getErrorCode());
assertEquals("Requested resource not found", e.getMessage());
}
AwsException describe = assertThrows(AwsException.class, () -> svc.describeTable("Users", region));
assertEquals("Requested resource not found: Table: Users not found", describe.getMessage());
}
/** Checked against real DynamoDB: every item call on a CREATING table fails this way, DescribeTable still works. */
@Test
void itemCalls_creatingTable_returnResourceNotFoundWithoutTableName() {
@@ -978,4 +978,19 @@ class DynamoDbVectorSearchIntegrationTest {
+ "constraint: Member must have length greater than or equal to 1");
}
@Test
@Order(44)
void searchVectorsRejectsOverlappingAndUndefinedProjectionPaths() {
expectValidation("SearchVectors", search(DOCS, "cosine", 1, """
, "ProjectionExpression": "#x, label", "ExpressionAttributeNames": {"#x": "label"}
"""),
"Invalid ProjectionExpression: Two document paths overlap with each other; "
+ "must remove or rewrite one of these paths; path one: [label], path two: [label]");
expectValidation("SearchVectors", search(DOCS, "cosine", 1, """
, "ProjectionExpression": "#undef"
"""),
"Invalid ProjectionExpression: An expression attribute name used in the document "
+ "path is not defined; attribute name: #undef");
}
}
@@ -285,6 +285,68 @@ class ProjectionEvaluatorTest {
assertEquals(Set.of("[alpha]", "list"), attributes);
}
@Test
void rejectsDuplicatePathsAsAnOverlap() {
AwsException ex = assertThrows(AwsException.class,
() -> ProjectionEvaluator.validateExpression("a, a", null));
assertEquals("ValidationException", ex.getErrorCode());
assertEquals("Invalid ProjectionExpression: Two document paths overlap with each other; "
+ "must remove or rewrite one of these paths; path one: [a], path two: [a]",
ex.getMessage());
}
@Test
void rejectsTwoAliasesResolvingToOneAttribute() {
AwsException ex = assertThrows(AwsException.class,
() -> ProjectionEvaluator.validateExpression("#a, #b", readValue("""
{"#a": "a", "#b": "a"}
""")));
assertEquals("Invalid ProjectionExpression: Two document paths overlap with each other; "
+ "must remove or rewrite one of these paths; path one: [a], path two: [a]",
ex.getMessage());
}
@Test
void rejectsParentAndChildPaths() {
AwsException ex = assertThrows(AwsException.class,
() -> ProjectionEvaluator.validateExpression("a, a.b.c", null));
assertEquals("Invalid ProjectionExpression: Two document paths overlap with each other; "
+ "must remove or rewrite one of these paths; path one: [a], path two: [a, b, c]",
ex.getMessage());
}
@Test
void reportsOverlappingPathsInRequestOrder() {
AwsException ex = assertThrows(AwsException.class,
() -> ProjectionEvaluator.validateExpression("a.b, a", null));
assertEquals("Invalid ProjectionExpression: Two document paths overlap with each other; "
+ "must remove or rewrite one of these paths; path one: [a, b], path two: [a]",
ex.getMessage());
}
@Test
void rejectsAListAndOneOfItsElements() {
AwsException ex = assertThrows(AwsException.class,
() -> ProjectionEvaluator.validateExpression("l, l[0]", null));
assertEquals("Invalid ProjectionExpression: Two document paths overlap with each other; "
+ "must remove or rewrite one of these paths; path one: [l], path two: [l, [0]]",
ex.getMessage());
}
@Test
void keepsDistinctSiblingPaths() {
assertDoesNotThrow(() -> ProjectionEvaluator.validateExpression("a.b, a.c, l[0], l[1]", null));
}
@Test
void rejectsAnUndefinedExpressionAttributeName() {
AwsException ex = assertThrows(AwsException.class,
() -> ProjectionEvaluator.validateExpression("#undef", null));
assertEquals("ValidationException", ex.getErrorCode());
assertEquals("Invalid ProjectionExpression: An expression attribute name used in the document path "
+ "is not defined; attribute name: #undef", ex.getMessage());
}
private static ObjectNode readValue(String json) {
try {
return (ObjectNode) mapper.readTree(json);