Light, fluffy, and always free - The AWS Local Emulator alternative
fix(dynamodb): reject key attribute values whose type does not match the key schema (#2625)
Stuart Langbf6c7b001cbe
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.javaindex bc56e39dbb..9b69cb9b4f 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@@ -90,6 +90,13 @@ final class DynamoDbNumberUtils {private static JsonNode normalizeAttrValue(JsonNode attr) {if (attr == null) return null;+ // A well-formed AttributeValue has exactly one type member. Rebuilding a+ // malformed one (e.g. {"S":"x","N":"1"}) around its "N" member would launder+ // it into a valid value before validation can reject it — pass it through.+ if (attr.isObject() && attr.size() != 1) {+ return attr;+ }+if (attr.has("N")) {String raw = attr.get("N").asText();String normalized = validateAndNormalize(raw);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.javaindex f0aee01670..c690975b29 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@@ -512,6 +512,7 @@ public class DynamoDbService implements ResourceProvider {final JsonNode normalizedItem = DynamoDbNumberUtils.normalizeNumbersInItem(item);DynamoDbItemSize.validateSize(normalizedItem);String itemKey = buildItemKey(table, normalizedItem);+ validateIndexKeyTypes(table, normalizedItem, false);withItemLock(storageKey, itemKey, () -> {var tableItems = itemsByTable.computeIfAbsent(scopedItemsKey(storageKey), k -> new ConcurrentSkipListMap<>());@@ -733,6 +734,9 @@ public class DynamoDbService implements ResourceProvider {}}+ // AWS validates index key values against the item the update produces.+ validateIndexKeyTypes(table, item, true);+items.put(itemKey, item);persistItems(storageKey);LOG.tracev("Updated item in {0}: key={1} updateExpression={2} item={3}",@@ -2548,7 +2552,7 @@ public class DynamoDbService implements ResourceProvider {throw new AwsException("ValidationException","One of the required keys was not given a value", 400);}- validateKeyAttributeValue(pkAttr, pkName);+ validateKeyAttributeValue(table, pkAttr, pkName, isKeyArg);String pk = extractScalarValue(pkAttr);String skName = table.getSortKeyName();@@ -2562,20 +2566,116 @@ public class DynamoDbService implements ResourceProvider {throw new AwsException("ValidationException","One of the required keys was not given a value", 400);}- validateKeyAttributeValue(skAttr, skName);+ validateKeyAttributeValue(table, skAttr, skName, isKeyArg);return pk + "#" + extractScalarValue(skAttr);}return pk;}- private void validateKeyAttributeValue(JsonNode attr, String keyName) {- if (attr != null && attr.has("S") && attr.get("S").asText().isEmpty()) {+ // A wire-format AttributeValue must be a JSON object with exactly one type member.+ // AWS enforces this for every attribute value; floci additionally relies on it+ // wherever a value becomes part of a storage or index key.+ private void validateAttributeValueShape(JsonNode attr) {+ if (!attr.isObject()) {+ // AWS's protocol layer rejects non-object values before validation runs.+ throw new AwsException("SerializationException", "Unexpected value type in payload", 400);+ }+ if (attr.isEmpty()) {+ throw new AwsException("ValidationException",+ "Supplied AttributeValue is empty, must contain exactly one of the supported datatypes", 400);+ }+ if (attr.size() > 1) {+ throw new AwsException("ValidationException",+ "Supplied AttributeValue has more than one datatypes set, "+ + "must contain exactly one of the supported datatypes", 400);+ }+ }++ private void validateKeyAttributeValue(TableDefinition table, JsonNode attr, String keyName, boolean isKeyArg) {+ if (attr == null) {+ return;+ }+ validateAttributeValueShape(attr);+ String expectedType = keyAttributeType(table, keyName);+ if (expectedType != null && !attr.has(expectedType)) {+ // AWS words the type mismatch differently for a Key argument+ // (Get/Delete/Update) than for a PutItem item body.+ if (isKeyArg) {+ throw new AwsException("ValidationException",+ "The provided key element does not match the schema", 400);+ }+ throw new AwsException("ValidationException",+ "One or more parameter values were invalid: Type mismatch for key " + keyName+ + " expected: " + expectedType + " actual: " + attr.fieldNames().next(), 400);+ }+ if (attr.has("S") && attr.get("S").asText().isEmpty()) {throw new AwsException("ValidationException","One or more parameter values were invalid: "+ "The AttributeValue for a key attribute cannot contain an empty string value. Key: " + keyName, 400);}}+ private String keyAttributeType(TableDefinition table, String keyName) {+ if (table.getAttributeDefinitions() == null) {+ return null;+ }+ return table.getAttributeDefinitions().stream()+ .filter(def -> keyName.equals(def.getAttributeName()))+ .map(AttributeDefinition::getAttributeType)+ .findFirst().orElse(null);+ }++ // AWS validates GSI/LSI key attribute values on every write that produces the item,+ // but only when the attribute is present — sparse indexes allow it to be absent.+ private void validateIndexKeyTypes(TableDefinition table, JsonNode item, boolean isUpdate) {+ if (table.getGlobalSecondaryIndexes() != null) {+ for (GlobalSecondaryIndex gsi : table.getGlobalSecondaryIndexes()) {+ validateIndexKeySchema(table, item, gsi.getIndexName(), gsi.getKeySchema(), isUpdate);+ }+ }+ if (table.getLocalSecondaryIndexes() != null) {+ for (LocalSecondaryIndex lsi : table.getLocalSecondaryIndexes()) {+ validateIndexKeySchema(table, item, lsi.getIndexName(), lsi.getKeySchema(), isUpdate);+ }+ }+ }++ private void validateIndexKeySchema(TableDefinition table, JsonNode item,+ String indexName, List<KeySchemaElement> keySchema,+ boolean isUpdate) {+ if (keySchema == null) {+ return;+ }+ for (KeySchemaElement element : keySchema) {+ String attrName = element.getAttributeName();+ JsonNode attr = item.get(attrName);+ if (attr == null) {+ continue;+ }+ validateAttributeValueShape(attr);+ String expectedType = keyAttributeType(table, attrName);+ if (expectedType != null && !attr.has(expectedType)) {+ throw new AwsException("ValidationException",+ "One or more parameter values were invalid: Type mismatch for Index Key " + attrName+ + " Expected: " + expectedType + " Actual: " + attr.fieldNames().next()+ + " IndexName: " + indexName, 400);+ }+ if (attr.has("S") && attr.get("S").asText().isEmpty()) {+ // AWS uses different wording for UpdateItem than for writes of a whole item.+ if (isUpdate) {+ throw new AwsException("ValidationException",+ "One or more parameter values are not valid. The update expression attempted to "+ + "update a secondary index key to a value that is not supported. "+ + "The AttributeValue for a key attribute cannot contain an empty string value.", 400);+ }+ throw new AwsException("ValidationException",+ "One or more parameter values are not valid. A value specified for a secondary "+ + "index key is not supported. The AttributeValue for a key attribute cannot "+ + "contain an empty string value. IndexName: " + indexName + ", IndexKey: " + attrName, 400);+ }+ }+ }+private String buildItemKeyFromNode(JsonNode item, String pkName, String skName) {return buildItemKeyFromNode(item, pkName, skName == null ? List.of() : List.of(skName));}diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbIntegrationTest.javaindex dfb847e197..b3cf9f940e 100644--- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbIntegrationTest.java@@ -3436,6 +3436,80 @@ given()deleteTable(tableName);}+ @Test+ void nullTypedKeyAttributeIsRejected() {+ given()+ .header("X-Amz-Target", "DynamoDB_20120810.CreateTable")+ .contentType(DYNAMODB_CONTENT_TYPE)+ .body("""+ {+ "TableName": "NullKeyTable",+ "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}],+ "AttributeDefinitions": [{"AttributeName": "id", "AttributeType": "S"}],+ "BillingMode": "PAY_PER_REQUEST"+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(200);++ // PutItem: mismatch is reported against the item body.+ given()+ .header("X-Amz-Target", "DynamoDB_20120810.PutItem")+ .contentType(DYNAMODB_CONTENT_TYPE)+ .body("""+ {+ "TableName": "NullKeyTable",+ "Item": {"id": {"NULL": true}, "name": {"S": "created"}}+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("One or more parameter values were invalid: "+ + "Type mismatch for key id expected: S actual: NULL"));++ // UpdateItem: mismatch in the Key argument uses the key-schema wording.+ given()+ .header("X-Amz-Target", "DynamoDB_20120810.UpdateItem")+ .contentType(DYNAMODB_CONTENT_TYPE)+ .body("""+ {+ "TableName": "NullKeyTable",+ "Key": {"id": {"NULL": true}},+ "UpdateExpression": "SET #n = :v",+ "ExpressionAttributeNames": {"#n": "name"},+ "ExpressionAttributeValues": {":v": {"S": "updated"}}+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", equalTo("The provided key element does not match the schema"));++ // Control: NULL is a valid type for a non-key attribute.+ given()+ .header("X-Amz-Target", "DynamoDB_20120810.PutItem")+ .contentType(DYNAMODB_CONTENT_TYPE)+ .body("""+ {+ "TableName": "NullKeyTable",+ "Item": {"id": {"S": "1"}, "name": {"NULL": true}}+ }+ """)+ .when()+ .post("/")+ .then()+ .statusCode(200);++ deleteTable("NullKeyTable");+ }+private void deleteTable(String tableName) {given().header("X-Amz-Target", "DynamoDB_20120810.DeleteTable")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.javaindex 1c58c2ba7c..da201d3776 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@@ -2090,6 +2090,310 @@ class DynamoDbServiceTest {assertEquals("ValidationException", ex.getErrorCode());}+ @Test+ void putItemNullPartitionKeyThrowsTypeMismatch() {+ String region = "eu-west-1";+ createUsersTable(region);++ ObjectNode nullKeyItem = mapper.createObjectNode();+ nullKeyItem.set("userId", mapper.createObjectNode().put("NULL", true));+ nullKeyItem.set("name", attributeValue("S", "created"));++ AwsException ex = assertThrows(AwsException.class, () ->+ service.putItem("Users", nullKeyItem, region));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("One or more parameter values were invalid: "+ + "Type mismatch for key userId expected: S actual: NULL", ex.getMessage());+ }++ @Test+ void putItemWrongScalarTypePartitionKeyThrowsTypeMismatch() {+ String region = "eu-west-1";+ createUsersTable(region);++ ObjectNode numberKeyItem = mapper.createObjectNode();+ numberKeyItem.set("userId", attributeValue("N", "42"));++ AwsException ex = assertThrows(AwsException.class, () ->+ service.putItem("Users", numberKeyItem, region));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("One or more parameter values were invalid: "+ + "Type mismatch for key userId expected: S actual: N", ex.getMessage());+ }++ @Test+ void putItemNullSortKeyThrowsTypeMismatch() {+ String region = "eu-west-1";+ createOrdersTable(region);++ ObjectNode nullSkItem = item("customerId", "c1");+ nullSkItem.set("orderId", mapper.createObjectNode().put("NULL", true));++ AwsException ex = assertThrows(AwsException.class, () ->+ service.putItem("Orders", nullSkItem, region));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("One or more parameter values were invalid: "+ + "Type mismatch for key orderId expected: S actual: NULL", ex.getMessage());+ }++ @Test+ void putItemNullNonKeyAttributeIsAccepted() {+ String region = "eu-west-1";+ createUsersTable(region);++ ObjectNode nullAttrItem = item("userId", "u1");+ nullAttrItem.set("name", mapper.createObjectNode().put("NULL", true));+ service.putItem("Users", nullAttrItem, region);++ JsonNode stored = service.getItem("Users", item("userId", "u1"), region);+ assertNotNull(stored);+ assertTrue(stored.get("name").get("NULL").asBoolean());+ }++ @Test+ void putItemMultiTypeKeyValueThrowsValidationException() {+ String region = "eu-west-1";+ createUsersTable(region);++ ObjectNode multiTypeItem = mapper.createObjectNode();+ multiTypeItem.set("userId", mapper.createObjectNode().put("S", "1").put("NULL", true));++ AwsException ex = assertThrows(AwsException.class, () ->+ service.putItem("Users", multiTypeItem, region));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("Supplied AttributeValue has more than one datatypes set, "+ + "must contain exactly one of the supported datatypes", ex.getMessage());+ }++ @Test+ void putItemEmptyKeyValueThrowsValidationException() {+ String region = "eu-west-1";+ createUsersTable(region);++ ObjectNode emptyValueItem = mapper.createObjectNode();+ emptyValueItem.set("userId", mapper.createObjectNode());++ AwsException ex = assertThrows(AwsException.class, () ->+ service.putItem("Users", emptyValueItem, region));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("Supplied AttributeValue is empty, "+ + "must contain exactly one of the supported datatypes", ex.getMessage());+ }++ @Test+ void putItemNonObjectKeyValueThrowsSerializationException() {+ String region = "eu-west-1";+ createUsersTable(region);++ ObjectNode rawValueItem = mapper.createObjectNode();+ rawValueItem.put("userId", "1");++ AwsException ex = assertThrows(AwsException.class, () ->+ service.putItem("Users", rawValueItem, region));+ assertEquals("SerializationException", ex.getErrorCode());+ }++ private TableDefinition createIndexedTable(String region) {+ GlobalSecondaryIndex gsi = new GlobalSecondaryIndex("gsi1",+ List.of(new KeySchemaElement("gsiKey", "HASH")), null, "ALL", null);+ LocalSecondaryIndex lsi = new LocalSecondaryIndex("lsi1",+ List.of(+ new KeySchemaElement("customerId", "HASH"),+ new KeySchemaElement("lsiKey", "RANGE")), null, "ALL");+ return service.createTable("Indexed",+ List.of(+ new KeySchemaElement("customerId", "HASH"),+ new KeySchemaElement("orderId", "RANGE")),+ List.of(+ new AttributeDefinition("customerId", "S"),+ new AttributeDefinition("orderId", "S"),+ new AttributeDefinition("gsiKey", "S"),+ new AttributeDefinition("lsiKey", "N")),+ 5L, 5L, List.of(gsi), List.of(lsi), region);+ }++ @Test+ void putItemNullGsiKeyThrowsIndexTypeMismatch() {+ String region = "eu-west-1";+ createIndexedTable(region);++ ObjectNode nullGsiItem = item("customerId", "c1", "orderId", "o1");+ nullGsiItem.set("gsiKey", mapper.createObjectNode().put("NULL", true));++ AwsException ex = assertThrows(AwsException.class, () ->+ service.putItem("Indexed", nullGsiItem, region));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("One or more parameter values were invalid: "+ + "Type mismatch for Index Key gsiKey Expected: S Actual: NULL IndexName: gsi1",+ ex.getMessage());+ }++ @Test+ void putItemWrongTypeLsiKeyThrowsIndexTypeMismatch() {+ String region = "eu-west-1";+ createIndexedTable(region);++ ObjectNode wrongLsiItem = item("customerId", "c1", "orderId", "o1", "lsiKey", "oops");++ AwsException ex = assertThrows(AwsException.class, () ->+ service.putItem("Indexed", wrongLsiItem, region));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("One or more parameter values were invalid: "+ + "Type mismatch for Index Key lsiKey Expected: N Actual: S IndexName: lsi1",+ ex.getMessage());+ }++ @Test+ void putItemOmittingIndexKeyAttributesIsAccepted() {+ String region = "eu-west-1";+ createIndexedTable(region);++ // Sparse index: absent GSI/LSI key attributes are valid.+ service.putItem("Indexed", item("customerId", "c1", "orderId", "o1"), region);++ assertNotNull(service.getItem("Indexed",+ item("customerId", "c1", "orderId", "o1"), region));+ }++ @Test+ void updateItemSettingWrongTypeGsiKeyThrowsIndexTypeMismatch() {+ String region = "eu-west-1";+ createIndexedTable(region);+ service.putItem("Indexed", item("customerId", "c1", "orderId", "o1"), region);++ ObjectNode exprValues = mapper.createObjectNode();+ exprValues.set(":v", mapper.createObjectNode().put("NULL", true));++ AwsException ex = assertThrows(AwsException.class, () ->+ service.updateItem("Indexed", item("customerId", "c1", "orderId", "o1"), null,+ "SET gsiKey = :v", null, exprValues, null, region));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("One or more parameter values were invalid: "+ + "Type mismatch for Index Key gsiKey Expected: S Actual: NULL IndexName: gsi1",+ ex.getMessage());+ }++ @Test+ void putItemMultiTypeGsiKeyValueThrowsValidationException() {+ String region = "eu-west-1";+ createIndexedTable(region);++ ObjectNode multiTypeGsiItem = item("customerId", "c1", "orderId", "o1");+ multiTypeGsiItem.set("gsiKey", mapper.createObjectNode().put("S", "x").put("N", "1"));++ AwsException ex = assertThrows(AwsException.class, () ->+ service.putItem("Indexed", multiTypeGsiItem, region));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("Supplied AttributeValue has more than one datatypes set, "+ + "must contain exactly one of the supported datatypes", ex.getMessage());+ }++ @Test+ void putItemEmptyObjectGsiKeyValueThrowsValidationException() {+ String region = "eu-west-1";+ createIndexedTable(region);++ ObjectNode emptyGsiItem = item("customerId", "c1", "orderId", "o1");+ emptyGsiItem.set("gsiKey", mapper.createObjectNode());++ AwsException ex = assertThrows(AwsException.class, () ->+ service.putItem("Indexed", emptyGsiItem, region));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("Supplied AttributeValue is empty, "+ + "must contain exactly one of the supported datatypes", ex.getMessage());+ }++ @Test+ void putItemNonObjectGsiKeyValueThrowsSerializationException() {+ String region = "eu-west-1";+ createIndexedTable(region);++ ObjectNode rawGsiItem = item("customerId", "c1", "orderId", "o1");+ rawGsiItem.put("gsiKey", "x");++ AwsException ex = assertThrows(AwsException.class, () ->+ service.putItem("Indexed", rawGsiItem, region));+ assertEquals("SerializationException", ex.getErrorCode());+ }++ @Test+ void putItemEmptyStringGsiKeyThrowsValidationException() {+ String region = "eu-west-1";+ createIndexedTable(region);++ ObjectNode emptyStringGsiItem = item("customerId", "c1", "orderId", "o1", "gsiKey", "");++ AwsException ex = assertThrows(AwsException.class, () ->+ service.putItem("Indexed", emptyStringGsiItem, region));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("One or more parameter values are not valid. A value specified for a secondary "+ + "index key is not supported. The AttributeValue for a key attribute cannot "+ + "contain an empty string value. IndexName: gsi1, IndexKey: gsiKey", ex.getMessage());+ }++ @Test+ void updateItemSettingEmptyStringGsiKeyThrowsValidationException() {+ String region = "eu-west-1";+ createIndexedTable(region);+ service.putItem("Indexed", item("customerId", "c1", "orderId", "o1"), region);++ ObjectNode exprValues = mapper.createObjectNode();+ exprValues.set(":v", attributeValue("S", ""));++ AwsException ex = assertThrows(AwsException.class, () ->+ service.updateItem("Indexed", item("customerId", "c1", "orderId", "o1"), null,+ "SET gsiKey = :v", null, exprValues, null, region));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("One or more parameter values are not valid. The update expression attempted to "+ + "update a secondary index key to a value that is not supported. "+ + "The AttributeValue for a key attribute cannot contain an empty string value.", ex.getMessage());+ }++ @Test+ void updateItemNullPartitionKeyThrowsValidationException() {+ String region = "eu-west-1";+ createUsersTable(region);++ ObjectNode nullKey = mapper.createObjectNode();+ nullKey.set("userId", mapper.createObjectNode().put("NULL", true));+ ObjectNode exprValues = mapper.createObjectNode();+ exprValues.set(":val", attributeValue("S", "updated"));++ AwsException ex = assertThrows(AwsException.class, () ->+ service.updateItem("Users", nullKey, null,+ "SET name = :val", null, exprValues, null, region));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("The provided key element does not match the schema", ex.getMessage());+ }++ @Test+ void getItemNullPartitionKeyThrowsValidationException() {+ String region = "eu-west-1";+ createUsersTable(region);++ ObjectNode nullKey = mapper.createObjectNode();+ nullKey.set("userId", mapper.createObjectNode().put("NULL", true));++ AwsException ex = assertThrows(AwsException.class, () ->+ service.getItem("Users", nullKey, region));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("The provided key element does not match the schema", ex.getMessage());+ }++ @Test+ void deleteItemNullPartitionKeyThrowsValidationException() {+ String region = "eu-west-1";+ createUsersTable(region);++ ObjectNode nullKey = mapper.createObjectNode();+ nullKey.set("userId", mapper.createObjectNode().put("NULL", true));++ AwsException ex = assertThrows(AwsException.class, () ->+ service.deleteItem("Users", nullKey, region));+ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("The provided key element does not match the schema", ex.getMessage());+ }+@Testvoid updateExpressionAcceptsNewlineBetweenSetAndAdd() {String region = "eu-west-1";