Files
floci/tools/aws/test_regen_iam_paginators.py
T
Allen Sanborn 3212ce3c15 fix(iam): page ListUsers, ListGroups and policy lists with MaxItems and Marker (#6267)
* fix(iam): page ListUsers, ListGroups and policy lists with MaxItems and Marker

ListUsers, ListGroups, ListAttached{User,Group,Role}Policies and
List{User,Group,Role}Policies read neither MaxItems nor Marker and always
answered IsTruncated=false with every entry. They now go through the same
paginate helper ListRoles and ListPolicies use: an omitted MaxItems returns
100 items as the API reference documents, a MaxItems outside 1 to 1000 is a
ValidationError, a Marker the handler did not issue is InvalidInput, and a
Marker appears only on a truncated page.

Users, groups and inline policy names are listed in name order and attached
policies in ARN order, so a Marker keeps pointing at the same place between
calls even when the entry it names is removed in between.

* fix(iam): resume the newly paged IAM lists only from their own markers

ListUsers, ListGroups and the attached and inline policy lists read a
Marker they could not verify as a list offset, so Marker=1 silently
skipped the first entry, and a marker issued for one role's list resumed
another role's list after the same policy. These lists have only ever
issued signed markers, so their cursor now carries the action and, for a
per-principal list, the principal, and any other marker is InvalidInput.
ListRoles, ListPolicies and the other readers keep their existing marker
handling.

Also covers the omitted-MaxItems default on ListUsers and ListGroups with
101 entries: 100 on the first page, IsTruncated and a Marker that fetches
the last one.

* fix(iam): bind the newly paged IAM lists' markers to the request account

IAM entities are stored per account, but the marker cursor named only the
action and principal, so a marker issued in one account resumed the same
listing in another account after the same name and skipped its earlier
entries. The cursor now carries the account the request reads from, and a
marker from another account is InvalidInput.

* feat(iam): generate the IAM paginator table from botocore

tools/aws/regen_iam_paginators.py writes src/main/resources/aws/iam-paginators.json
from botocore's iam/2010-05-08 model, as the other tools/aws generators do: every
operation whose request models Marker, with its input and output token, limit
key, truncation flag and result keys, the MaxItems bounds of maxItemsType
(1 to 1000), the default page size the limit's documentation states ("defaults
to 100"), and markerType's bounds.

The 34 operations botocore's paginators-1.json lists take their tokens and
result keys from it. The six that model Marker without a paginator
(GetServiceLastAccessedDetails, GetServiceLastAccessedDetailsWithEntities,
GetOrganizationsAccessReport, ListServiceSpecificCredentials,
ListDelegationRequests, ListPoliciesGrantingServiceAccess) are read from
their request and response shapes and marked paginator: false.
ListServiceSpecificCredentials documents no default and
ListPoliciesGrantingServiceAccess models no MaxItems; the table records
both as such rather than inventing a value.

make aws-data-sync regenerates it and make aws-data-check fails when it is
stale against the pinned botocore.

* fix(iam): page every IAM list through one path driven by the paginator table

IamQueryHandler paged eight lists by hand through paginateScoped, a few more
through paginate, and left the rest (the tag readers, ListAccessKeys,
ListInstanceProfiles, ListPolicyVersions, GetGroup, ListGroupsForUser,
ListEntitiesForPolicy, GetAccountAuthorizationDetails, the simulations and
others) ignoring MaxItems and Marker with IsTruncated=false. Every operation
the generated aws/iam-paginators.json lists now pages through one paginate
path that reads its entry: the limit's bounds and default, the members that
resume and continue it, and the result keys pagedList and pagedLists write
under. paginateScoped, paginateByMarker and the hardcoded 100/1000 are gone.
ListEntitiesForPolicy and GetAccountAuthorizationDetails page their several
lists as one, in the paginator's order.

Marker semantics, chosen deliberately: a Marker is opaque and resumes only the
listing that issued it, on every paged operation. AWS documents it as "the
value of the Marker element in the response that you received", so a value
Floci did not issue, a bare number included, is InvalidInput; ListRoles,
ListPolicies and the report readers no longer read one as an index. The
marker names the last item of its page, so a deletion or creation ahead of
it skips nothing and repeats nothing, and it is signed (not prefixed) over
the account, the operation and every request member except Marker and
MaxItems, so a marker from another operation, principal, filter or account
is refused while the page size may change between calls. Signing the scope
instead of carrying it keeps issued markers short. markerType's 320-character
bound is not checked separately: every other value is refused as unissued,
and a long ARN key could otherwise push an issued marker past it.

MaxItems is now checked before Marker, as a malformed request is rejected
before anything is read from it. An omitted MaxItems is the documented 100;
ListServiceSpecificCredentials, which documents no default, returns its whole
list.

IamListPaginationIntegrationTest.everyPaginatedOperationHonoursMaxItemsAndMarker
iterates the table's 34 paginated operations, each with a fixture listing two
items, and checks the MaxItems bounds, a one-item page, resumption without
loss or repetition, the default page, and refusal of an unissued, bare-index
or other operation's marker. Its fixture map must name exactly the table's
operations, so one AWS starts paging later fails until it has one.
ListAccountAliases can hold one alias, so it is checked for everything but a
cut page. The tests the table test subsumes are removed; the ordering, anchor,
cross-listing and cross-account tests stay. Two ServiceLastAccessed tests
that walked by bare index now use issued markers.

* fix(iam): hold paged requests to the model through IamRequestShapes

MaxItems and Marker are request constraints, and main now checks a
request against the model before it runs. Every operation the paginator
table pages joins that wave in regen_iam_shapes.py, and the bounds leave
iam-paginators.json (which keeps only defaultItems, the documented page
size) and limit(), which now only parses the number and applies the
default. A pytest pins that every operation the paginator table carries
is in the wave, so a list AWS starts paging later cannot slip past the
bounds.

Six paged operations join with Marker and MaxItems alone: the three
report readers, whose JobId is answered by hand as "length equal to 36"
and whose SortKey enum is checked by hand; ListPoliciesGrantingServiceAccess,
whose empty ServiceNamespaces is answered InvalidInput; and the two
Simulate operations, whose ContextEntries nest a list inside a list of
structures, which the walk refuses. Vendoring their whole request would
reword answers main already settled; vendoring nothing would leave their
paging unbounded (SimulateCustomPolicy with MaxItems=0 was a 500).

Markers fit markerType's 320 characters. A marker embeds the key of the
item its page ended on, so a policy ARN with a long path produced one
of 610 characters, which the model check would now refuse on the way
back. SignedMarkers takes a maximum length: a cursor that would exceed
it is carried as a SHA-256 digest (119 characters once signed and
encoded), and the instance keeps the digest -> key mapping. That keeps
the existing resume semantics exactly: the marker still resolves to the
full key, so a deleted anchor resumes at the first key after it, and
the signature still binds account, operation and filter. Two stateless
alternatives were rejected: a truncated key prefix plus digest cannot
order a deleted anchor against items sharing the prefix, and a position
index skips or repeats when items ahead of it are deleted. The cost is
one map entry per distinct long key a page has ended on, never evicted
(marked ponytail in the code); markers already do not survive a
restart, as the signing key is per instance. Keys short enough to embed
are carried as before.

Checkstyle (./mvnw checkstyle:check) reported six errors in files this
PR touches: javax import order and two inline org.w3c.dom.Node in the
pagination test, and an inline java.util.Base64 in SignedMarkersTest.
The test now parses through XmlParser.parseDocument instead of its own
DocumentBuilderFactory. The switch statements in ListEntitiesForPolicy
and the test's holder fixture are switch expressions.

Tests: aMarkerEndingOnALongPolicyArnFitsTheModelAndResumesPastItsDeletion
attaches three policies under a 391-character path, pages with
MaxItems=1, deletes the anchor and resumes through the model check.
Constructing SignedMarkers without the limit fails it (610 characters);
restoring the pre-wave iam-request-shapes.json fails the table-driven
test (MaxItems=0 answered 500, MaxItems=1001 answered 200).

* fix(iam): bind a caller-resolved list's marker to the resolved user

ListAccessKeys, ListMFADevices, ListSSHPublicKeys, ListSigningCertificates
and ListServiceSpecificCredentials default an omitted UserName to the
caller. The marker was signed over the raw request members, so two users
in one account who both omitted UserName shared a scope and one's marker
resumed the other's listing. These handlers now page over the request
with UserName set to the resolved user, so the marker is bound to the
user the list was read for, named or implicit.

* fix(iam): bound the SignedMarkers digest map and trim the pagination test

SignedMarkers held every long cursor it had issued a digest for, in a map
that never shrank. It is now an access-ordered LinkedHashMap capped at
10,000 entries, the idiom CloudWatch Logs uses for its Insights queries. A
marker whose digest was evicted resolves to null, the same as an unknown
digest, so callers refuse it as an invalid marker.

IamListPaginationIntegrationTest spent most of its time in RestAssured's
per-request overhead on the hundred-item fixtures. Those creates and
deletes now go concurrently through java.net.http. The users and groups
default test keeps its first-page checks of the default of 100 and drops
the second page, which the roles default test and the every-operation test
already cover. The SSH public key fixture is generated once per run.
2026-10-28 16:37:49 -04:00

129 lines
5.5 KiB
Python

"""Tests for regen_iam_paginators.
Run with: pytest tools/aws -q (or: make aws-data-test)
"""
from __future__ import annotations
import json
import pytest
import regen_iam_paginators as r
MAX_ITEMS_DOC = "<p>If you do not include this parameter, the number of items defaults to 100.</p>"
def model(**operations: tuple[dict, dict]) -> dict:
"""A model whose operations map to (request members, response members), each member naming
its shape."""
shapes = {
"maxItemsType": {"type": "integer", "min": 1, "max": 1000},
"markerType": {"type": "string", "min": 1, "max": 320, "pattern": "[\\u0020-\\u00FF]+"},
"booleanType": {"type": "boolean"},
"listType": {"type": "list"},
}
ops = {}
for name, (request, response) in operations.items():
shapes[f"{name}Request"] = {"type": "structure", "members": request}
shapes[f"{name}Response"] = {"type": "structure", "members": response}
ops[name] = {"input": {"shape": f"{name}Request"}, "output": {"shape": f"{name}Response"}}
return {"operations": ops, "shapes": shapes}
PAGED_REQUEST = {"Marker": {"shape": "markerType"},
"MaxItems": {"shape": "maxItemsType", "documentation": MAX_ITEMS_DOC}}
def paged_response(*lists: str) -> dict:
return {**{key: {"shape": "listType"} for key in lists},
"IsTruncated": {"shape": "booleanType"}, "Marker": {"shape": "markerType"}}
def paginator(*result_keys: str) -> dict:
return {"input_token": "Marker", "output_token": "Marker", "limit_key": "MaxItems",
"more_results": "IsTruncated",
"result_key": result_keys[0] if len(result_keys) == 1 else list(result_keys)}
def test_a_paginator_names_its_tokens_lists_and_default_but_no_bounds():
found = r.operations_from(model(ListRoles=(PAGED_REQUEST, paged_response("Roles"))),
{"ListRoles": paginator("Roles")})
assert found == {"ListRoles": {
"paginator": True, "inputToken": "Marker", "outputToken": "Marker", "limitKey": "MaxItems",
"moreResults": "IsTruncated", "resultKeys": ["Roles"], "defaultItems": 100,
}}
def test_several_result_keys_are_kept_in_the_paginators_order():
found = r.operations_from(
model(ListEntitiesForPolicy=(PAGED_REQUEST, paged_response("PolicyGroups", "PolicyUsers"))),
{"ListEntitiesForPolicy": paginator("PolicyGroups", "PolicyUsers")})
assert found["ListEntitiesForPolicy"]["resultKeys"] == ["PolicyGroups", "PolicyUsers"]
def test_an_operation_paged_without_a_paginator_is_read_from_its_shapes():
# ListDelegationRequests spells the flag isTruncated, and the table keeps the model's spelling.
response = {"DelegationRequests": {"shape": "listType"}, "Marker": {"shape": "markerType"},
"isTruncated": {"shape": "booleanType"}}
found = r.operations_from(model(ListDelegationRequests=(PAGED_REQUEST, response)), {})
entry = found["ListDelegationRequests"]
assert entry["paginator"] is False
assert entry["moreResults"] == "isTruncated"
assert entry["resultKeys"] == []
def test_a_request_without_max_items_has_no_limit():
found = r.operations_from(model(ListPoliciesGrantingServiceAccess=(
{"Marker": {"shape": "markerType"}}, paged_response("PoliciesGrantingServiceAccess"))), {})
assert found["ListPoliciesGrantingServiceAccess"]["limitKey"] is None
assert "defaultItems" not in found["ListPoliciesGrantingServiceAccess"]
def test_an_undocumented_default_is_null_rather_than_invented():
request = {"Marker": {"shape": "markerType"}, "MaxItems": {"shape": "maxItemsType"}}
found = r.operations_from(model(ListServiceSpecificCredentials=(request, paged_response("C"))), {})
assert found["ListServiceSpecificCredentials"]["defaultItems"] is None
def test_an_operation_without_a_marker_is_left_out():
assert r.operations_from(model(GetUser=({}, {"User": {"shape": "listType"}})), {}) == {}
def test_a_paginator_naming_a_member_the_shapes_lack_is_refused():
with pytest.raises(ValueError, match="response has no Users"):
r.operations_from(model(ListRoles=(PAGED_REQUEST, paged_response("Roles"))),
{"ListRoles": paginator("Users")})
def test_a_paginator_for_an_operation_without_a_marker_is_refused():
with pytest.raises(ValueError, match="no Marker"):
r.operations_from(model(ListRoles=({}, paged_response("Roles"))), {"ListRoles": paginator("Roles")})
def test_check_ignores_the_provenance_and_catches_a_changed_entry(tmp_path):
directory = tmp_path.joinpath("data", *r.MODEL_DIR)
directory.mkdir(parents=True)
(directory / "service-2.json").write_text(
json.dumps(model(ListRoles=(PAGED_REQUEST, paged_response("Roles")))), encoding="utf-8")
(directory / "paginators-1.json").write_text(
json.dumps({"pagination": {"ListRoles": paginator("Roles")}}), encoding="utf-8")
data = str(tmp_path / "data")
output = tmp_path / "iam-paginators.json"
assert r.main(["--botocore-data", data, "--output", str(output)]) == 0
assert r.main(["--check", "--botocore-data", data, "--output", str(output)]) == 0
stale = json.loads(output.read_text(encoding="utf-8"))
stale["_source"]["botocore"] = "another label"
output.write_text(json.dumps(stale), encoding="utf-8")
assert r.main(["--check", "--botocore-data", data, "--output", str(output)]) == 0
stale["operations"]["ListRoles"]["defaultItems"] = 10
output.write_text(json.dumps(stale), encoding="utf-8")
assert r.main(["--check", "--botocore-data", data, "--output", str(output)]) == 1