diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java index b685f94ca4..3d744a80a9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandler.java @@ -128,7 +128,9 @@ public class DynamoDbJsonHandler { List gsis = new ArrayList<>(); JsonNode gsiArray = request.path("GlobalSecondaryIndexes"); if (!gsiArray.isMissingNode() && gsiArray.isArray()) { + var gsiPosition = 0; for (JsonNode gsiNode : gsiArray) { + gsiPosition++; String indexName = gsiNode.path("IndexName").asText(); List gsiKeySchema = new ArrayList<>(); gsiNode.path("KeySchema").forEach(ks -> @@ -143,6 +145,8 @@ public class DynamoDbJsonHandler { nonKeyAttributes.add(nonKeyAttr.asText()); } } + rejectEmptyNonKeyAttributes(nonKeyAttrArray, "globalSecondaryIndexes." + gsiPosition + ".member"); + validateProjectionSpec(projectionType, nonKeyAttributes); GlobalSecondaryIndex gsi = new GlobalSecondaryIndex(indexName, gsiKeySchema, null, projectionType, nonKeyAttributes); JsonNode gsiPt = gsiNode.path("ProvisionedThroughput"); if (!gsiPt.isMissingNode()) { @@ -165,7 +169,9 @@ public class DynamoDbJsonHandler { List lsis = new ArrayList<>(); JsonNode lsiArray = request.path("LocalSecondaryIndexes"); if (!lsiArray.isMissingNode() && lsiArray.isArray()) { + var lsiPosition = 0; for (JsonNode lsiNode : lsiArray) { + lsiPosition++; String indexName = lsiNode.path("IndexName").asText(); List lsiKeySchema = new ArrayList<>(); lsiNode.path("KeySchema").forEach(ks -> @@ -178,6 +184,8 @@ public class DynamoDbJsonHandler { if (!lsiNonKeyAttrArray.isMissingNode() && lsiNonKeyAttrArray.isArray()) { lsiNonKeyAttrArray.forEach(a -> lsiNonKeyAttributes.add(a.asText())); } + rejectEmptyNonKeyAttributes(lsiNonKeyAttrArray, "localSecondaryIndexes." + lsiPosition + ".member"); + validateProjectionSpec(projectionType, lsiNonKeyAttributes); lsis.add(new LocalSecondaryIndex(indexName, lsiKeySchema, null, projectionType, lsiNonKeyAttributes)); } } @@ -197,6 +205,20 @@ public class DynamoDbJsonHandler { validateSseType(sseType); } + if ("PAY_PER_REQUEST".equals(billingMode) && !pt.isMissingNode()) { + throw new AwsException("ValidationException", + "One or more parameter values were invalid: Neither ReadCapacityUnits nor WriteCapacityUnits " + + "can be specified when BillingMode is PAY_PER_REQUEST", 400); + } + + JsonNode streamSpecCheck = request.path("StreamSpecification"); + if (streamSpecCheck.isObject() && !streamSpecCheck.path("StreamEnabled").asBoolean(false) + && streamSpecCheck.hasNonNull("StreamViewType")) { + throw new AwsException("ValidationException", + "One or more parameter values were invalid: StreamViewType cannot be specified " + + "when StreamEnabled is false", 400); + } + TableDefinition table = dynamoDbService.createTable(tableName, keySchema, attrDefs, readCapacity, writeCapacity, gsis, lsis, region); table.setTableStatus(initialStatus); @@ -271,6 +293,31 @@ public class DynamoDbJsonHandler { } } + // AWS reports an empty list as a length constraint on the 1-based member path, before the + // projection type check. A null NonKeyAttributes counts as not specified. + private static void rejectEmptyNonKeyAttributes(JsonNode nonKeyAttrArray, String memberPath) { + if (nonKeyAttrArray.isArray() && nonKeyAttrArray.isEmpty()) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '[]' at '" + memberPath + + ".projection.nonKeyAttributes' failed to satisfy constraint: " + + "Member must have length greater than or equal to 1", 400); + } + } + + // INCLUDE requires the NonKeyAttributes list; every other projection type forbids it. + private static void validateProjectionSpec(String projectionType, List nonKeyAttributes) { + if ("INCLUDE".equals(projectionType) && nonKeyAttributes.isEmpty()) { + throw new AwsException("ValidationException", + "One or more parameter values were invalid: " + + "ProjectionType is INCLUDE, but NonKeyAttributes is not specified", 400); + } + if (!"INCLUDE".equals(projectionType) && !nonKeyAttributes.isEmpty()) { + throw new AwsException("ValidationException", + "One or more parameter values were invalid: " + + "ProjectionType is " + projectionType + ", but NonKeyAttributes is specified", 400); + } + } + private Response handleDeleteTable(JsonNode request, String region) { String tableName = request.path("TableName").asText(); TableDefinition table = dynamoDbService.describeTable(tableName, region); @@ -569,6 +616,11 @@ public class DynamoDbJsonHandler { + "Non-expression parameters: {AttributeUpdates} Expression parameters: {UpdateExpression}", 400); } + // 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"); + ExpressionEvaluator.validateExpression(conditionExpression, "ConditionExpression", exprAttrNames, exprAttrValues); if (conditionExpression != null && expectedUpd != null) { @@ -994,6 +1046,12 @@ public class DynamoDbJsonHandler { throw new AwsException("ValidationException", "The Segment parameter is required but was not present in the request when parameter TotalSegments is present", 400); } + if (totalSegments != null && totalSegments > 1_000_000) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + totalSegments + + "' at 'totalSegments' failed to satisfy constraint: " + + "Member must have value less than or equal to 1000000", 400); + } if (segment != null && totalSegments != null && segment >= totalSegments) { throw new AwsException("ValidationException", "The Segment parameter is zero-based and must be less than parameter TotalSegments: " @@ -1299,7 +1357,9 @@ public class DynamoDbJsonHandler { List gsiUpdatesToApply = new ArrayList<>(); JsonNode gsiUpdates = request.path("GlobalSecondaryIndexUpdates"); if (!gsiUpdates.isMissingNode() && gsiUpdates.isArray()) { + var updatePosition = 0; for (JsonNode update : gsiUpdates) { + updatePosition++; JsonNode createNode = update.path("Create"); if (!createNode.isMissingNode()) { String indexName = createNode.path("IndexName").asText(); @@ -1316,6 +1376,9 @@ public class DynamoDbJsonHandler { nonKeyAttributes.add(nonKeyAttr.asText()); } } + rejectEmptyNonKeyAttributes(nonKeyAttrArray, + "globalSecondaryIndexUpdates." + updatePosition + ".member.create"); + validateProjectionSpec(projectionType, nonKeyAttributes); GlobalSecondaryIndex newGsi = new GlobalSecondaryIndex(indexName, gsiKeySchema, null, projectionType, nonKeyAttributes); JsonNode newGsiPt = createNode.path("ProvisionedThroughput"); if (!newGsiPt.isMissingNode()) { diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java index 674906388c..e64f964272 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java @@ -2630,22 +2630,15 @@ public class DynamoDbService implements ResourceProvider { if (last) { if (nextTok instanceof String finalAttr) { - if (child == null) { - ObjectNode newMap = objectMapper.createObjectNode(); - newMap.set(finalAttr, value); - - ObjectNode wrapper = objectMapper.createObjectNode(); - wrapper.set("M", newMap); - - obj.set(attrName, wrapper); - } else if (!child.has("M")) { + // AWS requires every intermediate of a document path to already + // exist as the right type; only the final element may be new. + if (child == null || !child.has("M")) { throw new AwsException( "ValidationException", "The document path provided in the update expression is invalid for update", 400); - } else { - ((ObjectNode) child.get("M")).set(finalAttr, value); } + ((ObjectNode) child.get("M")).set(finalAttr, value); } else if (nextTok instanceof Long finalIdx) { if (child == null || !child.has("L")) { throw new AwsException( @@ -2661,21 +2654,13 @@ public class DynamoDbService implements ResourceProvider { } if (nextTok instanceof String) { - if (child == null) { - ObjectNode newMap = objectMapper.createObjectNode(); - ObjectNode wrapper = objectMapper.createObjectNode(); - wrapper.set("M", newMap); - obj.set(attrName, wrapper); - - container = newMap; - } else if (!child.has("M")) { + if (child == null || !child.has("M")) { throw new AwsException( "ValidationException", "The document path provided in the update expression is invalid for update", 400); - } else { - container = child.get("M"); } + container = child.get("M"); } else if (nextTok instanceof Long) { if (child == null || !child.has("L")) { diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandlerTest.java index 3cd459a071..7cabf8ef77 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbJsonHandlerTest.java @@ -613,4 +613,305 @@ class DynamoDbJsonHandlerTest { && "ValidationException".equals(awsError.getErrorCode())), () -> assertEquals(1, describedIndexes.size())); } + + // Request validation for AWS parity: real DynamoDB rejects each of these with a + // ValidationException (paritysuite dynamodb-conformance tier1). + + private JsonNode json(String body) { + try { + return mapper.readTree(body); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private AwsException expectValidationException(String action, JsonNode request) { + var ex = assertThrows(AwsException.class, () -> handler.handle(action, request, "eu-west-1")); + assertEquals("ValidationException", ex.getErrorCode()); + return ex; + } + + @Test + void createTableRejectsProvisionedThroughputWithPayPerRequest() { + var ex = expectValidationException("CreateTable", json(""" + { + "TableName": "PprTable", + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}], + "BillingMode": "PAY_PER_REQUEST", + "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5} + } + """)); + assertEquals("One or more parameter values were invalid: Neither ReadCapacityUnits nor " + + "WriteCapacityUnits can be specified when BillingMode is PAY_PER_REQUEST", ex.getMessage()); + } + + @Test + void createTableRejectsGsiIncludeProjectionWithoutNonKeyAttributes() { + var ex = expectValidationException("CreateTable", json(""" + { + "TableName": "GsiIncTable", + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "g", "AttributeType": "S"} + ], + "BillingMode": "PAY_PER_REQUEST", + "GlobalSecondaryIndexes": [{ + "IndexName": "gsi1", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "INCLUDE"} + }] + } + """)); + assertEquals("One or more parameter values were invalid: " + + "ProjectionType is INCLUDE, but NonKeyAttributes is not specified", ex.getMessage()); + } + + @Test + void createTableRejectsLsiIncludeProjectionWithoutNonKeyAttributes() { + var ex = expectValidationException("CreateTable", json(""" + { + "TableName": "LsiIncTable", + "KeySchema": [ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"} + ], + "AttributeDefinitions": [ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "sk", "AttributeType": "S"}, + {"AttributeName": "lsiSk", "AttributeType": "S"} + ], + "BillingMode": "PAY_PER_REQUEST", + "LocalSecondaryIndexes": [{ + "IndexName": "lsi1", + "KeySchema": [ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "lsiSk", "KeyType": "RANGE"} + ], + "Projection": {"ProjectionType": "INCLUDE"} + }] + } + """)); + assertEquals("One or more parameter values were invalid: " + + "ProjectionType is INCLUDE, but NonKeyAttributes is not specified", ex.getMessage()); + } + + @Test + void createTableRejectsKeysOnlyProjectionCarryingNonKeyAttributes() { + var ex = expectValidationException("CreateTable", json(""" + { + "TableName": "KeysOnlyTable", + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "g", "AttributeType": "S"} + ], + "BillingMode": "PAY_PER_REQUEST", + "GlobalSecondaryIndexes": [{ + "IndexName": "gsi1", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "KEYS_ONLY", "NonKeyAttributes": ["x"]} + }] + } + """)); + assertEquals("One or more parameter values were invalid: " + + "ProjectionType is KEYS_ONLY, but NonKeyAttributes is specified", ex.getMessage()); + } + + @Test + void updateTableRejectsGsiIncludeProjectionWithoutNonKeyAttributes() { + createUsersTable("eu-west-1"); + var ex = expectValidationException("UpdateTable", json(""" + { + "TableName": "Users", + "AttributeDefinitions": [{"AttributeName": "g", "AttributeType": "S"}], + "GlobalSecondaryIndexUpdates": [{"Create": { + "IndexName": "gsi1", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "INCLUDE"} + }}] + } + """)); + assertEquals("One or more parameter values were invalid: " + + "ProjectionType is INCLUDE, but NonKeyAttributes is not specified", ex.getMessage()); + assertTrue(service.describeTable("Users", "eu-west-1").getGlobalSecondaryIndexes().isEmpty()); + } + + @Test + void updateTableRejectsAllProjectionCarryingNonKeyAttributes() { + createUsersTable("eu-west-1"); + var ex = expectValidationException("UpdateTable", json(""" + { + "TableName": "Users", + "AttributeDefinitions": [{"AttributeName": "g", "AttributeType": "S"}], + "GlobalSecondaryIndexUpdates": [{"Create": { + "IndexName": "gsi1", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL", "NonKeyAttributes": ["x"]} + }}] + } + """)); + assertEquals("One or more parameter values were invalid: " + + "ProjectionType is ALL, but NonKeyAttributes is specified", ex.getMessage()); + } + + // Checked against real DynamoDB: the projection is validated before the table lookup. + @Test + void updateTableValidatesGsiProjectionBeforeTableLookup() { + var ex = expectValidationException("UpdateTable", json(""" + { + "TableName": "NoSuchTable", + "AttributeDefinitions": [{"AttributeName": "g", "AttributeType": "S"}], + "GlobalSecondaryIndexUpdates": [{"Create": { + "IndexName": "gsi1", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "INCLUDE"} + }}] + } + """)); + assertEquals("One or more parameter values were invalid: " + + "ProjectionType is INCLUDE, but NonKeyAttributes is not specified", ex.getMessage()); + } + + // The empty-list, null, and index-position cases below were checked against real DynamoDB. + @Test + void createTableRejectsEmptyGsiNonKeyAttributesWithItsPosition() { + var ex = expectValidationException("CreateTable", json(""" + { + "TableName": "EmptyGsiNonKey", + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "g", "AttributeType": "S"} + ], + "BillingMode": "PAY_PER_REQUEST", + "GlobalSecondaryIndexes": [ + { + "IndexName": "gsi1", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "ALL"} + }, + { + "IndexName": "gsi2", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "KEYS_ONLY", "NonKeyAttributes": []} + } + ] + } + """)); + assertEquals("1 validation error detected: Value '[]' at " + + "'globalSecondaryIndexes.2.member.projection.nonKeyAttributes' failed to satisfy constraint: " + + "Member must have length greater than or equal to 1", ex.getMessage()); + } + + @Test + void createTableRejectsEmptyLsiNonKeyAttributes() { + var ex = expectValidationException("CreateTable", json(""" + { + "TableName": "EmptyLsiNonKey", + "KeySchema": [ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "sk", "KeyType": "RANGE"} + ], + "AttributeDefinitions": [ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "sk", "AttributeType": "S"}, + {"AttributeName": "lsiSk", "AttributeType": "S"} + ], + "BillingMode": "PAY_PER_REQUEST", + "LocalSecondaryIndexes": [{ + "IndexName": "lsi1", + "KeySchema": [ + {"AttributeName": "pk", "KeyType": "HASH"}, + {"AttributeName": "lsiSk", "KeyType": "RANGE"} + ], + "Projection": {"ProjectionType": "KEYS_ONLY", "NonKeyAttributes": []} + }] + } + """)); + assertEquals("1 validation error detected: Value '[]' at " + + "'localSecondaryIndexes.1.member.projection.nonKeyAttributes' failed to satisfy constraint: " + + "Member must have length greater than or equal to 1", ex.getMessage()); + } + + @Test + void updateTableRejectsEmptyGsiNonKeyAttributesBeforeProjectionTypeCheck() { + createUsersTable("eu-west-1"); + var ex = expectValidationException("UpdateTable", json(""" + { + "TableName": "Users", + "AttributeDefinitions": [{"AttributeName": "g", "AttributeType": "S"}], + "GlobalSecondaryIndexUpdates": [{"Create": { + "IndexName": "gsi1", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "INCLUDE", "NonKeyAttributes": []} + }}] + } + """)); + assertEquals("1 validation error detected: Value '[]' at " + + "'globalSecondaryIndexUpdates.1.member.create.projection.nonKeyAttributes' failed to satisfy constraint: " + + "Member must have length greater than or equal to 1", ex.getMessage()); + } + + @Test + void createTableTreatsNullNonKeyAttributesAsNotSpecified() throws Exception { + Response response = handler.handle("CreateTable", json(""" + { + "TableName": "NullNonKey", + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [ + {"AttributeName": "pk", "AttributeType": "S"}, + {"AttributeName": "g", "AttributeType": "S"} + ], + "BillingMode": "PAY_PER_REQUEST", + "GlobalSecondaryIndexes": [{ + "IndexName": "gsi1", + "KeySchema": [{"AttributeName": "g", "KeyType": "HASH"}], + "Projection": {"ProjectionType": "KEYS_ONLY", "NonKeyAttributes": null} + }] + } + """), "eu-west-1"); + assertEquals(200, response.getStatus()); + var gsi = service.describeTable("NullNonKey", "eu-west-1").findGsi("gsi1").orElseThrow(); + assertEquals("KEYS_ONLY", gsi.getProjectionType()); + } + + @Test + void createTableRejectsStreamViewTypeWithStreamEnabledFalse() { + var ex = expectValidationException("CreateTable", json(""" + { + "TableName": "StreamFalseTable", + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}], + "BillingMode": "PAY_PER_REQUEST", + "StreamSpecification": {"StreamEnabled": false, "StreamViewType": "NEW_AND_OLD_IMAGES"} + } + """)); + assertEquals("One or more parameter values were invalid: " + + "StreamViewType cannot be specified when StreamEnabled is false", ex.getMessage()); + } + + @Test + void scanRejectsTotalSegmentsAboveTheMaximum() { + var ex = expectValidationException("Scan", json(""" + {"TableName": "Users", "Segment": 0, "TotalSegments": 1000001} + """)); + assertEquals("1 validation error detected: Value '1000001' at 'totalSegments' failed to " + + "satisfy constraint: Member must have value less than or equal to 1000000", ex.getMessage()); + } + + @Test + void updateItemRejectsExpressionAttributeNamesWithNoExpression() { + createUsersTable("eu-west-1"); + var ex = expectValidationException("UpdateItem", json(""" + { + "TableName": "Users", + "Key": {"userId": {"S": "u1"}}, + "ExpressionAttributeNames": {"#s": "status"} + } + """)); + assertEquals("ExpressionAttributeNames can only be specified when using expressions: " + + "UpdateExpression is null, ConditionExpression is null", ex.getMessage()); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbServiceTest.java index 717aa2089b..99839dd32b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbServiceTest.java @@ -3102,10 +3102,33 @@ class DynamoDbServiceTest { return request; } + @Test + void updateItemRejectsSetThroughMissingIntermediateMapPath() { + createOrdersTable("us-east-1"); + service.putItem("Orders", item("customerId", "c9", "orderId", "o9"), "us-east-1"); + + ObjectNode exprNames = mapper.createObjectNode(); + exprNames.put("#missing", "missing"); + ObjectNode exprValues = mapper.createObjectNode(); + exprValues.set(":val", attributeValue("S", "x")); + + ObjectNode key = mapper.createObjectNode(); + key.set("customerId", attributeValue("S", "c9")); + key.set("orderId", attributeValue("S", "o9")); + + var ex = assertThrows(AwsException.class, () -> service.updateItem("Orders", key, null, + "SET #missing.subkey = :val", exprNames, exprValues, "NONE", null, "us-east-1", "NONE")); + assertEquals("The document path provided in the update expression is invalid for update", ex.getMessage()); + } + @Test void updateItemWithNestedDottedPathSetAndRemove() { createOrdersTable("us-east-1"); - service.putItem("Orders", item("customerId", "c1", "orderId", "o1"), "us-east-1"); + // AWS requires every intermediate of a document path to already exist, + // so the details map is seeded before SET #details.subkey runs. + ObjectNode initialItem = item("customerId", "c1", "orderId", "o1"); + initialItem.set("details", mapAttributeValue(mapper.createObjectNode())); + service.putItem("Orders", initialItem, "us-east-1"); ObjectNode exprNames = mapper.createObjectNode(); exprNames.put("#details", "details");