fix(dynamodb): refuse bad function calls and operand types in an UpdateExpression (#8195)

This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-13 08:50:26 -04:00
1 parent ede4ebf6b0
commit 410ed8e817
7 files changed
+350 -120

No files matched your search

@@ -21,7 +21,7 @@ final class DynamoDbReservedWords {
"TRUE", "FALSE"
);
// Full DynamoDB reserved words list (uppercase)
// DynamoDB reserved words list (uppercase). DynamoDB documents SIZE too, but accepts it as an attribute name.
private static final Set<String> RESERVED = Set.of(
"ABORT", "ABSOLUTE", "ACTION", "ADD", "AFTER", "AGENT", "AGGREGATE", "ALL",
"ALLOCATE", "ALTER", "ANALYZE", "AND", "ANY", "ARCHIVE", "ARE", "ARRAY", "AS", "ASC",
@@ -85,7 +85,7 @@ final class DynamoDbReservedWords {
"SAMPLE", "SATISFIES", "SAVE", "SAVEPOINT", "SCAN", "SCHEMA", "SCOPE", "SCROLL", "SEARCH",
"SECOND", "SECTION", "SEGMENT", "SEGMENTS", "SELECT", "SELF", "SEMI", "SENSITIVE",
"SEPARATE", "SEQUENCE", "SERIALIZABLE", "SESSION", "SET", "SETS", "SHARD", "SHARE",
"SHARED", "SHORT", "SHOW", "SIGNAL", "SIMILAR", "SIZE", "SKEWED", "SMALLINT", "SNAPSHOT",
"SHARED", "SHORT", "SHOW", "SIGNAL", "SIMILAR", "SKEWED", "SMALLINT", "SNAPSHOT",
"SOME", "SOURCE", "SPACE", "SPACES", "SPARSE", "SPECIFIC", "SPECIFICTYPE", "SPLIT", "SQL",
"SQLCODE", "SQLERROR", "SQLEXCEPTION", "SQLSTATE", "SQLWARNING", "START", "STATE", "STATIC",
"STATUS", "STORAGE", "STORE", "STORED", "STREAM", "STRING", "STRUCT", "STYLE", "SUB",
@@ -114,16 +114,23 @@ final class DynamoDbReservedWords {
if (expression == null || expression.isBlank()) return;
List<String> bareIdents = extractBareIdentifiers(expression);
for (String ident : bareIdents) {
String upper = ident.toUpperCase();
if (CLAUSE_KEYWORDS.contains(upper)) continue;
if (RESERVED.contains(upper)) {
throw new AwsException("ValidationException",
"Invalid " + expressionType + ": Attribute name is a reserved keyword; "
+ "reserved word: " + ident, 400);
if (isReserved(ident)) {
throw reservedWord(expressionType, ident);
}
}
}
static boolean isReserved(String ident) {
String upper = ident.toUpperCase();
return !CLAUSE_KEYWORDS.contains(upper) && RESERVED.contains(upper);
}
static AwsException reservedWord(String expressionType, String ident) {
return new AwsException("ValidationException",
"Invalid " + expressionType + ": Attribute name is a reserved keyword; "
+ "reserved word: " + ident, 400);
}
private static List<String> extractBareIdentifiers(String expr) {
List<String> result = new ArrayList<>();
int i = 0;
@@ -3996,44 +3996,6 @@ public class DynamoDbService {
return clause;
}
private static final Map<String, String> OPERAND_TYPE_NAMES = Map.of(
"S", "STRING", "N", "NUMBER", "B", "Binary", "BOOL", "BOOL", "NULL", "NULL", "L", "LIST", "M", "MAP");
void requireAddOrDeleteOperandTypes(String updateExpression, JsonNode exprAttrValues, boolean inValidationEnvelope) {
if (updateExpression == null || exprAttrValues == null) {
return;
}
String remaining = updateExpression.trim().replaceAll("\\s+", " ");
while (!remaining.isEmpty()) {
String keyword = remaining.substring(0, Math.max(remaining.indexOf(' '), 0)).toUpperCase();
String body = remaining.substring(keyword.length()).trim();
int nextClause = findNextClauseKeyword(body);
String actions = nextClause < 0 ? body : body.substring(0, nextClause);
remaining = nextClause < 0 ? "" : body.substring(nextClause);
Set<String> allowed = switch (keyword) {
case "ADD" -> Set.of("N", "SS", "NS", "BS");
case "DELETE" -> Set.of("SS", "NS", "BS");
default -> null;
};
while (allowed != null && !actions.isBlank()) {
int comma = findNextComma(actions);
String[] words = (comma < 0 ? actions : actions.substring(0, comma)).trim().split(" ");
actions = comma < 0 ? "" : actions.substring(comma + 1);
JsonNode operand = exprAttrValues.get(words[words.length - 1]);
if (operand == null) {
continue;
}
String type = DynamoDbAttributeValueValidator.typeOf(operand);
if (!allowed.contains(type)) {
throw new AwsException("ValidationException", (inValidationEnvelope ? "1 validation error detected: " : "")
+ "Invalid UpdateExpression: Incorrect operand type for operator or function;"
+ " operator: " + keyword + ", operand type: " + OPERAND_TYPE_NAMES.get(type)
+ ", typeSet: ALLOWED_FOR_ADD_OPERAND", 400);
}
}
}
}
private static void requireSameTypeAsOperand(JsonNode existingValue, JsonNode operand, List<String> types) {
for (String type : types) {
if (operand.has(type) && existingValue != null && !existingValue.has(type)) {
@@ -1,31 +1,67 @@
package io.floci.aws.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.dynamodb.ExpressionEvaluator.Token;
import io.floci.aws.services.dynamodb.ExpressionEvaluator.TokenType;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* Refuses an UpdateExpression that DynamoDB cannot parse, with the token and the text it reports.
* Given the request's names and values, it also refuses what DynamoDB finds wrong in the parsed
* expression before it reads the table.
*/
final class DynamoDbUpdateExpressionSyntax {
// DynamoDB allows a sum (a + b or a - b) only as the whole value, alone or in parentheses.
private enum Shape { OPERAND, GROUP, SUM, SUM_GROUP }
private static final String EXPRESSION_TYPE = "UpdateExpression";
private static final Set<String> CONDITION_FUNCTIONS = Set.of(
"attribute_exists", "attribute_not_exists", "attribute_type", "begins_with", "contains", "size");
private static final Map<String, String> ADD_OR_DELETE_OPERAND_TYPE_NAMES = Map.of(
"S", "STRING", "N", "NUMBER", "B", "Binary", "BOOL", "BOOL", "NULL", "NULL", "L", "LIST", "M", "MAP");
private sealed interface Operand permits PathOperand, ValueOperand, Call, Sum, Group {}
private record PathOperand(List<Token> names) implements Operand {}
private record ValueOperand(Token placeholder) implements Operand {}
private record Call(Token function, List<Operand> arguments) implements Operand {}
private record Sum(Operand left, Token sign, Operand right) implements Operand {}
private record Group(Operand inner) implements Operand {}
private record Action(String section, PathOperand target, Operand value) {}
private final String expression;
private final List<Token> tokens;
private final List<Action> actions = new ArrayList<>();
private final JsonNode names;
private final JsonNode values;
private int pos;
private DynamoDbUpdateExpressionSyntax(String expression) {
private DynamoDbUpdateExpressionSyntax(String expression, JsonNode names, JsonNode values) {
this.expression = expression;
this.tokens = ExpressionEvaluator.tokenize(expression);
this.names = names;
this.values = values;
}
static void check(String expression) {
new DynamoDbUpdateExpressionSyntax(expression).readSections();
new DynamoDbUpdateExpressionSyntax(expression, null, null).readSections();
}
static void check(String expression, JsonNode names, JsonNode values) {
DynamoDbUpdateExpressionSyntax syntax = new DynamoDbUpdateExpressionSyntax(expression, names, values);
syntax.readSections();
syntax.checkActions();
}
private void readSections() {
@@ -35,85 +71,212 @@ final class DynamoDbUpdateExpressionSyntax {
}
String section = tokens.get(pos++).value().toUpperCase(Locale.ROOT);
do {
readAction(section);
actions.add(readAction(section));
} while (accept(TokenType.COMMA));
} while (peek().type() != TokenType.EOF);
}
private void readAction(String section) {
readPath();
switch (section) {
private Action readAction(String section) {
PathOperand target = readPath();
Operand value = switch (section) {
case "SET" -> {
expect(TokenType.EQ);
readValue();
yield readValue();
}
case "ADD", "DELETE" -> expect(TokenType.VALUE_REF);
default -> { }
}
case "ADD", "DELETE" -> {
Token placeholder = peek();
expect(TokenType.VALUE_REF);
yield new ValueOperand(placeholder);
}
default -> null;
};
return new Action(section, target, value);
}
private Shape readValue() {
Shape first = readOperand(true);
// DynamoDB allows a sum (a + b or a - b) only as the whole value, alone or in parentheses.
private Operand readValue() {
Operand first = readOperand(true);
if (!isSign(peek())) {
return first;
}
if (first == Shape.SUM_GROUP) {
if (first instanceof Group group && group.inner() instanceof Sum) {
throw syntaxError();
}
pos++;
readOperand(false);
return Shape.SUM;
Token sign = tokens.get(pos++);
return new Sum(first, sign, readOperand(false));
}
// DynamoDB refuses redundant parentheses as soon as it closes them, before any later syntax error.
private Shape readOperand(boolean sumAllowed) {
private Operand readOperand(boolean sumAllowed) {
Token token = peek();
if (token.type() == TokenType.LPAREN) {
pos++;
Shape inner = sumAllowed ? readValue() : readOperand(false);
Operand inner = sumAllowed ? readValue() : readOperand(false);
expect(TokenType.RPAREN);
if (inner == Shape.GROUP || inner == Shape.SUM_GROUP) {
if (inner instanceof Group) {
throw new AwsException("ValidationException",
"Invalid UpdateExpression: The expression has redundant parentheses;", 400);
}
return inner == Shape.SUM ? Shape.SUM_GROUP : Shape.GROUP;
return new Group(inner);
}
if (token.type() == TokenType.VALUE_REF) {
pos++;
return Shape.OPERAND;
return new ValueOperand(token);
}
if (token.type() != TokenType.NAME_REF && isName(token)
&& tokens.get(pos + 1).type() == TokenType.LPAREN) {
pos += 2;
List<Operand> arguments = new ArrayList<>();
do {
readOperand(false);
arguments.add(readOperand(false));
} while (accept(TokenType.COMMA));
expect(TokenType.RPAREN);
return Shape.OPERAND;
return new Call(token, arguments);
}
readPath();
return Shape.OPERAND;
return readPath();
}
private void readPath() {
expectName();
private PathOperand readPath() {
List<Token> pathNames = new ArrayList<>();
pathNames.add(expectName());
while (true) {
if (accept(TokenType.DOT)) {
expectName();
pathNames.add(expectName());
} else if (accept(TokenType.LBRACKET)) {
expect(TokenType.NUMBER);
expect(TokenType.RBRACKET);
} else {
return;
return new PathOperand(pathNames);
}
}
}
private void expectName() {
if (!isName(peek())) {
private Token expectName() {
Token token = peek();
if (!isName(token)) {
throw syntaxError();
}
pos++;
return token;
}
// DynamoDB checks every placeholder, name and call in written order, the operands of a call
// before the call itself.
private void checkActions() {
for (Action action : actions) {
checkPath(action.target());
switch (action.section()) {
case "SET" -> checkOperand(action.value(), false);
case "ADD", "DELETE" -> checkAddOrDeleteOperand(action.section(), action.value());
default -> { }
}
}
}
private void checkOperand(Operand operand, boolean nested) {
switch (operand) {
case PathOperand path -> checkPath(path);
case ValueOperand value -> {
String placeholder = value.placeholder().value();
if (values == null || !values.has(placeholder)) {
throw ExpressionEvaluator.undefinedValue(EXPRESSION_TYPE, placeholder);
}
}
case Group group -> checkOperand(group.inner(), nested);
case Sum sum -> {
checkOperand(sum.left(), true);
checkOperand(sum.right(), true);
requireOperandTypes(sum.sign().value(), "N", sum.left(), sum.right());
}
case Call call -> {
for (Operand argument : call.arguments()) {
checkOperand(argument, true);
}
checkCall(call, nested);
}
}
}
private void checkPath(PathOperand path) {
for (Token name : path.names()) {
if (name.type() == TokenType.NAME_REF) {
if (names == null || !names.has(name.value())) {
throw ExpressionEvaluator.undefinedName(EXPRESSION_TYPE, name.value());
}
} else if (DynamoDbReservedWords.isReserved(name.value())) {
throw DynamoDbReservedWords.reservedWord(EXPRESSION_TYPE, name.value());
}
}
}
// DynamoDB allows list_append only as the whole value, alone or in parentheses.
private void checkCall(Call call, boolean nested) {
String function = call.function().value();
if (CONDITION_FUNCTIONS.contains(function)) {
throw invalid("The function is not allowed in an update expression; function: " + function);
}
if (!"if_not_exists".equals(function) && !"list_append".equals(function)) {
throw invalid("Invalid function name; function: " + function);
}
List<Operand> arguments = call.arguments();
if (arguments.size() != 2) {
throw invalid("Incorrect number of operands for operator or function; operator or function: "
+ function + ", number of operands: " + arguments.size());
}
if ("if_not_exists".equals(function)) {
if (!isPath(arguments.getFirst())) {
throw invalid("Operator or function requires a document path; operator or function: "
+ function);
}
return;
}
if (nested) {
throw invalid("The function is not allowed to be used this way in an expression; function: "
+ function);
}
requireOperandTypes(function, "L", arguments.getFirst(), arguments.getLast());
}
private void checkAddOrDeleteOperand(String section, Operand value) {
checkOperand(value, false);
String type = staticType(value);
Set<String> allowed = "ADD".equals(section) ? Set.of("N", "SS", "NS", "BS") : Set.of("SS", "NS", "BS");
if (!allowed.contains(type)) {
throw invalid("Incorrect operand type for operator or function; operator: " + section
+ ", operand type: " + ADD_OR_DELETE_OPERAND_TYPE_NAMES.get(type)
+ ", typeSet: ALLOWED_FOR_" + section + "_OPERAND");
}
}
private void requireOperandTypes(String operator, String expected, Operand first, Operand second) {
for (Operand operand : List.of(first, second)) {
String type = staticType(operand);
if (type != null && !type.equals(expected)) {
throw invalid("Incorrect operand type for operator or function; operator or function: "
+ operator + ", operand type: " + type);
}
}
}
// A path or a call has no type until DynamoDB reads the item.
private String staticType(Operand operand) {
return switch (operand) {
case ValueOperand value -> DynamoDbAttributeValueValidator.typeOf(values.get(value.placeholder().value()));
case Group group -> staticType(group.inner());
default -> null;
};
}
private static boolean isPath(Operand operand) {
return switch (operand) {
case PathOperand path -> true;
case Group group -> isPath(group.inner());
default -> false;
};
}
private static AwsException invalid(String message) {
return new AwsException("ValidationException", "Invalid UpdateExpression: " + message, 400);
}
// Function names are not keywords, so size or if_not_exists can name an attribute.
@@ -1041,15 +1041,9 @@ public class NativeDynamoDbJsonHandler {
// Validate EAN/EAV usage across UpdateExpression + ConditionExpression
if (updateExpression != null) {
if (!updateExpression.isEmpty()) {
DynamoDbUpdateExpressionSyntax.check(updateExpression);
DynamoDbUpdateExpressionSyntax.check(updateExpression, exprAttrNames, exprAttrValues);
}
// Undefined tokens must be caught before the unused-EAN/EAV checks below.
requireDefinedTokens(updateExpression, "UpdateExpression", exprAttrNames, exprAttrValues);
requireNonEmptyExpression(updateExpression, "UpdateExpression");
// The reserved word check looks past single spaces only.
String ue = updateExpression.trim().replaceAll("\\s+", " ");
DynamoDbReservedWords.check(ue, "UpdateExpression");
dynamoDbService.requireAddOrDeleteOperandTypes(updateExpression, exprAttrValues, true);
DynamoDbService.requireSectionsUsedOnce(updateExpression);
Set<String> hashTokens = extractHashTokens(updateExpression, conditionExpression);
checkUnusedEan(exprAttrNames, hashTokens);
@@ -3148,11 +3142,7 @@ public class NativeDynamoDbJsonHandler {
requireNonEmptyExpression(updateExpression, "UpdateExpression");
DynamoDbExpressionSize.checkRead(updateExpression, "UpdateExpression");
if (updateExpression != null) {
DynamoDbUpdateExpressionSyntax.check(updateExpression);
}
requireDefinedTokens(updateExpression, "UpdateExpression", exprAttrNames, exprAttrValues);
dynamoDbService.requireAddOrDeleteOperandTypes(updateExpression, exprAttrValues, false);
if (updateExpression != null) {
DynamoDbUpdateExpressionSyntax.check(updateExpression, exprAttrNames, exprAttrValues);
DynamoDbService.requireSectionsUsedOnce(updateExpression);
}
@@ -3593,8 +3583,7 @@ public class NativeDynamoDbJsonHandler {
private record ExprToken(char prefix, String text) {}
// Scans an expression once, left to right, for #name and :value placeholders, in the order
// they occur in the text. Both extractHashTokens/extractColonTokens (membership checks) and
// requireDefinedTokens (first-undefined-token-wins) build on this single scan.
// they occur in the text.
private static List<ExprToken> scanExprTokens(String expr) {
List<ExprToken> tokens = new ArrayList<>();
if (expr == null) {
@@ -3642,25 +3631,6 @@ public class NativeDynamoDbJsonHandler {
return tokens;
}
/**
* Rejects the first #name or :value token, in textual order, that neither
* ExpressionAttributeNames nor ExpressionAttributeValues defines. This matches DynamoDB for a
* single-action update expression; with several undefined tokens spread across an UpdateExpression's actions/clauses, DynamoDB
* may name a different one, though always with this same error type and message form.
*/
private static void requireDefinedTokens(String expression, String exprType,
JsonNode exprAttrNames, JsonNode exprAttrValues) {
for (ExprToken token : scanExprTokens(expression)) {
if (token.prefix() == '#') {
if (exprAttrNames == null || !exprAttrNames.has(token.text())) {
throw ExpressionEvaluator.undefinedName(exprType, token.text());
}
} else if (exprAttrValues == null || !exprAttrValues.has(token.text())) {
throw ExpressionEvaluator.undefinedValue(exprType, token.text());
}
}
}
/**
* 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
@@ -25,7 +25,7 @@ class DynamoDbAddDeleteOperandIntegrationTest {
private static final String TABLE = "add-delete-operands";
private static final String KEY = "{\"pk\":{\"S\":\"a\"}}";
private static final String REFUSED = "Invalid UpdateExpression: Incorrect operand type for operator or function;"
+ " operator: %s, operand type: %s, typeSet: ALLOWED_FOR_ADD_OPERAND";
+ " operator: %1$s, operand type: %2$s, typeSet: ALLOWED_FOR_%1$s_OPERAND";
@BeforeAll
static void configureRestAssured() {
@@ -35,6 +35,8 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.*;
@@ -2072,6 +2074,24 @@ class NativeDynamoDbJsonHandlerTest {
return (ObjectNode) mapper.createObjectNode().set(placeholder, attributeValue("S", "x"));
}
// Defines each placeholder the expression uses: :v and :s a string, :n a number, :l a list,
// :ss a string set and :m a map.
private ObjectNode valuesFor(String expression) {
ObjectNode values = mapper.createObjectNode();
Matcher placeholder = Pattern.compile(":[a-z]+").matcher(expression);
while (placeholder.find()) {
switch (placeholder.group()) {
case ":v", ":s" -> values.set(placeholder.group(), attributeValue("S", "x"));
case ":n" -> values.set(":n", attributeValue("N", "1"));
case ":l" -> values.putObject(":l").putArray("L");
case ":ss" -> values.putObject(":ss").putArray("SS").add("x");
case ":m" -> values.putObject(":m").putObject("M");
default -> { }
}
}
return values;
}
@Test
void updateItemRejectsAnUpdateExpressionOver4096BytesBeforeTheTableLookup() {
ObjectNode request = updateUserRequest();
@@ -2142,12 +2162,12 @@ class NativeDynamoDbJsonHandlerTest {
}
@ParameterizedTest
@ValueSource(strings = {"SET a = :v REMOVE b, c", "SET a = if_not_exists(b, :v), c = :v", "SET a = b + :v, c = :v"})
@ValueSource(strings = {"SET a = :v REMOVE b, c", "SET a = if_not_exists(b, :v), c = :v", "SET a = b + :n, c = :n"})
void updateItemReadsACommaOutsideASetTargetAsASeparator(String expression) {
ObjectNode request = updateUserRequest();
request.put("TableName", "Missing");
request.put("UpdateExpression", expression);
request.set("ExpressionAttributeValues", singleValue(":v"));
request.set("ExpressionAttributeValues", valuesFor(expression));
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("UpdateItem", request, "eu-west-1"));
@@ -2235,16 +2255,16 @@ class NativeDynamoDbJsonHandlerTest {
}
@ParameterizedTest
@ValueSource(strings = {"SET a = (:v) + (:v)", "SET a = ((:v) + :v)", "SET a = (:v + :v)", "SET a = (b)",
"SET a = list_append((:v), :v)", "SET a = list_append(if_not_exists(b, :v), :v)",
"SET a = (if_not_exists(b, :v) + :v)", "SET a[ 1 ] = :v", "SET a[0].b[10] = :v",
@ValueSource(strings = {"SET a = (:n) + (:n)", "SET a = ((:n) + :n)", "SET a = (:n + :n)", "SET a = (b)",
"SET a = list_append((:l), :l)", "SET a = list_append(if_not_exists(b, :l), :l)",
"SET a = (if_not_exists(b, :n) + :n)", "SET a[ 1 ] = :v", "SET a[0].b[10] = :v",
"REMOVE a[0], b.c", "set a = :v remove b", "SET\ta = :v\nREMOVE b"})
void updateItemAcceptsTheUpdateExpressionGrammar(String expression) {
ObjectNode request = updateUserRequest();
request.put("TableName", "Missing");
request.put("UpdateExpression", expression);
if (expression.contains(":v")) {
request.set("ExpressionAttributeValues", singleValue(":v"));
if (expression.contains(":")) {
request.set("ExpressionAttributeValues", valuesFor(expression));
}
AwsException ex = assertThrows(AwsException.class,
@@ -2296,6 +2316,109 @@ class NativeDynamoDbJsonHandlerTest {
assertEquals(message, ex.getMessage());
}
@ParameterizedTest
@CsvSource(delimiter = '|', textBlock = """
SET a = foo(:n) | Invalid function name; function: foo
SET a = IF_NOT_EXISTS(b, :n) | Invalid function name; function: IF_NOT_EXISTS
SET a = size(b) | The function is not allowed in an update expression; function: size
SET a = begins_with(b, :s) | The function is not allowed in an update expression; function: begins_with
SET a = size(b, c) | The function is not allowed in an update expression; function: size
SET a = if_not_exists(b) | Incorrect number of operands for operator or function; operator or function: if_not_exists, number of operands: 1
SET a = if_not_exists(b, :n, :n) | Incorrect number of operands for operator or function; operator or function: if_not_exists, number of operands: 3
SET a = list_append(:l) | Incorrect number of operands for operator or function; operator or function: list_append, number of operands: 1
SET a = if_not_exists(:n, b) | Operator or function requires a document path; operator or function: if_not_exists
SET a = if_not_exists(if_not_exists(b, :n), :n) | Operator or function requires a document path; operator or function: if_not_exists
SET a = list_append(:l, :l) + :n | The function is not allowed to be used this way in an expression; function: list_append
SET a = (list_append(:l, :l)) + :n | The function is not allowed to be used this way in an expression; function: list_append
SET a = list_append(:n, :l) + :n | The function is not allowed to be used this way in an expression; function: list_append
SET a = if_not_exists(b, list_append(:l, :l)) | The function is not allowed to be used this way in an expression; function: list_append
SET a = list_append(list_append(:l, :l), :l) | The function is not allowed to be used this way in an expression; function: list_append
SET a = list_append(:n, :l) | Incorrect operand type for operator or function; operator or function: list_append, operand type: N
SET a = list_append(b, :s) | Incorrect operand type for operator or function; operator or function: list_append, operand type: S
SET a = :s + :n | Incorrect operand type for operator or function; operator or function: +, operand type: S
SET a = :n - :l | Incorrect operand type for operator or function; operator or function: -, operand type: L
SET a = b + (:ss) | Incorrect operand type for operator or function; operator or function: +, operand type: SS
ADD a :l | Incorrect operand type for operator or function; operator: ADD, operand type: LIST, typeSet: ALLOWED_FOR_ADD_OPERAND
DELETE a :n | Incorrect operand type for operator or function; operator: DELETE, operand type: NUMBER, typeSet: ALLOWED_FOR_DELETE_OPERAND
""")
void updateItemChecksTheFunctionsAndOperandTypesBeforeTheTableLookup(String expression, String message) {
ObjectNode request = updateUserRequest();
request.put("TableName", "Missing");
request.put("UpdateExpression", expression);
request.set("ExpressionAttributeValues", valuesFor(expression));
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("UpdateItem", request, "eu-west-1"));
assertEquals("ValidationException", ex.getErrorCode());
assertEquals("1 validation error detected: Invalid UpdateExpression: " + message, ex.getMessage());
}
@ParameterizedTest
@CsvSource(delimiter = '|', textBlock = """
SET a = foo(:u) | An expression attribute value used in expression is not defined; attribute value: :u
SET a = foo(#u) | An expression attribute name used in the document path is not defined; attribute name: #u
SET a = foo(:n), b = :u | Invalid function name; function: foo
SET a = :u, b = foo(:n) | An expression attribute value used in expression is not defined; attribute value: :u
SET a = if_not_exists(:n, :u) | An expression attribute value used in expression is not defined; attribute value: :u
SET a = list_append(:l, :l) + :u | The function is not allowed to be used this way in an expression; function: list_append
SET a = :s + :u | An expression attribute value used in expression is not defined; attribute value: :u
SET out = foo(:n) | Attribute name is a reserved keyword; reserved word: out
SET a = foo(:n), out = :n | Invalid function name; function: foo
SET out = :u | Attribute name is a reserved keyword; reserved word: out
ADD c :u SET a = foo(:n) | An expression attribute value used in expression is not defined; attribute value: :u
ADD b :s SET a = foo(:n) | Incorrect operand type for operator or function; operator: ADD, operand type: STRING, typeSet: ALLOWED_FOR_ADD_OPERAND
SET a = foo(:n) ADD b :s | Invalid function name; function: foo
SET a = foo(:n) SET b = :n | Invalid function name; function: foo
""")
void updateItemChecksNamesValuesAndCallsInWrittenOrder(String expression, String message) {
ObjectNode request = updateUserRequest();
request.put("TableName", "Missing");
request.put("UpdateExpression", expression);
request.set("ExpressionAttributeValues", valuesFor(expression));
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("UpdateItem", request, "eu-west-1"));
assertEquals("1 validation error detected: Invalid UpdateExpression: " + message, ex.getMessage());
}
@ParameterizedTest
@ValueSource(strings = {"SET a = if_not_exists(b, :n) + :n", "SET a = :n - if_not_exists(b, :s)",
"SET a = (list_append(:l, :l))", "SET a = list_append(:l, if_not_exists(b, :n))",
"SET a = if_not_exists(b, if_not_exists(c, :n))", "SET a = if_not_exists((b), :n)",
"SET a = list_append(b, c)", "SET size = :n", "SET a = size", "ADD a :n, b :ss", "DELETE a :ss"})
void updateItemAcceptsTheUpdateFunctionsAndOperandTypes(String expression) {
ObjectNode request = updateUserRequest();
request.put("TableName", "Missing");
request.put("UpdateExpression", expression);
request.set("ExpressionAttributeValues", valuesFor(expression));
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("UpdateItem", request, "eu-west-1"));
assertEquals("ResourceNotFoundException", ex.getErrorCode(), ex.getMessage());
}
@ParameterizedTest
@CsvSource(delimiter = '|', textBlock = """
SET a = foo(:n) | Invalid function name; function: foo
SET out = :n | Attribute name is a reserved keyword; reserved word: out
SET a = foo(:n), out = :n | Invalid function name; function: foo
DELETE a :n | Incorrect operand type for operator or function; operator: DELETE, operand type: NUMBER, typeSet: ALLOWED_FOR_DELETE_OPERAND
""")
void transactWriteItemsChecksTheFunctionsAndReservedWordsBeforeTheTableLookup(String expression,
String message) {
ObjectNode update = mapper.createObjectNode();
update.set("Key", item("userId", "u1"));
update.put("UpdateExpression", expression);
update.set("ExpressionAttributeValues", valuesFor(expression));
ObjectNode request = transactWrite("Update", update);
update.put("TableName", "Missing");
AwsException ex = assertThrows(AwsException.class,
() -> handler.handle("TransactWriteItems", request, "eu-west-1"));
assertEquals("ValidationException", ex.getErrorCode());
assertEquals("Invalid UpdateExpression: " + message, ex.getMessage());
}
@ParameterizedTest
@CsvSource(delimiter = '|', textBlock = """
SET a = :v SET b = :v | SET
@@ -180,6 +180,11 @@ class ProjectionEvaluatorTest {
ex.getMessage());
}
@Test
void acceptsSizeAsAnAttributeName() {
assertDoesNotThrow(() -> ProjectionEvaluator.validateExpression("size, a.SIZE", null));
}
@Test
void allowableIndexBeyondTheListJustDropsTheAttribute() {
ObjectNode result = ProjectionEvaluator.project(listItem(), "l[4294967294]", null);