Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(dynamodb): report an empty or mistyped ExclusiveStartKey value the way AWS does (#5861)

TATSUNO “Taz” Yasuhiroe21d25a829d1
diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidator.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidator.java
index 2e1dcc5962..ef080efd3c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidator.java
@@ -18,8 +18,10 @@ import io.github.hectorvent.floci.services.dynamodb.ExpressionEvaluator.TokenTyp
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -439,38 +441,100 @@ final class DynamoDbAccessPathValidator {
static void validateExclusiveStartKey(JsonNode exclusiveStartKey, TableDefinition table,
DynamoDbAccessPath accessPath) {
if (exclusiveStartKey == null || exclusiveStartKey.isNull()) return;
- Set<String> expected = new HashSet<>();
- expected.add(table.getPartitionKeyName());
- String sortKey = table.getSortKeyName();
- if (sortKey != null) {
- expected.add(sortKey);
- }
- if (accessPath.isIndex()) {
- expected.addAll(accessPath.keyAttributeNames());
+ Set<String> expected = startKeyAttributeNames(table, accessPath);
+ for (String attribute : expected) {
+ JsonNode value = exclusiveStartKey.get(attribute);
+ if (value == null) {
+ continue;
+ }
+ String expectedType = startKeyAttributeType(table, attribute);
+ if (isEmptyKeyValue(value, expectedType)) {
+ throw DynamoDbKeyValueErrors.emptyKeyValue(expectedType, attribute);
+ }
+ if (expectedType == null || hasInvalidScalarValue(value, expectedType)) {
+ throw invalidStartingKey();
+ }
}
Set<String> actual = new HashSet<>();
exclusiveStartKey.fieldNames().forEachRemaining(actual::add);
- if (!actual.equals(expected) || hasInvalidKeyValue(exclusiveStartKey, table, expected)) {
+ if (!actual.equals(expected)) {
throw invalidStartingKey();
}
}
- private static boolean hasInvalidKeyValue(JsonNode exclusiveStartKey, TableDefinition table,
- Set<String> expected) {
- if (table.getAttributeDefinitions() == null) {
- return true;
+ // A Scan of a table with secondary indexes checks the key values against each index,
+ // in index name order, and names the index in the error. A Scan of an index checks
+ // only that index. With several bad values AWS reports one in no fixed order.
+ static void validateScanExclusiveStartKey(JsonNode exclusiveStartKey, TableDefinition table,
+ DynamoDbAccessPath accessPath) {
+ if (exclusiveStartKey == null || exclusiveStartKey.isNull()) {
+ return;
}
- for (String attribute : expected) {
- String expectedType = table.getAttributeDefinitions().stream()
- .filter(definition -> attribute.equals(definition.getAttributeName()))
- .map(AttributeDefinition::getAttributeType)
- .findFirst()
- .orElse(null);
- if (expectedType == null || hasInvalidScalarValue(exclusiveStartKey.get(attribute), expectedType)) {
- return true;
+ List<DynamoDbAccessPath> indexes = accessPath.isIndex()
+ ? List.of(accessPath)
+ : secondaryIndexNames(table).stream()
+ .map(indexName -> DynamoDbAccessPath.resolve(table, indexName))
+ .toList();
+ for (DynamoDbAccessPath index : indexes) {
+ Set<String> attributes = startKeyAttributeNames(table, index);
+ for (String attribute : attributes) {
+ JsonNode value = exclusiveStartKey.get(attribute);
+ String expectedType = startKeyAttributeType(table, attribute);
+ if (value != null && value.isObject() && !value.isEmpty()
+ && expectedType != null && !value.has(expectedType)) {
+ throw DynamoDbKeyValueErrors.indexKeyTypeMismatch(attribute, expectedType,
+ value.fieldNames().next(), index.indexName());
+ }
+ }
+ for (String attribute : attributes) {
+ JsonNode value = exclusiveStartKey.get(attribute);
+ String expectedType = startKeyAttributeType(table, attribute);
+ if (value != null && isEmptyKeyValue(value, expectedType)) {
+ throw DynamoDbKeyValueErrors.emptyIndexKeyValue(expectedType, index.indexName(), attribute);
+ }
}
}
- return false;
+ validateExclusiveStartKey(exclusiveStartKey, table, accessPath);
+ }
+
+ private static Set<String> startKeyAttributeNames(TableDefinition table, DynamoDbAccessPath accessPath) {
+ Set<String> names = new LinkedHashSet<>();
+ if (accessPath.isIndex()) {
+ accessPath.keySchema().forEach(key -> names.add(key.getAttributeName()));
+ }
+ names.add(table.getPartitionKeyName());
+ if (table.getSortKeyName() != null) {
+ names.add(table.getSortKeyName());
+ }
+ return names;
+ }
+
+ private static List<String> secondaryIndexNames(TableDefinition table) {
+ List<String> names = new ArrayList<>();
+ if (table.getGlobalSecondaryIndexes() != null) {
+ table.getGlobalSecondaryIndexes().forEach(gsi -> names.add(gsi.getIndexName()));
+ }
+ if (table.getLocalSecondaryIndexes() != null) {
+ table.getLocalSecondaryIndexes().forEach(lsi -> names.add(lsi.getIndexName()));
+ }
+ return names.stream().sorted().toList();
+ }
+
+ private static String startKeyAttributeType(TableDefinition table, String attribute) {
+ if (table.getAttributeDefinitions() == null) {
+ return null;
+ }
+ return table.getAttributeDefinitions().stream()
+ .filter(definition -> attribute.equals(definition.getAttributeName()))
+ .map(AttributeDefinition::getAttributeType)
+ .findFirst()
+ .orElse(null);
+ }
+
+ private static boolean isEmptyKeyValue(JsonNode value, String expectedType) {
+ return ("S".equals(expectedType) || "B".equals(expectedType))
+ && value.isObject() && value.size() == 1
+ && value.path(expectedType).isTextual() && value.get(expectedType).textValue().isEmpty();
}
private static boolean hasInvalidScalarValue(JsonNode value, String expectedType) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbKeyValueErrors.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbKeyValueErrors.java
new file mode 100644
index 0000000000..cfd243344a
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbKeyValueErrors.java
@@ -0,0 +1,35 @@
+package io.github.hectorvent.floci.services.dynamodb;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+
+final class DynamoDbKeyValueErrors {
+
+ private DynamoDbKeyValueErrors() {
+ }
+
+ static AwsException emptyKeyValue(String type, String keyName) {
+ return new AwsException("ValidationException",
+ "One or more parameter values are not valid. "
+ + "The AttributeValue for a key attribute cannot contain an "
+ + emptyValueKind(type) + ". Key: " + keyName, 400);
+ }
+
+ static AwsException emptyIndexKeyValue(String type, String indexName, String attributeName) {
+ return 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 " + emptyValueKind(type) + ". IndexName: " + indexName
+ + ", IndexKey: " + attributeName, 400);
+ }
+
+ static KeySchemaMismatchException indexKeyTypeMismatch(String attributeName, String expectedType,
+ String actualType, String indexName) {
+ return new KeySchemaMismatchException(
+ "One or more parameter values were invalid: Type mismatch for Index Key " + attributeName
+ + " Expected: " + expectedType + " Actual: " + actualType + " IndexName: " + indexName);
+ }
+
+ static String emptyValueKind(String type) {
+ return "B".equals(type) ? "empty binary value" : "empty string value";
+ }
+}
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 7c7d0c1651..cbfc6f799a 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
@@ -4095,16 +4095,10 @@ public class DynamoDbService {
throw new KeySchemaMismatchException("The provided key element does not match the schema");
}
if (attr.has("S") && attr.get("S").asText().isEmpty()) {
- throw new AwsException("ValidationException",
- "One or more parameter values are not valid. "
- + "The AttributeValue for a key attribute cannot contain an empty string value. Key: "
- + keyName, 400);
+ throw DynamoDbKeyValueErrors.emptyKeyValue("S", keyName);
}
if (attr.has("B") && attr.get("B").asText().isEmpty()) {
- throw new AwsException("ValidationException",
- "One or more parameter values are not valid. "
- + "The AttributeValue for a key attribute cannot contain an empty binary value. Key: "
- + keyName, 400);
+ throw DynamoDbKeyValueErrors.emptyKeyValue("B", keyName);
}
}
@@ -4199,33 +4193,29 @@ public class DynamoDbService {
validateAttributeValueShape(attr);
String expectedType = keyAttributeType(table, attrName);
if (expectedType != null && !attr.has(expectedType)) {
- throw new KeySchemaMismatchException(
- "One or more parameter values were invalid: Type mismatch for Index Key " + attrName
- + " Expected: " + expectedType + " Actual: " + attr.fieldNames().next()
- + " IndexName: " + indexName);
+ throw DynamoDbKeyValueErrors.indexKeyTypeMismatch(attrName, expectedType,
+ attr.fieldNames().next(), indexName);
}
if (attr.has("S") && attr.get("S").asText().isEmpty()) {
- throw emptyIndexKeyValue("empty string value", indexName, attrName, isUpdate);
+ throw emptyIndexKeyValue("S", indexName, attrName, isUpdate);
}
if (attr.has("B") && attr.get("B").asText().isEmpty()) {
- throw emptyIndexKeyValue("empty binary value", indexName, attrName, isUpdate);
+ throw emptyIndexKeyValue("B", indexName, attrName, isUpdate);
}
}
}
// AWS uses different wording for UpdateItem than for writes of a whole item.
- private static AwsException emptyIndexKeyValue(String what, String indexName, String attrName,
+ private static AwsException emptyIndexKeyValue(String type, String indexName, String attrName,
boolean isUpdate) {
if (isUpdate) {
return 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 " + what + ".", 400);
+ + "The AttributeValue for a key attribute cannot contain an "
+ + DynamoDbKeyValueErrors.emptyValueKind(type) + ".", 400);
}
- return 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 " + what + ". IndexName: " + indexName + ", IndexKey: " + attrName, 400);
+ return DynamoDbKeyValueErrors.emptyIndexKeyValue(type, indexName, attrName);
}
private String buildItemKeyFromNode(JsonNode item, String pkName, String skName) {
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 60a4e0fcd3..f38f5c8b1a 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
@@ -1305,7 +1305,7 @@ public class NativeDynamoDbJsonHandler {
rejectConsistentReadOnGsi(request, scanAccessPath);
if (exclusiveStartKey != null) {
- DynamoDbAccessPathValidator.validateExclusiveStartKey(exclusiveStartKey, scanTable, scanAccessPath);
+ DynamoDbAccessPathValidator.validateScanExclusiveStartKey(exclusiveStartKey, scanTable, scanAccessPath);
}
DynamoDbService.ScanResult result = dynamoDbService.scan(
diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathIntegrationTest.java
index 962ff9409f..14979bf648 100644
--- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathIntegrationTest.java
@@ -341,7 +341,8 @@ class DynamoDbAccessPathIntegrationTest {
""".formatted(TABLE))
.statusCode(400)
.body("__type", equalTo("ValidationException"))
- .body("message", equalTo("The provided starting key is invalid"));
+ .body("message", equalTo("One or more parameter values were invalid: Type mismatch for Index Key sk "
+ + "Expected: S Actual: BOOL IndexName: alternate-index"));
request("DynamoDB_20120810.Query", """
{
diff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidatorTest.java
index a2d3f05bc3..430cd092e1 100644
--- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidatorTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbAccessPathValidatorTest.java
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.dynamodb;
+import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
@@ -421,6 +422,116 @@ class DynamoDbAccessPathValidatorTest {
indexOnly.getMessage());
}
+ @Test
+ void queryNamesAnEmptyStartKeyValueInKeySchemaOrder() {
+ AwsException tableKey = assertThrows(AwsException.class,
+ () -> DynamoDbAccessPathValidator.validateExclusiveStartKey(
+ mapper.readTree("""
+ {"sk": {"S": ""}, "pk": {"S": ""}, "other": {"S": "x"}}
+ """), table, tablePath));
+ assertEquals("One or more parameter values are not valid. The AttributeValue for a key attribute "
+ + "cannot contain an empty string value. Key: pk", tableKey.getMessage());
+
+ AwsException indexKey = assertThrows(AwsException.class,
+ () -> DynamoDbAccessPathValidator.validateExclusiveStartKey(
+ mapper.readTree("""
+ {"pk": {"S": ""}, "sk": {"S": "a"}, "status": {"S": ""},
+ "createdAt": {"S": "a"}, "sequence": {"S": "a"}}
+ """), table, gsiPath));
+ assertEquals("One or more parameter values are not valid. The AttributeValue for a key attribute "
+ + "cannot contain an empty string value. Key: status", indexKey.getMessage());
+ }
+
+ @Test
+ void queryReportsAWrongStartKeyTypeBeforeALaterEmptyValue() {
+ AwsException error = assertThrows(AwsException.class,
+ () -> DynamoDbAccessPathValidator.validateExclusiveStartKey(
+ mapper.readTree("""
+ {"pk": {"N": "1"}, "sk": {"S": ""}}
+ """), table, tablePath));
+ assertEquals("The provided starting key is invalid", error.getMessage());
+ }
+
+ @Test
+ void scanNamesTheFirstIndexByNameForABadTableKey() {
+ AwsException empty = assertThrows(AwsException.class,
+ () -> DynamoDbAccessPathValidator.validateScanExclusiveStartKey(
+ mapper.readTree("""
+ {"pk": {"S": ""}, "sk": {"S": "a"}}
+ """), table, tablePath));
+ 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: alternate-index, IndexKey: pk", empty.getMessage());
+
+ AwsException mismatch = assertThrows(AwsException.class,
+ () -> DynamoDbAccessPathValidator.validateScanExclusiveStartKey(
+ mapper.readTree("""
+ {"pk": {"S": ""}, "sk": {"BOOL": true}}
+ """), table, tablePath));
+ assertEquals("One or more parameter values were invalid: Type mismatch for Index Key sk "
+ + "Expected: S Actual: BOOL IndexName: alternate-index", mismatch.getMessage());
+ }
+
+ @Test
+ void scanNamesTheIndexThatOwnsABadIndexKey() {
+ AwsException error = assertThrows(AwsException.class,
+ () -> DynamoDbAccessPathValidator.validateScanExclusiveStartKey(
+ mapper.readTree("""
+ {"pk": {"S": "a"}, "sk": {"S": "a"}, "tenantId": {"S": ""}}
+ """), table, tablePath));
+ 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: tenant-region-index, IndexKey: tenantId", error.getMessage());
+ }
+
+ @Test
+ void scanOfAnIndexChecksOnlyThatIndex() {
+ AwsException error = assertThrows(AwsException.class,
+ () -> DynamoDbAccessPathValidator.validateScanExclusiveStartKey(
+ mapper.readTree("""
+ {"pk": {"S": "a"}, "sk": {"S": "a"}, "status": {"S": "a"},
+ "createdAt": {"S": "a"}, "sequence": {"S": "a"}, "alternate": {"S": ""}}
+ """), table, gsiPath));
+ assertEquals("The provided starting key is invalid", error.getMessage());
+ }
+
+ @Test
+ void anEmptyIndexKeyGetsTheKeyWordingFromQueryAndTheIndexWordingFromScan() throws Exception {
+ JsonNode startKey = mapper.readTree("""
+ {"pk": {"S": "a"}, "sk": {"S": "a"}, "alternate": {"S": ""}}
+ """);
+
+ AwsException query = assertThrows(AwsException.class,
+ () -> DynamoDbAccessPathValidator.validateExclusiveStartKey(startKey, table, lsiPath));
+ assertEquals("One or more parameter values are not valid. The AttributeValue for a key attribute "
+ + "cannot contain an empty string value. Key: alternate", query.getMessage());
+
+ AwsException scan = assertThrows(AwsException.class,
+ () -> DynamoDbAccessPathValidator.validateScanExclusiveStartKey(startKey, table, lsiPath));
+ 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: alternate-index, IndexKey: alternate", scan.getMessage());
+ }
+
+ @Test
+ void scanOfATableWithoutIndexesUsesTheKeyWording() {
+ TableDefinition plain = new TableDefinition();
+ plain.setKeySchema(List.of(
+ new KeySchemaElement("pk", "HASH"),
+ new KeySchemaElement("sk", "RANGE")));
+ plain.setAttributeDefinitions(List.of(
+ new AttributeDefinition("pk", "S"),
+ new AttributeDefinition("sk", "B")));
+
+ AwsException error = assertThrows(AwsException.class,
+ () -> DynamoDbAccessPathValidator.validateScanExclusiveStartKey(
+ mapper.readTree("""
+ {"pk": {"S": "a"}, "sk": {"B": ""}}
+ """), plain, DynamoDbAccessPath.resolve(plain, null)));
+ assertEquals("One or more parameter values are not valid. The AttributeValue for a key attribute "
+ + "cannot contain an empty binary value. Key: sk", error.getMessage());
+ }
+
private void validateExpression(DynamoDbAccessPath accessPath, String expression) {
DynamoDbAccessPathValidator.validateQuery(
table, accessPath, null, expression, null, null, null,