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

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

* refactor(dynamodb): share the key value error builders between writes and start keys

* fix(dynamodb): brace the Scan start key early return and pin the index key wording
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-17 09:14:44 -04:00
1 parent 9ea977cafa
commit e21d25a829
6 files changed
+245 -44

No files matched your search

@@ -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) {
@@ -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";
}
}
@@ -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) {
@@ -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(
@@ -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", """
{
@@ -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,