Files
floci/tools/aws/test_regen_request_condition_keys.py
T
Priamo Germosen cc74f1c3a2 fix(iam): read an AssumeRole's source identity as the IAM user guide gives it (#9697)
Under enforcement an AssumeRole passing a SourceIdentity was neither held to sts:SetSourceIdentity nor read as sts:SourceIdentity, so a trust policy requiring a source identity refused every assume and one granting the permission was never consulted. The session kept no source identity either: the response returned none, its requests carried no aws:SourceIdentity, and a session assumed from it could set another. botocore gives the member and the Service Reference the key and the action, listing sts:SetSourceIdentity among the actions AssumeRole is authorized by, without saying when it is needed or which member carries the key.

The IAM user guide's page on source identity says both: "to pass source identity while assuming a role, use the -–source-identity AWS CLI option or the SourceIdentity AWS API parameter", "to specify a source identity, principals (IAM users and roles) must have permissions to sts:SetSourceIdentity", and when chaining it is "required in both the permissions policy of the principal who is assuming the role and in the role trust policy of the target role". tools/aws/fetch_sts_source_identity.py vendors it into tools/aws/sources/sts-source-identity.json. regen_request_condition_keys.py reads it for sts (CONDITION_SOURCES), so sts:SourceIdentity is read from AssumeRole's SourceIdentity, and regen_iam_authorized_actions.py crosses it with the reference's AuthorizedActions and botocore's request members into a new companions section of iam-authorized-actions.json: AssumeRole needs sts:SetSourceIdentity when it names SourceIdentity or its caller carries aws:SourceIdentity.

Enforcement checks the companion action on the role with the request's keys, and for a caller that is itself a role session checks it of the caller's own permissions alone too, since a trust policy naming the caller's role would otherwise stand in for them in the same account (the table's callerPolicyWhenChained, from the page's sentence on role chaining). STS checks it in the trust policy before the assume, as AWS names it where a statement granting both is conditioned on another sts:SourceIdentity. The session records the value under the key the table gives, aws:SourceIdentity, which its requests carry and a session assumed from it carries on, read there as sts:SourceIdentity too, and the response returns it. A chained request naming another value is refused with ValidationError, "The source identity is already set for this assume role session", and an AssumeRole naming a session tag key twice with InvalidParameterValue, "Duplicate tag keys found. Please note that Tag keys are case insensitive.", both as AWS's evaluation suite records them.

Part of #6640.
2026-11-28 21:09:11 -04:00

355 lines
21 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/sources/eks-condition-keys.json",
"tools/aws/fetch_eks_conditions.py",
"tools/aws/test_fetch_eks_conditions.py",
"tools/aws/sources/route53-condition-keys.json",
"tools/aws/fetch_route53_conditions.py",
"tools/aws/test_fetch_route53_conditions.py",
"tools/aws/sources/sts-source-identity.json",
"tools/aws/fetch_sts_source_identity.py",
"tools/aws/test_fetch_sts_source_identity.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_external_id_and_source_identity():
document = json.loads(OUTPUT.read_text())
assert document["members"]["sts:AssumeRole"] == {
"sts:ExternalId": ["ExternalId"], "sts:RoleSessionName": ["RoleSessionName"],
"sts:SourceIdentity": ["SourceIdentity"]}
# The IAM user guide names the member a source identity is passed in for AssumeRole alone: the federated
# operations take it from the assertion or the token.
assert document["members"]["sts:AssumeRoleWithWebIdentity"] == {"sts:RoleSessionName": ["RoleSessionName"]}
assert document["actions"]["sts:AssumeRoleWithSAML"] == ["sts:RoleSessionName", "sts:SourceIdentity"]
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"]
EKS = {"metadata": {"protocol": "rest-json"}, "operations": {
"CreateAccessEntry": {"input": {"shape": "Create"}}, "UpdateAccessEntry": {"input": {"shape": "Update"}},
"AssociateAccessPolicy": {"input": {"shape": "Associate"}},
"DisassociateAccessPolicy": {"input": {"shape": "Disassociate"}}}, "shapes": {
"Create": {"type": "structure", "members": {"principalArn": {"shape": "String"},
"kubernetesGroups": {"shape": "Groups"}}},
"Update": {"type": "structure", "members": {"principalArn": {"shape": "String", "location": "uri"},
"kubernetesGroups": {"shape": "Groups"}}},
"Associate": {"type": "structure", "members": {"policyArn": {"shape": "String"},
"accessScope": {"shape": "Scope"}}},
"Disassociate": {"type": "structure", "members": {"policyArn": {"shape": "String", "location": "uri"}}},
"Scope": {"type": "structure", "members": {"type": {"shape": "String"}, "namespaces": {"shape": "Groups"}}},
"Groups": {"type": "list", "member": {"shape": "String"}}, "String": {"type": "string"}}}
def test_a_vendored_key_is_read_where_the_request_carries_its_member_in_the_body():
# The Service Authorization Reference gives EKS's access entry keys as what the requests carry: a list's values
# are read each, a member in the URI or a structure, which the page does not say which value of holds the key,
# is not read.
actions = {"eks:CreateAccessEntry": ["eks:kubernetesGroups", "eks:principalArn"],
"eks:AssociateAccessPolicy": ["eks:accessScope", "eks:namespaces", "eks:policyArn"],
"eks:DisassociateAccessPolicy": ["eks:accessScope", "eks:namespaces", "eks:policyArn"]}
assert request_members("eks", EKS, actions) == {
"eks:CreateAccessEntry": {"eks:kubernetesGroups": ["kubernetesGroups.*"], "eks:principalArn": ["principalArn"]},
"eks:AssociateAccessPolicy": {"eks:namespaces": ["accessScope.namespaces.*"], "eks:policyArn": ["policyArn"]}}
def test_a_vendored_key_on_a_resource_type_alone_is_not_read_from_the_request():
# eks:kubernetesGroups is the access entry's own on UpdateAccessEntry, which takes it from its resource type
# alone, not what the update asks for.
reference = {"Name": "eks", "Resources": [{"Name": "access-entry", "ConditionKeys": ["eks:kubernetesGroups"]}],
"Actions": [{"Name": "UpdateAccessEntry", "Resources": [{"Name": "access-entry"}]},
{"Name": "CreateAccessEntry", "ActionConditionKeys": ["eks:kubernetesGroups"],
"Resources": [{"Name": "cluster"}]}]}
assert action_keys("eks", reference) == {"eks:CreateAccessEntry": ["eks:kubernetesGroups"]}
def test_the_vendored_table_reads_eks_access_entries_and_policies():
document = json.loads(OUTPUT.read_text())
assert document["members"]["eks:CreateAccessEntry"] == {
"eks:accessEntryType": ["type"], "eks:kubernetesGroups": ["kubernetesGroups.*"],
"eks:principalArn": ["principalArn"], "eks:username": ["username"]}
assert document["members"]["eks:AssociateAccessPolicy"] == {
"eks:namespaces": ["accessScope.namespaces.*"], "eks:policyArn": ["policyArn"]}
assert "eks:DisassociateAccessPolicy" not in document["members"]
assert "eks:UpdateAccessEntry" not in document["actions"]
ROUTE53 = {"metadata": {"protocol": "rest-xml"}, "operations": {
"AssociateVPCWithHostedZone": {"input": {"shape": "Associate"}},
"ListHostedZonesByVPC": {"input": {"shape": "ByVpc"}}}, "shapes": {
"Associate": {"type": "structure", "members": {"HostedZoneId": {"shape": "String", "location": "uri"},
"VPC": {"shape": "VPC"}}},
"VPC": {"type": "structure", "members": {"VPCRegion": {"shape": "String"}, "VPCId": {"shape": "String"}}},
"ByVpc": {"type": "structure", "members": {
"VPCId": {"shape": "String", "location": "querystring", "locationName": "vpcid"},
"VPCRegion": {"shape": "String", "location": "querystring", "locationName": "vpcregion"}}},
"String": {"type": "string"}}}
def test_a_vendored_format_composes_the_members_each_request_carries():
# Route 53's developer guide gives route53:VPCs "in the format of VPCId=<vpc-id>,VPCRegion=<region>": each member's
# place holds where the request carries it, in an XML body or in the query string.
actions = {"route53:AssociateVPCWithHostedZone": ["route53:VPCs"], "route53:ListHostedZonesByVPC": ["route53:VPCs"]}
assert request_members("route53", ROUTE53, actions) == {
"route53:AssociateVPCWithHostedZone": {"route53:VPCs": ["VPCId={VPC.VPCId},VPCRegion={VPC.VPCRegion}"]},
"route53:ListHostedZonesByVPC": {"route53:VPCs": ["VPCId={?vpcid},VPCRegion={?vpcregion}"]}}
assert member_shapes("route53", ROUTE53, actions) == {}
def test_the_vendored_table_reads_route53_vpcs():
document = json.loads(OUTPUT.read_text())
assert document["members"]["route53:CreateHostedZone"] == {
"route53:VPCs": ["VPCId={VPC.VPCId},VPCRegion={VPC.VPCRegion}"]}
assert document["members"]["route53:ListHostedZonesByVPC"] == {
"route53:VPCs": ["VPCId={?vpcid},VPCRegion={?vpcregion}"]}