Files
floci/tools/aws/regen_iam_shapes.py
T
Priamo Germosen c9c1c0990b feat(sts): read a Query request's declared constraints from the model (#6891)
`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.
2026-10-29 00:34:23 -05:00

93 lines
4.5 KiB
Python

#!/usr/bin/env python3
"""Vendor IAM request constraints from botocore's Apache-2.0 service model.
`IamRequestShapes` checks the operations listed here against the vendored file through the shared
`QueryConstraintCheck`: required members, lengths, patterns and enum values, as the model states
them. The list grows an operation at a time, each one taken off the hand-written checks in the
same change, so a wave is always reviewable against the messages it replaces.
Run from anywhere in the repo:
python3 tools/aws/regen_iam_shapes.py # rewrite the vendored file in place
python3 tools/aws/regen_iam_shapes.py --check # exit 1 when the vendored file is stale
"""
from __future__ import annotations
import sys
from pathlib import Path
import request_shapes
from request_shapes import REPO_ROOT
OUTPUT = REPO_ROOT / "src/main/resources/aws/iam-request-shapes.json"
MODEL = Path("iam/2010-05-08")
# One wave per group, each chosen so that no operation in it checks a declared constraint by hand,
# which is what keeps the vendored shapes adding the refusals AWS answers rather than rewording an
# answer already given.
#
# The managed-policy family, every member a scalar. `AttachRolePolicy` and `DetachRolePolicy` are
# the exception and the parity case: `IamService.validateRoleName` already answers `roleName` in
# Smithy's form.
#
# `GetAccountAuthorizationDetails` is the first operation read through the list walk. Its three
# members are declared and none of them is read at all today: `Filter` is a list of an enum,
# `MaxItems` a range and `Marker` a length and a pattern.
#
# The list operations follow it: every operation `aws/iam-paginators.json` pages, so `MaxItems`
# (1 to 1000) and `Marker` (1 to 320 characters) are held to the model here and nowhere else.
OPERATIONS = (
"AttachGroupPolicy", "AttachRolePolicy", "AttachUserPolicy",
"DetachGroupPolicy", "DetachRolePolicy", "DetachUserPolicy",
"GetPolicy", "DeletePolicy",
"CreatePolicyVersion", "GetPolicyVersion", "DeletePolicyVersion", "SetDefaultPolicyVersion",
"GetAccountAuthorizationDetails",
"GetGroup",
"ListAccessKeys", "ListAccountAliases", "ListAttachedGroupPolicies", "ListAttachedRolePolicies",
"ListAttachedUserPolicies", "ListDelegationRequests", "ListEntitiesForPolicy",
"ListGroupPolicies", "ListGroups", "ListGroupsForUser", "ListInstanceProfileTags",
"ListInstanceProfiles", "ListInstanceProfilesForRole", "ListMFADeviceTags", "ListMFADevices",
"ListOpenIDConnectProviderTags", "ListPolicies",
"ListPolicyTags", "ListPolicyVersions", "ListRolePolicies", "ListRoleTags", "ListRoles",
"ListSAMLProviderTags", "ListSSHPublicKeys", "ListServerCertificateTags",
"ListServerCertificates", "ListServiceSpecificCredentials", "ListSigningCertificates",
"ListUserPolicies", "ListUserTags", "ListUsers", "ListVirtualMFADevices",
)
# Paged operations vendored with their paging members alone, so `MaxItems` and `Marker` are still
# the model's while the rest of the request keeps the reading it has today.
PAGING_MEMBERS = ("Marker", "MaxItems")
PAGING_ONLY = (
# `JobId` is answered by hand as one fixed-length constraint ("length equal to 36"), which the
# walk would reword as a minimum; `SortKey` is held to its enum by hand too.
"GetOrganizationsAccessReport", "GetServiceLastAccessedDetails",
"GetServiceLastAccessedDetailsWithEntities",
# An empty `ServiceNamespaces` is answered by hand with `InvalidInput`, not the walk's null.
"ListPoliciesGrantingServiceAccess",
# `ContextEntries` nests a list inside a list of structures, which the walk refuses.
"SimulateCustomPolicy", "SimulatePrincipalPolicy",
)
def paging_only(model: dict, operations: tuple[str, ...] = PAGING_ONLY) -> dict:
"""`model` with each of `operations` reduced to its paging members, `PAGING_ONLY` by default."""
shapes = dict(model["shapes"])
for operation in operations:
name = model["operations"][operation]["input"]["shape"]
request = shapes[name]
shapes[name] = {"type": request["type"],
"members": {k: v for k, v in request["members"].items() if k in PAGING_MEMBERS}}
return {**model, "shapes": shapes}
# What the vendored file carries: the operations read whole, then the paged ones read in part.
VENDORED = OPERATIONS + PAGING_ONLY
def main(argv: list[str] | None = None) -> int:
return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT,
description=__doc__, operations=VENDORED, prepare=paging_only)
if __name__ == "__main__":
sys.exit(main())