mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
`GetAccessKeyInfo`, `GetSessionToken` and `GetWebIdentityToken` are held to the constraints botocore's STS model declares, which `tools/aws/regen_sts_shapes.py` vendors into `aws/sts-request-shapes.json` and `StsRequestShapes` reads through the same `QueryConstraintCheck` walk IAM reads its own file with. The two services share the protocol, the message wording and the generator, so what is new is which operations are read rather than how. What it adds is on `GetSessionToken`: `SerialNumber`, `TokenCode` and `MinimumSessionTokenSize` are declared and nothing read them, so a serial number under 9 characters, a token code that is not six digits and a size past 4096 answer `ValidationError` where they answered credentials. The size is still only validated, the token staying the length this emulator mints. `GetAccessKeyInfo` and `GetWebIdentityToken` keep the messages they already answered, from the same bounds and the same patterns, and about 130 lines of hand-written audience, tag and access-key checks come out. One answer moves: a value breaking two constraints is answered for both, where the if-else chain stopped at the first. That is the reading #6402 settled and #6580 already took for an empty role name. `jwtAlgorithmType` publishes a fixed length of 5 and no enum, the two values coming from the reference, so the walk takes a documented constraint keyed by member name and reports it in that member's place, which keeps a collected message in the model's order. It is reported only for a member the request carries that breaks nothing the model declares, which is the exclusivity the hand-written helper had. A value that is no number at all stays `InvalidParameterValue`, answered before the constraints, since the model declares a range and says nothing about what counts as a number; a digit string is a number of any width, so a `DurationSeconds` of `99999999999` breaks the maximum rather than being called no integer, as #6625 settled for an oversized `MaxItems`. Each operation asks for its violations where its own check ran rather than ahead of the switch, because `GetSessionToken` refuses session credentials before it reads anything. The whitespace around a number comes off wherever this handler reads one. The check takes a padded value and holds it to its range, so the read behind it parses the same text: parsing the value as the request spelled it threw there and fell back to the default, so a ` 3600 ` asking for an hour would have been handed the twelve hours `GetSessionToken` defaults to, or the five minutes a web identity token defaults to. IAM reads its own `MaxItems` that way already. The generator is not new code. `request_shapes.main` already drives the five generators that vendor member types, so it takes an `operations` argument now and both Query-protocol generators hand it their model, output and operations the same two-line way, which takes the hand-rolled driver out of `regen_iam_shapes.py` as well. ECR and Resource Groups still carry theirs and are a refactor of their own. The generator contract tests move with it: that a vendored file carries exactly the operations its generator lists and resolves every shape it names is one parametrized test over all four constraints generators rather than a copy per generator, and `build_constraints`'s own properties are tested once, where the shared module already tested them. The model transform the driver takes is driven through it as well, the file it writes carrying what the transform left and the staleness check calling that file current only when it prepares the model the same way, and IAM's own tests read the vendored file for each paged request reduced. Three sentences this handler wrote out by hand go the same way. The two range refusals and the length refusal on `TargetPrincipal` come from `SmithyValidationErrors`, which already wrote them word for word, and the "Must be an integer." refusal has one writer and three callers. The length comparison counts code points rather than UTF-16 units as a result, which is the reading the rest of the package uses.
163 lines
7.4 KiB
Python
163 lines
7.4 KiB
Python
"""Shared generator for the vendored request shapes a service's request check reads.
|
|
|
|
`regen_dynamodb_shapes.py`, `regen_sesv2_shapes.py`, `regen_apigateway_shapes.py` and
|
|
`regen_ecs_shapes.py` each name a botocore model and an output file and hand the rest to
|
|
`main()`. `regen_resource_groups_shapes.py` and
|
|
`regen_ecr_shapes.py` vendor constraints as well, through `build_constraints()`. The output keeps only what `RequestShapeModel` reads: the input
|
|
shape of every operation, reduced to the members carried in the JSON body, and for every shape
|
|
reachable from one, its type and the shapes of its members, list elements or map values.
|
|
`regen_emr_serverless_shapes.py` keeps every operation's output shape too, with `outputs=True`.
|
|
`regen_iam_shapes.py` and `regen_sts_shapes.py` name their operations instead, which switches
|
|
`main()` to `build_constraints()`.
|
|
|
|
Members bound to the URI, the query string or a header are left out: they never reach the body.
|
|
A model without such members, as DynamoDB's, comes out whole.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import sys
|
|
from collections.abc import Callable
|
|
from pathlib import Path
|
|
|
|
from regen_partitions import load_model as load_json_model
|
|
from regen_partitions import resolve_botocore_data, service_model, strip_source
|
|
|
|
REPO_ROOT = Path(__file__).resolve().parents[2]
|
|
|
|
|
|
def load_model(data: Path, model: Path) -> dict:
|
|
"""The `service-2.json` in the botocore version directory `model`, plain or gzipped."""
|
|
source = service_model(data / model)
|
|
if source is None:
|
|
raise SystemExit(f"error: no service model found in {data / model}")
|
|
return load_json_model(source)
|
|
|
|
|
|
def build(model: dict, provenance: str, generator: str, outputs: bool = False) -> dict:
|
|
shapes = model["shapes"]
|
|
kept: dict[str, dict] = {}
|
|
|
|
def keep(name: str, body_only: bool = False) -> None:
|
|
if name in kept:
|
|
return
|
|
shape = shapes[name]
|
|
kind = shape["type"]
|
|
entry: dict = {"type": kind}
|
|
kept[name] = entry
|
|
if kind == "structure":
|
|
members = {member: spec for member, spec in shape.get("members", {}).items()
|
|
if not (body_only and "location" in spec)}
|
|
entry["members"] = {member: spec["shape"] for member, spec in members.items()}
|
|
for spec in 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"], body_only=True)
|
|
if outputs and "output" in operation:
|
|
keep(operation["output"]["shape"], body_only=True)
|
|
|
|
return {
|
|
"_source": {
|
|
"generator": generator,
|
|
"botocore": provenance,
|
|
},
|
|
"operations": operations,
|
|
"shapes": dict(sorted(kept.items())),
|
|
}
|
|
|
|
|
|
def build_constraints(model: dict, operations: tuple[str, ...], provenance: str, generator: str) -> dict:
|
|
"""The input shapes of `operations` with the constraints `RequestConstraintCheck` reads: for every
|
|
shape reachable from one, its type, required members, min, max, pattern and enum, and the shapes
|
|
of its members, list elements or map keys and values. Unlike `build`, it keeps members bound to
|
|
the URI, query string or headers, so it suits the JSON protocols, whose members all travel in
|
|
the body."""
|
|
kept: dict[str, dict] = {}
|
|
|
|
def keep(name: str) -> None:
|
|
if name in kept:
|
|
return
|
|
shape = model["shapes"][name]
|
|
entry = {k: shape[k] for k in ("type", "required", "min", "max", "pattern", "enum") if k in shape}
|
|
kept[name] = entry
|
|
if shape["type"] == "structure":
|
|
entry["members"] = {k: v["shape"] for k, v in shape.get("members", {}).items()}
|
|
for child in entry["members"].values():
|
|
keep(child)
|
|
elif shape["type"] == "list":
|
|
entry["member"] = shape["member"]["shape"]
|
|
keep(entry["member"])
|
|
elif shape["type"] == "map":
|
|
for side in ("key", "value"):
|
|
entry[side] = shape[side]["shape"]
|
|
keep(entry[side])
|
|
|
|
inputs = {name: model["operations"][name]["input"]["shape"] for name in operations}
|
|
for name in inputs.values():
|
|
keep(name)
|
|
return {"_source": {"generator": generator, "botocore": provenance},
|
|
"operations": inputs, "shapes": dict(sorted(kept.items()))}
|
|
|
|
|
|
def render(doc: dict) -> str:
|
|
return json.dumps(doc, indent=2, sort_keys=False) + "\n"
|
|
|
|
|
|
def generator_name(script: str) -> str:
|
|
"""The script's path from the repository root, as the vendored file's `_source` records it, or
|
|
its file name when it runs from outside the repository."""
|
|
path = Path(script).resolve()
|
|
return path.relative_to(REPO_ROOT).as_posix() if path.is_relative_to(REPO_ROOT) else path.name
|
|
|
|
|
|
def main(argv: list[str] | None, *, script: str, model: Path, output: Path, description: str,
|
|
outputs: bool = False, operations: tuple[str, ...] | None = None,
|
|
prepare: Callable[[dict], dict] | None = None) -> int:
|
|
"""Drives one generator: parse the flags, read the model, write or check the vendored file.
|
|
|
|
`operations` picks the constraints flavour, keeping those operations' declared constraints
|
|
through `build_constraints` where the default keeps every operation's member types through
|
|
`build`. The two vendor different things and are driven the same way, which is why the
|
|
Query-protocol generators share this too rather than each repeating the flags and the
|
|
staleness check.
|
|
|
|
`prepare` is the one thing a generator may do to the model before any of that, for an operation
|
|
it vendors in part: IAM reduces a paged request to its paging members, the rest of it keeping
|
|
the reading it has today."""
|
|
parser = argparse.ArgumentParser(description=description, 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)
|
|
loaded = load_model(data, model)
|
|
if prepare is not None:
|
|
loaded = prepare(loaded)
|
|
generator = generator_name(script)
|
|
fresh = render(build_constraints(loaded, operations, provenance, generator) if operations is not None
|
|
else build(loaded, provenance, generator, outputs))
|
|
|
|
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")
|
|
shown = args.output.relative_to(REPO_ROOT) if args.output.is_relative_to(REPO_ROOT) else args.output
|
|
print(f"wrote {shown} from {provenance}")
|
|
return 0
|