fix(dynamodb): refuse duplicate set members, empty sets and false NULLs in every item operation (#7255)

* fix(dynamodb): refuse duplicate set members, empty sets and false NULLs in every item operation

* fix(dynamodb): read a NULL flag written as a string in any case

* fix(dynamodb): store a NULL flag written as a string as true and compare NULL values by type

* refactor(dynamodb): share the empty set and false NULL messages between both value checks
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-01 21:33:51 -04:00
1 parent 9a1908ff25
commit e0d199c359
7 files changed
+349 -61

No files matched your search

@@ -6,6 +6,9 @@ import io.github.hectorvent.floci.core.common.AwsException;
import java.util.Base64;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Checks a wire-format AttributeValue the way AWS does before a request runs.
@@ -18,8 +21,137 @@ final class DynamoDbAttributeValueValidator {
static final int MAX_NESTING_LEVELS = 32;
private static final String INVALID = "One or more parameter values were invalid: ";
static final String FALSE_NULL = INVALID + "Null attribute value types must have the value of true";
// Rust's Debug format also escapes these Other_Grapheme_Extend characters.
private static final Set<Integer> SPACING_GRAPHEME_EXTENDERS = Set.of(
0x09BE, 0x09D7, 0x0B3E, 0x0B57, 0x0BBE, 0x0BD7, 0x0CC2, 0x0CD5, 0x0CD6, 0x0D3E, 0x0D57,
0x0DCF, 0x0DDF, 0x1B35, 0x302E, 0x302F, 0xFF9E, 0xFF9F, 0x1133E, 0x11357, 0x114B0,
0x114BD, 0x115AF, 0x11930, 0x1D165, 0x1D16E, 0x1D16F, 0x1D170, 0x1D171, 0x1D172);
private DynamoDbAttributeValueValidator() {}
// DynamoDB reads the values of a request member in order and refuses the first one it cannot store.
static void requireStorable(JsonNode values, String prefix) {
String problem = firstProblem(values);
if (problem != null) {
throw validationEx(prefix + problem);
}
}
private static String firstProblem(JsonNode values) {
for (JsonNode value : values) {
String problem = problemOf(value);
if (problem != null) {
return problem;
}
}
return null;
}
// DynamoDB reads a NULL flag written as a string in any case.
static boolean hasFalseNull(JsonNode value) {
JsonNode flag = value.get("NULL");
if (flag == null) {
return false;
}
return flag.isTextual() ? !"true".equalsIgnoreCase(flag.textValue()) : !flag.asBoolean();
}
private static String problemOf(JsonNode value) {
if (hasFalseNull(value)) {
return FALSE_NULL;
}
if (value.path("N").isTextual()) {
String problem = DynamoDbNumberUtils.itemNumberProblem(value.get("N").asText());
if (problem != null) {
return problem;
}
}
for (String setType : List.of("NS", "SS", "BS")) {
if (value.has(setType)) {
String problem = setProblem(setType, value.get(setType));
if (problem != null) {
return problem;
}
}
}
String problem = firstProblem(value.path("L"));
return problem != null ? problem : firstProblem(value.path("M"));
}
// A number set is read in full before its members are compared by value.
private static String setProblem(String setType, JsonNode members) {
if (members.isEmpty()) {
return emptySetProblem(setType);
}
if ("NS".equals(setType)) {
for (JsonNode member : members) {
String problem = member.isTextual() ? DynamoDbNumberUtils.itemNumberProblem(member.asText()) : null;
if (problem != null) {
return problem;
}
}
}
List<JsonNode> held = DynamoDbSetOrder.orderAtFirstRepeat(setType, members);
if (held == null) {
return null;
}
return INVALID + switch (setType) {
case "NS" -> "Input collection contains duplicates.";
case "BS" -> "Input collection [" + joined(held, ",", text -> "\"" + text + "\"")
+ "]of type BS contains duplicates.";
default -> "Input collection [" + joined(held, ", ", DynamoDbAttributeValueValidator::debugString)
+ "] contains duplicates.";
};
}
static String emptySetProblem(String setType) {
return INVALID + switch (setType) {
case "NS" -> "An number set may not be empty";
case "BS" -> "Binary sets should not be empty";
default -> "An string set may not be empty";
};
}
private static String joined(List<JsonNode> members, String separator, Function<String, String> format) {
return members.stream().map(member -> format.apply(member.asText())).collect(Collectors.joining(separator));
}
// DynamoDB quotes a string as Rust's Debug format does.
private static String debugString(String text) {
StringBuilder quoted = new StringBuilder("\"");
text.codePoints().forEach(c -> {
switch (c) {
case 0 -> quoted.append("\\0");
case '\t' -> quoted.append("\\t");
case '\r' -> quoted.append("\\r");
case '\n' -> quoted.append("\\n");
case '"', '\\' -> quoted.append('\\').appendCodePoint(c);
default -> {
if (printable(c)) {
quoted.appendCodePoint(c);
} else {
quoted.append("\\u{").append(Integer.toHexString(c)).append('}');
}
}
}
});
return quoted.append('"').toString();
}
private static boolean printable(int c) {
return switch (Character.getType(c)) {
case Character.SPACE_SEPARATOR -> c == ' ';
case Character.LINE_SEPARATOR, Character.PARAGRAPH_SEPARATOR, Character.CONTROL, Character.FORMAT,
Character.SURROGATE, Character.PRIVATE_USE, Character.UNASSIGNED,
Character.NON_SPACING_MARK, Character.ENCLOSING_MARK -> false;
default -> !SPACING_GRAPHEME_EXTENDERS.contains(c);
};
}
static void validate(JsonNode value) {
requireBase64(value);
requireOneType(value);
@@ -9,7 +9,6 @@ import io.github.hectorvent.floci.core.common.AwsException;
import java.math.BigDecimal;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Consumer;
/**
* DynamoDB number validation and normalization.
@@ -122,32 +121,9 @@ final class DynamoDbNumberUtils {
return toNormalizedString(stripped);
}
static void forEachNumber(JsonNode values, Consumer<String> check) {
for (JsonNode value : values) {
JsonNode number = value.get("N");
if (number != null && number.isTextual()) {
check.accept(number.asText());
}
for (JsonNode member : value.path("NS")) {
if (member.isTextual()) {
check.accept(member.asText());
}
}
forEachNumber(value.path("L"), check);
forEachNumber(value.path("M"), check);
}
}
static void requireItemNumber(String text, String prefix) {
String problem = itemNumberProblem(text);
if (problem != null) {
throw new AwsException("ValidationException", prefix + problem, 400);
}
}
// An item call reads the exponent as a long and checks the range without wrapping around,
// unlike a PartiQL parameter. It counts the digits before it checks the range.
private static String itemNumberProblem(String text) {
static String itemNumberProblem(String text) {
int marker = exponentMarker(text);
BigDecimal mantissa;
long exponent;
@@ -223,6 +199,11 @@ final class DynamoDbNumberUtils {
return attr;
}
// DynamoDB stores a NULL flag written as a string as true.
if (attr.path("NULL").isTextual()) {
return JsonNodeFactory.instance.objectNode().put("NULL", true);
}
if (attr.has("N")) {
String raw = attr.get("N").asText();
String normalized = validateAndNormalize(raw);
@@ -11,6 +11,8 @@ import java.util.Arrays;
import java.util.Base64;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Function;
/**
@@ -21,6 +23,12 @@ final class DynamoDbSetOrder {
private record Keyed<K>(JsonNode member, K key) {}
private record Order<K>(Function<String, K> key, Comparator<K> compare) {}
private static final Order<BigDecimal> BY_VALUE = new Order<>(DynamoDbSetOrder::numberOf, Comparator.naturalOrder());
private static final Order<byte[]> BY_BYTE = new Order<>(DynamoDbSetOrder::bytesOf, Arrays::compareUnsigned);
private static final Order<byte[]> BY_CODE_POINT = new Order<>(DynamoDbSetOrder::utf8Of, Arrays::compareUnsigned);
private DynamoDbSetOrder() {}
/** Returns the members in DynamoDB's order, or the input itself when it is not an array. */
@@ -28,19 +36,43 @@ final class DynamoDbSetOrder {
if (!members.isArray()) {
return members;
}
return sortedBy(members, orderOf(setType));
}
/** Returns the members as DynamoDB holds them at the first repeat, or null when none repeats. */
static List<JsonNode> orderAtFirstRepeat(String setType, JsonNode members) {
return orderAtFirstRepeat(members, orderOf(setType));
}
private static Order<?> orderOf(String setType) {
return switch (setType) {
case "NS" -> sortedBy(members, DynamoDbSetOrder::numberOf, Comparator.naturalOrder());
case "BS" -> sortedBy(members, DynamoDbSetOrder::bytesOf, Arrays::compareUnsigned);
default -> sortedBy(members, DynamoDbSetOrder::utf8Of, Arrays::compareUnsigned);
case "NS" -> BY_VALUE;
case "BS" -> BY_BYTE;
default -> BY_CODE_POINT;
};
}
private static <K> ArrayNode sortedBy(JsonNode members, Function<String, K> key, Comparator<K> order) {
// The members before the repeat are sorted. The repeat and the rest stay as sent.
private static <K> List<JsonNode> orderAtFirstRepeat(JsonNode members, Order<K> order) {
List<JsonNode> sent = new ArrayList<>(members.size());
members.forEach(sent::add);
Map<K, JsonNode> sorted = new TreeMap<>(order.compare());
for (int i = 0; i < sent.size(); i++) {
if (sorted.putIfAbsent(order.key().apply(sent.get(i).asText()), sent.get(i)) != null) {
List<JsonNode> held = new ArrayList<>(sorted.values());
held.addAll(sent.subList(i, sent.size()));
return held;
}
}
return null;
}
private static <K> ArrayNode sortedBy(JsonNode members, Order<K> order) {
List<Keyed<K>> keyed = new ArrayList<>(members.size());
for (JsonNode member : members) {
keyed.add(new Keyed<>(member, key.apply(member.asText())));
keyed.add(new Keyed<>(member, order.key().apply(member.asText())));
}
keyed.sort(Comparator.comparing(Keyed::key, order));
keyed.sort(Comparator.comparing(Keyed::key, order.compare()));
ArrayNode result = JsonNodeFactory.instance.arrayNode(keyed.size());
for (Keyed<K> entry : keyed) {
result.add(entry.member());
@@ -1033,7 +1033,8 @@ final class ExpressionEvaluator {
if (a == null || b == null) return a == b;
for (String type : new String[]{"S", "B", "BOOL", "NULL"}) {
if (a.has(type) && b.has(type)) {
return a.get(type).asText().equals(b.get(type).asText());
// A NULL flag can be written as a string in any case, and it is always true.
return "NULL".equals(type) || a.get(type).asText().equals(b.get(type).asText());
}
if (a.has(type) || b.has(type)) return false;
}
@@ -629,8 +629,6 @@ public class NativeDynamoDbJsonHandler {
checkUnusedEan(exprAttrNames, extractHashTokens(conditionExpression));
checkUnusedEav(exprAttrValues, extractColonTokens(conditionExpression));
validateItemSets(item);
Consumer<JsonNode> expectedCheck = legacyExpectedCheck(tableName, region, item, false, expected,
conditionalOperator, returnValuesOnConditionCheckFailure);
JsonNode previousItem = dynamoDbService.putItem(tableName, item, conditionExpression,
@@ -1073,10 +1071,10 @@ public class NativeDynamoDbJsonHandler {
private static final String VALIDATION_ENVELOPE = "1 validation error detected: ";
// DynamoDB reads the numbers of each request member at its own stage.
// DynamoDB reads the values of each request member at its own stage.
private static void requireReadableValues(JsonNode values, String prefix) {
if (values != null) {
DynamoDbNumberUtils.forEachNumber(values, text -> DynamoDbNumberUtils.requireItemNumber(text, prefix));
DynamoDbAttributeValueValidator.requireStorable(values, prefix);
}
}
@@ -1531,13 +1529,15 @@ public class NativeDynamoDbJsonHandler {
}
requireValidReturnConsumedCapacity(request);
// BatchWriteItem still reads a number the way a PartiQL parameter is read.
// BatchWriteItem still reads a value the way a PartiQL parameter is read.
for (List<JsonNode> writes : items.values()) {
for (JsonNode writeReq : writes) {
DynamoDbNumberUtils.forEachNumber(writeReq.path("PutRequest").path("Item"),
DynamoDbNumberUtils::requirePartiQLParameterNumber);
DynamoDbNumberUtils.forEachNumber(writeReq.path("DeleteRequest").path("Key"),
DynamoDbNumberUtils::requirePartiQLParameterNumber);
for (JsonNode value : writeReq.path("PutRequest").path("Item")) {
requirePartiQLParameter(value, 1);
}
for (JsonNode value : writeReq.path("DeleteRequest").path("Key")) {
requirePartiQLParameter(value, 1);
}
}
}
@@ -1646,10 +1646,16 @@ public class NativeDynamoDbJsonHandler {
}
}
// DynamoDB compares the keys as sent before it reads their numbers.
// DynamoDB looks at each key as sent before it reads the values in the keys.
for (JsonNode tableRequest : items.values()) {
Set<JsonNode> sent = new HashSet<>();
for (JsonNode key : tableRequest.path("Keys")) {
for (JsonNode value : key) {
if (value.has("NULL")) {
throw new AwsException("ValidationException",
"The supplied Item contains a null AttributeValue", 400);
}
}
if (!sent.add(key)) {
throw new AwsException("ValidationException",
"Provided list of item keys contains duplicates", 400);
@@ -2843,28 +2849,16 @@ public class NativeDynamoDbJsonHandler {
return Response.ok(response).build();
}
/**
* Builds a ConsumedCapacity node if the request includes ReturnConsumedCapacity.
* Uses simple estimates: 0.5 RCU per item read, 1.0 WCU per item written.
*/
private void validateItemSets(JsonNode item) {
if (item == null || !item.isObject()) return;
item.fields().forEachRemaining(entry -> {
JsonNode attr = entry.getValue();
checkAttrSets(attr);
});
}
private void checkAttrSets(JsonNode attr) {
if (attr == null) return;
if (attr.has("NULL") && !attr.get("NULL").asBoolean()) {
if (DynamoDbAttributeValueValidator.hasFalseNull(attr)) {
throw new AwsException("ValidationException",
"One or more parameter values were invalid: Null attribute value types must have the value of true", 400);
DynamoDbAttributeValueValidator.FALSE_NULL, 400);
}
if (attr.has("SS")) {
JsonNode ss = attr.get("SS");
if (ss.isEmpty()) throw new AwsException("ValidationException",
"One or more parameter values were invalid: An string set may not be empty", 400);
DynamoDbAttributeValueValidator.emptySetProblem("SS"), 400);
Set<String> seen = new HashSet<>();
for (JsonNode e : ss) {
if (!seen.add(e.asText())) throw new AwsException("ValidationException",
@@ -2873,7 +2867,7 @@ public class NativeDynamoDbJsonHandler {
} else if (attr.has("NS")) {
JsonNode ns = attr.get("NS");
if (ns.isEmpty()) throw new AwsException("ValidationException",
"One or more parameter values were invalid: An number set may not be empty", 400);
DynamoDbAttributeValueValidator.emptySetProblem("NS"), 400);
Set<String> seen = new HashSet<>();
for (JsonNode e : ns) {
if (!seen.add(e.asText())) throw new AwsException("ValidationException",
@@ -2882,7 +2876,7 @@ public class NativeDynamoDbJsonHandler {
} else if (attr.has("BS")) {
JsonNode bs = attr.get("BS");
if (bs.isEmpty()) throw new AwsException("ValidationException",
"One or more parameter values were invalid: Binary sets should not be empty", 400);
DynamoDbAttributeValueValidator.emptySetProblem("BS"), 400);
Set<String> seen = new HashSet<>();
for (JsonNode e : bs) {
// A binary set names its type, and AWS leaves out the space before "of".