Files
floci/tools/aws/test_regen_iam_request_resources.py
T
Priamo Germosen 5c303afac6 fix(iam): check four more services on the resources their requests name (#7365)
Under IAM enforcement, DataSync, EMR, Rekognition and IAM Identity
Center requests were checked on `*`, so a grant scoped to a DataSync
agent, an EMR cluster, an Identity Center permission set or a
Rekognition custom model was refused, and a deny scoped to one never
applied.

The generated table of the resources requests name now reads them, 276
operations, from AWS's Service Reference and botocore as it reads the
earlier batches: their namespaces move from the generator's
NOT_COVERED to NAMESPACES and the table is regenerated, nothing in it
edited by hand; 1385 operations over 33 namespaces. Each resource
type Floci serves has the ARN format it mints: DataSync's
`agent/agent-<id>`, `location/loc-<id>` and `task/task-<id>`, EMR's
`cluster/<id>`, and IAM Identity Center's instances and permission
sets, with no Region or account. Of Rekognition, Floci serves the image
analyses alone, which act on no resource but a custom model.

Corrections, each with its reason:

- EMR requests naming a cluster by its job flow id, JobFlowId or
  JobFlowIds (AddInstanceGroups, AddJobFlowSteps, DescribeJobFlows,
  TerminateJobFlows and the four Set operations), are checked on that
  cluster: a job flow's id is the cluster's.
- EMR's AddTags and RemoveTags are checked on the cluster their
  ResourceId names, the one Floci tags, not on the one their ClusterId
  gives, which only scopes a session-scoped resource's tags. Read as
  generated, a ClusterId the grant covers would have let a request tag
  another cluster.
- EMR's ModifyInstanceGroups may leave out its ClusterId ("Required:
  No") and name each instance group by its id alone, which EMR then
  finds the cluster of. Such a request is checked on the cluster each
  group is in, where it was checked on `*`; a null ClusterId is read as
  none, as the handler reads it. An InstanceGroups that is not a list
  names no group to the check, and the handler now refuses it as naming
  none, where it modified the groups an object's values named.
- Rekognition's stream processor operations are checked on
  `streamprocessor/<Name>`: the Developer Guide's example gives a
  processor named streamProcessorForCam the ARN
  `...:streamprocessor/streamProcessorForCam`.
- IAM Identity Center's CreateAccountAssignment,
  DeleteAccountAssignment and ProvisionPermissionSet are also checked on
  the account their TargetId names, `account/<id>`, which the action
  acts on beside the instance and the permission set. A
  ProvisionPermissionSet for ALL_PROVISIONED_ACCOUNTS names no TargetId
  and provisions the permission set to every account it is provisioned
  to (the User Guide: up to 3,500 accounts that way, one with
  AWS_ACCOUNT), so it is checked on each of them, where a grant on the
  instance and the permission set alone let it through. Its TargetId
  names the account only for AWS_ACCOUNT, so a null one with
  ALL_PROVISIONED_ACCOUNTS names none.

The two lookups are the existing `through` entries, which named the
cluster or workgroup a Redshift Data session runs on: one may now read
each value of a list's field, and apply only `when` the request names
its resource no other way. StoredResourceArns.through gives a list of
ARNs, which EmrService and SsoAdminService now answer from what they
store, EmrService under the lock its handlers change clusters under.

Fixes the new formats needed:

- DataSync's ARN formats, and IAM Identity Center's applications' and
  trusted token issuers', name their account `${AccountId}` where every
  other format has `${Account}`. The generator now reads that slot as
  `${Account}`, so the caller's account fills it; a new Identity Center
  application was otherwise checked on `arn:aws:sso::*:application/*/*`,
  which no account-scoped grant matches.
- Identity Center's application providers are AWS's own,
  `arn:aws:sso::aws:applicationProvider/<id>`. An ARN of a type whose
  format fixes the account as `aws` is now checked in that account
  alone, not also as the caller's own copy, which does not exist and
  which a grant on the provider did not cover. An ARN of any other type
  giving the account `aws` is still checked as the caller's too.
- A permission set, an application or a trusted token issuer an
  Identity Center create makes is in the instance its InstanceArn
  names, whose id its ARN carries, `permissionSet/<instance id>/<id>`.
  It was checked with both ids open, which no grant scoped to an
  instance's permission sets matched. The generator now fills a variable
  no member fills from the ARN of another type the action acts on whose
  format is that variable alone, given by the ARN member named after it.

Left as generated, on `*`: Rekognition's CreateStreamProcessor and
StartMediaAnalysisJob, which name their collection or model two
structures deep, where the table reads none, and which Floci does not
serve.

Elastic Beanstalk and Redshift Serverless, which have as few resource
types, stay unread, each with its reason: an environment's ARN carries
an application name its requests do not give, and Redshift Serverless'
ARNs end in ids its requests name by name, so both need the stored
ARNs found first.

iam.md lists the four services, and AWS Payment Cryptography, which
the table already read, and gives the corrections, the rule for an
AWS-owned resource's ARN, and the cluster, accounts and instance the
lookups and the creates are checked on.
2026-11-03 17:14:32 -06:00

764 lines
52 KiB
Python

"""Tests for regen_iam_request_resources.
Run with: pytest tools/aws -q (or: make iam-request-resources-test)
"""
from __future__ import annotations
import json
from pathlib import Path
import pytest
import regen_iam_request_resources as r
FORMATS = {
"thing": "arn:${Partition}:svc:${Region}:${Account}:thing/${ThingName}",
"group": "arn:${Partition}:svc:${Region}:${Account}:group/${GroupName}/${GroupId}",
"pool": "arn:${Partition}:svc:${Region}:${Account}:pool/${PoolId}",
"catalog": "arn:${Partition}:svc:${Region}:${Account}:catalog",
"lb": "arn:${Partition}:svc:${Region}:${Account}:loadbalancer/${LoadBalancerName}",
"lb/app/": "arn:${Partition}:svc:${Region}:${Account}:loadbalancer/app/${LoadBalancerName}/${LoadBalancerId}",
}
def members(*names: str) -> dict[str, str]:
return {name.rstrip("[]"): name for name in names}
def test_a_member_holding_an_arn_names_any_type_the_action_acts_on():
assert r.resources_for("svc:DescribeThing", ["thing", "pool"], FORMATS, members("ThingArn", "ResourceArns[]")) == [
{"types": ["thing", "pool"], "arn": "ResourceArns[]"}, {"types": ["thing", "pool"], "arn": "ThingArn"}]
def test_a_member_fills_a_variable_its_stem_relates_to_and_of_its_kind():
assert r.resources_for("svc:GetThing", ["thing"], FORMATS, members("ThingName")) == [
{"type": "thing", "fill": {"ThingName": "ThingName"}}]
# A name fills a name and leaves an id open; an identifier fills either.
assert r.resources_for("svc:UpdateGroup", ["group"], FORMATS, members("GroupName")) == [
{"type": "group", "fill": {"GroupName": "GroupName"}}]
assert r.resources_for("svc:UpdatePool", ["pool"], FORMATS, members("PoolIdentifier")) == [
{"type": "pool", "fill": {"PoolId": "PoolIdentifier"}}]
# A longer name ending with the variable's stem fills it.
assert r.resources_for("svc:GetThing", ["thing"], FORMATS, members("SpecialThingName")) == [
{"type": "thing", "fill": {"ThingName": "SpecialThingName"}}]
def test_a_bare_name_fills_the_type_the_operation_is_about_and_no_other():
assert r.resources_for("svc:CreateThing", ["thing"], FORMATS, members("Name")) == [
{"type": "thing", "fill": {"ThingName": "Name"}}]
assert r.resources_for("svc:DescribeGroups", ["group"], FORMATS, members("Names[]")) == [
{"type": "group", "fill": {"GroupName": "Names[]"}}]
# StartRun's name is the run's, not the thing's.
assert r.resources_for("svc:StartRun", ["thing"], FORMATS, members("name")) == []
# A member holding the type's ARN leaves the bare name to something else.
assert r.resources_for("svc:CreateThingAlias", ["thing"], FORMATS, members("Name")) == []
def test_a_fixed_format_and_a_creates_own_type_are_named_without_members():
assert r.resources_for("svc:GetCatalog", ["catalog"], FORMATS, {}) == [{"type": "catalog", "fill": {}}]
assert r.resources_for("svc:CreatePool", ["pool"], FORMATS, members("Description")) == [{"type": "pool", "fill": {}}]
# Another type the action lists, which the request does not name, is not checked.
assert r.resources_for("svc:CreatePool", ["pool", "thing"], FORMATS, members("Description")) == [
{"type": "pool", "fill": {}}]
def test_types_named_only_through_the_same_members_are_alternatives():
# A classic load balancer's name fills its whole ARN, not an application one's id: the classic one is kept.
assert r.resources_for("svc:DeleteLoadBalancer", ["lb", "lb/app/"], FORMATS, members("LoadBalancerName")) == [
{"type": "lb", "fill": {"LoadBalancerName": "LoadBalancerName"}}]
def test_a_type_is_filled_from_one_list_at_most():
formats = {"pair": "arn:${Partition}:svc:${Region}:${Account}:pair/${LeftName}/${RightName}"}
assert r.resources_for("svc:GetPair", ["pair"], formats, members("LeftNames[]", "RightNames[]")) == []
# Only an operation that creates its type names it with every variable open.
assert r.resources_for("svc:GetPair", ["pair"], formats, {}) == []
LISTENERS = {
"loadbalancer/app/": FORMATS["lb/app/"],
"listener/app": "arn:${Partition}:svc:${Region}:${Account}:listener/app/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}",
"rule/app": "arn:${Partition}:svc:${Region}:${Account}:rule/app/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}/${RuleId}",
"pair": "arn:${Partition}:svc:${Region}:${Account}:pair/app/${LoadBalancerName}/${LoadBalancerId}/${A}/${B}",
}
def test_a_child_format_is_its_parents_with_the_type_word_replaced_and_one_id_appended():
assert r.child_id(LISTENERS["listener/app"], LISTENERS["loadbalancer/app/"]) == "ListenerId"
assert r.child_id(LISTENERS["rule/app"], LISTENERS["listener/app"]) == "RuleId"
# Two ids appended, a grandchild, the parent itself and the same type word are no children.
assert r.child_id(LISTENERS["pair"], LISTENERS["loadbalancer/app/"]) is None
assert r.child_id(LISTENERS["rule/app"], LISTENERS["loadbalancer/app/"]) is None
assert r.child_id(LISTENERS["loadbalancer/app/"], LISTENERS["loadbalancer/app/"]) is None
assert r.child_id(FORMATS["group"], FORMATS["lb"]) is None
def test_a_create_of_a_child_of_a_type_its_action_acts_on_names_it_from_the_parents_arn():
assert r.creates_for("svc:CreateListener", ["loadbalancer/app/"], LISTENERS, members("LoadBalancerArn", "RoleArn")) == [
{"type": "listener/app", "parent": "loadbalancer/app/", "arn": "LoadBalancerArn"}]
assert r.creates_for("svc:CreateRule", ["listener/app"], LISTENERS, members("ListenerArn")) == [
{"type": "rule/app", "parent": "listener/app", "arn": "ListenerArn"}]
# Only a creating verb, a child named after what it creates, and a type its action does not act on.
assert r.creates_for("svc:DescribeListeners", ["loadbalancer/app/"], LISTENERS, members("LoadBalancerArn")) == []
assert r.creates_for("svc:CreateRule", ["loadbalancer/app/"], LISTENERS, members("LoadBalancerArn")) == []
assert r.creates_for("svc:CreateListener", ["loadbalancer/app/", "listener/app"], LISTENERS, members("LoadBalancerArn")) == []
# A parent's ARN in no member, or in one of another type, names nothing.
assert r.creates_for("svc:CreateListener", ["loadbalancer/app/"], LISTENERS, members("Name")) == []
assert r.creates_for("svc:CreateListener", ["loadbalancer/app/"], LISTENERS, members("RoleArn")) == []
def test_an_arn_inside_a_structure_or_a_lists_structures_is_read_by_its_path():
shapes = {"String": {"type": "string"}, "Strings": {"type": "list", "member": {"shape": "String"}},
"Priority": {"type": "structure", "members": {"RuleArn": {"shape": "String"}, "Priority": {"shape": "String"},
"TargetArns": {"shape": "Strings"}}},
"Priorities": {"type": "list", "member": {"shape": "Priority"}},
"Config": {"type": "structure", "members": {"RoleArn": {"shape": "String"}, "Name": {"shape": "String"}}},
"In": {"type": "structure", "members": {"RulePriorities": {"shape": "Priorities"}, "Config": {"shape": "Config"},
"ListenerArn": {"shape": "String"}}}}
models = {"svc": {"metadata": {"protocol": "query"}, "operations": {"SetRulePriorities": {"input": {"shape": "In"}}},
"shapes": shapes}}
found = r.request_members(models, "SetRulePriorities")
assert found == {"RulePriorities[].RuleArn": "RulePriorities[].RuleArn",
"RulePriorities[].TargetArns": "RulePriorities[].TargetArns[]", "Config.RoleArn": "Config.RoleArn",
"ListenerArn": "ListenerArn"}
# Each holds the ARN of any type the action acts on, as a top-level one does, and neither holds the type
# the way a top-level member named for it does, nor names the parent of a create.
resources = r.resources_for("svc:SetRulePriorities", ["thing"], FORMATS, found)
assert {"types": ["thing"], "arn": "RulePriorities[].RuleArn"} in resources
assert r.creates_for("svc:CreateThing", ["thing"], FORMATS, {"Parts[].ThingArn": "Parts[].ThingArn"}) == []
def test_a_create_naming_others_marks_what_it_makes():
formats = {"webhook": "arn:${Partition}:svc:${Region}:${Account}:webhook:${WebhookName}",
"pipeline": "arn:${Partition}:svc:${Region}:${Account}:${PipelineName}",
"lb": FORMATS["lb"], "lb/app/": FORMATS["lb/app/"]}
webhook = {"type": "webhook", "fill": {"WebhookName": "webhook.name"}}
pipeline = {"type": "pipeline", "fill": {"PipelineName": "webhook.targetPipeline"}}
assert r.with_made([webhook, pipeline], "svc:PutWebhook", formats) == [dict(webhook, made=True), pipeline]
# A type made by its ARN format's leading resource word, so every load balancer type is made; with every
# resource made, or none, or for no create, nothing is marked.
classic = {"type": "lb", "fill": {"LoadBalancerName": "LoadBalancerName"}}
app = {"type": "lb/app/", "fill": {"LoadBalancerName": "Name"}}
assert r.with_made([classic, app], "svc:CreateLoadBalancer", formats) == [classic, app]
assert r.with_made([pipeline], "svc:PutWebhook", formats) == [pipeline]
assert r.with_made([webhook, pipeline], "svc:DescribeWebhook", formats) == [webhook, pipeline]
# A member that may hold the ARN of the parent too names no resource the create makes.
parent = {"types": ["pipeline", "webhook"], "arn": "PipelineArn"}
assert r.with_made([parent, webhook], "svc:PutWebhook", formats) == [parent, dict(webhook, made=True)]
def test_a_type_made_in_another_takes_that_ones_id_from_the_arn_member_named_after_it():
formats = {"instance": "arn:${Partition}:svc:::instance/${InstanceId}",
"set": "arn:${Partition}:svc:::set/${InstanceId}/${SetId}",
"pool": FORMATS["pool"]}
made = {"type": "set", "fill": {}, "made": True}
instance = {"types": ["instance", "set"], "arn": "InstanceArn"}
assert r.with_parent_ids([instance, made], formats, ["instance", "set"], members("InstanceArn", "Name")) == [
instance, {"type": "set", "fill": {"InstanceId": "InstanceArn"}, "arnOf": {"InstanceArn": "instance"},
"made": True}]
# Not from a type the action does not act on, a member in a structure, or with two ARN members to pick from,
# and not over a variable a member fills already.
assert r.with_parent_ids([made], formats, ["set"], members("InstanceArn")) == [made]
assert r.with_parent_ids([made], formats, ["instance", "set"], {"InstanceArn": "Config.InstanceArn"}) == [made]
assert r.with_parent_ids([made], formats, ["instance", "set"],
members("InstanceArn", "SourceInstanceArn")) == [made]
filled = {"type": "set", "fill": {"InstanceId": "InstanceId"}}
assert r.with_parent_ids([filled], formats, ["instance", "set"], members("InstanceArn", "InstanceId")) == [filled]
def test_stems_drop_the_suffixes_names_carry():
assert r.stem("TargetGroupArns") == "targetgroup"
assert r.stem("DBInstanceIdentifier") == "dbinstance"
# A plural's s goes, from a type's name and a member's alike, so they still meet.
assert r.related(r.stem("EventBusName"), r.stem("event-bus"))
assert r.related("autoscalinggroup", "group") and not r.related("ab", "b")
def reference(namespace: str, operations: dict[str, list[str]], resources: dict[str, str]) -> dict:
"""A Service Reference document: each operation its own action, acting on the types given."""
return {"Name": namespace,
"Actions": [{"Name": name, "Resources": [{"Name": kind} for kind in types]} for name, types in operations.items()],
"Operations": [{"Name": name, "AuthorizedActions": [{"Service": namespace, "Name": name}],
"SDK": [{"Name": namespace, "Method": name, "Package": "Boto3"}]} for name in operations],
"Resources": [{"Name": kind, "ARNFormats": [arn]} for kind, arn in resources.items()]}
def model(operations: dict[str, dict[str, str]], protocol: str = "json") -> dict:
"""A botocore model whose operations take the members given, each a string or a list of strings."""
shapes = {"String": {"type": "string"}, "Strings": {"type": "list", "member": {"shape": "String"}},
"AccountId": {"type": "string", "pattern": "[0-9]{12}"}}
ops = {}
for name, fields in operations.items():
shapes[name + "In"] = {"type": "structure", "members": {field: {"shape": shape} for field, shape in fields.items()}}
ops[name] = {"input": {"shape": name + "In"}}
return {"metadata": {"protocol": protocol}, "operations": ops, "shapes": shapes}
@pytest.fixture
def corrections(monkeypatch):
monkeypatch.setattr(r, "NAMESPACES", ("svc",))
monkeypatch.setattr(r, "HAND_BUILT", ("hand",))
monkeypatch.setattr(r, "NOT_COVERED", {"later": "a later batch"})
monkeypatch.setattr(r, "CORRECTIONS", {})
monkeypatch.setattr(r, "READ_IN_HAND_BUILT", {})
monkeypatch.setattr(r, "UNQUALIFIED", {})
monkeypatch.setattr(r, "MINTED_IDS", {})
monkeypatch.setattr(r, "FOUND_BY", {})
monkeypatch.setattr(r, "THROUGH", {})
monkeypatch.setattr(r, "CLIENTS_NOT_READ", {})
return monkeypatch
def write_models(root, models: dict[str, dict]):
for name, value in models.items():
directory = root / name / "2020-01-01"
directory.mkdir(parents=True)
(directory / "service-2.json").write_text(json.dumps(value), encoding="utf-8")
DOCUMENTS = [reference("svc", {"GetThing": ["thing"], "ListThings": []}, {"thing": FORMATS["thing"]}),
reference("other", {"Op": ["x"]}, {"x": "arn:${Partition}:other:::x"}),
reference("later", {"Op": ["y"]}, {"y": "arn:${Partition}:later:::y"})]
def test_a_built_document_validates_matches_botocore_and_names_the_namespaces_it_does_not_read(corrections, tmp_path):
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}})})
document = r.build(DOCUMENTS, "test", tmp_path, "botocore test")
assert r.validate(document) == []
assert r.derive(document, tmp_path) == []
assert document["operations"]["svc:GetThing"] == {"action": "svc:GetThing", "types": ["thing"],
"resources": [{"type": "thing", "fill": {"ThingName": "ThingName"}}]}
assert document["operations"]["svc:ListThings"]["resources"] == []
assert document["otherNamespaces"] == ["other"]
assert json.loads(r.render(document)) == document
def test_a_member_holding_an_account_id_gives_the_account_of_the_types_named_by_variables(corrections, tmp_path):
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String", "registryId": "AccountId"},
"ListThings": {"registryId": "AccountId"}})})
document = r.build(DOCUMENTS, "test", tmp_path, "botocore test")
assert r.validate(document) == [] and r.derive(document, tmp_path) == []
assert document["operations"]["svc:GetThing"]["resources"] == [
{"type": "thing", "fill": {"ThingName": "ThingName"}, "account": "registryId"}]
# An ARN carries its own account, and a format without one takes none.
assert r.with_account([{"types": ["thing"], "arn": "ThingArn"}], FORMATS, ["registryId"]) == [
{"types": ["thing"], "arn": "ThingArn"}]
assert r.with_account([{"type": "catalog", "fill": {}}], {"catalog": "arn:${Partition}:svc:::catalog"},
["registryId"]) == [{"type": "catalog", "fill": {}}]
# Two account members, either of which it could be, give none.
assert r.with_account([{"type": "thing", "fill": {}}], FORMATS, ["a", "b"]) == [{"type": "thing", "fill": {}}]
def test_a_format_whose_account_is_an_account_id_variable_takes_the_account_every_other_format_does():
documents = [reference("svc", {}, {"agent": "arn:${Partition}:svc:${Region}:${AccountId}:agent/${AgentId}",
"account": "arn:${Partition}:svc:::account/${AccountId}",
"thing": FORMATS["thing"]})]
# An account id in the resource, past the account, stays a variable a member fills.
assert r.arn_formats(documents, {"svc"}) == {"svc": {
"account": "arn:${Partition}:svc:::account/${AccountId}",
"agent": "arn:${Partition}:svc:${Region}:${Account}:agent/${AgentId}",
"thing": FORMATS["thing"]}}
def test_a_file_that_is_not_json_is_reported_and_not_read(corrections, tmp_path, capsys):
output = tmp_path / "iam-request-resources.json"
output.write_text("{not json", encoding="utf-8")
for mode in ("--check", "--verify"):
assert r.main([mode, "--output", str(output)]) == 1
assert "could not be read" in capsys.readouterr().err
def test_a_file_that_cannot_be_read_is_reported(corrections, tmp_path, capsys):
output = tmp_path / "iam-request-resources.json"
output.write_text("{}", encoding="utf-8")
def refuse(*args, **kwargs):
raise PermissionError(13, "Permission denied")
# The read is refused rather than the file made unreadable, which a run as root could read anyway.
corrections.setattr(Path, "read_text", refuse)
assert r.main(["--check", "--output", str(output)]) == 1
assert "could not be read" in capsys.readouterr().err
def test_a_hand_edited_entry_does_not_match_botocore(corrections, tmp_path):
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}})})
document = r.build(DOCUMENTS, "test", tmp_path, "botocore test")
document["operations"]["svc:GetThing"]["resources"] = []
assert r.validate(document) == []
assert len(r.derive(document, tmp_path)) == 1
def test_a_type_checked_without_a_qualifier_is_recorded_and_must_be_one_the_file_reads(corrections, tmp_path):
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}})})
corrections.setattr(r, "UNQUALIFIED", {"svc:thing": "its service checks a qualified ARN without the qualifier"})
document = r.build(DOCUMENTS, "test", tmp_path, "botocore test")
assert document["unqualified"] == {"svc": ["thing"]}
assert r.validate(document) == [] and r.derive(document, tmp_path) == []
# A hand edit no longer matches, and a type the file has no format for fails the build.
document["unqualified"] = {}
assert r.validate(document) == [] and len(r.derive(document, tmp_path)) == 1
corrections.setattr(r, "UNQUALIFIED", {"svc:gone": "no longer there"})
with pytest.raises(ValueError, match="svc:gone"):
r.build(DOCUMENTS, "test", tmp_path, "botocore test")
def test_a_type_whose_service_mints_an_id_after_its_name_is_recorded_and_must_be_one_the_file_reads(corrections, tmp_path):
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}})})
corrections.setattr(r, "MINTED_IDS", {"svc:thing": "its service follows the name with an id it mints"})
document = r.build(DOCUMENTS, "test", tmp_path, "botocore test")
assert document["mintedIds"] == {"svc": ["thing"]}
assert r.validate(document) == [] and r.derive(document, tmp_path) == []
# A hand edit no longer matches, and a type the file has no format for fails the build.
document["mintedIds"] = {}
assert r.validate(document) == [] and len(r.derive(document, tmp_path)) == 1
corrections.setattr(r, "MINTED_IDS", {"svc:gone": "no longer there"})
with pytest.raises(ValueError, match="svc:gone"):
r.build(DOCUMENTS, "test", tmp_path, "botocore test")
def test_a_type_whose_arn_is_all_an_id_its_service_mints_is_found_by_the_members_naming_it(corrections, tmp_path):
documents = [reference("svc", {"PutTarget": ["target"], "TagTarget": ["target"], "GetByResource": ["target"],
"RunOn": ["target", "group"]},
{"target": "arn:${Partition}:svc:${Region}:${Account}:target/${ResourceId}",
"group": "arn:${Partition}:svc:${Region}:${Account}:group/${GroupId}"})]
write_models(tmp_path, {"svc": model({"PutTarget": {"Namespace": "String", "ResourceId": "String",
"Dimension": "String"},
"TagTarget": {"ResourceArn": "String"},
"GetByResource": {"ResourceId": "String"},
"RunOn": {"GroupName": "String"}})})
corrections.setattr(r, "FOUND_BY", {"svc:target": (["Namespace", "ResourceId", "Dimension"], "its service mints the id"),
"svc:group": (["GroupName"], "its service mints the id")})
document = r.build(documents, "test", tmp_path, "botocore test")
assert r.validate(document) == [] and r.derive(document, tmp_path) == []
operations = document["operations"]
# Found by the three, in order, rather than filled by ResourceId, which is not the id the ARN ends in.
assert operations["svc:PutTarget"]["resources"] == [
{"type": "target", "fill": {}, "find": ["Namespace", "ResourceId", "Dimension"]}]
# Its ARN names it as given, and a request lacking a member names none.
assert operations["svc:TagTarget"]["resources"] == [{"types": ["target"], "arn": "ResourceArn"}]
assert operations["svc:GetByResource"]["resources"] == []
# Found by its name though no member fills its id, so the rule derives nothing for it.
assert operations["svc:RunOn"]["resources"] == [{"type": "group", "fill": {}, "find": ["GroupName"]}]
# A hand edit no longer matches, and a type the file has no format for fails the build.
operations["svc:PutTarget"]["resources"] = [{"type": "target", "fill": {"ResourceId": "ResourceId"}}]
assert r.validate(document) == [] and len(r.derive(document, tmp_path)) == 1
corrections.setattr(r, "FOUND_BY", {"svc:gone": (["Namespace"], "no longer there")})
with pytest.raises(ValueError, match="svc:gone"):
r.build(documents, "test", tmp_path, "botocore test")
def test_a_member_naming_a_resource_of_no_type_names_the_one_it_runs_on_through_it(corrections, tmp_path):
documents = [reference("svc", {"Run": ["cluster", "group"], "RunOnGroup": ["group"], "RunOnCluster": ["cluster"],
"ListSessions": []},
{"cluster": "arn:${Partition}:svc:${Region}:${Account}:cluster:${ClusterName}",
"group": "arn:${Partition}:svc:${Region}:${Account}:group/${GroupId}"})]
write_models(tmp_path, {"svc": model({"Run": {"SessionId": "String"}, "RunOnGroup": {"SessionId": "String"},
"RunOnCluster": {"Sql": "String"}, "ListSessions": {"SessionId": "String"}})})
corrections.setattr(r, "THROUGH", {"svc:SessionId": (["cluster", "group"], "a session runs on one")})
document = r.build(documents, "test", tmp_path, "botocore test")
assert r.validate(document) == [] and r.derive(document, tmp_path) == []
operations = document["operations"]
# Named through the session, as one of the types the action acts on.
assert operations["svc:Run"]["resources"] == [{"types": ["cluster", "group"], "through": "SessionId"}]
assert operations["svc:RunOnGroup"]["resources"][-1] == {"types": ["group"], "through": "SessionId"}
# Not by a request without the member, nor for an action acting on none of the types.
assert not any("through" in resource for resource in operations["svc:RunOnCluster"]["resources"])
assert operations["svc:ListSessions"]["resources"] == []
# A hand edit no longer matches, and a type the file has no format for fails the build.
operations["svc:Run"]["resources"] = []
assert r.validate(document) == [] and len(r.derive(document, tmp_path)) == 1
corrections.setattr(r, "THROUGH", {"svc:SessionId": (["gone"], "no longer there")})
with pytest.raises(ValueError, match="svc:gone"):
r.build(documents, "test", tmp_path, "botocore test")
def test_a_client_not_read_gives_no_members_and_aws_listing_it_is_no_untrue_claim(corrections, tmp_path):
corrections.setattr(r, "CLIENTS_NOT_READ", {"svcv2": "a second API Floci does not serve"})
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}}),
"svcv2": model({"GetThing": {"ThingArn": "String"}})})
documents = [dict(DOCUMENTS[0], Operations=[dict(op, SDK=op["SDK"] + [{"Name": "svcv2", "Package": "Boto3"}])
for op in DOCUMENTS[0]["Operations"]])] + DOCUMENTS[1:]
document = r.build(documents, "test", tmp_path, "botocore test")
assert document["namespaces"] == {"svc": ["svc"]} and document["clientsNotRead"] == {"svcv2": "a second API Floci does not serve"}
assert document["operations"]["svc:GetThing"]["resources"] == [{"type": "thing", "fill": {"ThingName": "ThingName"}}]
assert r.validate(document) == [] and r.derive(document, tmp_path) == []
upstream = r.checked_actions(documents)
assert r.verify_against(document, upstream, {"svc": {"thing": FORMATS["thing"]}}) == ([], [])
document["clientsNotRead"] = {}
assert len(r.derive(document, tmp_path)) == 1
def test_a_member_taking_an_arn_before_a_name_is_read_as_the_variable_of_that_types_arn():
shapes = {"String": {"type": "string"},
"BusNameOrArn": {"type": "string", "pattern": "(arn:aws[\\w-]*:svc:[a-z]+-[a-z]+-[\\w-]+:[0-9]{12}:bus\\/)?[/\\.\\-_A-Za-z0-9]+"},
"In": {"type": "structure", "members": {"Name": {"shape": "String"}, "BusName": {"shape": "BusNameOrArn"}}}}
models = {"svc": {"metadata": {"protocol": "json"}, "operations": {"PutRule": {"input": {"shape": "In"}}}, "shapes": shapes}}
assert r.name_or_arn_members(models, "PutRule") == {"BusName": "bus"}
formats = {"bus": "arn:${Partition}:svc:${Region}:${Account}:bus/${BusName}",
"rule": "arn:${Partition}:svc:${Region}:${Account}:rule/${BusName}/${RuleName}"}
assert r.named_by("bus", formats) == "bus" and r.named_by("rule", formats) is None
rules = [{"type": "rule", "fill": {"BusName": "BusName", "RuleName": "Name"}},
{"type": "rule", "fill": {"RuleName": "Name"}, "when": {"BusName": ["default"]}},
{"types": ["rule"], "arn": "RuleArn"}]
assert r.with_arn_of(rules, formats, {"BusName": "bus"}) == [
dict(rules[0], arnOf={"BusName": "bus"}), dict(rules[1], arnOf={"BusName": "bus"}), rules[2]]
def test_a_field_of_each_of_a_lists_structures_taking_an_arn_before_a_name_is_read_by_its_path():
shapes = {"String": {"type": "string"},
"BusNameOrArn": {"type": "string", "pattern": "(arn:aws[\\w-]*:svc:[a-z]+-[a-z]+-[\\w-]+:[0-9]{12}:bus\\/)?[\\.\\-_A-Za-z0-9]+"},
"Entry": {"type": "structure", "members": {"Source": {"shape": "String"}, "BusName": {"shape": "BusNameOrArn"}}},
"Entries": {"type": "list", "member": {"shape": "Entry"}},
"Config": {"type": "structure", "members": {"BusName": {"shape": "BusNameOrArn"}}},
"In": {"type": "structure", "members": {"Entries": {"shape": "Entries"}, "Config": {"shape": "Config"}}}}
models = {"svc": {"metadata": {"protocol": "json"}, "operations": {"PutEvents": {"input": {"shape": "In"}}}, "shapes": shapes}}
# Only a list's structures give one value for each, so a lone structure's field is not read.
assert r.name_or_arn_members(models, "PutEvents") == {"Entries[].BusName": "bus"}
formats = {"bus": "arn:${Partition}:svc:${Region}:${Account}:bus/${BusName}"}
buses = [{"type": "bus", "fill": {"BusName": "Entries[].BusName"}, "absent": {"Entries[].BusName": "default"}}]
assert r.with_arn_of(buses, formats, r.name_or_arn_members(models, "PutEvents")) == [
dict(buses[0], arnOf={"Entries[].BusName": "bus"})]
def test_a_correction_for_an_operation_the_file_does_not_read_fails(corrections, tmp_path):
corrections.setattr(r, "CORRECTIONS", {"svc:Gone": ([], "no longer there")})
with pytest.raises(ValueError, match="svc:Gone"):
r.build(DOCUMENTS, "test", tmp_path, "botocore test")
def good_document() -> dict:
return {"namespaces": {"svc": ["svc"]}, "clientsNotRead": {"svcv2": "not served"}, "handBuilt": ["hand"],
"notCovered": {"later": "a later batch"},
"otherNamespaces": ["other"], "arnFormats": {"svc": {"thing": FORMATS["thing"], "group": FORMATS["group"]}},
"unqualified": {"svc": ["thing"]}, "mintedIds": {"svc": ["thing"]},
"operations": {
"svc:A": {"action": "svc:A", "types": ["thing"], "resources": [{"types": ["thing"], "arn": "ThingArn"}]},
"svc:B": {"action": "svc:B", "types": ["group"], "resources": [{"type": "group", "fill": {"GroupName": "Names[]"}}]},
"svc:C": {"action": "svc:C", "types": [], "resources": []}}}
def test_a_well_formed_document_validates():
assert r.validate(good_document()) == []
document = good_document()
document["operations"]["svc:B"]["resources"][0]["when"] = {"Type": ["application", None]}
document["operations"]["svc:B"]["resources"][0]["account"] = "registryId"
document["operations"]["svc:B"]["resources"][0]["unless"] = {"Bus": ["default"]}
document["operations"]["svc:B"]["resources"][0]["absent"] = {"Bus": "default"}
document["operations"]["svc:B"]["resources"][0]["arnOf"] = {"Bus": "thing"}
document["operations"]["svc:A"]["resources"][0]["before"] = "#"
# A member filling a variable read up to a character, as a CodeBuild build id names its project before ':'.
document["operations"]["svc:B"]["resources"][0]["before"] = ":"
assert r.validate(document) == []
assert r.validate(with_a_create()) == []
# A field of each of a list's structures fills a variable, read as given when absent, or as an ARN.
document = good_document()
document["operations"]["svc:B"]["resources"][0].update(
fill={"GroupName": "Groups[].Name"}, absent={"Groups[].Name": "default"}, arnOf={"Groups[].Name": "thing"})
assert r.validate(document) == []
# A field of a structure fills a variable, read as one value, and a variable no member fills may be fixed.
document = good_document()
document["operations"]["svc:B"]["resources"][0].update(
fill={"GroupName": "Group.Name"}, absent={"Group.Name": "default"}, fixed={"GroupId": "g-1"}, made=True)
document["operations"]["svc:A"]["resources"][0]["made"] = True
assert r.validate(document) == []
# A type whose ARN is all an id its service mints, found by the members naming it.
document = good_document()
document["operations"]["svc:B"]["resources"][0].update(fill={}, find=["Namespace", "Id"])
assert r.validate(document) == []
# A resource named through a member naming another of its service's own, which it runs on, or through each
# value of a list's field when another member is absent.
document = good_document()
document["operations"]["svc:A"]["resources"] = [{"types": ["thing"], "through": "SessionId"},
{"types": ["thing"], "through": "Parts[].PartId",
"when": {"ThingName": [None]}}]
assert r.validate(document) == []
def with_a_create() -> dict:
document = good_document()
document["arnFormats"]["svc"]["part"] = "arn:${Partition}:svc:${Region}:${Account}:part/${ThingName}/${PartId}"
document["operations"]["svc:A"]["creates"] = [{"type": "part", "parent": "thing", "arn": "ThingArn"}]
return document
@pytest.mark.parametrize("change, problem", [
(lambda d: d["operations"]["svc:A"]["resources"][0].update(types=["pool"]), "not resource types"),
(lambda d: d["operations"]["svc:A"]["resources"][0].update(arn="a.b.c"), "no member"),
(lambda d: d["operations"]["svc:A"]["resources"][0].update(arn="a[][]"), "no member"),
(lambda d: d["operations"]["svc:A"]["resources"].__setitem__(0, {"types": ["thing"], "through": "Ids[][]"}),
"no member"),
(lambda d: d["operations"]["svc:A"]["resources"].__setitem__(0, {"types": ["thing"], "through": "a.b.c"}),
"no member"),
(lambda d: d["operations"]["svc:A"]["resources"].__setitem__(0, {"types": ["thing"], "through": "SessionId",
"when": {"Ids[]": ["a"]}}), "no member's values"),
(lambda d: d["operations"]["svc:A"]["resources"].__setitem__(0, {"types": ["thing"], "through": "SessionId",
"unless": {"Id": ["a"]}}), "neither an ARN member"),
(lambda d: d["operations"]["svc:A"]["resources"].__setitem__(0, {"types": ["pool"], "through": "SessionId"}),
"not resource types"),
(lambda d: d["operations"]["svc:A"]["resources"].__setitem__(0, {"types": ["thing"], "through": "SessionId",
"before": "#"}), "neither an ARN member"),
(lambda d: d["operations"]["svc:B"]["resources"][0]["fill"].update(GroupName="Group.Names[]"), "no variables"),
(lambda d: d["operations"]["svc:B"]["resources"][0]["fill"].update(GroupName="A.B.Name"), "no variables"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fixed={"Other": "x"}), "fixes"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fixed={"GroupName": "x"}), "fixes"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fixed={"GroupId": ""}), "fixes"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fixed={"GroupId": 1}), "fixes"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fixed=["GroupId"]), "fixes"),
(lambda d: d["operations"]["svc:A"]["resources"][0].update(fixed={"GroupId": "x"}), "neither an ARN member"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(made=False), "not true"),
(lambda d: d["operations"]["svc:A"]["resources"][0].update(made="true"), "not true"),
(lambda d: d["operations"]["svc:B"]["resources"][0]["fill"].update(GroupName="Groups[].Names[]"), "no variables"),
(lambda d: d["operations"]["svc:B"]["resources"][0]["fill"].update(GroupId="Groups[].Id"), "more than one list"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(absent={"Groups[].Name": "default"}), "absent members"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(arnOf={"Groups[].Name": "thing"}), "types of one variable"),
(lambda d: d["operations"]["svc:B"]["resources"][0]["fill"].update(Other="Name"), "no variables"),
(lambda d: d["operations"]["svc:B"]["resources"][0]["fill"].update(GroupId="Ids[]"), "more than one list"),
(lambda d: d["operations"]["svc:A"].update(action="other:A"), "no action of its namespace"),
(lambda d: d["operations"]["svc:A"].pop("types"), "an action, its types"),
(lambda d: d["arnFormats"]["svc"].update(thing="*"), "arnFormats"),
(lambda d: d["operations"].update({"other:X": {"action": "other:X", "types": [], "resources": []}}),
"namespace the file reads"),
(lambda d: d["notCovered"].update(later=""), "reason"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(when={"Type": []}), "no member's values"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(when={"Types[]": ["a"]}), "no member's values"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(when={"Type": [1]}), "no member's values"),
(lambda d: d["operations"]["svc:A"]["resources"][0].update(before="##"), "no one character"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(before="##"), "no one character"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(before=":", fill={"GroupName": "Names[]"}) or
d["operations"]["svc:B"]["resources"][0].update(before=1), "no one character"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(account="Ids[]"), "no account of its ARN"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(account="a.b"), "no account of its ARN"),
(lambda d: d["arnFormats"]["svc"].update(group="arn:${Partition}:svc:::group/${GroupName}")
or d["operations"]["svc:B"]["resources"][0].update(account="registryId"), "no account of its ARN"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(unless={"Type": []}), "no member's values"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(absent={"Bus": ""}), "absent members"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(absent={"Bus[]": "default"}), "absent members"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(arnOf={"Bus": "pool"}), "types of one variable"),
(lambda d: d["arnFormats"]["svc"].update(group="arn:${Partition}:svc:${Region}:${Account}:group/${GroupName}/${Id}")
or d["operations"]["svc:B"]["resources"][0].update(arnOf={"Bus": "group"}), "types of one variable"),
(lambda d: d["operations"]["svc:A"]["resources"][0].update(unless={"Type": ["a"]}), "neither an ARN member"),
(lambda d: d["clientsNotRead"].update(svcv2=""), "clientsNotRead"),
(lambda d: d.update(unqualified={"svc": ["pool"]}), "unqualified"),
(lambda d: d.update(unqualified={"other": ["thing"]}), "unqualified"),
(lambda d: d.update(unqualified={"svc": []}), "unqualified"),
(lambda d: d.pop("unqualified"), "unqualified"),
(lambda d: d.update(mintedIds={"svc": ["group"]}), "mintedIds"),
(lambda d: d.update(mintedIds={"other": ["thing"]}), "mintedIds"),
(lambda d: d.update(mintedIds={"svc": []}), "mintedIds"),
(lambda d: d.pop("mintedIds"), "mintedIds"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(find=["Namespace"]), "beside a fill"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find=[]), "beside a fill"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find=["Ids[]"]), "beside a fill"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find="Namespace"), "beside a fill"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find=["Namespace"], account="registryId"),
"beside a fill"),
(lambda d: d["operations"]["svc:B"]["resources"][0].update(fill={}, find=["Namespace"], absent={"Namespace": "ecs"}),
"beside a fill"),
(lambda d: d["operations"]["svc:A"]["resources"][0].update(find=["Namespace"]), "neither an ARN member"),
])
def test_a_malformed_document_is_rejected(change, problem):
document = good_document()
change(document)
assert any(problem in p for p in r.validate(document)), r.validate(document)
@pytest.mark.parametrize("change, problem", [
(lambda d: d["operations"]["svc:A"]["creates"][0].update(parent="group"), "no parent of it"),
(lambda d: d["operations"]["svc:A"]["creates"][0].update(type="group"), "no parent of it"),
(lambda d: d["operations"]["svc:A"]["creates"][0].update(arn="a.b"), "no type made under"),
(lambda d: d["operations"]["svc:A"]["creates"][0].pop("parent"), "no type made under"),
(lambda d: d["arnFormats"]["svc"].update(part="arn:${Partition}:svc:${Region}:${Account}:part/${PartId}"),
"no parent of it"),
])
def test_a_malformed_create_is_rejected(change, problem):
document = with_a_create()
change(document)
assert any(problem in p for p in r.validate(document)), r.validate(document)
def test_verify_fails_on_an_action_type_or_format_aws_does_not_give_and_reports_an_added_operation():
document = good_document()
upstream = {"svc:A": {"action": "svc:A", "types": ["thing"], "clients": ["svc"]},
"svc:B": {"action": "svc:Other", "types": ["group"], "clients": ["svc"]},
"svc:C": {"action": "svc:C", "types": ["thing"], "clients": ["svc"]},
"svc:D": {"action": "svc:D", "types": [], "clients": ["svc"]}}
untrue, added = r.verify_against(document, upstream, {"svc": {"thing": FORMATS["thing"], "group": "arn:${Partition}:svc:::g"}})
assert any("svc:B" in u for u in untrue) and any("svc:C" in u for u in untrue)
assert any("group" in u and "ARN format" in u for u in untrue)
assert added == ["svc:D"]
def test_every_correction_is_the_vendored_entry_of_an_operation_the_file_reads():
operations = json.loads(r.OUTPUT.read_text(encoding="utf-8"))["operations"]
assert r.CORRECTIONS
for operation, (resources, reason) in r.CORRECTIONS.items():
assert operation in operations and reason, operation
# A resource's account and the ARNs its members may give are botocore's, and whether a create makes it the
# rule's, on top of the correction.
assert [{key: value for key, value in resource.items() if key not in ("account", "arnOf", "made")}
for resource in operations[operation]["resources"]] == resources, operation
def test_a_correction_gives_the_operation_its_resources(corrections):
corrections.setattr(r, "CORRECTIONS", {"svc:GetThing": ([{"type": "thing", "fill": {}}], "a reason")})
entry = r.entry_for("svc:GetThing", {"action": "svc:GetThing", "types": ["thing"]}, FORMATS, {})
assert entry["resources"] == [{"type": "thing", "fill": {}}]
def test_the_vendored_file_is_well_formed():
document = json.loads(r.OUTPUT.read_text(encoding="utf-8"))
assert r.validate(document) == []
operations = document["operations"]
assert operations["elasticloadbalancing:CreateTargetGroup"]["resources"] == [
{"type": "targetgroup", "fill": {"TargetGroupName": "Name"}}]
assert operations["states:DescribeStateMachine"]["resources"] == [{"types": ["statemachine"], "arn": "stateMachineArn"}]
assert operations["ecr:DescribeRepositories"]["resources"] == [
{"type": "repository", "fill": {"RepositoryName": "repositoryNames[]"}, "account": "registryId"}]
# Its request has no registryId, so the repositories are the caller's.
assert operations["ecr:BatchGetRepositoryScanningConfiguration"]["resources"] == [
{"type": "repository", "fill": {"RepositoryName": "repositoryNames[]"}}]
assert operations["cognito-idp:DescribeUserPool"]["resources"] == [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]
# StartExecution's name is the execution's, so only its state machine ARN is read, up to a test case's #.
assert operations["states:StartExecution"]["resources"] == [
{"types": ["statemachine"], "arn": "stateMachineArn", "before": "#"}]
# An ARN inside a structure or each of a list's structures.
assert operations["elasticloadbalancing:SetRulePriorities"]["resources"] == [
{"types": ["listener-rule/app", "listener-rule/net"], "arn": "RulePriorities[].RuleArn"}]
assert operations["states:CreateStateMachineAlias"]["resources"] == [
{"types": ["statemachine"], "arn": "routingConfiguration[].stateMachineVersionArn"}]
# An EventBridge rule is on the bus EventBusName names, by name or ARN, or the default one when it names none.
assert operations["events:DescribeRule"]["resources"] == [
{"type": "rule-on-default-event-bus", "fill": {"RuleName": "Name"}, "when": {"EventBusName": ["default"]},
"absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}},
{"type": "rule-on-custom-event-bus", "fill": {"EventBusName": "EventBusName", "RuleName": "Name"},
"unless": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}]
assert operations["events:DescribeEventBus"]["resources"] == [
{"types": ["event-busv2"], "arn": "EventBusArn", "endpoint": "eventsv2"},
{"type": "event-bus", "fill": {"EventBusName": "Name"}, "absent": {"Name": "default"}, "endpoint": "events",
"arnOf": {"Name": "event-bus"}}]
# Each PutEvents entry is on the bus it names, by name or ARN, or the default one when it names none; an
# EventBridge V2 request is on the one bus its EventBusArn names.
assert operations["events:PutEvents"]["resources"] == [
{"types": ["event-busv2"], "arn": "EventBusArn", "endpoint": "eventsv2"},
{"type": "event-bus", "fill": {"EventBusName": "Entries[].EventBusName"},
"absent": {"Entries[].EventBusName": "default"}, "endpoint": "events",
"arnOf": {"Entries[].EventBusName": "event-bus"}}]
# EventBridge V2 is read beside EventBridge, and where both name an operation's resources, which one applies is
# the endpoint serving the request, never a member a caller could add.
assert document["namespaces"]["events"] == ["eventbridgev2", "events"]
assert "eventbridgev2" not in document["clientsNotRead"]
assert operations["events:DeleteSubscriber"]["resources"] == [{"types": ["subscriber"], "arn": "SubscriberArn"}]
assert operations["events:DeleteEventBus"]["resources"] == [
{"types": ["event-busv2"], "arn": "EventBusArn", "endpoint": "eventsv2"},
{"type": "event-bus", "fill": {"EventBusName": "Name"}, "endpoint": "events"}]
assert operations["events:CreateEventBus"]["resources"][1:] == [
{"type": "event-bus", "fill": {"EventBusName": "Name"}, "endpoint": "events", "made": True},
{"type": "event-busv2", "fill": {"EventBusName": "Name"}, "endpoint": "eventsv2"}]
# A create's tags are checked on what it makes: not a dead-letter target or the bus a subscriber is made on.
assert "made" not in operations["events:CreateEventBus"]["resources"][0]
assert [resource for resource in operations["events:CreateSubscriber"]["resources"] if resource.get("made")] == [
{"type": "subscriber", "fill": {"SubscriberName": "Name"}, "made": True}]
assert not any("when" in resource or "unless" in resource
for operation, entry in operations.items() if operation.startswith("events:")
and "endpoint" in json.dumps(entry) for resource in entry["resources"])
# A state machine's version or alias is checked on the state machine.
assert document["unqualified"] == {"states": ["statemachine"]}
# A listener is made under a load balancer, and a rule under a listener.
assert operations["elasticloadbalancing:CreateListener"]["creates"] == [
{"type": f"listener/{kind}", "parent": f"loadbalancer/{kind}/", "arn": "LoadBalancerArn"}
for kind in ("app", "gwy", "net")]
assert operations["elasticloadbalancing:CreateRule"]["creates"] == [
{"type": f"listener-rule/{kind}", "parent": f"listener/{kind}", "arn": "ListenerArn"} for kind in ("app", "net")]
assert set(document["handBuilt"]) >= {"lambda", "s3", "sqs"}
# A scalable target is found by the three members naming it, its ARN ending in the id the service mints.
assert operations["application-autoscaling:DeregisterScalableTarget"]["resources"] == [
{"type": "ScalableTarget", "fill": {}, "find": ["ServiceNamespace", "ResourceId", "ScalableDimension"]}]
assert operations["application-autoscaling:TagResource"]["resources"] == [
{"types": ["ScalableTarget"], "arn": "ResourceARN"}]
# A Data API request runs on the cluster it names, or on the serverless workgroup its name or ARN finds.
assert operations["redshift-data:ExecuteStatement"]["resources"][1:] == [
{"type": "cluster", "fill": {"ClusterName": "ClusterIdentifier"}},
{"type": "workgroup", "fill": {}, "find": ["WorkgroupName"]},
{"types": ["cluster", "workgroup"], "through": "SessionId"}]
# A request naming its session alone runs on the cluster or workgroup the session was opened on.
assert operations["redshift-data:BatchExecuteStatement"]["resources"][-1] == {
"types": ["cluster", "workgroup"], "through": "SessionId"}
assert operations["redshift-data:ListStatements"]["resources"] == []
assert operations["redshift-data:ListSessions"]["resources"] == []
# The v2 API's Type picks the load balancer it creates, application when it gives none.
assert operations["elasticloadbalancing:CreateLoadBalancer"]["resources"][1] == {
"type": "loadbalancer/app/", "fill": {"LoadBalancerName": "Name"}, "when": {"Type": ["application", None]}}
@pytest.mark.parametrize("operation", ["SendTaskSuccess", "SendTaskFailure", "SendTaskHeartbeat"])
def test_callback_resources_are_resolved_from_the_token(operation):
resources, reason = r.CORRECTIONS[f"states:{operation}"]
assert resources == [{"type": kind, "fill": {}, "find": ["taskToken"]}
for kind in ("activity", "statemachine")]
assert "2026-11-02" in reason
assert "no resource types" in reason
def test_list_tables_correction_names_the_literal_collection_without_selectors():
resources, reason = r.CORRECTIONS["dynamodb:ListTables"]
assert resources == [{"type": "table", "fill": {}}]
assert "table/?" in reason
formats = {"table": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}"}
assert not r._resource_problems("dynamodb:ListTables", resources[0], [], formats)
assert r._resource_problems("dynamodb:OtherOperation", resources[0], [], formats)
assert r.reads("dynamodb:ListTables")
assert not r.reads("dynamodb:BatchWriteItem")
assert not r.reads("dynamodb:ExecuteStatement")
def test_hand_built_correction_is_generated_without_claiming_other_operations(corrections, tmp_path):
corrections.setattr(r, "CORRECTIONS", {"hand:ListThings": ([{"type": "thing", "fill": {}}], "measured collection")})
documents = DOCUMENTS + [reference("hand", {"ListThings": [], "PutThing": ["thing"]},
{"thing": "arn:${Partition}:hand:${Region}:${Account}:thing/${ThingName}"})]
hand = model({"ListThings": {}, "PutThing": {"ThingName": "String"}})
hand["metadata"]["endpointPrefix"] = "hand"
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}}), "hand": hand})
document = r.build(documents, "test", tmp_path, "botocore test")
assert document["operations"]["hand:ListThings"] == {
"action": "hand:ListThings", "types": [], "resources": [{"type": "thing", "fill": {}}]}
assert "hand:PutThing" not in document["operations"]
assert document["namespaces"]["hand"] == ["hand"]
assert document["handBuilt"] == ["hand"]
assert r.validate(document) == []
assert r.derive(document, tmp_path) == []
assert r.verify_against(document, r.checked_actions(documents), document["arnFormats"]) == ([], [])
def test_hand_built_operations_listed_to_read_follow_the_rule(corrections, tmp_path):
corrections.setattr(r, "READ_IN_HAND_BUILT", {"hand:GetThing": "a family the rule reads"})
documents = DOCUMENTS + [reference("hand", {"GetThing": ["thing"], "PutThing": ["thing"]},
{"thing": "arn:${Partition}:hand:${Region}:${Account}:thing/${ThingName}"})]
hand = model({"GetThing": {"ThingName": "String"}, "PutThing": {"ThingName": "String"}})
hand["metadata"]["endpointPrefix"] = "hand"
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}}), "hand": hand})
document = r.build(documents, "test", tmp_path, "botocore test")
assert document["operations"]["hand:GetThing"] == {
"action": "hand:GetThing", "types": ["thing"], "resources": [{"type": "thing", "fill": {"ThingName": "ThingName"}}]}
assert "hand:PutThing" not in document["operations"]
assert r.reads("hand:GetThing") and not r.reads("hand:PutThing")
assert r.validate(document) == []
def test_operations_listed_to_read_must_exist_and_be_hand_built(corrections, tmp_path):
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}})})
corrections.setattr(r, "READ_IN_HAND_BUILT", {"hand:Gone": "no longer there"})
with pytest.raises(ValueError, match="READ_IN_HAND_BUILT names hand:Gone, which the reference does not give"):
r.build(DOCUMENTS, "test", tmp_path, "botocore test")
def test_measured_callback_correction_retains_action_metadata_and_rejects_unlisted_resources():
formats = {"activity": "arn:${Partition}:states:${Region}:${Account}:activity:${ActivityName}",
"statemachine": "arn:${Partition}:states:${Region}:${Account}:stateMachine:${StateMachineName}"}
resource = {"type": "activity", "fill": {}, "find": ["taskToken"]}
assert not r._resource_problems("states:SendTaskSuccess", resource, [], formats)
assert r._resource_problems("states:SendTaskSuccess", {**resource, "find": ["otherToken"]}, [], formats)
assert r._resource_problems("states:OtherOperation", resource, [], formats)
assert r._resource_problems("states:SendTaskSuccess", resource, [], {})