fix(dynamodb): check BatchGetItem and BatchWriteItem table names, list sizes and enums before the tables (#7650)

This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-11-06 09:37:11 -04:00
1 parent c1a88b8ab8
commit 07d75c8c8e
7 files changed
+202 -41

No files matched your search

@@ -0,0 +1,131 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.json.JsonWriteFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/** The checks DynamoDB runs on the RequestItems map of BatchGetItem and BatchWriteItem. */
final class DynamoDbBatchRequestItems {
private static final List<String> TABLE_NAME_RULES =
SmithyValidationErrors.constraintSet(3, 255, "[a-zA-Z0-9_.-]+", null);
private static final List<String> TABLE_ARN_RULES = List.of("Valid resource name or resource arn must be given. "
+ "Valid resource arn format is 'arn:<awsPartition>:<vendor>:<region>:<subscriber>:resourceType/resourceName', "
+ "where Resource name must have length less than or equal to 255, "
+ "Resource name must have length greater than or equal to 3, "
+ "Resource name must satisfy regular expression pattern: [a-zA-Z0-9_.-]+");
private static final List<String> KEYS_AND_ATTRIBUTES_MEMBERS = List.of("AttributesToGet", "ConsistentRead",
"ExpressionAttributeNames", "Keys", "ProjectionExpression");
private static final ObjectWriter ECHO_WRITER =
new ObjectMapper().writer().without(JsonWriteFeature.WRITE_HEX_UPPER_CASE);
private DynamoDbBatchRequestItems() {}
static void requireValidLengths(JsonNode requestItems, boolean write) {
List<String> violations = new ArrayList<>();
addIfPresent(violations, SmithyValidationErrors.sizeOutOfRange("RequestItems",
requestItems.properties().size(), 1, write ? 25 : 100));
for (Map.Entry<String, JsonNode> table : requestItems.properties()) {
String name = table.getKey();
String path = "RequestItems." + name;
addIfPresent(violations, SmithyValidationErrors.sizeOutOfRange(path,
name.codePointCount(0, name.length()), 1, 1024));
if (write) {
addListSize(violations, path + ".member", table.getValue(), 25);
} else {
addListSize(violations, path + ".member.AttributesToGet", table.getValue().get("AttributesToGet"),
Integer.MAX_VALUE);
addListSize(violations, path + ".member.Keys", table.getValue().get("Keys"), 100);
}
}
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
}
static String tableNamesViolation(JsonNode requestItems, String region, boolean write) {
for (Map.Entry<String, JsonNode> table : requestItems.properties()) {
String name = table.getKey();
boolean arn = AwsArnUtils.looksLikeArn(name);
boolean valid = arn
? DynamoDbTableNames.isTableArn(name, region)
: DynamoDbTableNames.nameViolations(name).isEmpty();
if (!valid) {
// The first bad name picks the rules DynamoDB lists.
return SmithyValidationErrors.Violations.QUOTED.mapKeys("requestItems", echo(requestItems, write),
arn ? TABLE_ARN_RULES : TABLE_NAME_RULES);
}
}
return null;
}
// DynamoDB lists the members of a table entry by name and leaves out null and unknown ones.
private static String echo(JsonNode requestItems, boolean write) {
ObjectNode echo = JsonNodeFactory.instance.objectNode();
for (Map.Entry<String, JsonNode> table : requestItems.properties()) {
echo.set(table.getKey(), write ? writeRequestsEcho(table.getValue()) : keysAndAttributesEcho(table.getValue()));
}
try {
return ECHO_WRITER.writeValueAsString(echo);
} catch (JsonProcessingException e) {
throw new UncheckedIOException(e);
}
}
private static ObjectNode keysAndAttributesEcho(JsonNode tableRequest) {
ObjectNode echo = JsonNodeFactory.instance.objectNode();
for (String member : KEYS_AND_ATTRIBUTES_MEMBERS) {
JsonNode value = tableRequest.get(member);
if (value != null && !value.isNull()) {
echo.set(member, value);
}
}
return echo;
}
private static ArrayNode writeRequestsEcho(JsonNode writeRequests) {
ArrayNode echo = JsonNodeFactory.instance.arrayNode();
for (JsonNode writeRequest : writeRequests) {
ObjectNode request = echo.addObject();
addRequestEcho(request, writeRequest, "DeleteRequest", "Key");
addRequestEcho(request, writeRequest, "PutRequest", "Item");
}
return echo;
}
private static void addRequestEcho(ObjectNode echo, JsonNode writeRequest, String member, String attributes) {
JsonNode request = writeRequest.get(member);
if (request == null || request.isNull()) {
return;
}
ObjectNode requestEcho = echo.putObject(member);
JsonNode value = request.get(attributes);
if (value != null && !value.isNull()) {
requestEcho.set(attributes, value);
}
}
private static void addListSize(List<String> violations, String path, JsonNode list, int max) {
if (list != null && list.isArray()) {
addIfPresent(violations, SmithyValidationErrors.sizeOutOfRange(path, list.size(), 1, max));
}
}
private static void addIfPresent(List<String> violations, String violation) {
if (violation != null) {
violations.add(violation);
}
}
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.dynamodb;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import java.util.ArrayList;
@@ -110,6 +111,15 @@ public final class DynamoDbTableNames {
return new ResolvedTableRef(tableName, region);
}
static boolean isTableArn(String value, String region) {
try {
return region.equals(parseArn(value).region())
&& AwsRegions.partitionFor(region).equals(AwsArnUtils.parse(value).partition());
} catch (AwsException notATableArn) {
return false;
}
}
private static void validateTableName(String tableName) {
String violation = nameViolation(tableName);
if (violation != null) {
@@ -1668,11 +1668,11 @@ public class NativeDynamoDbJsonHandler {
private Response handleBatchWriteItem(JsonNode request, String region) {
JsonNode requestItems = request.get("RequestItems");
if (requestItems == null || requestItems.isNull() || requestItems.isMissingNode()
|| !requestItems.fields().hasNext()) {
if (requestItems == null || requestItems.isNull() || requestItems.isMissingNode()) {
throw new AwsException("ValidationException",
"The requestItems parameter is required for BatchWriteItem", 400);
}
requireValidBatchMembers(request, region, true);
Map<String, List<JsonNode>> items = new HashMap<>();
Iterator<Map.Entry<String, JsonNode>> tables = requestItems.fields();
while (tables.hasNext()) {
@@ -1686,25 +1686,6 @@ public class NativeDynamoDbJsonHandler {
items.put(entry.getKey(), writes);
}
// Per-table check: max 25 write requests
for (Map.Entry<String, List<JsonNode>> entry : items.entrySet()) {
if (entry.getValue().size() > 25) {
// Build a representation of the requestItems
StringBuilder sb = new StringBuilder("{");
sb.append(entry.getKey()).append("=[");
List<String> reprs = new ArrayList<>();
for (JsonNode w : entry.getValue()) {
reprs.add(w.toString());
}
sb.append(String.join(", ", reprs)).append("]}");
throw SmithyValidationErrors.validationException(
"Value '" + sb + "' at 'requestItems' failed to satisfy constraint: "
+ "Map value must satisfy constraint: [Member must have length less than or equal to 25, "
+ "Member must have length greater than or equal to 1]");
}
}
requireValidReturnConsumedCapacity(request);
// BatchWriteItem still reads a value the way a PartiQL parameter is read.
for (List<JsonNode> writes : items.values()) {
for (JsonNode writeReq : writes) {
@@ -1776,13 +1757,7 @@ public class NativeDynamoDbJsonHandler {
throw new AwsException("ValidationException",
"The requestItems parameter is required for BatchGetItem", 400);
}
// BatchGetItem answers an empty map from the validation framework, BatchWriteItem
// still answers with its own sentence.
if (!requestItems.fields().hasNext()) {
throw SmithyValidationErrors.validationException(
"Value at 'RequestItems' failed to satisfy constraint: "
+ "Member must have length greater than or equal to 1");
}
requireValidBatchMembers(request, region, false);
Map<String, JsonNode> items = new HashMap<>();
Iterator<Map.Entry<String, JsonNode>> tables = requestItems.fields();
while (tables.hasNext()) {
@@ -1795,7 +1770,6 @@ public class NativeDynamoDbJsonHandler {
boolean usesAttributesToGet = false;
boolean usesProjectionExpression = false;
for (JsonNode tableRequest : items.values()) {
DynamoDbAccessPathValidator.validateAttributesToGet(tableRequest.get("AttributesToGet"));
usesAttributesToGet |= tableRequest.hasNonNull("AttributesToGet");
usesProjectionExpression |= tableRequest.hasNonNull("ProjectionExpression");
}
@@ -1805,7 +1779,6 @@ public class NativeDynamoDbJsonHandler {
+ "Non-expression parameters: {AttributesToGet} Expression parameters: {ProjectionExpression}", 400);
}
// Per-table check: max 100 keys
for (Map.Entry<String, JsonNode> entry : items.entrySet()) {
JsonNode projection = entry.getValue().path("ProjectionExpression");
if (projection.isTextual()) {
@@ -1813,13 +1786,6 @@ public class NativeDynamoDbJsonHandler {
ProjectionEvaluator.validateExpression(projection.asText(),
entry.getValue().get("ExpressionAttributeNames"));
}
JsonNode keysNode = entry.getValue().has("Keys") ? entry.getValue().get("Keys") : null;
if (keysNode != null && keysNode.size() > 100) {
throw SmithyValidationErrors.validationException(
"Value at 'RequestItems." + entry.getKey()
+ ".member.Keys' failed to satisfy constraint: "
+ "Member must have length less than or equal to 100");
}
}
// DynamoDB looks at each key as sent before it reads the values in the keys.
@@ -3067,6 +3033,18 @@ public class NativeDynamoDbJsonHandler {
}
}
private static void requireValidBatchMembers(JsonNode request, String region, boolean write) {
JsonNode requestItems = request.get("RequestItems");
DynamoDbBatchRequestItems.requireValidLengths(requestItems, write);
List<String> validationErrors = new ArrayList<>();
addIfPresent(validationErrors, DynamoDbBatchRequestItems.tableNamesViolation(requestItems, region, write));
addReturnConsumedCapacityError(request, validationErrors);
if (write) {
addIfPresent(validationErrors, returnItemCollectionMetricsError(request));
}
throwValidationErrors(validationErrors);
}
private static void requireValidReturnConsumedCapacity(JsonNode request) {
List<String> validationErrors = new ArrayList<>();
addReturnConsumedCapacityError(request, validationErrors);