fix(dynamodb): reject a request member of the wrong JSON type (#4636)

* chore(dynamodb): vendor the input shapes of botocore's DynamoDB model

tools/aws/regen_dynamodb_shapes.py keeps each operation's input shape and
the type of every shape it reaches, from the pinned botocore release.
make aws-data-sync regenerates it and make aws-data-check keeps it in sync.

* fix(dynamodb): reject a request member of the wrong JSON type

DynamoDB answers a member of the wrong JSON type with a
SerializationException before it runs the operation, such as
"NUMBER_VALUE cannot be converted to String" for a number BillingMode or
IndexName. The message names the JSON token and the Java type, or says
"Unexpected field type", "Unexpected value type in payload",
"Start of structure or map found where not expected" or "UnknownError"
by where the value sits. The first bad member in body order is reported.
A JSON null counts as absent and an unknown member is ignored.

Floci now checks every DynamoDB JSON request against the vendored input
shapes. A number in an ExclusiveStartKey S value is one of these errors on
AWS, so that test now expects the SerializationException.

* fix(dynamodb): keep provenance out of the shapes freshness check

The shapes file now carries its provenance in a _source block, like the
other vendored AWS data, and --check compares it without that block. A
run against --botocore-data or a local checkout no longer reports the
file as stale when only the botocore label differs.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-09-29 11:18:40 -04:00
1 parent 33617e340d
commit 1465251e0c
10 files changed
+2207 -5

No files matched your search

+2 -2
View File
@@ -6,8 +6,8 @@ name: Partition Literals
# partition regexes in src/main/java against the checked-in per-file baseline: a
# literal in a new file fails, growth in an existing file fails, and a drop fails until
# the baseline is regenerated so the remaining count stays exact. The second job checks
# that the vendored partition data (src/main/resources/aws/partitions.json) still matches
# what tools/aws/regen_partitions.py produces from the pinned botocore release. Python-only,
# that the vendored AWS data (src/main/resources/aws/*.json) still matches what tools/aws/
# produces from the pinned botocore release. Python-only,
# so both are fast and independent of the Java build job.
on:
+11 -2
View File
@@ -12,6 +12,8 @@
#
# AWS partition data: src/main/resources/aws/partitions.json is generated from botocore's
# published partition metadata (plus two CDK region rules) by tools/aws/regen_partitions.py.
# src/main/resources/aws/dynamodb-request-shapes.json is generated from botocore's DynamoDB
# model by tools/aws/regen_dynamodb_shapes.py.
PYTHON ?= python3
@@ -175,8 +177,9 @@ partition-test: ## Run the partition tooling's unit tests
aws-data-sync: ## Regenerate src/main/resources/aws/*.json from botocore, the CDK and Terraform (commit the result)
$(PYTHON) tools/aws/regen_partitions.py
$(PYTHON) tools/aws/regen_region_facts.py
$(PYTHON) tools/aws/regen_dynamodb_shapes.py
aws-data-check: ## CI gate: the vendored partition data must match a fresh generation
aws-data-check: ## CI gate: the vendored AWS data must match a fresh generation
@$(PYTHON) tools/aws/regen_partitions.py --check || { \
echo ""; \
echo "error: src/main/resources/aws/partitions.json is out of date."; \
@@ -189,8 +192,14 @@ aws-data-check: ## CI gate: the vendored partition data must match a fresh gener
echo " Run 'make aws-data-sync' with local/aws checked out and commit the result."; \
exit 1; \
}
@$(PYTHON) tools/aws/regen_dynamodb_shapes.py --check || { \
echo ""; \
echo "error: src/main/resources/aws/dynamodb-request-shapes.json is out of date."; \
echo " Run 'make aws-data-sync' and commit the result."; \
exit 1; \
}
aws-data-test: ## Run the partition-data generator's unit tests
aws-data-test: ## Run the AWS data generators' unit tests
$(PYTHON) -m pytest tools/aws -q
iam-namespaces-sync: ## Regenerate src/main/resources/aws/iam-service-namespaces.json from AWS (commit the result)
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.cloudcontrol.CloudControlJsonHandler;
import io.github.hectorvent.floci.services.bcmpricingcalculator.BcmPricingCalculatorJsonHandler;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsJsonHandler;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbRequestShapes;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbResponses;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamsJsonHandler;
import io.github.hectorvent.floci.services.networkfirewall.NetworkFirewallJsonHandler;
@@ -137,6 +138,7 @@ public class AwsJsonController {
if (targetMatch.prefix().startsWith("DynamoDBStreams_")) {
yield dynamoDbStreamsJsonHandler.handle(action, request, region);
}
DynamoDbRequestShapes.check(action, request);
yield dynamoDbJsonHandler.handle(action, request, region);
}
case "sqs" -> sqsJsonHandler.handle(action, request, region);
@@ -0,0 +1,198 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Rejects a DynamoDB request member of the wrong JSON type with the SerializationException
* DynamoDB answers before it runs the operation. The input shapes come from the vendored
* {@code aws/dynamodb-request-shapes.json}, generated from botocore's DynamoDB model by
* {@code tools/aws/regen_dynamodb_shapes.py}.
*
* <p>AWS reads the body in order and reports the first bad member, without naming it. A JSON
* null counts as an absent member, and a member the model does not know is ignored.
*/
public final class DynamoDbRequestShapes {
static final String RESOURCE_NAME = "aws/dynamodb-request-shapes.json";
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String OBJECT_NOT_EXPECTED = "Start of structure or map found where not expected";
private static final String UNKNOWN_ERROR = "UnknownError";
private static final String UNEXPECTED_FIELD_TYPE = "Unexpected field type";
private static final String UNEXPECTED_VALUE_TYPE = "Unexpected value type in payload";
record Shape(String type, Map<String, String> members, String element) {
}
record Model(Map<String, String> operations, Map<String, Shape> shapes) {
}
private static final class Holder {
static final Model MODEL = load();
}
private DynamoDbRequestShapes() {
}
/** Checks a DynamoDB request body against the input shape of {@code action}, if the model has one. */
public static void check(String action, JsonNode request) {
check(Holder.MODEL, action, request);
}
static void check(Model model, String action, JsonNode request) {
String input = model.operations().get(action);
if (input != null) {
checkValue(model, model.shapes().get(input), request, true);
}
}
private static void checkValue(Model model, Shape shape, JsonNode value, boolean member) {
if (value.isNull()) {
return;
}
switch (shape.type()) {
case "structure" -> checkStructure(model, shape, value, member);
case "list" -> checkList(model, shape, value, member);
case "map" -> checkMap(model, shape, value, member);
default -> checkScalar(shape.type(), value);
}
}
private static void checkStructure(Model model, Shape shape, JsonNode value, boolean member) {
if (value.isArray()) {
throw serialization(UNKNOWN_ERROR);
}
if (!value.isObject()) {
throw serialization(member ? UNEXPECTED_FIELD_TYPE : UNEXPECTED_VALUE_TYPE);
}
Iterator<Map.Entry<String, JsonNode>> fields = value.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
String memberShape = shape.members().get(field.getKey());
if (memberShape != null) {
checkValue(model, model.shapes().get(memberShape), field.getValue(), true);
}
}
}
private static void checkList(Model model, Shape shape, JsonNode value, boolean member) {
if (value.isObject()) {
throw serialization(OBJECT_NOT_EXPECTED);
}
if (!value.isArray()) {
throw serialization(member ? UNEXPECTED_FIELD_TYPE : UNKNOWN_ERROR);
}
Shape element = model.shapes().get(shape.element());
for (JsonNode item : value) {
checkValue(model, element, item, false);
}
}
private static void checkMap(Model model, Shape shape, JsonNode value, boolean member) {
if (value.isArray()) {
throw serialization(UNKNOWN_ERROR);
}
if (!value.isObject()) {
throw serialization(member ? UNEXPECTED_FIELD_TYPE : UNKNOWN_ERROR);
}
Shape element = model.shapes().get(shape.element());
for (JsonNode item : value) {
checkValue(model, element, item, false);
}
}
private static void checkScalar(String type, JsonNode value) {
if (value.isObject()) {
throw serialization(OBJECT_NOT_EXPECTED);
}
if (value.isArray()) {
throw serialization(UNKNOWN_ERROR);
}
switch (type) {
case "string" -> requireToken(value.isTextual(), value, "String");
case "integer" -> requireToken(value.isNumber(), value, "Integer");
case "long" -> requireToken(value.isNumber(), value, "Long");
case "double" -> requireToken(value.isNumber(), value, "Double");
case "timestamp" -> requireToken(value.isNumber(), value, "Date");
case "boolean" -> checkBoolean(value);
case "blob" -> {
if (!value.isTextual() && !value.isBinary()) {
throw serialization("only base-64-encoded strings are convertible to bytes");
}
}
default -> {
}
}
}
private static void checkBoolean(JsonNode value) {
if (value.isTextual()) {
String text = value.asText();
if (!"true".equalsIgnoreCase(text) && !"false".equalsIgnoreCase(text)) {
throw serialization("Unexpected token received from parser");
}
return;
}
requireToken(value.isBoolean(), value, "Boolean");
}
private static void requireToken(boolean accepted, JsonNode value, String target) {
if (!accepted) {
throw serialization(token(value) + " cannot be converted to " + target);
}
}
private static String token(JsonNode value) {
if (value.isIntegralNumber()) {
return "NUMBER_VALUE";
}
if (value.isNumber()) {
return "DECIMAL_VALUE";
}
if (value.isBoolean()) {
return value.booleanValue() ? "TRUE_VALUE" : "FALSE_VALUE";
}
return "STRING_VALUE";
}
private static AwsException serialization(String message) {
return new AwsException("SerializationException", message, 400);
}
private static Model load() {
try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(RESOURCE_NAME)) {
if (in == null) {
throw new IllegalStateException("DynamoDB request shape resource not found: " + RESOURCE_NAME);
}
return parse(MAPPER.readTree(in));
} catch (IOException e) {
throw new IllegalStateException("Failed to read the DynamoDB request shapes " + RESOURCE_NAME, e);
}
}
static Model parse(JsonNode root) {
Map<String, String> operations = new HashMap<>();
root.path("operations").fields().forEachRemaining(op -> operations.put(op.getKey(), op.getValue().asText()));
Map<String, Shape> shapes = new HashMap<>();
Iterator<Map.Entry<String, JsonNode>> entries = root.path("shapes").fields();
while (entries.hasNext()) {
Map.Entry<String, JsonNode> entry = entries.next();
JsonNode node = entry.getValue();
Map<String, String> members = new LinkedHashMap<>();
node.path("members").fields().forEachRemaining(m -> members.put(m.getKey(), m.getValue().asText()));
String element = node.hasNonNull("member") ? node.get("member").asText() : node.path("value").asText(null);
shapes.put(entry.getKey(), new Shape(node.path("type").asText(), members, element));
}
return new Model(operations, shapes);
}
}
File diff suppressed because it is too large. Load diff
@@ -363,7 +363,8 @@ class DynamoDbAccessPathIntegrationTest {
}
""".formatted(TABLE))
.statusCode(400)
.body("__type", equalTo("ValidationException"));
.body("__type", equalTo("SerializationException"))
.body("message", equalTo("NUMBER_VALUE cannot be converted to String"));
}
@Test
@@ -693,6 +693,43 @@ class DynamoDbIntegrationTest {
.body("message", equalTo(message));
}
@Test
void aNonStringMemberFailsToDeserialize() {
given()
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "NonStringBillingModeTable",
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
"BillingMode": 5
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("SerializationException"))
.body("message", equalTo("NUMBER_VALUE cannot be converted to String"));
given()
.header("X-Amz-Target", "DynamoDB_20120810.UpdateTable")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "NoSuchNonStringTable",
"GlobalSecondaryIndexUpdates": [{"Delete": {"IndexName": true}}]
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("SerializationException"))
.body("message", equalTo("TRUE_VALUE cannot be converted to String"));
}
@Test
void createTableWithGsiAndLsi() {
given()
@@ -0,0 +1,110 @@
package io.github.hectorvent.floci.services.dynamodb;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class DynamoDbRequestShapesTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@Test
void stringMemberNamesTheJsonTokenItGot() {
assertRejected("Scan", "{\"TableName\":\"t\",\"IndexName\":5}", "NUMBER_VALUE cannot be converted to String");
assertRejected("Scan", "{\"TableName\":\"t\",\"IndexName\":5.5}", "DECIMAL_VALUE cannot be converted to String");
assertRejected("Scan", "{\"TableName\":\"t\",\"IndexName\":1e3}", "DECIMAL_VALUE cannot be converted to String");
assertRejected("Scan", "{\"TableName\":\"t\",\"IndexName\":true}", "TRUE_VALUE cannot be converted to String");
assertRejected("Scan", "{\"TableName\":\"t\",\"IndexName\":false}", "FALSE_VALUE cannot be converted to String");
assertRejected("Scan", "{\"TableName\":\"t\",\"IndexName\":{}}", "Start of structure or map found where not expected");
assertRejected("Scan", "{\"TableName\":\"t\",\"IndexName\":[]}", "UnknownError");
}
@Test
void numericMembersAcceptAnyNumberAndNameTheirJavaType() {
assertAccepted("Scan", "{\"TableName\":\"t\",\"Limit\":5.5}");
assertAccepted("Scan", "{\"TableName\":\"t\",\"Limit\":99999999999}");
assertRejected("Scan", "{\"TableName\":\"t\",\"Limit\":\"5\"}", "STRING_VALUE cannot be converted to Integer");
assertRejected("Scan", "{\"TableName\":\"t\",\"Limit\":false}", "FALSE_VALUE cannot be converted to Integer");
assertRejected("UpdateTable",
"{\"TableName\":\"t\",\"ProvisionedThroughput\":{\"ReadCapacityUnits\":\"5\",\"WriteCapacityUnits\":5}}",
"STRING_VALUE cannot be converted to Long");
assertRejected("UpdateTableReplicaAutoScaling", "{\"TableName\":\"t\",\"ProvisionedWriteCapacityAutoScalingUpdate\":"
+ "{\"ScalingPolicyUpdate\":{\"TargetTrackingScalingPolicyConfiguration\":{\"TargetValue\":\"50\"}}}}",
"STRING_VALUE cannot be converted to Double");
assertAccepted("ListBackups", "{\"TimeRangeLowerBound\":1577836800}");
assertRejected("ListBackups", "{\"TimeRangeLowerBound\":\"2020-01-01T00:00:00Z\"}",
"STRING_VALUE cannot be converted to Date");
}
@Test
void booleanMemberAcceptsItsWordsAsStrings() {
assertAccepted("Scan", "{\"TableName\":\"t\",\"ConsistentRead\":\"false\"}");
assertAccepted("Scan", "{\"TableName\":\"t\",\"ConsistentRead\":\"TRUE\"}");
assertRejected("Scan", "{\"TableName\":\"t\",\"ConsistentRead\":\"abc\"}", "Unexpected token received from parser");
assertRejected("Scan", "{\"TableName\":\"t\",\"ConsistentRead\":0}", "NUMBER_VALUE cannot be converted to Boolean");
}
@Test
void blobMemberTakesOnlyAString() {
assertRejected("PutItem", "{\"TableName\":\"t\",\"Item\":{\"a\":{\"B\":5}}}",
"only base-64-encoded strings are convertible to bytes");
assertRejected("PutItem", "{\"TableName\":\"t\",\"Item\":{\"a\":{\"BS\":[true]}}}",
"only base-64-encoded strings are convertible to bytes");
}
@Test
void containerMessageDependsOnWhereTheValueSits() {
assertRejected("UpdateTable", "{\"TableName\":\"t\",\"ProvisionedThroughput\":\"a\"}", "Unexpected field type");
assertRejected("UpdateTable", "{\"TableName\":\"t\",\"ProvisionedThroughput\":[]}", "UnknownError");
assertRejected("Scan", "{\"TableName\":\"t\",\"AttributesToGet\":\"a\"}", "Unexpected field type");
assertRejected("Scan", "{\"TableName\":\"t\",\"AttributesToGet\":{}}", "Start of structure or map found where not expected");
assertRejected("Scan", "{\"TableName\":\"t\",\"ExpressionAttributeNames\":5}", "Unexpected field type");
assertRejected("PutItem", "{\"TableName\":\"t\",\"Item\":{\"a\":5}}", "Unexpected value type in payload");
assertRejected("UpdateTable", "{\"TableName\":\"t\",\"GlobalSecondaryIndexUpdates\":[\"a\"]}",
"Unexpected value type in payload");
assertRejected("BatchWriteItem", "{\"RequestItems\":{\"t\":5}}", "UnknownError");
assertRejected("BatchGetItem", "{\"RequestItems\":{\"t\":{\"Keys\":[5]}}}", "UnknownError");
}
@Test
void nestedMembersAreCheckedToo() {
assertRejected("UpdateTable", "{\"TableName\":\"t\",\"GlobalSecondaryIndexUpdates\":[{\"Delete\":{\"IndexName\":5}}]}",
"NUMBER_VALUE cannot be converted to String");
assertRejected("CreateTable", "{\"TableName\":\"t\",\"BillingMode\":5}", "NUMBER_VALUE cannot be converted to String");
assertRejected("Scan", "{\"TableName\":\"t\",\"ExclusiveStartKey\":{\"pk\":{\"S\":123}}}",
"NUMBER_VALUE cannot be converted to String");
}
@Test
void firstBadMemberInBodyOrderWins() {
assertRejected("Scan", "{\"TableName\":\"t\",\"Limit\":\"5\",\"IndexName\":5}", "STRING_VALUE cannot be converted to Integer");
assertRejected("Scan", "{\"TableName\":\"t\",\"IndexName\":5,\"Limit\":\"5\"}", "NUMBER_VALUE cannot be converted to String");
}
@Test
void nullAndUnknownMembersAreLeftToTheOperation() {
assertAccepted("Scan", "{\"TableName\":\"t\",\"IndexName\":null,\"Limit\":null,\"Unknown\":5}");
assertAccepted("Scan", "{\"TableName\":\"t\",\"AttributesToGet\":[null]}");
assertAccepted("NoSuchOperation", "{\"TableName\":5}");
}
private static void assertRejected(String action, String body, String message) {
AwsException error = assertThrows(AwsException.class, () -> DynamoDbRequestShapes.check(action, json(body)));
assertEquals("SerializationException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertEquals(message, error.getMessage());
}
private static void assertAccepted(String action, String body) {
assertDoesNotThrow(() -> DynamoDbRequestShapes.check(action, json(body)));
}
private static JsonNode json(String body) throws Exception {
return MAPPER.readTree(body);
}
}
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""Regenerate src/main/resources/aws/dynamodb-request-shapes.json from botocore's DynamoDB model.
DynamoDB rejects a request member of the wrong JSON type with a SerializationException before
it runs the operation. The Java side (`DynamoDbRequestShapes`) needs each operation's input
shapes to do the same, so this script keeps only what that check reads: the input shape of
every operation, and for every shape reachable from one, its type and the shapes of its
members, list elements or map values.
The model is botocore's `dynamodb/2012-08-10/service-2.json` (Apache-2.0,
https://github.com/boto/botocore). It is located, in order, at `--botocore-data`, the
`local/aws/botocore` checkout, then the installed `botocore` package, which
`requirements.txt` pins so CI regenerates the same bytes.
Run from anywhere in the repo:
python3 tools/aws/regen_dynamodb_shapes.py # rewrite the vendored file in place
python3 tools/aws/regen_dynamodb_shapes.py --check # exit 1 when the vendored file is stale
"""
from __future__ import annotations
import argparse
import gzip
import json
import sys
from pathlib import Path
from regen_partitions import resolve_botocore_data, strip_source
REPO_ROOT = Path(__file__).resolve().parents[2]
OUTPUT = REPO_ROOT / "src/main/resources/aws/dynamodb-request-shapes.json"
MODEL = Path("dynamodb/2012-08-10/service-2.json")
def load_model(data: Path) -> dict:
plain = data / MODEL
if plain.exists():
return json.loads(plain.read_text(encoding="utf-8"))
compressed = plain.with_name(plain.name + ".gz")
if compressed.exists():
with gzip.open(compressed, "rt", encoding="utf-8") as f:
return json.load(f)
raise SystemExit(f"error: {plain} not found")
def build(model: dict, provenance: str) -> dict:
shapes = model["shapes"]
kept: dict[str, dict] = {}
def keep(name: str) -> None:
if name in kept:
return
shape = shapes[name]
kind = shape["type"]
entry: dict = {"type": kind}
kept[name] = entry
if kind == "structure":
entry["members"] = {member: spec["shape"] for member, spec in shape.get("members", {}).items()}
for spec in shape.get("members", {}).values():
keep(spec["shape"])
elif kind == "list":
entry["member"] = shape["member"]["shape"]
keep(shape["member"]["shape"])
elif kind == "map":
entry["value"] = shape["value"]["shape"]
keep(shape["value"]["shape"])
operations = {}
for name, operation in sorted(model["operations"].items()):
if "input" in operation:
operations[name] = operation["input"]["shape"]
keep(operation["input"]["shape"])
return {
"_source": {
"generator": "tools/aws/regen_dynamodb_shapes.py",
"botocore": provenance,
},
"operations": operations,
"shapes": dict(sorted(kept.items())),
}
def render(doc: dict) -> str:
return json.dumps(doc, indent=2, sort_keys=False) + "\n"
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--check", action="store_true", help="exit 1 when the vendored file differs from a fresh generation")
parser.add_argument("--botocore-data", type=Path, help="botocore data directory")
parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS)
args = parser.parse_args(argv)
data, provenance = resolve_botocore_data(args.botocore_data)
fresh = render(build(load_model(data), provenance))
if args.check:
current = args.output.read_text(encoding="utf-8") if args.output.exists() else ""
if strip_source(current) != strip_source(fresh):
print(f"{args.output} is stale (generated from {provenance}).", file=sys.stderr)
return 1
return 0
args.output.write_text(fresh, encoding="utf-8")
print(f"wrote {args.output.relative_to(REPO_ROOT)} from {provenance}")
return 0
if __name__ == "__main__":
sys.exit(main())
+72
View File
@@ -0,0 +1,72 @@
"""Tests for regen_dynamodb_shapes.
Run with: pytest tools/aws -q (or: make aws-data-test)
"""
from __future__ import annotations
import regen_dynamodb_shapes as r
MODEL = {
"operations": {
"Scan": {"input": {"shape": "ScanInput"}, "output": {"shape": "ScanOutput"}},
"DescribeLimits": {"input": {"shape": "DescribeLimitsInput"}},
"NoInput": {},
},
"shapes": {
"ScanInput": {"type": "structure", "members": {
"TableName": {"shape": "TableName"},
"AttributesToGet": {"shape": "AttributeNameList"},
"ExclusiveStartKey": {"shape": "Key"},
}},
"ScanOutput": {"type": "structure", "members": {"Count": {"shape": "Integer"}}},
"DescribeLimitsInput": {"type": "structure", "members": {}},
"TableName": {"type": "string", "min": 3},
"AttributeNameList": {"type": "list", "member": {"shape": "AttributeName"}},
"AttributeName": {"type": "string"},
"Key": {"type": "map", "key": {"shape": "AttributeName"}, "value": {"shape": "AttributeValue"}},
"AttributeValue": {"type": "structure", "members": {"S": {"shape": "AttributeName"}}},
"Integer": {"type": "integer"},
},
}
def test_keeps_only_input_shapes_and_their_types():
doc = r.build(MODEL, "botocore test")
assert doc["_source"] == {"generator": "tools/aws/regen_dynamodb_shapes.py", "botocore": "botocore test"}
assert doc["operations"] == {"DescribeLimits": "DescribeLimitsInput", "Scan": "ScanInput"}
assert "ScanOutput" not in doc["shapes"]
assert "Integer" not in doc["shapes"]
assert doc["shapes"]["ScanInput"] == {"type": "structure", "members": {
"TableName": "TableName", "AttributesToGet": "AttributeNameList", "ExclusiveStartKey": "Key"}}
assert doc["shapes"]["TableName"] == {"type": "string"}
assert doc["shapes"]["AttributeNameList"] == {"type": "list", "member": "AttributeName"}
assert doc["shapes"]["Key"] == {"type": "map", "value": "AttributeValue"}
def test_check_ignores_provenance(tmp_path, monkeypatch):
output = tmp_path / "shapes.json"
output.write_text(r.render(r.build(MODEL, "botocore 0.0.1 (local/aws/botocore)")), encoding="utf-8")
monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "--botocore-data /elsewhere"))
monkeypatch.setattr(r, "load_model", lambda data: MODEL)
assert r.main(["--check", "--output", str(output)]) == 0
def test_check_reports_changed_shapes(tmp_path, monkeypatch):
output = tmp_path / "shapes.json"
changed = {**MODEL, "shapes": {**MODEL["shapes"], "TableName": {"type": "integer"}}}
output.write_text(r.render(r.build(changed, "botocore test")), encoding="utf-8")
monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "botocore test"))
monkeypatch.setattr(r, "load_model", lambda data: MODEL)
assert r.main(["--check", "--output", str(output)]) == 1
def test_output_is_stable():
first = r.render(r.build(MODEL, "botocore test"))
second = r.render(r.build(MODEL, "botocore test"))
assert first == second
assert first.endswith("\n")