fix(dynamodb): reject unused ExpressionAttributeNames/Values on PutItem, DeleteItem, Scan, Query (#2923)

* fix(dynamodb): reject unused ExpressionAttributeNames/Values on PutItem, DeleteItem, Scan, Query

The checkUnusedEan / checkUnusedEav helpers were only wired into handleUpdateItem
and (names only) handleQuery, so PutItem, DeleteItem and Scan accepted expression
attribute entries not referenced by any expression and performed the operation,
where AWS returns ValidationException. Query accepted unused values for the same
reason.

Wire both helpers into handlePutItem, handleDeleteItem and handleScan, and add the
missing checkUnusedEav call to handleQuery, each checking against the tokens
actually referenced by that operation's expressions.

Closes #2893

* fix(dynamodb): also reject unused EAV on legacy KeyConditions + FilterExpression Query

Addresses PR review: the unused ExpressionAttributeNames/Values check in
handleQuery was gated on KeyConditionExpression != null, so a Query combining
legacy KeyConditions with FilterExpression skipped it. Widen the guard to fire
whenever any expression parameter (KCE, FilterExpression, ProjectionExpression)
is present, and add an integration case for the mixed path. Also replace an em
dash in the new test comment per repo style.

* test(dynamodb): reference the aliased name in the reserved-word conformance case

The sdk-test-node "reserved word aliased via ExpressionAttributeNames passes"
case supplied ExpressionAttributeNames {#st: status} on a PutItem whose
ConditionExpression (attribute_not_exists(pk)) never referenced #st. Real AWS —
and now Floci, per #2893 — rejects unused ExpressionAttributeNames entries with
ValidationException. Point the ConditionExpression at #st so the alias is
actually used; the reserved-word aliasing behaviour under test is unchanged.

* fix(dynamodb): run Query unused EAN/EAV check unconditionally

Addresses PR review: the previous guard (keyConditionExpr || filterExpr ||
projectionExpression) still let a legacy KeyConditions Query carrying a stray
ExpressionAttributeNames/Values map through without validation. Drop the guard
so the checks always run; the token sets are still derived only from the
expressions that can legitimately reference those maps, so a correct request is
unaffected. Add an integration case for legacy KeyConditions with no expression
parameter.

* test(dynamodb): reference the aliased name in the sdk-test-java reserved-word case

Mirror of the sdk-test-node fix: reservedWordWithAliasPasses supplied an unused
ExpressionAttributeNames {#st: status} on a PutItem whose ConditionExpression
referenced pk, which #2893 now correctly rejects. Point the condition at #st.

* fix(dynamodb): AWS "can only be specified when using expressions" wording for PutItem/DeleteItem

Addresses PR review: when ExpressionAttributeNames/Values is supplied with no
expression parameter at all, this PR's new checkUnusedEan/checkUnusedEav calls
reported "Value provided in ExpressionAttributeNames unused in expressions:
keys: {...}". Real AWS answers that sub-case with "<param> can only be
specified when using expressions: ConditionExpression is null" instead.

Add rejectExprAttrsWithoutExpression, parameterised on the null-expression
message, and wire it into handlePutItem and handleDeleteItem ahead of the
unused-alias checks. Both operations only accept ConditionExpression, so the
named param is unambiguous; the wording matches the pre-existing PutItem+EAV
guard from #826. EAV is checked before EAN to preserve that guard's order.

Scan and Query still return the "unused in expressions" 400 for this sub-case:
those ops accept multiple expression parameters and AWS's exact wording there
is unverified. The helper is parameterised so it is a one-line change per op
once the strings are measured.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-03 10:49:08 -04:00
1 parent 732e009207
commit 262495df67
4 files changed
+393 -20

No files matched your search

@@ -817,11 +817,12 @@ class DynamoDbConformanceChangesTest {
@Test @Order(101)
void reservedWordWithAliasPasses() {
// Using #status alias should work fine
// Using the #st alias should work fine. The alias must be referenced by the
// expression: AWS rejects ExpressionAttributeNames entries left unused.
assertThatCode(() -> ddb.putItem(r -> r
.tableName(TABLE)
.item(Map.of("pk", av("rw-alias"), "sk", av("s"), "status", av("ok")))
.conditionExpression("attribute_not_exists(pk)")
.conditionExpression("attribute_not_exists(#st)")
.expressionAttributeNames(Map.of("#st", "status"))))
.doesNotThrowAnyException();
}
@@ -612,11 +612,12 @@ describe('DynamoDB — Phase 9: Reserved words', () => {
});
it('reserved word aliased via ExpressionAttributeNames passes', async () => {
// Using #st alias for the reserved word 'status'
// Using #st alias for the reserved word 'status'. The alias must be referenced
// by the expression: AWS rejects ExpressionAttributeNames entries left unused.
await ddb.send(new PutItemCommand({
TableName: table,
Item: { pk: s('rw-ok'), sk: s('s'), status: s('active') },
ConditionExpression: 'attribute_not_exists(pk)',
ConditionExpression: 'attribute_not_exists(#st)',
ExpressionAttributeNames: { '#st': 'status' },
}));
@@ -328,13 +328,17 @@ public class DynamoDbJsonHandler {
+ "Non-expression parameters: {Expected} Expression parameters: {ConditionExpression}", 400);
}
if (exprAttrValues != null && conditionExpression == null) {
throw new AwsException("ValidationException",
"ExpressionAttributeValues can only be specified when using expressions: ConditionExpression is null", 400);
}
// EAN/EAV with no expression to reference them: AWS reports "can only be specified
// when using expressions", not the "unused in expressions" wording (#2893).
rejectExprAttrsWithoutExpression(exprAttrNames, exprAttrValues,
conditionExpression != null, "ConditionExpression is null");
ExpressionEvaluator.validateExpression(conditionExpression, "ConditionExpression", exprAttrNames, exprAttrValues);
// Reject ExpressionAttributeNames/Values entries not referenced by ConditionExpression (AWS parity, #2893)
checkUnusedEan(exprAttrNames, extractHashTokens(conditionExpression));
checkUnusedEav(exprAttrValues, extractColonTokens(conditionExpression));
validateItemSets(item);
JsonNode oldItem = null;
@@ -439,8 +443,17 @@ public class DynamoDbJsonHandler {
+ String.join("; ", delValidationErrors), 400);
}
// EAN/EAV with no expression to reference them: AWS reports "can only be specified
// when using expressions", not the "unused in expressions" wording (#2893).
rejectExprAttrsWithoutExpression(exprAttrNames, exprAttrValues,
conditionExpression != null, "ConditionExpression is null");
ExpressionEvaluator.validateExpression(conditionExpression, "ConditionExpression", exprAttrNames, exprAttrValues);
// Reject ExpressionAttributeNames/Values entries not referenced by ConditionExpression (AWS parity, #2893)
checkUnusedEan(exprAttrNames, extractHashTokens(conditionExpression));
checkUnusedEav(exprAttrValues, extractColonTokens(conditionExpression));
JsonNode expectedDel = request.has("Expected") ? request.get("Expected") : null;
String condOpDel = request.has("ConditionalOperator")
? request.get("ConditionalOperator").asText() : "AND";
@@ -876,21 +889,23 @@ public class DynamoDbJsonHandler {
DynamoDbAccessPathValidator.validateSelection(queryTable, queryAccessPath, select,
projectionExpression, attributesToGet, exprAttrNames);
rejectConsistentReadOnGsi(request, queryAccessPath);
// Validate EAN/EAV usage when using expression format
if (keyConditionExpr != null) {
// Check undefined #tokens in FilterExpression
if (filterExpr != null) {
for (String token : extractHashTokens(filterExpr)) {
if (exprAttrNames == null || !exprAttrNames.has(token)) {
throw new AwsException("ValidationException",
"Invalid FilterExpression: An expression attribute name used in the document path is not defined; attribute name: " + token, 400);
}
// Check undefined #tokens in FilterExpression
if (filterExpr != null) {
for (String token : extractHashTokens(filterExpr)) {
if (exprAttrNames == null || !exprAttrNames.has(token)) {
throw new AwsException("ValidationException",
"Invalid FilterExpression: An expression attribute name used in the document path is not defined; attribute name: " + token, 400);
}
}
// Check unused EAN across all expressions (KCE + FE + PE)
Set<String> hashTokens = extractHashTokens(keyConditionExpr, filterExpr, projectionExpression);
checkUnusedEan(exprAttrNames, hashTokens);
}
// Reject ExpressionAttributeNames/Values entries not referenced by any expression
// (AWS parity, #2893). Unconditional: a legacy KeyConditions request that still
// carries EAN/EAV must be rejected, and either map can only be referenced from
// KeyConditionExpression, FilterExpression or (names only) ProjectionExpression.
Set<String> hashTokens = extractHashTokens(keyConditionExpr, filterExpr, projectionExpression);
checkUnusedEan(exprAttrNames, hashTokens);
checkUnusedEav(exprAttrValues, extractColonTokens(keyConditionExpr, filterExpr));
if (exclusiveStartKey != null) {
validateExclusiveStartKey(exclusiveStartKey, queryTable, queryAccessPath, false);
@@ -999,6 +1014,10 @@ public class DynamoDbJsonHandler {
ExpressionEvaluator.validateExpression(filterExpr, "FilterExpression", exprAttrNames, exprAttrValues);
ProjectionEvaluator.validateExpression(projectionExpressionScan);
// Reject ExpressionAttributeNames/Values entries not referenced by any expression (AWS parity, #2893)
checkUnusedEan(exprAttrNames, extractHashTokens(filterExpr, projectionExpressionScan));
checkUnusedEav(exprAttrValues, extractColonTokens(filterExpr));
if (select != null && !VALID_SELECT.contains(select)) {
throw new AwsException("ValidationException",
"1 validation error detected: Value '" + select + "' at 'select' failed to satisfy constraint: "
@@ -1851,6 +1870,29 @@ public class DynamoDbJsonHandler {
return tokens;
}
/**
* Rejects ExpressionAttributeNames/Values supplied when the request carries no expression to
* reference them. AWS answers this sub-case with "&lt;param&gt; can only be specified when using
* expressions: &lt;nullExpressionParams&gt;" rather than the "unused in expressions" wording used
* once an alias is merely unreferenced (#2893). {@code nullExpressionParams} must spell the absent
* expression parameter(s) exactly as AWS reports them for the operation, e.g. "ConditionExpression is null".
* EAV is checked before EAN to match the pre-existing PutItem guard.
*/
private static void rejectExprAttrsWithoutExpression(JsonNode exprAttrNames, JsonNode exprAttrValues,
boolean hasAnyExpression, String nullExpressionParams) {
if (hasAnyExpression) {
return;
}
if (exprAttrValues != null) {
throw new AwsException("ValidationException",
"ExpressionAttributeValues can only be specified when using expressions: " + nullExpressionParams, 400);
}
if (exprAttrNames != null) {
throw new AwsException("ValidationException",
"ExpressionAttributeNames can only be specified when using expressions: " + nullExpressionParams, 400);
}
}
private static void checkUnusedEan(JsonNode exprAttrNames, Set<String> usedHashTokens) {
if (exprAttrNames == null) return;
List<String> unused = new ArrayList<>();
@@ -3540,6 +3540,335 @@ given()
deleteTable("NullKeyTable");
}
// Reproduces #2893: unused ExpressionAttributeNames/Values must be rejected on
// PutItem, DeleteItem, Scan and Query, matching AWS ValidationException behavior.
@Test
void unusedExpressionAttributesAreRejected() {
String tableName = "UnusedExprAttrTable";
given()
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
"BillingMode": "PAY_PER_REQUEST"
}
""".formatted(tableName))
.when().post("/")
.then().statusCode(200);
// PutItem: unused ExpressionAttributeNames entry
given()
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"Item": {"pk": {"S": "a"}},
"ConditionExpression": "attribute_not_exists(pk)",
"ExpressionAttributeNames": {"#st": "status"}
}
""".formatted(tableName))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo("Value provided in ExpressionAttributeNames "
+ "unused in expressions: keys: {#st}"));
// PutItem: unused ExpressionAttributeValues entry
given()
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"Item": {"pk": {"S": "a"}},
"ConditionExpression": "attribute_not_exists(pk)",
"ExpressionAttributeValues": {":unused": {"S": "x"}}
}
""".formatted(tableName))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo("Value provided in ExpressionAttributeValues "
+ "unused in expressions: keys: {:unused}"));
// DeleteItem: unused ExpressionAttributeNames entry
given()
.header("X-Amz-Target", "DynamoDB_20120810.DeleteItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"Key": {"pk": {"S": "a"}},
"ConditionExpression": "attribute_exists(pk)",
"ExpressionAttributeNames": {"#st": "status"}
}
""".formatted(tableName))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo("Value provided in ExpressionAttributeNames "
+ "unused in expressions: keys: {#st}"));
// DeleteItem: unused ExpressionAttributeValues entry
given()
.header("X-Amz-Target", "DynamoDB_20120810.DeleteItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"Key": {"pk": {"S": "a"}},
"ConditionExpression": "attribute_exists(pk)",
"ExpressionAttributeValues": {":unused": {"S": "x"}}
}
""".formatted(tableName))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo("Value provided in ExpressionAttributeValues "
+ "unused in expressions: keys: {:unused}"));
// Scan: unused ExpressionAttributeNames entry
given()
.header("X-Amz-Target", "DynamoDB_20120810.Scan")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"FilterExpression": "#d = :d",
"ExpressionAttributeNames": {"#d": "data", "#st": "status"},
"ExpressionAttributeValues": {":d": {"S": "v"}}
}
""".formatted(tableName))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo("Value provided in ExpressionAttributeNames "
+ "unused in expressions: keys: {#st}"));
// Scan: unused ExpressionAttributeValues entry
given()
.header("X-Amz-Target", "DynamoDB_20120810.Scan")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"FilterExpression": "#d = :d",
"ExpressionAttributeNames": {"#d": "data"},
"ExpressionAttributeValues": {":d": {"S": "v"}, ":unused": {"S": "x"}}
}
""".formatted(tableName))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo("Value provided in ExpressionAttributeValues "
+ "unused in expressions: keys: {:unused}"));
// Query: unused ExpressionAttributeValues entry
given()
.header("X-Amz-Target", "DynamoDB_20120810.Query")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"KeyConditionExpression": "pk = :pk",
"ExpressionAttributeValues": {":pk": {"S": "a"}, ":unused": {"S": "x"}}
}
""".formatted(tableName))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo("Value provided in ExpressionAttributeValues "
+ "unused in expressions: keys: {:unused}"));
// Query: unused ExpressionAttributeNames entry
given()
.header("X-Amz-Target", "DynamoDB_20120810.Query")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"KeyConditionExpression": "pk = :pk",
"ExpressionAttributeNames": {"#st": "status"},
"ExpressionAttributeValues": {":pk": {"S": "a"}}
}
""".formatted(tableName))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo("Value provided in ExpressionAttributeNames "
+ "unused in expressions: keys: {#st}"));
// Query: legacy KeyConditions combined with FilterExpression, unused EAV entry.
// keyConditionExpr is null here, so the check must not be gated on it.
given()
.header("X-Amz-Target", "DynamoDB_20120810.Query")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"KeyConditions": {
"pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "a"}]}
},
"FilterExpression": "#d = :d",
"ExpressionAttributeNames": {"#d": "data"},
"ExpressionAttributeValues": {":d": {"S": "v"}, ":unused": {"S": "x"}}
}
""".formatted(tableName))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo("Value provided in ExpressionAttributeValues "
+ "unused in expressions: keys: {:unused}"));
// Query: legacy KeyConditions with no expression parameter at all, stray EAV.
given()
.header("X-Amz-Target", "DynamoDB_20120810.Query")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"KeyConditions": {
"pk": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "a"}]}
},
"ExpressionAttributeValues": {":unused": {"S": "x"}}
}
""".formatted(tableName))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo("Value provided in ExpressionAttributeValues "
+ "unused in expressions: keys: {:unused}"));
// Only the unused entries are reported: #used is referenced, #a and #b are not.
given()
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"Item": {"pk": {"S": "a"}},
"ConditionExpression": "attribute_not_exists(#used)",
"ExpressionAttributeNames": {"#used": "pk", "#a": "x", "#b": "y"}
}
""".formatted(tableName))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo("Value provided in ExpressionAttributeNames "
+ "unused in expressions: keys: {#a, #b}"));
// No expression parameter at all: AWS reports the alias map "can only be specified
// when using expressions", distinct from the "unused in expressions" wording above.
// PutItem and DeleteItem only accept ConditionExpression, so it is the named param.
// PutItem: ExpressionAttributeNames without ConditionExpression
given()
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"Item": {"pk": {"S": "a"}},
"ExpressionAttributeNames": {"#st": "status"}
}
""".formatted(tableName))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo("ExpressionAttributeNames can only be specified "
+ "when using expressions: ConditionExpression is null"));
// PutItem: ExpressionAttributeValues without ConditionExpression (pre-existing guard)
given()
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"Item": {"pk": {"S": "a"}},
"ExpressionAttributeValues": {":unused": {"S": "x"}}
}
""".formatted(tableName))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo("ExpressionAttributeValues can only be specified "
+ "when using expressions: ConditionExpression is null"));
// DeleteItem: ExpressionAttributeNames without ConditionExpression
given()
.header("X-Amz-Target", "DynamoDB_20120810.DeleteItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"Key": {"pk": {"S": "a"}},
"ExpressionAttributeNames": {"#st": "status"}
}
""".formatted(tableName))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo("ExpressionAttributeNames can only be specified "
+ "when using expressions: ConditionExpression is null"));
// DeleteItem: ExpressionAttributeValues without ConditionExpression; with both maps
// present the values message wins, matching the pre-existing PutItem guard order.
given()
.header("X-Amz-Target", "DynamoDB_20120810.DeleteItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"Key": {"pk": {"S": "a"}},
"ExpressionAttributeNames": {"#st": "status"},
"ExpressionAttributeValues": {":unused": {"S": "x"}}
}
""".formatted(tableName))
.when().post("/")
.then()
.statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo("ExpressionAttributeValues can only be specified "
+ "when using expressions: ConditionExpression is null"));
// Control: fully-referenced expression attributes are still accepted.
given()
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "%s",
"Item": {"pk": {"S": "a"}, "data": {"S": "v"}},
"ConditionExpression": "attribute_not_exists(#p)",
"ExpressionAttributeNames": {"#p": "pk"}
}
""".formatted(tableName))
.when().post("/")
.then().statusCode(200);
deleteTable(tableName);
}
private void deleteTable(String tableName) {
given()
.header("X-Amz-Target", "DynamoDB_20120810.DeleteTable")