mirror of
https://github.com/floci-io/floci.git
synced 2026-12-04 10:38:00 -05:00
fix(dynamodb): parse the whole UpdateExpression before reading names and values (#8190)
This commit is contained in:
1 parent
1686f29e04
commit
38085d1d75
7 files changed
+346
-127
No files matched your search
@@ -3527,12 +3527,11 @@ public class DynamoDbService {
|
||||
List<String> touched) {
|
||||
// Parse SET and REMOVE clauses from expressions like:
|
||||
// "SET #n = :newName, age = :newAge REMOVE oldField"
|
||||
if (expression.isBlank()) {
|
||||
if (expression.isEmpty()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Invalid UpdateExpression: The expression can not be empty;", 400);
|
||||
}
|
||||
requireAssignmentAfterSetTarget(expression);
|
||||
requireClosedParentheses(expression, "");
|
||||
DynamoDbUpdateExpressionSyntax.check(expression);
|
||||
// AWS tokenizes UpdateExpression whitespace-insensitively, so collapse runs of
|
||||
// whitespace (newlines, tabs, multiple spaces) so clause-keyword dispatch and the
|
||||
// comma-separated action parsing below work regardless of formatting. Normalize
|
||||
@@ -4424,37 +4423,6 @@ public class DynamoDbService {
|
||||
}
|
||||
}
|
||||
|
||||
// DynamoDB reads an unclosed call or group to the end of the expression and reports the
|
||||
// raw text from its last token on, trailing whitespace included. UpdateItem wraps the
|
||||
// error in the validation envelope, TransactWriteItems does not.
|
||||
static void requireClosedParentheses(String expression, String envelope) {
|
||||
int depth = 0;
|
||||
int lastToken = 0;
|
||||
for (int i = 0; i < expression.length(); i++) {
|
||||
char c = expression.charAt(i);
|
||||
if (Character.isWhitespace(c)) {
|
||||
continue;
|
||||
}
|
||||
if (c == '(') {
|
||||
depth++;
|
||||
} else if (c == ')') {
|
||||
depth--;
|
||||
if (depth < 0) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (i == 0 || isUpdatePunctuation(c) || isUpdatePunctuation(expression.charAt(i - 1))
|
||||
|| Character.isWhitespace(expression.charAt(i - 1))) {
|
||||
lastToken = i;
|
||||
}
|
||||
}
|
||||
if (depth > 0) {
|
||||
throw new AwsException("ValidationException",
|
||||
envelope + "Invalid UpdateExpression: Syntax error; token: \"<EOF>\", near: \""
|
||||
+ expression.substring(lastToken) + "\"", 400);
|
||||
}
|
||||
}
|
||||
|
||||
static void requireSectionsUsedOnce(String expression) {
|
||||
Set<String> seen = new HashSet<>();
|
||||
for (ExpressionEvaluator.Token token : ExpressionEvaluator.tokenize(expression)) {
|
||||
@@ -4467,59 +4435,7 @@ public class DynamoDbService {
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isUpdatePunctuation(char c) {
|
||||
return "()[],.=+-".indexOf(c) >= 0;
|
||||
}
|
||||
|
||||
private static final Set<String> UPDATE_SECTIONS = Set.of("SET", "REMOVE", "ADD", "DELETE");
|
||||
|
||||
// DynamoDB reads a SET target path up to "=", so a comma before it fails on the comma.
|
||||
static void requireAssignmentAfterSetTarget(String expression) {
|
||||
List<ExpressionEvaluator.Token> tokens = ExpressionEvaluator.tokenize(expression);
|
||||
boolean inSet = false;
|
||||
int target = -1;
|
||||
int depth = 0;
|
||||
for (int i = 0; i < tokens.size(); i++) {
|
||||
ExpressionEvaluator.Token token = tokens.get(i);
|
||||
if (target >= 0) {
|
||||
switch (token.type()) {
|
||||
case COMMA -> throw new AwsException("ValidationException",
|
||||
"Invalid UpdateExpression: Syntax error; token: \",\", near: \""
|
||||
+ expression.substring(tokens.get(i - 1).pos(), tokens.get(i + 1).end()) + "\"",
|
||||
400);
|
||||
case EQ -> {
|
||||
if (i == target) {
|
||||
return;
|
||||
}
|
||||
target = -1;
|
||||
}
|
||||
case IDENTIFIER, NAME_REF, DOT, LBRACKET, NUMBER, RBRACKET -> { }
|
||||
default -> {
|
||||
return;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
switch (token.type()) {
|
||||
case LPAREN -> depth++;
|
||||
case RPAREN -> depth--;
|
||||
case COMMA -> target = inSet && depth == 0 ? i + 1 : -1;
|
||||
case IDENTIFIER -> {
|
||||
String word = token.value().toUpperCase(Locale.ROOT);
|
||||
if (depth == 0 && UPDATE_SECTIONS.contains(word)) {
|
||||
inSet = word.equals("SET");
|
||||
target = inSet ? i + 1 : -1;
|
||||
}
|
||||
}
|
||||
case UNKNOWN -> {
|
||||
if (!isUpdatePunctuation(token.value().charAt(0))) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
default -> { }
|
||||
}
|
||||
}
|
||||
}
|
||||
static final Set<String> UPDATE_SECTIONS = Set.of("SET", "REMOVE", "ADD", "DELETE");
|
||||
|
||||
static int findNextComma(String s) {
|
||||
// Find next comma that is not inside a function call
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
package io.floci.aws.services.dynamodb;
|
||||
|
||||
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.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Refuses an UpdateExpression that DynamoDB cannot parse, with the token and the text it reports.
|
||||
*/
|
||||
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 final String expression;
|
||||
private final List<Token> tokens;
|
||||
private int pos;
|
||||
|
||||
private DynamoDbUpdateExpressionSyntax(String expression) {
|
||||
this.expression = expression;
|
||||
this.tokens = ExpressionEvaluator.tokenize(expression);
|
||||
}
|
||||
|
||||
static void check(String expression) {
|
||||
new DynamoDbUpdateExpressionSyntax(expression).readSections();
|
||||
}
|
||||
|
||||
private void readSections() {
|
||||
do {
|
||||
if (!isSection(peek())) {
|
||||
throw syntaxError();
|
||||
}
|
||||
String section = tokens.get(pos++).value().toUpperCase(Locale.ROOT);
|
||||
do {
|
||||
readAction(section);
|
||||
} while (accept(TokenType.COMMA));
|
||||
} while (peek().type() != TokenType.EOF);
|
||||
}
|
||||
|
||||
private void readAction(String section) {
|
||||
readPath();
|
||||
switch (section) {
|
||||
case "SET" -> {
|
||||
expect(TokenType.EQ);
|
||||
readValue();
|
||||
}
|
||||
case "ADD", "DELETE" -> expect(TokenType.VALUE_REF);
|
||||
default -> { }
|
||||
}
|
||||
}
|
||||
|
||||
private Shape readValue() {
|
||||
Shape first = readOperand(true);
|
||||
if (!isSign(peek())) {
|
||||
return first;
|
||||
}
|
||||
if (first == Shape.SUM_GROUP) {
|
||||
throw syntaxError();
|
||||
}
|
||||
pos++;
|
||||
readOperand(false);
|
||||
return Shape.SUM;
|
||||
}
|
||||
|
||||
// DynamoDB refuses redundant parentheses as soon as it closes them, before any later syntax error.
|
||||
private Shape readOperand(boolean sumAllowed) {
|
||||
Token token = peek();
|
||||
if (token.type() == TokenType.LPAREN) {
|
||||
pos++;
|
||||
Shape inner = sumAllowed ? readValue() : readOperand(false);
|
||||
expect(TokenType.RPAREN);
|
||||
if (inner == Shape.GROUP || inner == Shape.SUM_GROUP) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Invalid UpdateExpression: The expression has redundant parentheses;", 400);
|
||||
}
|
||||
return inner == Shape.SUM ? Shape.SUM_GROUP : Shape.GROUP;
|
||||
}
|
||||
if (token.type() == TokenType.VALUE_REF) {
|
||||
pos++;
|
||||
return Shape.OPERAND;
|
||||
}
|
||||
if (token.type() != TokenType.NAME_REF && isName(token)
|
||||
&& tokens.get(pos + 1).type() == TokenType.LPAREN) {
|
||||
pos += 2;
|
||||
do {
|
||||
readOperand(false);
|
||||
} while (accept(TokenType.COMMA));
|
||||
expect(TokenType.RPAREN);
|
||||
return Shape.OPERAND;
|
||||
}
|
||||
readPath();
|
||||
return Shape.OPERAND;
|
||||
}
|
||||
|
||||
private void readPath() {
|
||||
expectName();
|
||||
while (true) {
|
||||
if (accept(TokenType.DOT)) {
|
||||
expectName();
|
||||
} else if (accept(TokenType.LBRACKET)) {
|
||||
expect(TokenType.NUMBER);
|
||||
expect(TokenType.RBRACKET);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void expectName() {
|
||||
if (!isName(peek())) {
|
||||
throw syntaxError();
|
||||
}
|
||||
pos++;
|
||||
}
|
||||
|
||||
// Function names are not keywords, so size or if_not_exists can name an attribute.
|
||||
private static boolean isName(Token token) {
|
||||
return switch (token.type()) {
|
||||
case NAME_REF, FUNCTION -> true;
|
||||
case IDENTIFIER -> !isSection(token);
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean isSection(Token token) {
|
||||
return token.type() == TokenType.IDENTIFIER
|
||||
&& DynamoDbService.UPDATE_SECTIONS.contains(token.value().toUpperCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
private static boolean isSign(Token token) {
|
||||
return token.type() == TokenType.UNKNOWN && ("+".equals(token.value()) || "-".equals(token.value()));
|
||||
}
|
||||
|
||||
private Token peek() {
|
||||
return tokens.get(pos);
|
||||
}
|
||||
|
||||
private boolean accept(TokenType type) {
|
||||
if (peek().type() != type) {
|
||||
return false;
|
||||
}
|
||||
pos++;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void expect(TokenType type) {
|
||||
if (!accept(type)) {
|
||||
throw syntaxError();
|
||||
}
|
||||
}
|
||||
|
||||
private AwsException syntaxError() {
|
||||
return new AwsException("ValidationException", "Invalid UpdateExpression: Syntax error; "
|
||||
+ ExpressionEvaluator.syntaxErrorDetail(expression, tokens, pos), 400);
|
||||
}
|
||||
}
|
||||
@@ -83,7 +83,9 @@ final class ExpressionEvaluator {
|
||||
|
||||
if (isDigit(c)) {
|
||||
int start = i;
|
||||
while (i < len && isDigit(expression.charAt(i))) {
|
||||
i++;
|
||||
// DynamoDB reads a leading 0 as a number of its own, so a[01] fails on "1".
|
||||
while (c != '0' && i < len && isDigit(expression.charAt(i))) {
|
||||
i++;
|
||||
}
|
||||
tokens.add(new Token(TokenType.NUMBER, expression.substring(start, i), start));
|
||||
@@ -216,14 +218,8 @@ final class ExpressionEvaluator {
|
||||
return advance();
|
||||
}
|
||||
|
||||
// DynamoDB quotes the text from the token before the failing one through the token after it.
|
||||
private IllegalArgumentException syntaxError() {
|
||||
Token token = peek();
|
||||
int from = pos > 0 ? tokens.get(pos - 1).pos() : 0;
|
||||
int to = pos + 1 < tokens.size() ? tokens.get(pos + 1).end() : expression.length();
|
||||
String text = token.type() == TokenType.EOF ? "<EOF>" : token.value();
|
||||
return new IllegalArgumentException(
|
||||
"token: \"%s\", near: \"%s\"".formatted(text, expression.substring(from, to)));
|
||||
return new IllegalArgumentException(syntaxErrorDetail(expression, tokens, pos));
|
||||
}
|
||||
|
||||
Expr parseExpression() {
|
||||
@@ -383,6 +379,15 @@ final class ExpressionEvaluator {
|
||||
}
|
||||
}
|
||||
|
||||
// DynamoDB quotes the text from the token before the failing one through the token after it.
|
||||
static String syntaxErrorDetail(String expression, List<Token> tokens, int pos) {
|
||||
Token token = tokens.get(pos);
|
||||
int from = pos > 0 ? tokens.get(pos - 1).pos() : 0;
|
||||
int to = pos + 1 < tokens.size() ? tokens.get(pos + 1).end() : expression.length();
|
||||
String text = token.type() == TokenType.EOF ? "<EOF>" : token.value();
|
||||
return "token: \"%s\", near: \"%s\"".formatted(text, expression.substring(from, to));
|
||||
}
|
||||
|
||||
// ── Parse helper ──
|
||||
|
||||
static Expr parse(String expression) {
|
||||
|
||||
@@ -1035,31 +1035,19 @@ public class NativeDynamoDbJsonHandler {
|
||||
+ "Non-expression parameters: {Expected} Expression parameters: {ConditionExpression}", 400);
|
||||
}
|
||||
|
||||
// DynamoDB checks the condition in full before it parses the update.
|
||||
ExpressionEvaluator.validateSemantics(conditionExpression, "ConditionExpression", exprAttrNames, exprAttrValues);
|
||||
|
||||
// Validate EAN/EAV usage across UpdateExpression + ConditionExpression
|
||||
if (updateExpression != null) {
|
||||
// Pre-validate syntax: expression must start with a valid clause keyword.
|
||||
// AWS tokenizes UpdateExpression whitespace-insensitively, so collapse runs
|
||||
// of whitespace (newlines, tabs, multiple spaces) before matching keywords.
|
||||
String ue = updateExpression.trim().replaceAll("\\s+", " ");
|
||||
if (!ue.isEmpty()) {
|
||||
String upper = ue.toUpperCase();
|
||||
if (!upper.startsWith("SET ") && !upper.startsWith("REMOVE ") && !upper.startsWith("ADD ") && !upper.startsWith("DELETE ")) {
|
||||
String[] parts = ue.split("\\s+", 3);
|
||||
String token = parts[0];
|
||||
String near = parts.length >= 2
|
||||
? (token + " " + parts[1]).substring(0, Math.min(token.length() + 1 + parts[1].length(), 20))
|
||||
: token;
|
||||
throw new AwsException("ValidationException",
|
||||
"Invalid UpdateExpression: Syntax error; token: \"" + token + "\", near: \"" + near + "\"", 400);
|
||||
}
|
||||
DynamoDbService.requireAssignmentAfterSetTarget(updateExpression);
|
||||
DynamoDbService.requireClosedParentheses(updateExpression, "1 validation error detected: ");
|
||||
if (!updateExpression.isEmpty()) {
|
||||
DynamoDbUpdateExpressionSyntax.check(updateExpression);
|
||||
}
|
||||
// Undefined tokens, then ConditionExpression's semantic errors, must both be caught
|
||||
// before the unused-EAN/EAV checks below.
|
||||
// Undefined tokens must be caught before the unused-EAN/EAV checks below.
|
||||
requireDefinedTokens(updateExpression, "UpdateExpression", exprAttrNames, exprAttrValues);
|
||||
ExpressionEvaluator.validateSemantics(conditionExpression, "ConditionExpression", 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);
|
||||
@@ -1067,8 +1055,6 @@ public class NativeDynamoDbJsonHandler {
|
||||
checkUnusedEan(exprAttrNames, hashTokens);
|
||||
Set<String> colonTokensAll = extractColonTokens(updateExpression, conditionExpression);
|
||||
checkUnusedEav(exprAttrValues, colonTokensAll);
|
||||
} else {
|
||||
ExpressionEvaluator.validateSemantics(conditionExpression, "ConditionExpression", exprAttrNames, exprAttrValues);
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
throw inValidationEnvelope(e);
|
||||
@@ -3161,6 +3147,9 @@ 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) {
|
||||
|
||||
Reference in new issue
Block a user