mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(dynamodb): refuse an over-limit UpdateItem statement before the condition (#8076)
This commit is contained in:
1 parent
f8e5a883d8
commit
67814c5d21
5 files changed
+201
-12
No files matched your search
@@ -14,6 +14,7 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
|
||||
@@ -62,11 +63,16 @@ final class DynamoDbItemSize {
|
||||
return calculateItemSize(item) <= MAX_ITEM_SIZE;
|
||||
}
|
||||
|
||||
static boolean updateItemWithinLimit(JsonNode item, int statementSize) {
|
||||
return calculateItemSize(item) <= MAX_ITEM_SIZE && statementSize <= MAX_ITEM_SIZE;
|
||||
static boolean updateStatementWithinLimit(int statementSize) {
|
||||
return statementSize <= MAX_ITEM_SIZE;
|
||||
}
|
||||
|
||||
static int updateStatementSize(String expression, Function<String, List<Object>> paths, JsonNode values) {
|
||||
/**
|
||||
* The size of an UpdateExpression statement, or empty when an action lacks the assignment or the
|
||||
* value its clause needs, or leaves a parenthesis open. The update parser refuses such a statement.
|
||||
*/
|
||||
static OptionalInt updateStatementSize(String expression, Function<String, List<Object>> paths,
|
||||
JsonNode values) {
|
||||
int size = UPDATE_COST;
|
||||
PathTree targets = new PathTree();
|
||||
String remaining = expression.trim().replaceAll("\\s+", " ");
|
||||
@@ -79,11 +85,38 @@ final class DynamoDbItemSize {
|
||||
while (!actions.isBlank()) {
|
||||
int comma = DynamoDbService.findNextComma(actions);
|
||||
String action = (comma < 0 ? actions : actions.substring(0, comma)).trim();
|
||||
if (!readable(keyword, action)) {
|
||||
return OptionalInt.empty();
|
||||
}
|
||||
size += actionSize(keyword, action, targets, paths, values);
|
||||
actions = comma < 0 ? "" : actions.substring(comma + 1);
|
||||
}
|
||||
}
|
||||
return size + targets.size();
|
||||
return OptionalInt.of(size + targets.size());
|
||||
}
|
||||
|
||||
private static boolean readable(String clause, String action) {
|
||||
if (leavesParenthesisOpen(action)) {
|
||||
return false;
|
||||
}
|
||||
return switch (clause) {
|
||||
case "SET" -> action.indexOf('=') >= 0;
|
||||
case "ADD" -> action.indexOf(' ') >= 0;
|
||||
default -> true;
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean leavesParenthesisOpen(String action) {
|
||||
int open = 0;
|
||||
for (int i = 0; i < action.length(); i++) {
|
||||
char c = action.charAt(i);
|
||||
if (c == '(') {
|
||||
open++;
|
||||
} else if (c == ')' && open > 0) {
|
||||
open--;
|
||||
}
|
||||
}
|
||||
return open > 0;
|
||||
}
|
||||
|
||||
private static int actionSize(String clause, String action, PathTree targets,
|
||||
|
||||
@@ -1394,6 +1394,12 @@ public class DynamoDbService {
|
||||
|
||||
String itemKey = buildItemKey(table, key, true);
|
||||
|
||||
// AWS refuses an over-limit statement before it evaluates the condition.
|
||||
if (sizeRule == UpdateSizeRule.UPDATE_ITEM && updateExpression != null) {
|
||||
DynamoDbItemSize.updateStatementSize(updateExpression, path -> parsePath(path, expressionAttrNames),
|
||||
expressionAttrValues).ifPresent(DynamoDbService::requireUpdateStatementWithinSizeLimit);
|
||||
}
|
||||
|
||||
return withItemLock(storageKey, itemKey, () -> {
|
||||
ConcurrentSkipListMap<String, JsonNode> items = itemsFor(storageKey, stagedItems, true);
|
||||
|
||||
@@ -1503,12 +1509,7 @@ public class DynamoDbService {
|
||||
// AWS validates index key values against the item the update produces.
|
||||
validateIndexKeyTypes(table, item, true);
|
||||
|
||||
if (sizeRule == UpdateSizeRule.UPDATE_ITEM && updateExpression != null) {
|
||||
requireUpdateItemWithinSizeLimit(item, DynamoDbItemSize.updateStatementSize(updateExpression,
|
||||
path -> parsePath(path, expressionAttrNames), expressionAttrValues));
|
||||
} else {
|
||||
requireUpdatedItemWithinSizeLimit(item);
|
||||
}
|
||||
requireUpdatedItemWithinSizeLimit(item);
|
||||
|
||||
if (stagedItems == null) {
|
||||
pointInTimeRecovery.recordItem(regionResolver.getAccountId(), storageKey, table, itemKey, existing);
|
||||
@@ -2427,8 +2428,8 @@ public class DynamoDbService {
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireUpdateItemWithinSizeLimit(JsonNode item, int statementSize) {
|
||||
if (!DynamoDbItemSize.updateItemWithinLimit(item, statementSize)) {
|
||||
private static void requireUpdateStatementWithinSizeLimit(int statementSize) {
|
||||
if (!DynamoDbItemSize.updateStatementWithinLimit(statementSize)) {
|
||||
throw new UpdatedItemTooLargeException();
|
||||
}
|
||||
}
|
||||
@@ -3463,6 +3464,7 @@ public class DynamoDbService {
|
||||
throw new AwsException("ValidationException",
|
||||
"Invalid UpdateExpression: The expression can not be empty;", 400);
|
||||
}
|
||||
requireAssignmentAfterSetTarget(expression);
|
||||
requireClosedParentheses(expression, "");
|
||||
// AWS tokenizes UpdateExpression whitespace-insensitively, so collapse runs of
|
||||
// whitespace (newlines, tabs, multiple spaces) so clause-keyword dispatch and the
|
||||
@@ -4389,6 +4391,54 @@ public class DynamoDbService {
|
||||
return "()[],.=+-".indexOf(c) >= 0;
|
||||
}
|
||||
|
||||
// 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 && List.of("SET", "REMOVE", "ADD", "DELETE").contains(word)) {
|
||||
inSet = word.equals("SET");
|
||||
target = inSet ? i + 1 : -1;
|
||||
}
|
||||
}
|
||||
case UNKNOWN -> {
|
||||
if (!isUpdatePunctuation(token.value().charAt(0))) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
default -> { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static int findNextComma(String s) {
|
||||
// Find next comma that is not inside a function call
|
||||
int depth = 0;
|
||||
|
||||
@@ -1023,6 +1023,7 @@ public class NativeDynamoDbJsonHandler {
|
||||
throw new AwsException("ValidationException",
|
||||
"Invalid UpdateExpression: Syntax error; token: \"" + token + "\", near: \"" + near + "\"", 400);
|
||||
}
|
||||
DynamoDbService.requireAssignmentAfterSetTarget(updateExpression);
|
||||
DynamoDbService.requireClosedParentheses(updateExpression, "1 validation error detected: ");
|
||||
}
|
||||
// Undefined tokens, then ConditionExpression's semantic errors, must both be caught
|
||||
|
||||
@@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.services.dynamodb.model.AttributeDefinition;
|
||||
import io.floci.aws.services.dynamodb.model.ConditionalCheckFailedException;
|
||||
import io.floci.aws.services.dynamodb.model.KeySchemaElement;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -209,6 +210,51 @@ class DynamoDbItemSizeServiceTest {
|
||||
assertRefused(() -> update("b", "SET b = if_not_exists(b, :pad)", ceiling + 1, 0));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"'SET c = if_not_exists(c, :huge)', attribute_exists(nope)",
|
||||
"'SET c = if_not_exists(c, :huge)', attribute_exists(c)",
|
||||
"'SET c = if_not_exists(c, :huge)',",
|
||||
"SET pk = :huge,"
|
||||
})
|
||||
void updateItemRefusesAnOverLimitStatementBeforeTheCondition(String expression, String condition) {
|
||||
seed("a", "c", stringValue("x"));
|
||||
|
||||
assertRefused(() -> service.updateItem(TABLE, key("a"), null, expression, null,
|
||||
values(":huge", stringValue("h".repeat(MAX_ITEM_SIZE + 100))), "NONE", condition, REGION, "NONE"));
|
||||
assertEquals("pk".length() + "a".length() + "c".length() + "x".length(), storedBytes("a"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', textBlock = """
|
||||
SET a
|
||||
SET a = :v, b
|
||||
ADD a
|
||||
SET ,
|
||||
ADD ,
|
||||
SET a = if_not_exists(b, :v
|
||||
SET a = list_append(c, :v
|
||||
SET a = if_not_exists(list_append(c, :v), :v
|
||||
SET a, b = :v
|
||||
""")
|
||||
void updateItemLeavesAStatementItCannotSizeToTheUpdateParser(String expression) {
|
||||
seed("a", "c", stringValue("x"));
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> service.updateItem(TABLE, key("a"), null,
|
||||
expression, null, values(":v", stringValue("v")), "NONE", REGION));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateItemChecksTheConditionBeforeTheFinishedItem() {
|
||||
seed("a", "b", stringValue(padding("a", MAX_ITEM_SIZE, 0)));
|
||||
|
||||
assertThrows(ConditionalCheckFailedException.class, () -> service.updateItem(TABLE, key("a"), null,
|
||||
"SET d = :d", null, values(":d", stringValue("y")), "NONE", "attribute_exists(nope)", REGION, "NONE"));
|
||||
assertRefused(() -> service.updateItem(TABLE, key("a"), null,
|
||||
"SET d = :d", null, values(":d", stringValue("y")), "NONE", null, REGION, "NONE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateItemMeasuresALegacyAttributeUpdateByTheFinishedItem() {
|
||||
updateAttribute("a", MAX_ITEM_SIZE);
|
||||
|
||||
@@ -1784,6 +1784,50 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
});
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', textBlock = """
|
||||
SET a, b = :v | a, b
|
||||
SET a , b = :v | a , b
|
||||
SET a,b = :v | a,b
|
||||
set a, b = :v | a, b
|
||||
SET a = :v, b, c = :v | b, c
|
||||
SET a.b[1], c = :v | ], c
|
||||
SET #n, b = :v | #n, b
|
||||
SET , b = :v | SET , b
|
||||
SET , | SET ,
|
||||
SET a, | a,
|
||||
SET a = :v, , b = :v | , , b
|
||||
SET a, b = (:v | a, b
|
||||
SET a = if_not_exists(b, :v), c, d = :v | c, d
|
||||
REMOVE b SET a, c = :v | a, c
|
||||
SET a, b = :v $ | a, b
|
||||
""")
|
||||
void updateItemRejectsACommaInASetTargetBeforeTheTableLookup(String expression, String near) {
|
||||
ObjectNode request = updateUserRequest();
|
||||
request.put("TableName", "Missing");
|
||||
request.put("UpdateExpression", expression);
|
||||
request.set("ExpressionAttributeValues", singleValue(":v"));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("UpdateItem", request, "eu-west-1"));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("1 validation error detected: Invalid UpdateExpression: Syntax error; "
|
||||
+ "token: \",\", near: \"" + near + "\"", ex.getMessage());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"SET a = :v REMOVE b, c", "SET a = if_not_exists(b, :v), c = :v", "SET a = b + :v, c = :v"})
|
||||
void updateItemReadsACommaOutsideASetTargetAsASeparator(String expression) {
|
||||
ObjectNode request = updateUserRequest();
|
||||
request.put("TableName", "Missing");
|
||||
request.put("UpdateExpression", expression);
|
||||
request.set("ExpressionAttributeValues", singleValue(":v"));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("UpdateItem", request, "eu-west-1"));
|
||||
assertEquals("ResourceNotFoundException", ex.getErrorCode(), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateItemAcceptsAnUpdateExpressionOfExactly4096Bytes() throws Exception {
|
||||
createUsersTable("eu-west-1");
|
||||
@@ -2015,6 +2059,21 @@ class NativeDynamoDbJsonHandlerTest {
|
||||
assertEquals("Invalid UpdateExpression: Syntax error; token: \"<EOF>\", near: \":v\"", ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void transactWriteItemsRejectsACommaInASetTarget() {
|
||||
createUsersTable("eu-west-1");
|
||||
ObjectNode update = mapper.createObjectNode();
|
||||
update.set("Key", item("userId", "u1"));
|
||||
update.put("UpdateExpression", "SET a, b = :v");
|
||||
update.set("ExpressionAttributeValues", singleValue(":v"));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> handler.handle("TransactWriteItems", transactWrite("Update", update), "eu-west-1"));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("Invalid UpdateExpression: Syntax error; token: \",\", near: \"a, b\"", ex.getMessage());
|
||||
assertNull(service.getItem("Users", item("userId", "u1"), "eu-west-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void transactWriteItemsRejectsAPutItemWithALeafAtLevel33() {
|
||||
createUsersTable("eu-west-1");
|
||||
|
||||
Reference in new issue
Block a user