From 49edfcbd5f9a1338ffd5f7e677b4d76f5dc5c410 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?TATSUNO=20=E2=80=9CTaz=E2=80=9D=20Yasuhiro?= Date: Mon, 2 Nov 2026 00:48:33 +0900 Subject: [PATCH] fix(dynamodb): check every number in an item request first and read its exponent as a long (#7203) * fix(dynamodb): check every number in an item request first and read its exponent as a long * fix(dynamodb): read only the members an item operation has, each at the stage DynamoDB reads it * chore(dynamodb): pass each request member to the number check and walk the values with plain loops --- .../dynamodb/DynamoDbNumberUtils.java | 83 +++++------ .../dynamodb/NativeDynamoDbJsonHandler.java | 68 +++++++-- .../NativeDynamoDbJsonHandlerTest.java | 132 ++++++++++++++++++ 3 files changed, 233 insertions(+), 50 deletions(-) diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbNumberUtils.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbNumberUtils.java index 079f4b0e98..1daa2730a8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbNumberUtils.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbNumberUtils.java @@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.AwsException; import java.math.BigDecimal; import java.util.Set; import java.util.TreeSet; +import java.util.function.Consumer; /** * DynamoDB number validation and normalization. @@ -121,57 +122,61 @@ final class DynamoDbNumberUtils { return toNormalizedString(stripped); } - // AWS checks every number in a request before the table lookup. Single-item write - // APIs wrap the error in the validation envelope, Query and Scan do not. - static void requireStorable(JsonNode attributes, boolean inValidationEnvelope) { - if (attributes == null || !attributes.isObject()) { - return; - } - for (JsonNode value : attributes) { - requireStorableValue(value, inValidationEnvelope ? "1 validation error detected: " : ""); + static void forEachNumber(JsonNode values, Consumer check) { + for (JsonNode value : values) { + JsonNode number = value.get("N"); + if (number != null && number.isTextual()) { + check.accept(number.asText()); + } + for (JsonNode member : value.path("NS")) { + if (member.isTextual()) { + check.accept(member.asText()); + } + } + forEachNumber(value.path("L"), check); + forEachNumber(value.path("M"), check); } } - private static void requireStorableValue(JsonNode value, String prefix) { - if (!value.isObject()) { - return; - } - if (value.has("N")) { - requireStorableNumber(value.get("N").asText(), prefix); - } - for (JsonNode n : value.path("NS")) { - requireStorableNumber(n.asText(), prefix); - } - for (JsonNode element : value.path("L")) { - requireStorableValue(element, prefix); - } - for (JsonNode entry : value.path("M")) { - requireStorableValue(entry, prefix); + static void requireItemNumber(String text, String prefix) { + String problem = itemNumberProblem(text); + if (problem != null) { + throw new AwsException("ValidationException", prefix + problem, 400); } } - private static void requireStorableNumber(String numStr, String prefix) { - BigDecimal bd; + // An item call reads the exponent as a long and checks the range without wrapping around, + // unlike a PartiQL parameter. It counts the digits before it checks the range. + private static String itemNumberProblem(String text) { + int marker = exponentMarker(text); + BigDecimal mantissa; + long exponent; try { - bd = new BigDecimal(numStr); + mantissa = new BigDecimal(marker < 0 ? text : text.substring(0, marker)); + exponent = marker < 0 ? 0 : Long.parseLong(text.substring(marker + 1)); } catch (NumberFormatException e) { - throw new AwsException("ValidationException", - "The parameter cannot be converted to a numeric value: " + numStr, 400); + return PARAMETER_NOT_NUMERIC + ": " + text; } - BigDecimal stripped = bd.stripTrailingZeros(); - if (stripped.precision() > 38) { - throw new AwsException("ValidationException", - prefix + TOO_MANY_DIGITS, 400); + if (38 < mantissa.stripTrailingZeros().precision()) { + return TOO_MANY_DIGITS; } - BigDecimal abs = stripped.abs(); - if (abs.compareTo(MAX_ABS) >= 0) { - throw new AwsException("ValidationException", - prefix + NUMBER_OVERFLOW, 400); + long magnitude = (long) mantissa.precision() - mantissa.scale() + 1; + if (127 - magnitude < exponent) { + return NUMBER_OVERFLOW; } - if (abs.signum() > 0 && abs.compareTo(MIN_ABS_NONZERO) < 0) { - throw new AwsException("ValidationException", - prefix + NUMBER_UNDERFLOW, 400); + if (exponent < -128 - magnitude) { + return NUMBER_UNDERFLOW; } + return null; + } + + private static int exponentMarker(String text) { + int lower = text.indexOf('e'); + int upper = text.indexOf('E'); + if (lower < 0 || upper < 0) { + return Math.max(lower, upper); + } + return Math.min(lower, upper); } // AWS answers with the overflow wording for any arithmetic result it cannot store, diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java index 097a5389fa..93add973fa 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java @@ -599,10 +599,10 @@ public class NativeDynamoDbJsonHandler { if (!validationErrors.isEmpty()) { throw SmithyValidationErrors.validationException(validationErrors); } + requireReadableValues(item, VALIDATION_ENVELOPE); DynamoDbExpressionSize.checkWrite(conditionExpression, "ConditionExpression"); DynamoDbAttributeValueValidator.requireNestingWithinLimit(item); DynamoDbAttributeValueValidator.requireNestingWithinLimit(exprAttrValues); - DynamoDbNumberUtils.requireStorable(exprAttrValues, true); JsonNode expected = request.has("Expected") ? request.get("Expected") : null; DynamoDbAttributeValueValidator.requireNestingWithinLimit(legacyValues(expected)); @@ -614,6 +614,7 @@ public class NativeDynamoDbJsonHandler { "Can not use both expression and non-expression parameters in the same request: " + "Non-expression parameters: {Expected} Expression parameters: {ConditionExpression}", 400); } + requireReadableValues(exprAttrValues, VALIDATION_ENVELOPE); // EAN/EAV with no expression to reference them: AWS reports "can only be specified // when using expressions", not the "unused in expressions" wording (#2893). @@ -654,15 +655,14 @@ public class NativeDynamoDbJsonHandler { JsonNode attributesToGet = request.has("AttributesToGet") ? request.get("AttributesToGet") : null; DynamoDbAccessPathValidator.validateAttributesToGet(attributesToGet); + requireValidReturnConsumedCapacity(request); + requireReadableValues(key, ""); if (attributesToGet != null && projectionExpression != null) { throw new AwsException("ValidationException", "Can not use both expression and non-expression parameters in the same request: " + "Non-expression parameters: {AttributesToGet} Expression parameters: {ProjectionExpression}", 400); } - // Validate enums before table lookup - requireValidReturnConsumedCapacity(request); - // Validate ProjectionExpression syntax and reserved words before item lookup if (projectionExpression != null) { DynamoDbExpressionSize.checkRead(projectionExpression, "ProjectionExpression"); @@ -717,9 +717,9 @@ public class NativeDynamoDbJsonHandler { if (!delValidationErrors.isEmpty()) { throw SmithyValidationErrors.validationException(delValidationErrors); } + requireReadableValues(key, VALIDATION_ENVELOPE); DynamoDbExpressionSize.checkWrite(conditionExpression, "ConditionExpression"); DynamoDbAttributeValueValidator.requireNestingWithinLimit(exprAttrValues); - DynamoDbNumberUtils.requireStorable(exprAttrValues, true); JsonNode expectedDel = request.has("Expected") ? request.get("Expected") : null; DynamoDbAttributeValueValidator.requireNestingWithinLimit(legacyValues(expectedDel)); @@ -728,6 +728,7 @@ public class NativeDynamoDbJsonHandler { "Can not use both expression and non-expression parameters in the same request: " + "Non-expression parameters: {Expected} Expression parameters: {ConditionExpression}", 400); } + requireReadableValues(exprAttrValues, VALIDATION_ENVELOPE); // EAN/EAV with no expression to reference them: AWS reports "can only be specified // when using expressions", not the "unused in expressions" wording (#2893). @@ -783,13 +784,12 @@ public class NativeDynamoDbJsonHandler { + "Member must satisfy enum value set: [NONE, ALL_OLD, ALL_NEW, UPDATED_OLD, UPDATED_NEW]"); } requireValidReturnConsumedCapacity(request); + requireReadableValues(key, VALIDATION_ENVELOPE); DynamoDbExpressionSize.checkWrite(updateExpression, "UpdateExpression"); DynamoDbExpressionSize.checkWrite(conditionExpression, "ConditionExpression"); DynamoDbAttributeValueValidator.requireNestingWithinLimit(exprAttrValues); - DynamoDbNumberUtils.requireStorable(exprAttrValues, true); ObjectNode attributeUpdateValues = legacyValues(attributeUpdates); DynamoDbAttributeValueValidator.requireNestingWithinLimit(attributeUpdateValues); - DynamoDbNumberUtils.requireStorable(attributeUpdateValues, true); DynamoDbAttributeValueValidator.requireNestingWithinLimit( legacyValues(request.has("Expected") ? request.get("Expected") : null)); @@ -803,11 +803,13 @@ public class NativeDynamoDbJsonHandler { "Can not use both expression and non-expression parameters in the same request: " + "Non-expression parameters: {AttributeUpdates} Expression parameters: {UpdateExpression}", 400); } + requireReadableValues(exprAttrValues, VALIDATION_ENVELOPE); // EAN/EAV with no expression to reference them, mirroring the PutItem guard. rejectExprAttrsWithoutExpression(exprAttrNames, exprAttrValues, updateExpression != null || conditionExpression != null, "UpdateExpression is null, ConditionExpression is null"); + requireReadableValues(attributeUpdateValues, VALIDATION_ENVELOPE); ExpressionEvaluator.validateSyntax(conditionExpression, "ConditionExpression"); @@ -888,6 +890,7 @@ public class NativeDynamoDbJsonHandler { } dynamoDbService.requireItemCallKey(tableName, keyOrItem, isKeyArg, region); validateLegacyExpected(expected); + requireReadableValues(legacyValues(expected), VALIDATION_ENVELOPE); return existing -> evaluateLegacyExpected(existing, expected, conditionalOperator, returnValuesOnConditionCheckFailure); } @@ -1068,6 +1071,15 @@ public class NativeDynamoDbJsonHandler { return values; } + private static final String VALIDATION_ENVELOPE = "1 validation error detected: "; + + // DynamoDB reads the numbers of each request member at its own stage. + private static void requireReadableValues(JsonNode values, String prefix) { + if (values != null) { + DynamoDbNumberUtils.forEachNumber(values, text -> DynamoDbNumberUtils.requireItemNumber(text, prefix)); + } + } + private static final Set VALID_SELECT = Set.of( "ALL_ATTRIBUTES", "ALL_PROJECTED_ATTRIBUTES", "SPECIFIC_ATTRIBUTES", "COUNT"); @@ -1117,6 +1129,10 @@ public class NativeDynamoDbJsonHandler { ? List.of("AttributesToGet", "QueryFilter", "ConditionalOperator") : List.of("AttributesToGet", "QueryFilter", "ConditionalOperator", "KeyConditions"), List.of("ProjectionExpression", "FilterExpression", "KeyConditionExpression")); + requireReadableValues(exprAttrValues, ""); + requireReadableValues(exclusiveStartKey, ""); + requireReadableValues(legacyValues(keyConditions), ""); + requireReadableValues(legacyValues(queryFilter), ""); if (keyConditionExpr == null && keyConditions == null) { throw new AwsException("ValidationException", @@ -1133,7 +1149,6 @@ public class NativeDynamoDbJsonHandler { DynamoDbExpressionSize.checkRead(filterExpr, "FilterExpression"); DynamoDbExpressionSize.checkRead(projectionExpression, "ProjectionExpression"); DynamoDbAttributeValueValidator.requireNestingWithinLimit(exprAttrValues); - DynamoDbNumberUtils.requireStorable(exprAttrValues, false); DynamoDbAttributeValueValidator.requireNestingWithinLimit(legacyValues(keyConditions), false); DynamoDbAttributeValueValidator.requireNestingWithinLimit(legacyValues(queryFilter), false); ExpressionEvaluator.validateSyntax(keyConditionExpr, "KeyConditionExpression"); @@ -1282,11 +1297,13 @@ public class NativeDynamoDbJsonHandler { rejectMixedParameters(request, List.of("AttributesToGet", "ScanFilter", "ConditionalOperator"), List.of("ProjectionExpression", "FilterExpression")); + requireReadableValues(exprAttrValues, ""); + requireReadableValues(exclusiveStartKey, ""); + requireReadableValues(legacyValues(scanFilter), ""); DynamoDbExpressionSize.checkReadWithSize(filterExpr, "FilterExpression"); DynamoDbExpressionSize.checkRead(projectionExpressionScan, "ProjectionExpression"); DynamoDbAttributeValueValidator.requireNestingWithinLimit(exprAttrValues); - DynamoDbNumberUtils.requireStorable(exprAttrValues, false); ExpressionEvaluator.validateSyntax(filterExpr, "FilterExpression"); // DynamoDB reports filter errors before projection errors. requireDefinedTokens(filterExpr, "FilterExpression", exprAttrNames, exprAttrValues); @@ -1513,6 +1530,17 @@ public class NativeDynamoDbJsonHandler { } } + requireValidReturnConsumedCapacity(request); + // BatchWriteItem still reads a number the way a PartiQL parameter is read. + for (List writes : items.values()) { + for (JsonNode writeReq : writes) { + DynamoDbNumberUtils.forEachNumber(writeReq.path("PutRequest").path("Item"), + DynamoDbNumberUtils::requirePartiQLParameterNumber); + DynamoDbNumberUtils.forEachNumber(writeReq.path("DeleteRequest").path("Key"), + DynamoDbNumberUtils::requirePartiQLParameterNumber); + } + } + for (Map.Entry> entry : items.entrySet()) { TableDefinition bwTable = dynamoDbService.requireTableForItemCall(entry.getKey(), region); Set seen = new HashSet<>(); @@ -1531,7 +1559,6 @@ public class NativeDynamoDbJsonHandler { // The per-table write cost needs the stored images from before the batch runs. String returnCCBatch = request.path("ReturnConsumedCapacity").asText("NONE"); - requireValidReturnConsumedCapacity(request); Map costs = null; if (!"NONE".equals(returnCCBatch)) { costs = new LinkedHashMap<>(); @@ -1619,6 +1646,18 @@ public class NativeDynamoDbJsonHandler { } } + // DynamoDB compares the keys as sent before it reads their numbers. + for (JsonNode tableRequest : items.values()) { + Set sent = new HashSet<>(); + for (JsonNode key : tableRequest.path("Keys")) { + if (!sent.add(key)) { + throw new AwsException("ValidationException", + "Provided list of item keys contains duplicates", 400); + } + } + tableRequest.path("Keys").forEach(key -> requireReadableValues(key, "")); + } + for (Map.Entry entry : items.entrySet()) { TableDefinition bgTable = dynamoDbService.requireTableForItemCall(entry.getKey(), region); JsonNode keys = entry.getValue().get("Keys"); @@ -2376,7 +2415,8 @@ public class NativeDynamoDbJsonHandler { JsonNode transactItemsNode = requireValidTransactRequest(request); for (JsonNode txItem : transactItemsNode) { - for (JsonNode op : txItem) { + for (Map.Entry action : txItem.properties()) { + JsonNode op = action.getValue(); String conditionExpression = op.has("ConditionExpression") ? op.get("ConditionExpression").asText() : null; String updateExpression = op.has("UpdateExpression") @@ -2388,6 +2428,11 @@ public class NativeDynamoDbJsonHandler { DynamoDbAttributeValueValidator.requireNestingWithinLimit(op.get("Item"), false); DynamoDbAttributeValueValidator.requireNestingWithinLimit(op.get("Key"), false); DynamoDbAttributeValueValidator.requireNestingWithinLimit(opExprAttrValues, false); + requireReadableValues(op.get("Put".equals(action.getKey()) ? "Item" : "Key"), ""); + // An action without an expression ignores its ExpressionAttributeValues. + if (conditionExpression != null || updateExpression != null) { + requireReadableValues(opExprAttrValues, ""); + } DynamoDbExpressionSize.checkRead(op.path("UpdateExpression").textValue(), "UpdateExpression"); DynamoDbExpressionSize.checkReadWithSize(conditionExpression, "ConditionExpression"); ExpressionEvaluator.validateSyntax(conditionExpression, "ConditionExpression"); @@ -2535,6 +2580,7 @@ public class NativeDynamoDbJsonHandler { private Response handleTransactGetItems(JsonNode request, String region) { JsonNode transactItemsNode = requireValidTransactRequest(request); + transactItemsNode.forEach(txItem -> requireReadableValues(txItem.path("Get").path("Key"), "")); for (JsonNode txItem : transactItemsNode) { DynamoDbExpressionSize.checkRead(txItem.path("Get").path("ProjectionExpression").textValue(), diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandlerTest.java index 8950484157..1039fbcb40 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandlerTest.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import java.nio.file.Path; @@ -2066,6 +2067,137 @@ class NativeDynamoDbJsonHandlerTest { ex.getMessage()); } + @ParameterizedTest + @CsvSource(delimiter = '|', textBlock = """ + abc | NOT_NUMERIC + '' | NOT_NUMERIC + 1e | NOT_NUMERIC + 1e9223372036854775808 | NOT_NUMERIC + 1e-9223372036854775809 | NOT_NUMERIC + 1e126 | OVERFLOW + 0.1e127 | OVERFLOW + 0e126 | OVERFLOW + 1e2147483647 | OVERFLOW + 1.5e9223372036854775807 | OVERFLOW + 1e-131 | UNDERFLOW + 0.000e-128 | UNDERFLOW + 1e-9223372036854775808 | UNDERFLOW + 1234567890123456789012345678901234567890 | DIGITS + 1234567890123456789012345678901234567890e200 | DIGITS + 9.9999999999999999999999999999999999999e125 | NONE + 0.000e126 | NONE + 1e-130 | NONE + 1e+000000000000000000000000000005 | NONE + """) + void putItemReadsANumberExponentAsALongBeforeTheTableLookup(String number, String problem) { + ObjectNode request = mapper.createObjectNode(); + request.put("TableName", "Missing"); + request.set("Item", item("userId", "u1").set("n", attributeValue("N", number))); + + AwsException ex = assertThrows(AwsException.class, + () -> handler.handle("PutItem", request, "eu-west-1")); + String expected = numberProblem(problem, number); + if (expected == null) { + assertEquals("ResourceNotFoundException", ex.getErrorCode()); + } else { + assertEquals("1 validation error detected: " + expected, ex.getMessage()); + } + } + + private static String numberProblem(String problem, String number) { + return switch (problem) { + case "NOT_NUMERIC" -> DynamoDbNumberUtils.PARAMETER_NOT_NUMERIC + ": " + number; + case "OVERFLOW" -> DynamoDbNumberUtils.NUMBER_OVERFLOW; + case "UNDERFLOW" -> DynamoDbNumberUtils.NUMBER_UNDERFLOW; + case "DIGITS" -> DynamoDbNumberUtils.TOO_MANY_DIGITS; + default -> null; + }; + } + + @ParameterizedTest + @CsvSource(delimiter = '|', textBlock = """ + PutItem | true | OVERFLOW | {"TableName":"Missing","Item":{"userId":{"S":"u1"},"n":{"NS":["1","%s"]}}} + PutItem | true | OVERFLOW | {"TableName":"Users","Item":{"userId":{"S":"u1"}},"Expected":{"n":{"ComparisonOperator":"EQ","AttributeValueList":[{"N":"%s"}]}}} + PutItem | true | OVERFLOW | {"TableName":"Missing","Item":{"userId":{"S":"u1"}},"ConditionExpression":"n = :v","ExpressionAttributeValues":{":v":{"M":{"x":{"L":[{"N":"%s"}]}}}}} + UpdateItem | true | OVERFLOW | {"TableName":"Missing","Key":{"userId":{"N":"%s"}},"UpdateExpression":"SET a = :a","ExpressionAttributeValues":{":a":{"S":"x"}}} + UpdateItem | true | OVERFLOW | {"TableName":"Missing","Key":{"userId":{"S":"u1"}},"AttributeUpdates":{"n":{"Action":"PUT","Value":{"N":"%s"}}}} + DeleteItem | true | OVERFLOW | {"TableName":"Users","Key":{"userId":{"S":"u1"}},"Expected":{"n":{"Value":{"N":"%s"}}}} + GetItem | false | OVERFLOW | {"TableName":"Missing","Key":{"userId":{"N":"%s"}},"ProjectionExpression":"a","AttributesToGet":["a"]} + BatchGetItem | false | OVERFLOW | {"RequestItems":{"Missing":{"Keys":[{"userId":{"N":"%s"}}]}}} + Query | false | OVERFLOW | {"TableName":"Missing","KeyConditionExpression":"userId = :p","ExpressionAttributeValues":{":p":{"S":"u1"}},"ExclusiveStartKey":{"userId":{"S":"u1"},"n":{"N":"%s"}}} + Query | false | OVERFLOW | {"TableName":"Missing","KeyConditions":{"userId":{"ComparisonOperator":"EQ","AttributeValueList":[{"S":"u1"}]}},"QueryFilter":{"n":{"ComparisonOperator":"EQ","AttributeValueList":[{"N":"%s"}]}}} + Scan | false | OVERFLOW | {"TableName":"Missing","ScanFilter":{"n":{"ComparisonOperator":"EQ","AttributeValueList":[{"N":"%s"}]}}} + TransactWriteItems | false | OVERFLOW | {"TransactItems":[{"Put":{"TableName":"Missing","Item":{"userId":{"S":"u1"},"n":{"N":"%s"}},"ConditionExpression":"a = = b"}}]} + TransactWriteItems | false | OVERFLOW | {"TransactItems":[{"Update":{"TableName":"Missing","Key":{"userId":{"S":"u1"}},"UpdateExpression":"SET n = :v","ExpressionAttributeValues":{":v":{"N":"%s"}}}}]} + TransactGetItems | false | OVERFLOW | {"TransactItems":[{"Get":{"TableName":"Missing","Key":{"userId":{"N":"%s"}}}}]} + BatchWriteItem | false | UNDERFLOW | {"RequestItems":{"Missing":[{"DeleteRequest":{"Key":{"userId":{"N":"%s"}}}}]}} + """) + void everyNumberInARequestIsReadBeforeTheOtherChecks(String operation, boolean enveloped, String problem, + String template) throws Exception { + createUsersTable("eu-west-1"); + String number = "1e2147483647"; + JsonNode request = mapper.readTree(template.formatted(number)); + + AwsException ex = assertThrows(AwsException.class, () -> handler.handle(operation, request, "eu-west-1")); + assertEquals((enveloped ? "1 validation error detected: " : "") + numberProblem(problem, number), + ex.getMessage()); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', textBlock = """ + GetItem | {"TableName":"Missing","Key":{"userId":{"S":"u1"}},"Item":{"n":{"N":"abc"}}} + PutItem | {"TableName":"Missing","Item":{"userId":{"S":"u1"}},"Key":{"userId":{"N":"abc"}}} + UpdateItem | {"TableName":"Missing","Key":{"userId":{"S":"u1"}},"UpdateExpression":"SET a = :a","ExpressionAttributeValues":{":a":{"S":"x"}},"Item":{"n":{"N":"abc"}}} + DeleteItem | {"TableName":"Missing","Key":{"userId":{"S":"u1"}},"ExclusiveStartKey":{"userId":{"N":"abc"}}} + Query | {"TableName":"Missing","KeyConditionExpression":"userId = :p","ExpressionAttributeValues":{":p":{"S":"u1"}},"Key":{"userId":{"N":"abc"}}} + Scan | {"TableName":"Missing","KeyConditions":{"userId":{"ComparisonOperator":"EQ","AttributeValueList":[{"N":"abc"}]}}} + TransactWriteItems | {"TransactItems":[{"Put":{"TableName":"Missing","Item":{"userId":{"S":"u1"}},"Key":{"userId":{"N":"abc"}}}}]} + TransactWriteItems | {"TransactItems":[{"Delete":{"TableName":"Missing","Key":{"userId":{"S":"u1"}},"ExpressionAttributeValues":{":v":{"N":"abc"}}}}]} + TransactGetItems | {"TransactItems":[{"Get":{"TableName":"Missing","Key":{"userId":{"S":"u1"}},"Item":{"n":{"N":"abc"}}}}]} + """) + void aNumberThatTheOperationDoesNotReadIsIgnored(String operation, String request) throws Exception { + AwsException ex = assertThrows(AwsException.class, + () -> handler.handle(operation, mapper.readTree(request), "eu-west-1")); + assertEquals("ResourceNotFoundException", ex.getErrorCode(), ex.getMessage()); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', textBlock = """ + PutItem | {"TableName":"Missing","Item":{"userId":{"S":"u1"}},"ConditionExpression":"n = :v","ExpressionAttributeValues":{":v":{"N":"abc"}},"Expected":{"n":{"Exists":false}}} | Can not use both expression and non-expression parameters + PutItem | {"TableName":"Users","Item":{"userId":{"S":"u1"}},"Expected":{"n":{"Value":{"N":"abc"},"Exists":false}}} | Value cannot be used when Exists is false for Attribute: n + UpdateItem | {"TableName":"Missing","Key":{"userId":{"S":"u1"}},"UpdateExpression":"SET a = :a","ExpressionAttributeValues":{":a":{"S":"x"}},"AttributeUpdates":{"n":{"Action":"PUT","Value":{"N":"abc"}}}} | Can not use both expression and non-expression parameters + UpdateItem | {"TableName":"Missing","Key":{"userId":{"S":"u1"}},"ExpressionAttributeValues":{":a":{"S":"x"}},"AttributeUpdates":{"n":{"Action":"PUT","Value":{"N":"abc"}}}} | ExpressionAttributeValues can only be specified when using expressions + """) + void numbersInValuesAndLegacyConditionsAreReadAfterTheMemberChecks(String operation, String request, + String message) throws Exception { + createUsersTable("eu-west-1"); + AwsException ex = assertThrows(AwsException.class, + () -> handler.handle(operation, mapper.readTree(request), "eu-west-1")); + assertTrue(ex.getMessage().contains(message), ex.getMessage()); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', textBlock = """ + GetItem | {"TableName":"Missing","Key":{"userId":{"N":"abc"}},"ReturnConsumedCapacity":"BAD"} + BatchWriteItem | {"RequestItems":{"Missing":[{"PutRequest":{"Item":{"userId":{"N":"abc"}}}}]},"ReturnConsumedCapacity":"BAD"} + """) + void returnConsumedCapacityIsCheckedBeforeTheNumbers(String operation, String request) throws Exception { + AwsException ex = assertThrows(AwsException.class, + () -> handler.handle(operation, mapper.readTree(request), "eu-west-1")); + assertTrue(ex.getMessage().startsWith("1 validation error detected: Value 'BAD' at 'returnConsumedCapacity'"), + ex.getMessage()); + } + + @Test + void batchGetItemRefusesRepeatedKeysBeforeItReadsTheirNumbers() throws Exception { + JsonNode request = mapper.readTree( + "{\"RequestItems\":{\"Missing\":{\"Keys\":[{\"userId\":{\"N\":\"abc\"}},{\"userId\":{\"N\":\"abc\"}}]}}}"); + + AwsException ex = assertThrows(AwsException.class, + () -> handler.handle("BatchGetItem", request, "eu-west-1")); + assertEquals("Provided list of item keys contains duplicates", ex.getMessage()); + } + @Test void updateItemRejectsAnAttributeUpdatesValueWithALeafAtLevel33BeforeTheTableLookup() { ObjectNode request = updateUserRequest();