Files
floci/tools/aws/test_regen_request_condition_keys.py
T
Priamo Germosen b4cc436ad0 fix(iam): read EventBridge's rule and target condition keys from the vendored user guide (#9673)
Under enforcement a PutRule scoped by events:source was refused for every event pattern, and a PutTargets scoped by events:TargetArn for every target, as #8320 reports: the request condition key table never filled either key, so a Null or ForAllValues condition on them never saw a value. The table's reader is generic, but which member carries a key comes from SERVICES in regen_request_condition_keys.py, and EventBridge was not there. Neither botocore nor the Service Reference says where a request carries these keys: botocore models EventPattern as a string ("The event pattern").

EventBridge's user guide says it, in its table of condition keys: events:source is "the literal string for the source field of the event", with events:detail-type, events:detail.service, events:detail.eventTypeCode and events:detail.userIdentity.principalId the same for their fields, which a rule's event pattern gives ("EventPattern is a mandatory argument to PutRule"), and events:TargetArn is "the ARN of the target for the rule". A vendored source, tools/aws/sources/eventbridge-condition-keys.json, written by tools/aws/fetch_eventbridge_conditions.py from that page, gives each key its member, and the generator reads it for events (CONDITION_SOURCES), each key in the one operation the page names: PutEvents, CreateEventSource and UpdateEventSource take events:source too, which the page does not describe, so they are not read there. --verify checks the file against the page.

The table writes a field of a JSON document a string member holds after #: EventPattern#source.* is each literal string of the pattern's source, read by one generic step of the JSON reader. A pattern leaving a field out names nothing, so ForAllValues allows it and a Null check refuses it, as the page's examples show. The fields are read at the pattern's top level, where every example on the page gives them, so a $or branch's names nothing, and a matcher such as {"prefix": "aws."} is no literal string and names nothing. events:TargetArn reads each target's own Arn, not its dead-letter queue's.

Closes #8320.
2026-11-28 15:50:13 -04:00

265 lines
15 KiB
Python

"""Action coverage and request members for the condition keys read from requests and the resources they act on."""
import json
import subprocess
import pytest
from regen_request_condition_keys import OUTPUT, action_keys, member_shapes, request_members, validate
def test_resource_and_action_keys_are_combined():
reference = {"Name": "lambda", "Resources": [{"Name": "webFunctionEndpoint",
"ConditionKeys": ["lambda:Resource/WebFunctionAuthType"]}],
"Actions": [{"Name": "UpdateWebFunctionEndpoint",
"ActionConditionKeys": ["lambda:Request/WebFunctionAuthType", "aws:TagKeys"],
"Resources": [{"Name": "webFunctionEndpoint"}]},
{"Name": "GetWebFunction", "ActionConditionKeys": ["aws:ResourceTag/${TagKey}"]}]}
assert action_keys("lambda", reference) == {"lambda:UpdateWebFunctionEndpoint": [
"lambda:Request/WebFunctionAuthType", "lambda:Resource/WebFunctionAuthType"]}
def test_only_the_keys_a_namespace_reads_are_kept():
reference = {"Name": "redshift", "Resources": [{"Name": "dbuser"}],
"Actions": [{"Name": "GetClusterCredentials",
"ActionConditionKeys": ["redshift:DbName", "redshift:DbUser",
"redshift:DurationSeconds"],
"Resources": [{"Name": "dbuser"}]},
{"Name": "JoinGroup", "Resources": [{"Name": "dbgroup"}]}]}
assert action_keys("redshift", reference) == {"redshift:GetClusterCredentials": ["redshift:DbUser"]}
def test_a_nested_member_is_found_and_a_resource_key_has_none():
model = {"metadata": {"protocol": "rest-json"},
"operations": {"CreateWebFunction": {"input": {"shape": "Input"}},
"GetWebFunctionEndpoint": {"input": {"shape": "Get"}}}, "shapes": {
"Input": {"members": {"endpointConfig": {"shape": "Config"}, "functionName": {"shape": "String"}}},
"Config": {"members": {"authType": {"shape": "AuthType"}}},
"Get": {"members": {"endpointName": {"shape": "String"}}}, "AuthType": {}, "String": {}}}
assert request_members("lambda", model, {
"lambda:CreateWebFunction": ["lambda:Request/WebFunctionAuthType"],
"lambda:GetWebFunctionEndpoint": ["lambda:Resource/WebFunctionAuthType"]}) == {
"lambda:CreateWebFunction": {"lambda:Request/WebFunctionAuthType": ["endpointConfig.authType"]}}
def test_another_namespaces_actions_are_left_to_it():
model = {"metadata": {"protocol": "query"}, "operations": {}, "shapes": {}}
assert request_members("redshift", model, {
"lambda:CreateWebFunction": ["lambda:Request/WebFunctionAuthType"]}) == {}
def test_an_action_whose_request_does_not_carry_the_key_is_left_out():
assert request_members("redshift", {"metadata": {"protocol": "query"}, "operations": {}, "shapes": {}},
{"redshift:CreateClusterUser": ["redshift:DbUser"]}) == {}
def test_a_request_key_without_a_member_fails():
model = {"metadata": {"protocol": "rest-json"},
"operations": {"CreateWebFunctionEndpoint": {"input": {"shape": "Input"}}},
"shapes": {"Input": {"members": {"endpointName": {"shape": "String"}}}, "String": {}}}
with pytest.raises(ValueError, match="no authType member"):
request_members("lambda", model,
{"lambda:CreateWebFunctionEndpoint": ["lambda:Request/WebFunctionAuthType"]})
def test_a_nested_member_of_a_query_request_fails():
model = {"metadata": {"protocol": "query"},
"operations": {"GetClusterCredentials": {"input": {"shape": "Input"}}}, "shapes": {
"Input": {"members": {"User": {"shape": "User"}}},
"User": {"members": {"DbUser": {"shape": "String"}}}, "String": {"type": "string"}}}
with pytest.raises(ValueError, match="User.DbUser, which a flat form does not carry"):
request_members("redshift", model, {"redshift:GetClusterCredentials": ["redshift:DbUser"]})
def xml_model(location=None, flattened=False):
"""A REST-XML request whose list names its elements, as Route 53's change batch does."""
batch = {"shape": "Batch", **({"location": location} if location else {})}
return {"metadata": {"protocol": "rest-xml"},
"operations": {"ChangeResourceRecordSets": {"input": {"shape": "Input"}}}, "shapes": {
"Input": {"members": {"ChangeBatch": batch}},
"Batch": {"members": {"Changes": {"shape": "Changes"}}},
"Changes": {"type": "list", "member": {"shape": "Change", "locationName": "Change"},
**({"flattened": True} if flattened else {})},
"Change": {"members": {"Action": {"shape": "ChangeAction"},
"ResourceRecordSet": {"shape": "Record"}}},
"Record": {"members": {"Name": {"shape": "DNSName"}, "Type": {"shape": "RRType"}}},
"ChangeAction": {}, "DNSName": {}, "RRType": {}}}
ROUTE53_ACTIONS = {"route53:ChangeResourceRecordSets": ["route53:ChangeResourceRecordSetsActions",
"route53:ChangeResourceRecordSetsNormalizedRecordNames",
"route53:ChangeResourceRecordSetsRecordTypes"]}
def test_an_xml_member_is_carried_by_its_elements_with_its_shape():
assert request_members("route53", xml_model(), ROUTE53_ACTIONS) == {"route53:ChangeResourceRecordSets": {
"route53:ChangeResourceRecordSetsActions": ["ChangeBatch.Changes.Change.Action"],
"route53:ChangeResourceRecordSetsNormalizedRecordNames": ["ChangeBatch.Changes.Change.ResourceRecordSet.Name"],
"route53:ChangeResourceRecordSetsRecordTypes": ["ChangeBatch.Changes.Change.ResourceRecordSet.Type"]}}
assert member_shapes("route53", xml_model(), ROUTE53_ACTIONS) == {"route53:ChangeResourceRecordSets": {
"ChangeBatch.Changes.Change.Action": "ChangeAction",
"ChangeBatch.Changes.Change.ResourceRecordSet.Name": "DNSName",
"ChangeBatch.Changes.Change.ResourceRecordSet.Type": "RRType"}}
def test_a_json_member_keeps_its_member_names_and_has_a_shape():
model = {"metadata": {"protocol": "rest-json"},
"operations": {"CreateWebFunctionEndpoint": {"input": {"shape": "Input"}}},
"shapes": {"Input": {"members": {"authType": {"shape": "AuthType"}}}, "AuthType": {}}}
assert member_shapes("lambda", model, {"lambda:CreateWebFunctionEndpoint": [
"lambda:Request/WebFunctionAuthType"]}) == {"lambda:CreateWebFunctionEndpoint": {"authType": "AuthType"}}
@pytest.mark.parametrize("model, problem", [
(xml_model(location="uri"), "carried in the uri"),
(xml_model(flattened=True), "a map or a flattened list"),
])
def test_an_xml_member_the_body_does_not_nest_fails(model, problem):
with pytest.raises(ValueError, match=problem):
request_members("route53", model, ROUTE53_ACTIONS)
def test_the_vendored_table_covers_its_namespaces():
document = json.loads(OUTPUT.read_text())
assert validate(document) == []
assert document["actions"]["lambda:UpdateWebFunctionEndpoint"] == [
"lambda:Request/WebFunctionAuthType", "lambda:Resource/WebFunctionAuthType"]
assert document["members"]["lambda:CreateWebFunction"] == {
"lambda:Request/WebFunctionAuthType": ["endpointConfig.authType"]}
assert document["actions"]["redshift:CreateClusterUser"] == ["redshift:DbUser"]
assert "redshift:CreateClusterUser" not in document["members"]
assert document["members"]["redshift:GetClusterCredentials"] == {"redshift:DbUser": ["DbUser"]}
assert document["actions"]["route53:ChangeResourceRecordSets"] == ROUTE53_ACTIONS[
"route53:ChangeResourceRecordSets"]
assert document["memberShapes"]["route53:ChangeResourceRecordSets"][
"ChangeBatch.Changes.Change.ResourceRecordSet.Name"] == "DNSName"
assert document["protocols"] == {"eks": "rest-json", "events": "json", "lambda": "rest-json",
"redshift": "query", "route53": "rest-xml", "sts": "query"}
@pytest.mark.parametrize("changed", [
"src/main/resources/aws/request-condition-keys.json",
"tools/aws/regen_request_condition_keys.py",
"tools/aws/test_regen_request_condition_keys.py",
"tools/aws/regen_dynamodb_condition_keys.py",
"tools/aws/regen_iam_tag_on_create.py",
"tools/aws/sources/eventbridge-condition-keys.json",
"tools/aws/fetch_eventbridge_conditions.py",
"tools/aws/test_fetch_eventbridge_conditions.py",
"tools/aws/regen_iam_passed_roles.py",
"tools/aws/regen_partitions.py",
"tools/aws/regen_query_services.py",
"",
])
def test_aggregate_gate_checks_the_table_and_its_imports(tmp_path, changed):
result = run_aggregate_gate(tmp_path, changed, fail=True)
assert "checked:request-condition-keys-verify" in result.stdout
assert result.returncode != 0
assert "the request condition key table" in result.stdout
@pytest.mark.parametrize("changed", [
"docs/services/lambda-web-functions.md",
"docs/services/redshift.md",
"src/main/resources/aws/dynamodb-condition-keys.json",
"src/main/resources/aws/request-condition-keys.json.bak",
])
def test_aggregate_gate_does_not_check_unrelated_data(tmp_path, changed):
result = run_aggregate_gate(tmp_path, changed, fail=True)
assert "checked:request-condition-keys-verify" not in result.stdout
assert result.returncode == 0
def test_aggregate_gate_accepts_a_successful_check(tmp_path):
result = run_aggregate_gate(tmp_path, "src/main/resources/aws/request-condition-keys.json", fail=False)
assert "checked:request-condition-keys-verify" in result.stdout
assert result.returncode == 0
def run_aggregate_gate(tmp_path, changed, fail):
recursive_make = tmp_path / "check-gate"
recursive_make.write_text(
'#!/bin/sh\nprintf "checked:%s\\n" "$2"\n'
+ ('[ "$2" != request-condition-keys-verify ]\n' if fail else 'exit 0\n'))
recursive_make.chmod(0o700)
return subprocess.run(
["make", "--no-print-directory", "iam-data-verify", "CHANGED=" + changed,
"MAKE=" + str(recursive_make)],
cwd=OUTPUT.parents[4], capture_output=True, text=True, check=False)
def test_eks_cluster_request_members_and_create_only_bootstrap_key():
document = json.loads(OUTPUT.read_text())
create = document["members"]["eks:CreateCluster"]
assert create == {
"eks:authenticationMode": ["accessConfig.authenticationMode"],
"eks:bootstrapClusterCreatorAdminPermissions": ["accessConfig.bootstrapClusterCreatorAdminPermissions"],
"eks:endpointPrivateAccess": ["resourcesVpcConfig.endpointPrivateAccess"],
"eks:endpointPublicAccess": ["resourcesVpcConfig.endpointPublicAccess"],
}
assert document["members"]["eks:UpdateClusterConfig"] == {
key: paths for key, paths in create.items() if key != "eks:bootstrapClusterCreatorAdminPermissions"
}
assert "eks:DescribeCluster" not in document["actions"]
def test_assume_role_reads_its_session_name_and_external_id():
document = json.loads(OUTPUT.read_text())
assert document["members"]["sts:AssumeRole"] == {
"sts:ExternalId": ["ExternalId"], "sts:RoleSessionName": ["RoleSessionName"]}
assert document["members"]["sts:AssumeRoleWithWebIdentity"] == {"sts:RoleSessionName": ["RoleSessionName"]}
assert document["actions"]["sts:AssumeRoleWithSAML"] == ["sts:RoleSessionName"]
assert "sts:AssumeRoleWithSAML" not in document["members"]
assert "sts:GetCallerIdentity" not in document["actions"]
EVENTS = {"metadata": {"protocol": "json"}, "operations": {
"PutRule": {"input": {"shape": "PutRuleRequest"}}, "PutTargets": {"input": {"shape": "PutTargetsRequest"}},
"PutEvents": {"input": {"shape": "PutEventsRequest"}}}, "shapes": {
"PutRuleRequest": {"type": "structure", "members": {"Name": {"shape": "RuleName"},
"EventPattern": {"shape": "EventPattern"}}},
"PutTargetsRequest": {"type": "structure", "members": {"Rule": {"shape": "RuleName"},
"Targets": {"shape": "TargetList"}}},
"TargetList": {"type": "list", "member": {"shape": "Target"}},
"Target": {"type": "structure", "members": {"Arn": {"shape": "TargetArn"},
"DeadLetterConfig": {"shape": "DeadLetterConfig"}}},
"DeadLetterConfig": {"type": "structure", "members": {"Arn": {"shape": "ResourceArn"}}},
"PutEventsRequest": {"type": "structure", "members": {"Entries": {"shape": "Entries"}}},
"Entries": {"type": "list", "member": {"shape": "Entry"}},
"Entry": {"type": "structure", "members": {"Source": {"shape": "String"}}},
"RuleName": {"type": "string"}, "EventPattern": {"type": "string"}, "TargetArn": {"type": "string"},
"ResourceArn": {"type": "string"}, "String": {"type": "string"}}}
def test_a_vendored_key_is_read_from_its_member_in_the_one_operation_its_page_names():
# EventBridge's user guide reads events:source from the field of PutRule's event pattern, a JSON document the
# string member holds, and events:TargetArn from each target's own ARN, not its dead-letter queue's; PutEvents
# takes events:source too, which the page does not describe, so it is not read there.
actions = {"events:PutRule": ["events:source"], "events:PutTargets": ["events:TargetArn"],
"events:PutEvents": ["events:source"]}
assert request_members("events", EVENTS, actions) == {
"events:PutRule": {"events:source": ["EventPattern#source.*"]},
"events:PutTargets": {"events:TargetArn": ["Targets.*.Arn"]}}
assert member_shapes("events", EVENTS, actions)["events:PutRule"] == {"EventPattern#source.*": "EventPattern"}
def test_a_vendored_member_its_request_does_not_have_or_a_document_that_is_no_string_fails(monkeypatch):
import regen_request_condition_keys as r
entry = r.SERVICES["events"]
monkeypatch.setitem(r.SERVICES, "events", {**entry, "request": {**entry["request"], "events:TargetArn":
"Targets.*.Missing"}})
with pytest.raises(ValueError, match="Targets.*.Missing, which its request does not have"):
request_members("events", EVENTS, {"events:PutTargets": ["events:TargetArn"]})
monkeypatch.setitem(r.SERVICES, "events", {**entry, "request": {**entry["request"], "events:source":
"Targets#source.*"}})
with pytest.raises(ValueError, match="not a string"):
request_members("events", {**EVENTS, "operations": {"PutRule": {"input": {"shape": "PutTargetsRequest"}}}},
{"events:PutRule": ["events:source"]})
def test_the_vendored_table_reads_eventbridge_rules_and_targets():
document = json.loads(OUTPUT.read_text())
assert document["members"]["events:PutRule"]["events:source"] == ["EventPattern#source.*"]
assert document["members"]["events:PutRule"]["events:detail.service"] == ["EventPattern#detail.service.*"]
assert document["members"]["events:PutTargets"] == {"events:TargetArn": ["Targets.*.Arn"]}
assert "events:PutEvents" not in document["members"]