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 ab2a11921d..c5cf837acd 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 @@ -572,6 +572,15 @@ public class NativeDynamoDbJsonHandler { + "Member must satisfy enum value set: [INDEXES, TOTAL, NONE]"; } + private static String returnItemCollectionMetricsError(JsonNode request) { + JsonNode value = request.get("ReturnItemCollectionMetrics"); + if (value == null || value.isNull() || VALID_RETURN_ITEM_COLLECTION_METRICS.contains(value.asText())) { + return null; + } + return "Value '" + value.asText() + "' at 'returnItemCollectionMetrics' failed to satisfy constraint: " + + "Member must satisfy enum value set: [SIZE, NONE]"; + } + private Response handlePutItem(JsonNode request, String region) { String tableName = request.has("TableName") ? request.path("TableName").asText() : null; DynamoDbTableNames.resolve(tableName); // validate tableName before other params @@ -2418,7 +2427,7 @@ public class NativeDynamoDbJsonHandler { } private Response handleTransactWriteItems(JsonNode request, String region) { - JsonNode transactItemsNode = requireValidTransactRequest(request); + JsonNode transactItemsNode = requireValidTransactRequest(request, true); for (JsonNode txItem : transactItemsNode) { for (Map.Entry action : txItem.properties()) { @@ -2515,24 +2524,173 @@ public class NativeDynamoDbJsonHandler { } } - private static JsonNode requireValidTransactRequest(JsonNode request) { - JsonNode transactItems = request.path("TransactItems"); - List validationErrors = new ArrayList<>(); - if (transactItems.isMissingNode() || transactItems.isNull() || !transactItems.isArray()) { - validationErrors.add("Value null at 'transactItems' failed to satisfy constraint: " - + "Member must have length greater than or equal to 1"); - } else if (transactItems.isEmpty()) { - validationErrors.add("Value '[]' at 'transactItems' failed to satisfy constraint: " - + "Member must have length greater than or equal to 1"); - } else if (transactItems.size() > 100) { - validationErrors.add("Value '" + transactItems + "' at 'transactItems' failed to satisfy constraint: " - + "Member must have length less than or equal to 100"); + // DynamoDB reads an action with more than one operation as the first one in this order. + private static final List TRANSACT_WRITE_OPS = List.of("ConditionCheck", "Put", "Delete", "Update"); + + private static final int MAX_TRANSACT_ITEMS = 100; + + // DynamoDB names the required members of an action in this order. + private static final Map> TRANSACT_REQUIRED_MEMBERS = Map.of( + "Put", List.of("Item", "TableName"), + "Delete", List.of("Key", "TableName"), + "Update", List.of("UpdateExpression", "Key", "TableName"), + "ConditionCheck", List.of("ConditionExpression", "Key", "TableName"), + "Get", List.of("Key", "TableName")); + + // DynamoDB's newer validator gives up on a request nested this deep, and the older one answers. + private static final int OLDER_VALIDATOR_DEPTH = 128; + + private record TransactAction(int index, String type, JsonNode op) { + String path(String member) { + return "transactItems." + (index + 1) + ".member." + decapitalize(type) + "." + decapitalize(member); + } + } + + // DynamoDB checks the lengths with its newer validator first. It skips that validator when a + // required member is missing or the request is nested too deep, and the older one checks the rest. + private static JsonNode requireValidTransactRequest(JsonNode request, boolean write) { + String token = write ? request.path("ClientRequestToken").textValue() : null; + List memberErrors = new ArrayList<>(); + if (token != null) { + addIfPresent(memberErrors, SmithyValidationErrors.lengthOutOfRange("clientRequestToken", token, 1, + MAX_CLIENT_REQUEST_TOKEN_LENGTH)); + } + addReturnConsumedCapacityError(request, memberErrors); + if (write) { + addIfPresent(memberErrors, returnItemCollectionMetricsError(request)); + } + JsonNode transactItems = request.path("TransactItems"); + if (transactItems.isMissingNode() || transactItems.isNull() || !transactItems.isArray()) { + List validationErrors = new ArrayList<>(); + validationErrors.add(SmithyValidationErrors.notNull("transactItems")); + validationErrors.addAll(memberErrors); + throwValidationErrors(validationErrors); + } + List ops = write ? TRANSACT_WRITE_OPS : List.of("Get"); + List actions = new ArrayList<>(); + List required = new ArrayList<>(); + boolean missing = false; + boolean noOperation = false; + boolean manyOperations = false; + for (int i = 0; i < transactItems.size(); i++) { + JsonNode txItem = transactItems.get(i); + List types = ops.stream().filter(txItem::hasNonNull).toList(); + noOperation |= types.isEmpty(); + manyOperations |= types.size() > 1; + if (!write && types.isEmpty()) { + required.add(SmithyValidationErrors.notNull("transactItems." + (i + 1) + ".member.get")); + missing = true; + } + if (types.isEmpty()) { + continue; + } + TransactAction action = new TransactAction(i, types.getFirst(), txItem.get(types.getFirst())); + actions.add(action); + for (String member : TRANSACT_REQUIRED_MEMBERS.get(action.type())) { + JsonNode value = action.op().get(member); + if (value == null || value.isNull()) { + required.add(SmithyValidationErrors.notNull(action.path(member))); + missing = true; + } else if ("TableName".equals(member) && value.asText().isEmpty()) { + required.add(SmithyValidationErrors.lengthTooShort(action.path(member), "", 1)); + } + } + } + boolean older = transactDepth(transactItems, ops) >= OLDER_VALIDATOR_DEPTH; + if (!missing && !older) { + requireTransactLengths(transactItems.size(), actions, token); + } + + if (transactItems.size() > MAX_TRANSACT_ITEMS) { + required.addFirst("Value '" + transactItems + "' at 'transactItems' failed to satisfy constraint: " + + "Member must have length less than or equal to " + MAX_TRANSACT_ITEMS); + } + // The older validator stops at a missing member, before the operation and name checks. + if (!required.isEmpty()) { + required.addAll(memberErrors); + throwValidationErrors(required); + } + List tableNames = new ArrayList<>(); + for (TransactAction action : actions) { + String name = action.op().get("TableName").asText(); + if (!AwsArnUtils.looksLikeArn(name)) { + tableNames.addAll(nameViolations(name, action.path("TableName"))); + } + } + boolean refuseNoOperation = write && noOperation; + // A request too deep for the newer validator also gets an older answer for an empty action. + if (older) { + throwValidationErrors(memberErrors); + if (refuseNoOperation) { + throw new AwsException("ValidationException", + "Invalid Request: TransactWriteRequest should contain Delete or Put or Update request", 400); + } + throwValidationErrors(tableNames); + } else { + List listed = refuseNoOperation + ? new ArrayList<>(List.of("Value '' at 'transactItems' failed to satisfy constraint: " + + "TransactWriteRequest should contain Delete or Put or Update or ConditionCheck")) + : tableNames; + listed.addAll(memberErrors); + throwValidationErrors(listed); + } + if (manyOperations) { + throw new AwsException("ValidationException", + "TransactItems can only contain one of Check, Put, Update or Delete", 400); } - addReturnConsumedCapacityError(request, validationErrors); - throwValidationErrors(validationErrors); return transactItems; } + // The newer validator names a member by its 0-based position and leaves the value out. + private static void requireTransactLengths(int count, List actions, String token) { + SmithyValidationErrors.Violations unquoted = SmithyValidationErrors.Violations.WITHOUT_VALUES; + List validationErrors = new ArrayList<>(); + if (token != null) { + addIfPresent(validationErrors, unquoted.lengthOutOfRange("ClientRequestToken", token, 1, + MAX_CLIENT_REQUEST_TOKEN_LENGTH)); + } + addIfPresent(validationErrors, SmithyValidationErrors.sizeOutOfRange("TransactItems", count, 1, + MAX_TRANSACT_ITEMS)); + for (TransactAction action : actions) { + addIfPresent(validationErrors, unquoted.lengthOutOfRange( + "TransactItems." + action.index() + ".member." + action.type() + ".TableName", + action.op().get("TableName").asText(), 1, 1024)); + } + throwValidationErrors(validationErrors); + } + + // DynamoDB leaves unknown members out when it measures how deep a request nests. + private static int transactDepth(JsonNode transactItems, List ops) { + int deepest = 0; + for (JsonNode txItem : transactItems) { + for (String op : ops) { + for (String member : List.of("Item", "Key", "ExpressionAttributeValues")) { + deepest = Math.max(deepest, jsonDepth(txItem.path(op).path(member))); + } + } + } + // The request, TransactItems, the action and the operation hold these members. + return deepest + 4; + } + + private static int jsonDepth(JsonNode node) { + int deepest = 0; + for (JsonNode child : node) { + deepest = Math.max(deepest, jsonDepth(child)); + } + return node.isContainerNode() ? deepest + 1 : 0; + } + + private static String decapitalize(String name) { + return Character.toLowerCase(name.charAt(0)) + name.substring(1); + } + + private static void addIfPresent(List validationErrors, String error) { + if (error != null) { + validationErrors.add(error); + } + } + private static void addReturnConsumedCapacityError(JsonNode request, List validationErrors) { String error = returnConsumedCapacityError(request); if (error != null) { @@ -2585,7 +2743,7 @@ public class NativeDynamoDbJsonHandler { } private Response handleTransactGetItems(JsonNode request, String region) { - JsonNode transactItemsNode = requireValidTransactRequest(request); + JsonNode transactItemsNode = requireValidTransactRequest(request, false); transactItemsNode.forEach(txItem -> requireReadableValues(txItem.path("Get").path("Key"), "")); for (JsonNode txItem : transactItemsNode) { diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbConsumedCapacityIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbConsumedCapacityIntegrationTest.java index 7201de5a50..d66839bec8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbConsumedCapacityIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbConsumedCapacityIntegrationTest.java @@ -601,8 +601,8 @@ class DynamoDbConsumedCapacityIntegrationTest { rejected("TransactWriteItems", """ {"TransactItems": [], "ReturnConsumedCapacity": "INVALID"} """) - .body("message", equalTo("2 validation errors detected: Value '[]' at 'transactItems' failed to " - + "satisfy constraint: Member must have length greater than or equal to 1; " + invalid)); + .body("message", equalTo("1 validation error detected: Value at 'TransactItems' failed to " + + "satisfy constraint: Member must have length greater than or equal to 1")); send("TransactGetItems", """ { 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 35750c96cf..bfe1c0fa86 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 @@ -2330,6 +2330,69 @@ class NativeDynamoDbJsonHandlerTest { assertEquals(message, ex.getMessage()); } + @ParameterizedTest + @CsvSource(delimiter = '|', quoteCharacter = '`', textBlock = """ + TransactWriteItems | {"TransactItems":[{"Put":{"TableName":"Tbl","Item":{}}},{"Update":{"TableName":"bad!name","Key":{},"UpdateExpression":"SET a = :a"}}]} | 1 validation error detected: Value 'bad!name' at 'transactItems.2.member.update.tableName' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+ + TransactWriteItems | {"TransactItems":[{"ConditionCheck":{"TableName":"a!","Key":{},"ConditionExpression":"x"}}],"ReturnConsumedCapacity":"BOGUS","ReturnItemCollectionMetrics":"BOGUS2"} | 4 validation errors detected: Value 'a!' at 'transactItems.1.member.conditionCheck.tableName' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+; Value 'a!' at 'transactItems.1.member.conditionCheck.tableName' failed to satisfy constraint: Member must have length greater than or equal to 3; Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]; Value 'BOGUS2' at 'returnItemCollectionMetrics' failed to satisfy constraint: Member must satisfy enum value set: [SIZE, NONE] + TransactWriteItems | {"TransactItems":[],"ClientRequestToken":"0123456789012345678901234567890123456"} | 2 validation errors detected: Value at 'ClientRequestToken' failed to satisfy constraint: Member must have length less than or equal to 36; Value at 'TransactItems' failed to satisfy constraint: Member must have length greater than or equal to 1 + TransactWriteItems | {"TransactItems":[{"Put":{"TableName":"bad!name","Item":{}}},{"Delete":{"TableName":"","Key":{}}}],"ReturnConsumedCapacity":"BOGUS"} | 1 validation error detected: Value at 'TransactItems.1.member.Delete.TableName' failed to satisfy constraint: Member must have length greater than or equal to 1 + TransactWriteItems | {"TransactItems":[{"Put":{"TableName":""}}],"ClientRequestToken":"0123456789012345678901234567890123456","ReturnConsumedCapacity":"BOGUS"} | 4 validation errors detected: Value null at 'transactItems.1.member.put.item' failed to satisfy constraint: Member must not be null; Value '' at 'transactItems.1.member.put.tableName' failed to satisfy constraint: Member must have length greater than or equal to 1; Value '0123456789012345678901234567890123456' at 'clientRequestToken' failed to satisfy constraint: Member must have length less than or equal to 36; Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE] + TransactWriteItems | {"TransactItems":[{"Update":{}},{"Put":{"TableName":"bad!name","Item":{}}}]} | 3 validation errors detected: Value null at 'transactItems.1.member.update.updateExpression' failed to satisfy constraint: Member must not be null; Value null at 'transactItems.1.member.update.key' failed to satisfy constraint: Member must not be null; Value null at 'transactItems.1.member.update.tableName' failed to satisfy constraint: Member must not be null + TransactWriteItems | {"TransactItems":[{"Put":{"TableName":"bad!name","Item":{}}},{"Foo":{}}],"ReturnConsumedCapacity":"BOGUS"} | 2 validation errors detected: Value '' at 'transactItems' failed to satisfy constraint: TransactWriteRequest should contain Delete or Put or Update or ConditionCheck; Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE] + TransactWriteItems | {"TransactItems":[{"Put":{"TableName":"Tbl"}},{"Put":null}]} | 1 validation error detected: Value null at 'transactItems.1.member.put.item' failed to satisfy constraint: Member must not be null + TransactWriteItems | {"TransactItems":[{"Put":{"TableName":"Tbl","Item":{}},"Delete":{"TableName":"bad!name","Key":{}}}],"ReturnItemCollectionMetrics":"BOGUS2"} | 1 validation error detected: Value 'BOGUS2' at 'returnItemCollectionMetrics' failed to satisfy constraint: Member must satisfy enum value set: [SIZE, NONE] + TransactWriteItems | {"TransactItems":[{"Put":{"TableName":"Tbl","Item":{}},"Delete":{"TableName":"bad!name","Key":{}}}]} | TransactItems can only contain one of Check, Put, Update or Delete + TransactGetItems | {"TransactItems":[{"Get":{"TableName":"Tbl","Key":{}}},{"Get":{"TableName":"bad!name","Key":{}}}]} | 1 validation error detected: Value 'bad!name' at 'transactItems.2.member.get.tableName' failed to satisfy constraint: Member must satisfy regular expression pattern: [a-zA-Z0-9_.-]+ + TransactGetItems | {"TransactItems":[{"Get":{"TableName":""}},{"Put":{}}],"ReturnConsumedCapacity":"BOGUS"} | 4 validation errors detected: Value null at 'transactItems.1.member.get.key' failed to satisfy constraint: Member must not be null; Value '' at 'transactItems.1.member.get.tableName' failed to satisfy constraint: Member must have length greater than or equal to 1; Value null at 'transactItems.2.member.get' failed to satisfy constraint: Member must not be null; Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE] + TransactWriteItems | {"TransactItems":null,"ClientRequestToken":"0123456789012345678901234567890123456","ReturnConsumedCapacity":"BOGUS","ReturnItemCollectionMetrics":"BOGUS2"} | 4 validation errors detected: Value null at 'transactItems' failed to satisfy constraint: Member must not be null; Value '0123456789012345678901234567890123456' at 'clientRequestToken' failed to satisfy constraint: Member must have length less than or equal to 36; Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]; Value 'BOGUS2' at 'returnItemCollectionMetrics' failed to satisfy constraint: Member must satisfy enum value set: [SIZE, NONE] + TransactGetItems | {"ReturnConsumedCapacity":"BOGUS"} | 2 validation errors detected: Value null at 'transactItems' failed to satisfy constraint: Member must not be null; Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE] + """) + void aTransactionReportsItsMemberErrorsTogether(String operation, String request, String message) throws Exception { + AwsException ex = assertThrows(AwsException.class, + () -> handler.handle(operation, mapper.readTree(request), "eu-west-1")); + assertEquals("ValidationException", ex.getErrorCode()); + assertEquals(message, ex.getMessage()); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', quoteCharacter = '`', textBlock = """ + 61 | {"TransactItems":[{},{"Delete":{"TableName":"bad!name","Key":{}}}]} | Invalid Request: TransactWriteRequest should contain Delete or Put or Update request + 61 | {"TransactItems":[{}],"ReturnConsumedCapacity":"BOGUS"} | 1 validation error detected: Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE] + 61 | {"TransactItems":[{"Put":{"TableName":"","Item":{}}}]} | 1 validation error detected: Value '' at 'transactItems.1.member.put.tableName' failed to satisfy constraint: Member must have length greater than or equal to 1 + 60 | {"TransactItems":[{"Put":{"TableName":"","Item":{}}}]} | 1 validation error detected: Value at 'TransactItems.0.member.Put.TableName' failed to satisfy constraint: Member must have length greater than or equal to 1 + 60 | {"TransactItems":[{}],"ReturnConsumedCapacity":"BOGUS"} | 2 validation errors detected: Value '' at 'transactItems' failed to satisfy constraint: TransactWriteRequest should contain Delete or Put or Update or ConditionCheck; Value 'BOGUS' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE] + """) + void aTransactionNestedTooDeepForTheNewerValidatorIsCheckedByTheOlderOne(int levels, String request, + String message) throws Exception { + ObjectNode body = (ObjectNode) mapper.readTree(request); + ObjectNode put = mapper.createObjectNode().put("TableName", "Tbl"); + put.set("Item", mapper.createObjectNode().set("d", nestedMaps(levels))); + ((ArrayNode) body.get("TransactItems")).add(mapper.createObjectNode().set("Put", put)); + + AwsException ex = assertThrows(AwsException.class, + () -> handler.handle("TransactWriteItems", body, "eu-west-1")); + assertEquals(message, ex.getMessage()); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', textBlock = """ + TransactWriteItems | {"TransactItems":[]} | 1 validation error detected: Value at 'TransactItems' failed to satisfy constraint: Member must have length greater than or equal to 1 + TransactGetItems | {"TransactItems":[]} | 1 validation error detected: Value at 'TransactItems' failed to satisfy constraint: Member must have length greater than or equal to 1 + TransactWriteItems | {"TransactItems":[{"Put":{"TableName":"","Item":{}}}]} | 1 validation error detected: Value at 'TransactItems.0.member.Put.TableName' failed to satisfy constraint: Member must have length greater than or equal to 1 + """) + void aTransactionNestedDeepInUnknownMembersIsCheckedByTheNewerValidator(String operation, String request, + String message) throws Exception { + ObjectNode body = (ObjectNode) mapper.readTree(request); + body.set("Foo", nestedMaps(63)); + for (JsonNode action : body.get("TransactItems")) { + action.forEach(op -> ((ObjectNode) op).set("Foo", nestedMaps(63))); + ((ObjectNode) action).set("Foo", nestedMaps(63)); + } + + AwsException ex = assertThrows(AwsException.class, () -> handler.handle(operation, body, "eu-west-1")); + assertEquals(message, ex.getMessage()); + } + @Test void updateItemRejectsAnAttributeUpdatesValueWithALeafAtLevel33BeforeTheTableLookup() { ObjectNode request = updateUserRequest(); @@ -2752,9 +2815,10 @@ class NativeDynamoDbJsonHandlerTest { void transactWriteItemsCancelsOnAConditionCheckKeyMissingItsAttribute() throws Exception { createUsersTable("eu-west-1"); - Response response = handler.handle("TransactWriteItems", - transactWriteOf(transactMember("ConditionCheck", "Users", "Key", mapper.createObjectNode())), - "eu-west-1"); + ObjectNode check = transactMember("ConditionCheck", "Users", "Key", mapper.createObjectNode()); + ((ObjectNode) check.get("ConditionCheck")).put("ConditionExpression", "attribute_exists(userId)"); + + Response response = handler.handle("TransactWriteItems", transactWriteOf(check), "eu-west-1"); assertEquals("The provided key element does not match the schema", onlyValidationErrorMessage(response)); }