fix(dynamodb): refuse unconvertible and out-of-range PartiQL number parameters before parsing the statement (#7179)

* fix(dynamodb): refuse unconvertible and out-of-range PartiQL number parameters before parsing the statement

* fix(dynamodb): decode binary PartiQL parameters first, and count types while reading each parameter

* fix(dynamodb): take a PartiQL parameter member set to null as absent

* fix(dynamodb): drop null parameter members before IAM reads the PartiQL attributes
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-01 07:50:48 -04:00
1 parent 28bde18804
commit 664db0cef3
7 files changed
+228 -23

No files matched your search

@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import java.util.Base64;
@@ -55,8 +56,8 @@ final class DynamoDbAttributeValueValidator {
static final String NESTING_EXCEEDED = "Nesting Levels have exceeded supported limits";
static void requireParameterNestingWithinLimit(JsonNode value) {
if (depthOf(value) > MAX_NESTING_LEVELS + 1) {
static void requireParameterLevelWithinLimit(int level) {
if (MAX_NESTING_LEVELS + 1 < level) {
throw validationEx(NESTING_EXCEEDED + ": Attributes in the item have nested levels beyond supported limit");
}
}
@@ -100,7 +101,17 @@ final class DynamoDbAttributeValueValidator {
}
}
private static void requireBase64(JsonNode value) {
// A PartiQL parameter takes a member set to null as absent.
static JsonNode dropNullMembers(JsonNode value) {
if (value instanceof ObjectNode object) {
object.properties().removeIf(member -> member.getValue().isNull());
object.path("M").forEach(DynamoDbAttributeValueValidator::dropNullMembers);
object.path("L").forEach(DynamoDbAttributeValueValidator::dropNullMembers);
}
return value;
}
static void requireBase64(JsonNode value) {
if (!value.isObject()) {
return;
}
@@ -244,7 +244,8 @@ public final class DynamoDbConditionKeys {
}
try {
List<JsonNode> parameters = new ArrayList<>();
body.path("Parameters").forEach(parameters::add);
body.path("Parameters").forEach(parameter ->
parameters.add(DynamoDbAttributeValueValidator.dropNullMembers(parameter.deepCopy())));
return DynamoDbPartiQLParser.parse(statement, parameters)
instanceof DynamoDbPartiQLParser.Stmt.Select select ? select : null;
} catch (RuntimeException ignored) {
@@ -7,6 +7,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import java.math.BigDecimal;
import java.util.Set;
import java.util.TreeSet;
/**
* DynamoDB number validation and normalization.
@@ -22,9 +24,59 @@ final class DynamoDbNumberUtils {
static final String NUMBER_UNDERFLOW =
"Number underflow. Attempting to store a number with magnitude smaller than supported range";
static final String TOO_MANY_DIGITS = "Attempting to store more than 38 significant digits in a Number";
static final String PARAMETER_NOT_NUMERIC = "The parameter cannot be converted to a numeric value";
private DynamoDbNumberUtils() {}
// DynamoDB measures a PartiQL number in 32-bit arithmetic, so an exponent near the limit wraps
// around and reads as an underflow.
static String partiQLNumberProblem(BigDecimal number) {
int magnitude = number.precision() - number.scale() + 1;
if (127 < magnitude) {
return NUMBER_OVERFLOW;
}
if (magnitude < -128) {
return NUMBER_UNDERFLOW;
}
if (38 < number.stripTrailingZeros().precision()) {
return TOO_MANY_DIGITS;
}
return null;
}
// DynamoDB reads a PartiQL parameter as BigDecimal does, but only with an exponent that fits in
// an int. Unlike a literal, the parameter is not rounded to 38 digits.
static BigDecimal requirePartiQLParameterNumber(String text) {
if (text.isEmpty()) {
throw new AwsException("ValidationException", PARAMETER_NOT_NUMERIC, 400);
}
BigDecimal number;
try {
int exponent = Math.max(text.indexOf('e'), text.indexOf('E'));
if (0 <= exponent) {
Integer.parseInt(text.substring(exponent + 1));
}
number = new BigDecimal(text);
} catch (NumberFormatException e) {
throw new AwsException("ValidationException", PARAMETER_NOT_NUMERIC + ": " + text, 400);
}
String problem = partiQLNumberProblem(number);
if (problem != null) {
throw new AwsException("ValidationException", problem, 400);
}
return number;
}
// Members are equal by value here, so 1 and 1.0 are duplicates.
static void requirePartiQLParameterNumberSet(JsonNode members) {
Set<BigDecimal> seen = new TreeSet<>();
for (JsonNode member : members) {
if (!seen.add(requirePartiQLParameterNumber(member.asText()))) {
throw new AwsException("ValidationException", "Input collection contains duplicates", 400);
}
}
}
/**
* Validates and normalizes a DynamoDB number string.
* Throws ValidationException if the number is out of range or has too many significant digits.
@@ -1639,29 +1639,13 @@ public class DynamoDbPartiQLParser {
value = value.round(DECIMAL_LITERAL);
number = new PVal.Num(value.toString());
}
String problem = numberLiteralProblem(value);
String problem = DynamoDbNumberUtils.partiQLNumberProblem(value);
if (problem != null) {
defer(problem + " under " + literalPath);
}
return number;
}
// DynamoDB measures a literal in 32-bit arithmetic, so an exponent near the limit wraps around
// and reads as an underflow.
private static String numberLiteralProblem(BigDecimal number) {
int magnitude = number.precision() - number.scale() + 1;
if (127 < magnitude) {
return DynamoDbNumberUtils.NUMBER_OVERFLOW;
}
if (magnitude < -128) {
return DynamoDbNumberUtils.NUMBER_UNDERFLOW;
}
if (38 < number.stripTrailingZeros().precision()) {
return DynamoDbNumberUtils.TOO_MANY_DIGITS;
}
return null;
}
private PVal.Num parseSignedNumber(Token sign) {
Token operand = advance();
PVal.Num number = switch (operand.type()) {
@@ -3613,6 +3613,7 @@ public class NativeDynamoDbJsonHandler {
}
private Response handleExecuteStatement(JsonNode request, String region) {
decodePartiQLParameters(request.path("Parameters"));
List<String> validationErrors = new ArrayList<>();
addPartiQLReturnValuesError(request, "returnValuesOnConditionCheckFailure", validationErrors);
addLengthError(request, "NextToken", "nextToken", MAX_NEXT_TOKEN_LENGTH, validationErrors);
@@ -3642,6 +3643,7 @@ public class NativeDynamoDbJsonHandler {
private Response handleExecuteTransaction(JsonNode request, String region) {
JsonNode stmts = request.path("TransactStatements");
stmts.forEach(s -> decodePartiQLParameters(s.path("Parameters")));
List<String> validationErrors = new ArrayList<>();
addLengthError(request, "ClientRequestToken", "clientRequestToken", MAX_CLIENT_REQUEST_TOKEN_LENGTH,
validationErrors);
@@ -3771,6 +3773,7 @@ public class NativeDynamoDbJsonHandler {
private Response handleBatchExecuteStatement(JsonNode request, String region) {
JsonNode stmts = request.path("Statements");
stmts.forEach(s -> decodePartiQLParameters(s.path("Parameters")));
List<String> validationErrors = new ArrayList<>();
addReturnConsumedCapacityError(request, validationErrors);
addStatementListErrors(stmts, "statements", validationErrors);
@@ -3867,10 +3870,43 @@ public class NativeDynamoDbJsonHandler {
}
List<JsonNode> params = new ArrayList<>();
for (JsonNode parameter : node) {
DynamoDbAttributeValueValidator.requireParameterNestingWithinLimit(parameter);
checkAttrSets(parameter);
requirePartiQLParameter(parameter, 1);
params.add(parameter);
}
return params;
}
// DynamoDB decodes the binary values of every statement before it checks anything else.
private static void decodePartiQLParameters(JsonNode parameters) {
for (JsonNode parameter : parameters) {
DynamoDbAttributeValueValidator.dropNullMembers(parameter);
DynamoDbAttributeValueValidator.requireBase64(parameter);
}
}
// DynamoDB reads the parameters in order and refuses the first value it cannot take. It reads the
// members of a map in the order of a HashMap sized for them, and a number before the type count.
private void requirePartiQLParameter(JsonNode value, int level) {
DynamoDbAttributeValueValidator.requireParameterLevelWithinLimit(level);
if (value.has("N")) {
DynamoDbNumberUtils.requirePartiQLParameterNumber(value.get("N").asText());
} else if (value.has("NS")) {
DynamoDbNumberUtils.requirePartiQLParameterNumberSet(value.get("NS"));
}
switch (DynamoDbAttributeValueValidator.typeOf(value)) {
case "M" -> {
Map<String, JsonNode> members = HashMap.newHashMap(value.get("M").size());
value.get("M").properties().forEach(member -> members.put(member.getKey(), member.getValue()));
for (JsonNode member : members.values()) {
requirePartiQLParameter(member, level + 1);
}
}
case "L" -> {
for (JsonNode member : value.get("L")) {
requirePartiQLParameter(member, level + 1);
}
}
default -> checkAttrSets(value);
}
}
}
@@ -40,6 +40,17 @@ class DynamoDbConditionKeysTest {
assertEquals("SPECIFIC_ATTRIBUTES", result.select());
}
@Test
void partiqlAttributesTakeAParameterMemberSetToNullAsAbsent() {
JsonNode body = mapper.createObjectNode().put("Statement", "SELECT payload FROM FgacTable WHERE PK = ?")
.set("Parameters", json("[{\"S\":\"one\",\"N\":null}]"));
DynamoDbConditionKeys.Result result = DynamoDbConditionKeys.extract("dynamodb:PartiQLSelect", body, table);
assertEquals(List.of("payload", "PK"), result.attributes());
assertTrue(body.at("/Parameters/0").has("N"));
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"GetItem | {} | ALL_ATTRIBUTES",
@@ -9,6 +9,7 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.stream.Collectors;
@@ -624,6 +625,115 @@ class DynamoDbPartiQLIntegrationTest {
.body("Responses[0].Error.Message", equalTo("Requested resource not found"));
}
@ParameterizedTest
@Order(30)
@CsvSource(delimiter = '|', textBlock = """
[{"N":"abc"}] | The parameter cannot be converted to a numeric value: abc
[{"N":""}] | The parameter cannot be converted to a numeric value
[{"N":"1e2147483648"}] | The parameter cannot be converted to a numeric value: 1e2147483648
[{"N":"0.1e2147483648"}] | The parameter cannot be converted to a numeric value: 0.1e2147483648
[{"N":"1e-2147483648"}] | The parameter cannot be converted to a numeric value: 1e-2147483648
[{"N":"1e2147483645"}] | Number overflow. Attempting to store a number with magnitude larger than supported range
[{"N":"1e2147483647"}] | Number underflow. Attempting to store a number with magnitude smaller than supported range
[{"N":"0e-131"}] | Number underflow. Attempting to store a number with magnitude smaller than supported range
[{"N":"1.23456789012345678901234567890123456789"}] | Attempting to store more than 38 significant digits in a Number
[{"NS":["1","1.0"]}] | Input collection contains duplicates
[{"N":"abc"},%1$s] | The parameter cannot be converted to a numeric value: abc
[%1$s,{"N":"abc"}] | Nesting Levels have exceeded supported limits: Attributes in the item have nested levels beyond supported limit
[{"M":{"a":{"N":"abc"},"z":%1$s}}] | The parameter cannot be converted to a numeric value: abc
[{"M":{"a":{"N":"abc"},"d":%1$s}}] | Nesting Levels have exceeded supported limits: Attributes in the item have nested levels beyond supported limit
[{"L":[{"N":"1e126"},{"N":"abc"}]}] | Number overflow. Attempting to store a number with magnitude larger than supported range
[{"NS":["1","1"]},{"N":"abc"}] | Input collection contains duplicates
[{},{"N":"abc"}] | Supplied AttributeValue is empty, must contain exactly one of the supported datatypes
[{"S":"a","N":"1"},{"N":"abc"}] | Supplied AttributeValue has more than one datatypes set, must contain exactly one of the supported datatypes
[{"S":"a","N":"abc"}] | The parameter cannot be converted to a numeric value: abc
[{"N":null},{"N":"abc"}] | Supplied AttributeValue is empty, must contain exactly one of the supported datatypes
[{"S":"a","N":null},{"N":"abc"}] | The parameter cannot be converted to a numeric value: abc
""")
void aParameterIsRefusedAtTheFirstValueThatCannotBeRead(String parameters, String message) {
String deep = "{\"M\":{\"n\":".repeat(40) + "{\"S\":\"leaf\"}" + "}}".repeat(40);
request("DynamoDB_20120810.ExecuteStatement", """
{"Statement":"SELECT * FROM \\"%s\\" WHERE pk = 'x' AND x = ? AND y = ?","Parameters":%s}
""".formatted(TABLE, parameters.formatted(deep)))
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo(message));
}
@Test
@Order(31)
void aParameterIsReadBeforeTheStatementIsParsed() {
String unconvertible = "The parameter cannot be converted to a numeric value: abc";
request("DynamoDB_20120810.ExecuteStatement", """
{"Statement":"SELECT * FROM \\"%s\\" WHERE pk = ? #","Parameters":[{"N":"abc"}]}
""".formatted(TABLE))
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo(unconvertible));
request("DynamoDB_20120810.ExecuteTransaction", """
{"TransactStatements":[{"Statement":"UPDATE \\"%1$s\\" SET n = ? WHERE pk = 'x'","Parameters":[{"N":"abc"}]},
{"Statement":"UPDATE \\"%1$s\\" SET n = 1 WHERE pk = 'y' #"}]}
""".formatted(TABLE))
.statusCode(400)
.body("message", equalTo(unconvertible));
request("DynamoDB_20120810.BatchExecuteStatement", """
{"Statements":[{"Statement":"SELECT * FROM \\"%s\\" WHERE pk = ? #","Parameters":[{"N":"abc"}]}]}
""".formatted(TABLE))
.statusCode(200)
.body("Responses[0].Error.Code", equalTo("ValidationError"))
.body("Responses[0].Error.Message", equalTo(unconvertible));
}
@Test
@Order(32)
void aBinaryParameterIsDecodedBeforeAnythingElse() {
String update = "UPDATE \\\"" + TABLE + "\\\" SET n = ? WHERE pk = 'x'";
request("DynamoDB_20120810.ExecuteStatement", """
{"Statement":"","Parameters":[{"N":"abc"},{"B":"AQI"}]}
""")
.statusCode(400)
.body("__type", equalTo("SerializationException"))
.body("message", equalTo("Base64 encoded length is expected a multiple of 4 bytes but found: 3"));
request("DynamoDB_20120810.ExecuteTransaction", """
{"TransactStatements":[{"Statement":"%1$s","Parameters":[{"N":"abc"}]},
{"Statement":"%1$s","Parameters":[{"B":"AQI"}]}]}
""".formatted(update))
.statusCode(400)
.body("__type", equalTo("SerializationException"));
request("DynamoDB_20120810.BatchExecuteStatement", """
{"Statements":[{"Statement":""},{"Statement":"%s","Parameters":[{"B":"AQI"}]}]}
""".formatted(update))
.statusCode(400)
.body("__type", equalTo("SerializationException"));
}
@Test
@Order(33)
void aParameterMemberSetToNullIsAbsent() {
request("DynamoDB_20120810.BatchExecuteStatement", """
{"Statements":[{"Statement":"SELECT * FROM \\"%s\\" WHERE pk = ?","Parameters":[{"N":null}]}]}
""".formatted(TABLE))
.statusCode(200)
.body("Responses[0].Error.Code", equalTo("ValidationError"))
.body("Responses[0].Error.Message",
equalTo("Supplied AttributeValue is empty, must contain exactly one of the supported datatypes"));
request("DynamoDB_20120810.ExecuteStatement", """
{"Statement":"INSERT INTO \\"%s\\" VALUE {'pk': 'null-member', 'v': ?}",
"Parameters":[{"M":{"x":{"S":"a"}},"N":null}]}
""".formatted(TABLE))
.statusCode(200);
request("DynamoDB_20120810.GetItem", """
{"TableName":"%s","Key":{"pk":{"S":"null-member"}}}
""".formatted(TABLE))
.statusCode(200)
.body("Item.v.M.x.S", equalTo("a"))
.body("Item.v.containsKey('N')", equalTo(false));
}
private static void putItem(String pk, String attributes) {
request("DynamoDB_20120810.PutItem", """
{"TableName":"%s","Item":{"pk":{"S":"%s"},%s}}