Files
floci/tools/aws/test_regen_request_condition_keys.py
T
Priamo Germosen 1b7ddb1101 fix(iam): read EKS access entry condition keys from the vendored Service Authorization Reference (#9682)
Under enforcement a CreateAccessEntry scoped by eks:principalArn or eks:accessEntryType was refused for every entry, and an AssociateAccessPolicy scoped by eks:policyArn or eks:namespaces for every association, as #8311 reports: the request condition key table read none of these keys, so a condition on them never saw a value. Neither botocore nor the Service Reference says which request member carries them.

The Service Authorization Reference's table of the keys EKS defines says it: eks:principalArn, eks:kubernetesGroups, eks:policyArn and eks:namespaces filter on "the <member> present in the access entry requests" or in "the associate / disassociate access policy requests", and eks:accessEntryType and eks:username on "the access entry type" and "the Kubernetes username" present in them, the access entry requests' type and username. A vendored source, tools/aws/sources/eks-condition-keys.json, written by tools/aws/fetch_eks_conditions.py from that page, gives each key its member, and the generator reads it for eks (CONDITION_SOURCES) beside the cluster keys it already reads.

The page gives what a request carries, so a vendored key is read from an action's request only where the reference lists it on the action itself; one the reference gives a resource type alone is the stored resource's value. A list's values are each read (kubernetesGroups, accessScope.namespaces). A vendored member the request carries outside its body, as DisassociateAccessPolicy carries policyArn in its path, or as a structure, as accessScope is, the page not saying which of its values the key holds, is not read.

The keys the reference gives the access entry itself, its stored principal, type, groups and username on the operations acting on one, are not read yet: those requests are checked on an access entry ARN whose identity and id are left open, which names no one entry to read them from.

Closes #8311.
2026-11-28 17:12:28 -04:00

316 lines
19 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/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"]
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"]