From fb0e72c96a987125d3c4e4391a5eda6d314924b4 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:00:33 -0400 Subject: [PATCH] fix(iam): check iam:PassRole on an EKS Auto Mode cluster's node role (#9576) CreateCluster and UpdateClusterConfig take EKS Auto Mode's node role in computeConfig.nodeRoleArn. AWS's Service Reference lists iam:PassRole for both operations, with iam:PassedToService ec2.amazonaws.com and eks.amazonaws.com, but not which member's role goes to which service. Floci never checked the node role: CreateCluster read only its cluster role, by hand, and UpdateClusterConfig was left out of the table. A new vendored source, tools/aws/sources/eks-roles.json, written by its own script from the EKS API reference and user guide, gives each member's role and the service its trust policy is for. CreateCluster's roleArn is the cluster IAM role ("provides permissions for the Kubernetes control plane"), whose page links from the member and whose trust policy names eks.amazonaws.com. nodeRoleArn is "the IAM Role EKS will assign to EC2 Managed Instances", whose description names the EKS Auto Mode IAM reference, whose node IAM role section links the guide's page of that role, whose trust policy names ec2.amazonaws.com. The generator reads the source (ROLE_SOURCES) to choose, among the services the Service Reference names for an operation, the one each member's role is for. It fails on a vendored role for a service the reference does not name, and on one no operation reads. --verify checks the source against the live pages. So CreateCluster now needs iam:PassRole on roleArn for eks.amazonaws.com and on computeConfig.nodeRoleArn for ec2.amazonaws.com, and UpdateClusterConfig on its node role for ec2.amazonaws.com. Both move into the generated table. So do CreateNodegroup, CreateFargateProfile, CreateAddon and UpdateAddon, whose roles PassedRoles read by hand, the same members to eks.amazonaws.com the generator gives from botocore and the Service Reference. Their hand readers are gone, and Step Functions' EKS tasks now check them as a direct request does. --- .github/workflows/iam-data-drift.yml | 3 + Makefile | 3 +- docs/services/iam.md | 15 +- .../io/floci/aws/core/common/PassedRoles.java | 18 +- src/main/resources/aws/iam-passed-roles.json | 27 ++- .../aws/core/common/PassedRolesTest.java | 10 +- ...IamPassRoleEnforcementIntegrationTest.java | 25 ++ tools/aws/fetch_eks_roles.py | 224 ++++++++++++++++++ tools/aws/regen_iam_passed_roles.py | 153 ++++++++++-- tools/aws/sources/eks-roles.json | 39 +++ tools/aws/test_fetch_eks_roles.py | 80 +++++++ tools/aws/test_regen_iam_passed_roles.py | 49 +++- 12 files changed, 594 insertions(+), 52 deletions(-) create mode 100644 tools/aws/fetch_eks_roles.py create mode 100644 tools/aws/sources/eks-roles.json create mode 100644 tools/aws/test_fetch_eks_roles.py diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.yml index cd0d65af35..53ae46586b 100644 --- a/.github/workflows/iam-data-drift.yml +++ b/.github/workflows/iam-data-drift.yml @@ -52,6 +52,9 @@ on: - 'src/main/resources/aws/iam-passed-roles.json' - 'tools/aws/regen_iam_passed_roles.py' - 'tools/aws/test_regen_iam_passed_roles.py' + - 'tools/aws/sources/eks-roles.json' + - 'tools/aws/fetch_eks_roles.py' + - 'tools/aws/test_fetch_eks_roles.py' - 'src/main/resources/aws/iam-passed-network-connectors.json' - 'tools/aws/regen_iam_passed_network_connectors.py' - 'tools/aws/test_regen_iam_passed_network_connectors.py' diff --git a/Makefile b/Makefile index c07ee0f04b..9416ec2137 100644 --- a/Makefile +++ b/Makefile @@ -622,7 +622,8 @@ IAM_AUTHORIZED_ACTIONS_PATHS := src/main/resources/aws/iam-authorized-actions.js src/main/resources/aws/rest-routes.json tools/aws/sources/s3-required-actions.json \ tools/aws/fetch_s3_required_actions.py tools/aws/test_fetch_s3_required_actions.py IAM_PASSED_ROLES_PATHS := src/main/resources/aws/iam-passed-roles.json $(IAM_PASSED_ROLES_GENERATOR) \ - tools/aws/test_regen_iam_passed_roles.py + tools/aws/test_regen_iam_passed_roles.py tools/aws/sources/eks-roles.json tools/aws/fetch_eks_roles.py \ + tools/aws/test_fetch_eks_roles.py IAM_PASSED_NETWORK_CONNECTORS_PATHS := src/main/resources/aws/iam-passed-network-connectors.json \ tools/aws/regen_iam_passed_network_connectors.py $(IAM_PASSED_ROLES_GENERATOR) \ tools/aws/test_regen_iam_passed_network_connectors.py diff --git a/docs/services/iam.md b/docs/services/iam.md index 57d79f18db..c792dd80a4 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3074,7 +3074,16 @@ role each passes: `UpdatePipe` pass `RoleArn` to `pipes.amazonaws.com`. - **EKS:** `CreateCluster` passes `roleArn`, `CreateNodegroup` `nodeRole`, `CreateFargateProfile` `podExecutionRoleArn`, and `CreateAddon` and `UpdateAddon` `serviceAccountRoleArn` and each of - their `podIdentityAssociations`' `roleArn`, to `eks.amazonaws.com`. `CreatePodIdentityAssociation` + their `podIdentityAssociations`' `roleArn`, to `eks.amazonaws.com`, all read from the table below. + `CreateCluster` and `UpdateClusterConfig` pass EKS Auto Mode's `computeConfig.nodeRoleArn` to + `ec2.amazonaws.com`. The Service Reference passes both operations' roles to `ec2.amazonaws.com` and + `eks.amazonaws.com` without saying which member's goes where, so a vendored source, + `tools/aws/sources/eks-roles.json`, written by `tools/aws/fetch_eks_roles.py` from the EKS API + reference and user guide, gives each member's role and the service its trust policy is for: + `roleArn` is the cluster IAM role ("The Amazon Resource Name (ARN) of the IAM role that provides + permissions for the Kubernetes control plane", trusted by `eks.amazonaws.com`), and `nodeRoleArn` + "the IAM Role EKS will assign to EC2 Managed Instances", the node IAM role (trusted by + `ec2.amazonaws.com`). `CreatePodIdentityAssociation` and `UpdatePodIdentityAssociation` pass `roleArn` to `pods.eks.amazonaws.com`, but not `targetRoleArn`, which the association's role assumes. `CreateAccessEntry` passes `principalArn` to `ec2.amazonaws.com` when its `type` is `EC2_LINUX` or `EC2_WINDOWS`: "If you create an access @@ -3192,8 +3201,8 @@ when the caller may not pass the role. `StartQuery`, for two); one whose role is a parameter of the runbook it runs (SSM `StartAutomationExecution`, Config `PutRemediationConfigurations`); one the Service Reference passes roles from to several services without saying which member goes where (EMR `RunJobFlow`, - whose `JobFlowRole` also names an instance profile, EKS `UpdateClusterConfig`, CloudWatch Logs - `CreateImportTask`); and one the botocore + whose `JobFlowRole` also names an instance profile, CloudWatch Logs `CreateImportTask`); and one + the botocore models Floci is pinned to do not have yet (SSM `RegisterDefaultHostManagementConfiguration`, Kinesis Analytics `ImportSnapshot`, Secrets Manager `AssociateCrossAccountReplica`), whose role the generator reads as soon as a release that has it is pinned. EC2's `RequestSpotFleet` names diff --git a/src/main/java/io/floci/aws/core/common/PassedRoles.java b/src/main/java/io/floci/aws/core/common/PassedRoles.java index ad6868ea49..8fa9989538 100644 --- a/src/main/java/io/floci/aws/core/common/PassedRoles.java +++ b/src/main/java/io/floci/aws/core/common/PassedRoles.java @@ -64,9 +64,9 @@ import java.util.regex.Pattern; * you must grant your user permission to pass the role to Amazon ECS"), task roles to * {@code ecs-tasks.amazonaws.com}. * - *

An EKS request passes the cluster's {@code roleArn}, a node group's {@code nodeRole}, a Fargate - * profile's {@code podExecutionRoleArn}, and an add-on's service account role and the role of each Pod - * Identity association it makes, to {@code eks.amazonaws.com}. A Pod Identity association passes its + *

EKS's cluster, node group, Fargate profile and add-on roles are read from the table, a cluster's + * {@code roleArn} going to {@code eks.amazonaws.com} and its EKS Auto Mode {@code computeConfig.nodeRoleArn} + * to {@code ec2.amazonaws.com}, as the vendored EKS role source gives them. A Pod Identity association passes its * {@code roleArn} to {@code pods.eks.amazonaws.com}: the EKS user guide has "The IAM principal that is * creating the association must have iam:PassRole." Its target role is not passed but assumed with the * association's role: "Pod Identity then automatically performs two role assumptions in sequence: first @@ -133,7 +133,6 @@ final class PassedRoles { private static final String EVENTS = ServicePrincipals.of("events"); private static final String SCHEDULER = ServicePrincipals.of("scheduler"); private static final String PIPES = ServicePrincipals.of("pipes"); - private static final String EKS = ServicePrincipals.of("eks"); private static final String EKS_PODS = ServicePrincipals.of("pods.eks"); private static final String CLOUDFORMATION = ServicePrincipals.of("cloudformation"); private static final String AUTOSCALING = ServicePrincipals.of("autoscaling"); @@ -290,10 +289,6 @@ final class PassedRoles { case "events:PutTargets" -> fromJson(ctx, EVENTS, "Targets", "[]", "RoleArn"); case "scheduler:CreateSchedule", "scheduler:UpdateSchedule" -> fromJson(ctx, SCHEDULER, "Target", "RoleArn"); case "pipes:CreatePipe", "pipes:UpdatePipe" -> fromJson(ctx, PIPES, "RoleArn"); - case "eks:CreateCluster" -> fromJson(ctx, EKS, "roleArn"); - case "eks:CreateNodegroup" -> fromJson(ctx, EKS, "nodeRole"); - case "eks:CreateFargateProfile" -> fromJson(ctx, EKS, "podExecutionRoleArn"); - case "eks:CreateAddon", "eks:UpdateAddon" -> eksAddonRoles(jsonBody(ctx)); case "eks:CreatePodIdentityAssociation", "eks:UpdatePodIdentityAssociation" -> fromJson(ctx, EKS_PODS, "roleArn"); case "eks:CreateAccessEntry" -> eksNodeAccessEntry(jsonBody(ctx)); @@ -664,13 +659,6 @@ final class PassedRoles { return passed(arns, service); } - /** An EKS add-on's service account role and the role of each Pod Identity association it makes. */ - private static List eksAddonRoles(JsonNode body) { - List roles = new ArrayList<>(values(body, "serviceAccountRoleArn")); - roles.addAll(values(body, "podIdentityAssociations", "[]", "roleArn")); - return passed(roles, EKS); - } - /** An EKS access entry's principal, when its type is one whose nodes run as that role. */ private static List eksNodeAccessEntry(JsonNode body) { List type = values(body, "type"); diff --git a/src/main/resources/aws/iam-passed-roles.json b/src/main/resources/aws/iam-passed-roles.json index 41aa9de4fb..36ac66c7ca 100644 --- a/src/main/resources/aws/iam-passed-roles.json +++ b/src/main/resources/aws/iam-passed-roles.json @@ -401,22 +401,37 @@ ]}, "ecs:UpdateService": {"passedTo": ["ecs", "ecs-tasks"], "byHand": "the task definition's roles and the service's infrastructure roles"}, "eks:CreateAccessEntry": {"passedTo": ["ec2"], "byHand": "the principal, for the node types alone"}, - "eks:CreateAddon": {"passedTo": ["eks"], "byHand": "the service account role and each Pod Identity association's role"}, + "eks:CreateAddon": {"passedTo": ["eks"], "roles": [ + {"member": "podIdentityAssociations[].roleArn", "passedTo": "eks"}, + {"member": "serviceAccountRoleArn", "passedTo": "eks"} + ]}, "eks:CreateCapability": {"passedTo": ["eks"], "roles": [ {"member": "roleArn", "passedTo": "eks"} ]}, - "eks:CreateCluster": {"passedTo": ["ec2", "eks"], "byHand": "the cluster role"}, - "eks:CreateFargateProfile": {"passedTo": ["eks"], "byHand": "the pod execution role"}, - "eks:CreateNodegroup": {"passedTo": ["eks"], "byHand": "the node role"}, + "eks:CreateCluster": {"passedTo": ["ec2", "eks"], "roles": [ + {"member": "computeConfig.nodeRoleArn", "passedTo": "ec2"}, + {"member": "roleArn", "passedTo": "eks"} + ]}, + "eks:CreateFargateProfile": {"passedTo": ["eks"], "roles": [ + {"member": "podExecutionRoleArn", "passedTo": "eks"} + ]}, + "eks:CreateNodegroup": {"passedTo": ["eks"], "roles": [ + {"member": "nodeRole", "passedTo": "eks"} + ]}, "eks:CreatePodIdentityAssociation": {"passedTo": ["pods.eks"], "byHand": "the association's role, not its target role"}, "eks:RegisterCluster": {"passedTo": ["eks"], "roles": [ {"member": "connectorConfig.roleArn", "passedTo": "eks"} ]}, - "eks:UpdateAddon": {"passedTo": ["eks"], "byHand": "the service account role and each Pod Identity association's role"}, + "eks:UpdateAddon": {"passedTo": ["eks"], "roles": [ + {"member": "podIdentityAssociations[].roleArn", "passedTo": "eks"}, + {"member": "serviceAccountRoleArn", "passedTo": "eks"} + ]}, "eks:UpdateCapability": {"passedTo": ["eks"], "roles": [ {"member": "roleArn", "passedTo": "eks"} ]}, - "eks:UpdateClusterConfig": {"passedTo": ["ec2", "eks"], "notRead": "the reference passes the node role to ec2 or eks and nothing says which"}, + "eks:UpdateClusterConfig": {"passedTo": ["ec2", "eks"], "roles": [ + {"member": "computeConfig.nodeRoleArn", "passedTo": "ec2"} + ]}, "eks:UpdatePodIdentityAssociation": {"passedTo": ["pods.eks"], "byHand": "the association's role, not its target role"}, "elasticfilesystem:CreateReplicationConfiguration": {"passedTo": ["elasticfilesystem"], "roles": [ {"member": "Destinations[].RoleArn", "passedTo": "elasticfilesystem"} diff --git a/src/test/java/io/floci/aws/core/common/PassedRolesTest.java b/src/test/java/io/floci/aws/core/common/PassedRolesTest.java index 2ea0648799..c84a3ccbc9 100644 --- a/src/test/java/io/floci/aws/core/common/PassedRolesTest.java +++ b/src/test/java/io/floci/aws/core/common/PassedRolesTest.java @@ -224,6 +224,14 @@ class PassedRolesTest { String eks = "eks.amazonaws.com"; assertEquals(List.of(passed("cluster", eks)), PassedRoles.of("eks:CreateCluster", json("{\"name\":\"c\",\"roleArn\":\"" + ROLES + "cluster\"}"), LOOKUPS)); + // EKS Auto Mode's node role is the one its EC2 Managed Instances run as, passed to EC2. + String autoMode = "{\"computeConfig\":{\"enabled\":true,\"nodePools\":[\"general-purpose\"],\"nodeRoleArn\":\"" + + ROLES + "auto-node\"}}"; + assertEquals(List.of(passed("auto-node", EC2), passed("cluster", eks)), PassedRoles.of("eks:CreateCluster", + json(autoMode.replace("{\"computeConfig\"", "{\"roleArn\":\"" + ROLES + "cluster\",\"computeConfig\"")), + LOOKUPS)); + assertEquals(List.of(passed("auto-node", EC2)), PassedRoles.of("eks:UpdateClusterConfig", json(autoMode), + LOOKUPS)); assertEquals(List.of(passed("node", eks)), PassedRoles.of("eks:CreateNodegroup", json("{\"nodeRole\":\"" + ROLES + "node\"}"), LOOKUPS)); assertEquals(List.of(passed("fargate", eks)), PassedRoles.of("eks:CreateFargateProfile", @@ -233,7 +241,7 @@ class PassedRolesTest { {"serviceAccount":"a","roleArn":"%1$spod-a"},{"serviceAccount":"b","roleArn":"%1$spod-b"}]}""" .formatted(ROLES); for (String action : List.of("eks:CreateAddon", "eks:UpdateAddon")) { - assertEquals(List.of(passed("addon", eks), passed("pod-a", eks), passed("pod-b", eks)), + assertEquals(List.of(passed("pod-a", eks), passed("pod-b", eks), passed("addon", eks)), PassedRoles.of(action, json(addon), LOOKUPS)); } // The association's role goes to Pod Identity; its target role is assumed with it, not passed. diff --git a/src/test/java/io/floci/aws/services/iam/IamPassRoleEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamPassRoleEnforcementIntegrationTest.java index 65eb379a4b..3a8b4d6933 100644 --- a/src/test/java/io/floci/aws/services/iam/IamPassRoleEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamPassRoleEnforcementIntegrationTest.java @@ -601,6 +601,31 @@ class IamPassRoleEnforcementIntegrationTest { } /** Creates an EKS cluster as the account's admin, removed afterwards, and returns its name. */ + @Test + void anEksAutoModeClusterNeedsPassRoleOnItsNodeRoleForEc2AndItsClusterRoleForEks() { + // The node role is the role EKS Auto Mode's EC2 Managed Instances run as, so it is passed to EC2; the + // cluster role, the control plane's, to EKS. + String cluster = role("auto-cluster"); + String node = role("auto-node"); + User user = user("passrole-eks-auto"); + String body = """ + {"name":"passrole-auto-%s","roleArn":"%s","computeConfig":{"enabled":true,"nodePools":["general-purpose"], + "nodeRoleArn":"%s"},"kubernetesNetworkConfig":{"elasticLoadBalancing":{"enabled":true}}, + "storageConfig":{"blockStorage":{"enabled":true}}}""".formatted(suffix(), cluster, node); + + user.policy(allow("eks:CreateCluster", "*") + "," + passRole(cluster, "eks.amazonaws.com")); + denied(user.rest("eks").body(body).post("/clusters").then()); + user.policy(allow("eks:CreateCluster", "*") + "," + passRole(cluster, "eks.amazonaws.com") + "," + + passRole(node, "eks.amazonaws.com")); + denied(user.rest("eks").body(body).post("/clusters").then()); + + user.policy(allow("eks:CreateCluster", "*") + "," + passRole(cluster, "eks.amazonaws.com") + "," + + passRole(node, "ec2.amazonaws.com")); + String name = user.rest("eks").body(body).post("/clusters").then().statusCode(200) + .extract().path("cluster.name"); + cleanup.register(() -> admin("eks").delete("/clusters/" + name)); + } + private String eksCluster() { String name = "passrole-cluster-" + suffix(); admin("eks").contentType("application/json") diff --git a/tools/aws/fetch_eks_roles.py b/tools/aws/fetch_eks_roles.py new file mode 100644 index 0000000000..b509f192a7 --- /dev/null +++ b/tools/aws/fetch_eks_roles.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Vendor which role an Amazon EKS request member names, and the service that role is for, into +tools/aws/sources/eks-roles.json, a source of the passed-roles table. + +AWS's Service Reference passes CreateCluster's and UpdateClusterConfig's roles to `ec2.amazonaws.com` and +`eks.amazonaws.com` without saying which member's role goes where, and botocore does not say it as data either. The +EKS API reference describes each member as the role it names, and the EKS user guide gives each role's trust policy, +the service it is for. CreateCluster's `roleArn` is the cluster role, its description linking the guide's page of it: + + The Amazon Resource Name (ARN) of the IAM role that provides permissions for the Kubernetes control plane to make + calls to AWS API operations on your behalf. For more information, see Amazon EKS Service IAM Role in the Amazon + EKS User Guide. + + https://docs.aws.amazon.com/eks/latest/APIReference/API_CreateCluster.html + https://docs.aws.amazon.com/eks/latest/userguide/service_IAM_role.html ("Service": "eks.amazonaws.com") + +and EKS Auto Mode's `nodeRoleArn`, a member of the ComputeConfigRequest both operations take, is the node role, its +description naming the guide's IAM reference for EKS Auto Mode, whose section of that role links the guide's page of +it: + + The ARN of the IAM Role EKS will assign to EC2 Managed Instances in your EKS Auto Mode cluster. ... For more + information, see the IAM Reference in the Amazon EKS User Guide. + + https://docs.aws.amazon.com/eks/latest/APIReference/API_ComputeConfigRequest.html + https://docs.aws.amazon.com/eks/latest/userguide/auto-learn-iam.html (section "Node IAM role") + https://docs.aws.amazon.com/eks/latest/userguide/create-node-role.html ("Service": "ec2.amazonaws.com") + +This script copies each member's description as it stands, the guide's section that names its role where the +description names the IAM reference, and the title and trust policy's service principals of the page of the role. +Nothing in the output is written by hand; regen_iam_passed_roles.py reads it to choose, among the services the +Service Reference passes an operation's roles to, the one each member's role is for. + +Run from anywhere in the repo: + python3 tools/aws/fetch_eks_roles.py # rewrite the vendored file from the pages + python3 tools/aws/fetch_eks_roles.py --verify # online: the file still says what the pages do +""" +from __future__ import annotations + +import argparse +import html +import json +import re +import sys +import urllib.parse +import urllib.request +from datetime import datetime, timezone +from pathlib import Path + +API_REFERENCE = "https://docs.aws.amazon.com/eks/latest/APIReference/" +USER_GUIDE = "https://docs.aws.amazon.com/eks/latest/userguide/" +AUTO_MODE_IAM_REFERENCE = USER_GUIDE + "auto-learn-iam.html" +REPO_ROOT = Path(__file__).resolve().parents[2] +OUTPUT = REPO_ROOT / "tools/aws/sources/eks-roles.json" + +# The members that name a role, each by the API reference page and anchor describing it: a request member of an +# operation (`operation`) or a member of a type a request holds (`type`). One whose description names the guide's IAM +# reference for EKS Auto Mode is given the section of that page naming its role. +MEMBERS = ( + {"operation": "CreateCluster", "member": "roleArn"}, + {"type": "ComputeConfigRequest", "member": "nodeRoleArn", "section": "Node IAM role"}, +) +# A description naming the guide's IAM reference rather than linking a page. +IAM_REFERENCE_RE = re.compile(r"\bsee the IAM Reference in the Amazon EKS User Guide\b") +# A trust policy in a code block of a role's page. +TRUST_RE = re.compile(r'"Principal"\s*:\s*\{\s*"Service"') + + +def text(fragment: str) -> str: + """A fragment of a page as text, spaces collapsed.""" + return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip() + + +def code(fragment: str) -> str: + """A code block as the text it shows, the page's copy button left out.""" + fragment = re.sub(r'

.*?
', "", fragment, flags=re.S) + return html.unescape(re.sub(r"<[^>]+>", "", re.sub(r"", "", fragment, flags=re.S))).strip() + + +def api_page(member: dict) -> str: + """The API reference page describing the member: its operation's or its type's.""" + return API_REFERENCE + "API_" + (member.get("operation") or member["type"]) + ".html" + + +def anchor(member: dict) -> str: + """The id of the member's entry on its API reference page.""" + if "operation" in member: + return f"AmazonEKS-{member['operation']}-request-{member['member']}" + return f"AmazonEKS-Type-{member['type']}-{member['member']}" + + +def read_description(page: str, member: dict) -> tuple[str, list[str]]: + """The member's description on its API reference page, as text, and the pages it links.""" + match = re.search(r'id="' + re.escape(anchor(member)) + r'"[^>]*>(?P.*?)', page, re.S) + if match is None: + raise ValueError(f"{api_page(member)} has no entry {anchor(member)}: its layout changed") + entry = match.group("entry") + described = re.search(r"]*>(?P.*?)

\s*Type:", entry + "

Type:", re.S) + body = described.group("body") if described else entry + links = [urllib.parse.urljoin(api_page(member), href) for href in re.findall(r'href="([^"#][^"]*)"', body)] + return text(body), links + + +def read_section(page: str, heading: str) -> tuple[str, list[str]]: + """The text of the section of the page under `heading`, to the next one, and the pages it links.""" + match = re.search(r"]*>\s*" + re.escape(heading) + r"\s*(?P.*?)(?= dict: + """The title of a role's page and the service principals each trust policy on it names.""" + title = re.search(r"(?P<title>.*?)", page, re.S) + services: set[str] = set() + for block in re.findall(r"]*>(.*?)", page, re.S): + shown = code(block) + if not TRUST_RE.search(shown): + continue + for statement in json.loads(shown)["Statement"]: + service = statement["Principal"]["Service"] + services.update([service] if isinstance(service, str) else service) + if title is None or not services: + raise ValueError(f"{url} gives no trust policy naming a service: its layout changed") + return {"title": text(title.group("title")), "trustedBy": sorted(services)} + + +def role_page(member: dict, description: str, links: list[str], fetch) -> tuple[dict, str]: + """The page of the role the member names, and what the guide says names it there: the page its description links + that has a trust policy, or the one the IAM reference's section of its role links.""" + found: dict = {} + if IAM_REFERENCE_RE.search(description): + if "section" not in member: + raise ValueError(f"{api_page(member)} names the IAM reference for {member['member']}, and no section of it " + f"is given here") + section, links = read_section(fetch(AUTO_MODE_IAM_REFERENCE), member["section"]) + found = {"reference": AUTO_MODE_IAM_REFERENCE, "section": member["section"], "sectionText": section} + pages = [] + for link in dict.fromkeys(links): + if not link.startswith(USER_GUIDE): + continue + try: + pages.append((link, read_role(fetch(link), link))) + except ValueError: + continue + if len(pages) != 1: + raise ValueError(f"{member['member']}'s description links {len(pages)} pages of a role, not one: " + f"{[link for link, _ in pages] or links}") + link, role = pages[0] + return {**found, "rolePage": link, **role}, link + + +def build(fetch) -> dict: + members = [] + pages = [] + for member in MEMBERS: + description, links = read_description(fetch(api_page(member)), member) + role, link = role_page(member, description, links, fetch) + pages += [api_page(member)] + ([role["reference"]] if "reference" in role else []) + [link] + named = {key: member[key] for key in ("operation", "type") if key in member} + members.append({**named, "member": member["member"], "description": description, **role}) + return { + "_source": { + "pages": list(dict.fromkeys(pages)), + "fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)), + "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), + "note": "Each member's description on its API reference page, copied as it stands; where it names the " + "EKS Auto Mode IAM reference, that page's section of its role; and the title of the user guide's " + "page of the role and the service principals its trust policies name.", + }, + "members": members, + } + + +def fetch_url(url: str) -> str: + request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"}) + with urllib.request.urlopen(request, timeout=60) as response: + return response.read().decode("utf-8") + + +def fetch_all(fetch=fetch_url) -> tuple: + """The pages, each fetched once, as a reader of them.""" + cache: dict[str, str] = {} + + def cached(url: str) -> str: + if url not in cache: + cache[url] = fetch(url) + return cache[url] + + build(cached) + return (cache,) + + +def stale(vendored: dict, pages: dict[str, str]) -> bool: + """Whether the pages now give something other than the vendored file, its date aside.""" + return vendored.get("members") != build(lambda url: pages[url])["members"] + + +def main(argv: list[str] | None = None, fetch=fetch_url) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the pages") + args = parser.parse_args(argv) + try: + (pages,) = fetch_all(fetch) + except OSError as e: + print(f"error: could not read the Amazon EKS documentation ({e})", file=sys.stderr) + return 2 + if args.verify: + vendored = json.loads(OUTPUT.read_text(encoding="utf-8")) + if stale(vendored, pages): + print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the EKS API reference and user guide " + f"do: run tools/aws/fetch_eks_roles.py and then make iam-passed-roles-sync", file=sys.stderr) + return 1 + print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the EKS API reference and user guide") + return 0 + built = build(lambda url: pages[url]) + OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8") + print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['members'])} members' roles)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/regen_iam_passed_roles.py b/tools/aws/regen_iam_passed_roles.py index 4ee68bd094..20b6110981 100644 --- a/tools/aws/regen_iam_passed_roles.py +++ b/tools/aws/regen_iam_passed_roles.py @@ -29,7 +29,9 @@ read from its XML body by the elements botocore serializes them as (S3's `PutBuc `PassedRoles` does not read there, fails generation. What the rule gets wrong for an operation is corrected here, each with its reason: a role member it does not see (`EXTRA_MEMBERS`), a member it sees that passes no role (`EXCLUDED_MEMBERS`), and which service a member's role goes to -when the reference names several (`MEMBER_SERVICES`). +when the reference names several (`MEMBER_SERVICES`). Where a namespace's documentation says it, which +service that is comes from a vendored source instead (`ROLE_SOURCES`): EKS's API reference names the +role each member takes, and its user guide the service each role's trust policy is for. Only the namespaces in `NAMESPACES` are read, and in them every operation the reference lists with `iam:PassRole`, whether Floci serves it or not, so an operation Floci adds is checked from the @@ -64,6 +66,7 @@ Run from anywhere in the repo: from __future__ import annotations import argparse +import functools import json import re import sys @@ -71,6 +74,7 @@ from collections.abc import Callable, Iterable from datetime import datetime, timezone from pathlib import Path +import fetch_eks_roles from regen_iam_authorized_actions import fetch_references from regen_partitions import resolve_botocore_data from regen_query_services import latest_model_dir, load_model @@ -183,12 +187,7 @@ BY_HAND = { "ecs:UpdateCapacityProvider": "the infrastructure role, by name or ARN", "ecs:UpdateService": "the task definition's roles and the service's infrastructure roles", "eks:CreateAccessEntry": "the principal, for the node types alone", - "eks:CreateAddon": "the service account role and each Pod Identity association's role", - "eks:CreateCluster": "the cluster role", - "eks:CreateFargateProfile": "the pod execution role", - "eks:CreateNodegroup": "the node role", "eks:CreatePodIdentityAssociation": "the association's role, not its target role", - "eks:UpdateAddon": "the service account role and each Pod Identity association's role", "eks:UpdatePodIdentityAssociation": "the association's role, not its target role", "events:PutRule": "the rule's role", "events:PutTargets": "each target's role", @@ -273,7 +272,6 @@ NOT_READ = { "ec2:RequestSpotFleet": "the request names its roles in EC2's own protocol, one of them as an instance profile", "ecs:CreateDaemon": "the roles are the daemon task definition's, which only a lookup finds", "ecs:UpdateDaemon": "the roles are the daemon task definition's, which only a lookup finds", - "eks:UpdateClusterConfig": "the reference passes the node role to ec2 or eks and nothing says which", "elasticmapreduce:RunJobFlow": "JobFlowRole names an instance profile, and the reference passes the roles " "to three services without saying which goes where", "elasticmapreduce:UpdateStudio": NO_ROLE_MEMBER, @@ -408,6 +406,23 @@ MEMBER_SERVICES = { "rds:*": {"*": "rds"}, } +# ROLE_SOURCES: the namespaces whose documentation says which role a request member names and the service that role is +# for, where the reference passes an operation's roles to several services without saying which member's goes where, +# and the vendored pages that say so. Granted for EKS: the API reference describes CreateCluster's roleArn as the +# cluster role, linking the user guide's page of it, whose trust policy names "eks.amazonaws.com", and EKS Auto Mode's +# computeConfig.nodeRoleArn as "the IAM Role EKS will assign to EC2 Managed Instances", naming the guide's IAM +# reference for EKS Auto Mode, whose section of the node role links the guide's page of it, whose trust policy names +# "ec2.amazonaws.com"; tools/aws/fetch_eks_roles.py vendors those pages and `vendored_service` reads them, choosing +# among the services the reference names. The file is written by its own script from the pages, unchanged, and nothing +# about an operation is stated here. +ROLE_SOURCES: dict[str, Path] = { + "eks": REPO_ROOT / "tools/aws/sources/eks-roles.json", +} +# The script that writes each namespace's role source, whose pages `verify_role_sources` reads it against. +ROLE_FETCHERS = { + "eks": fetch_eks_roles, +} + # --------------------------------------------------------------------------- # # The Service Reference: which operations pass a role, to which services @@ -547,34 +562,79 @@ def role_members(model: dict, operation: str) -> dict[str, bool]: PATH_STEP_RE = re.compile(r"^(?P[A-Za-z][A-Za-z0-9_]*)(?:\[(?P[A-Za-z0-9_]*)\]|\{(?P[A-Za-z0-9_]*)\})?$") -def member_exists(model: dict, operation: str, path: str) -> bool: - """Whether the operation's request has a string member at `path`, a `{KEY}` step naming a key - the map's key enum lists when it has one.""" +def _walk(model: dict, operation: str, path: str) -> tuple[str, str, dict] | None: + """The structure shape holding the member `path` ends at, that member's name, and the shape it holds past the + path's last step; None for a path the operation's request does not have, a `{KEY}` step naming a key the map's + key enum does not list.""" spec = model["operations"].get(operation) if spec is None or "input" not in spec or not readable(model): - return False - shape = model["shapes"][spec["input"]["shape"]] + return None + owner = spec["input"]["shape"] + shape = model["shapes"][owner] + walked = None for step in path.split("."): match = PATH_STEP_RE.match(step) if match is None or shape["type"] != "structure": - return False - found = [member for name, member in shape.get("members", {}).items() + return None + found = [(name, member) for name, member in shape.get("members", {}).items() if member.get("locationName", name) == match["name"]] if not found: - return False - shape = model["shapes"][found[0]["shape"]] + return None + name, member = found[0] + walked = (owner, name) + owner = member["shape"] + shape = model["shapes"][owner] if match["list"] is not None: if shape["type"] != "list": - return False - shape = model["shapes"][shape["member"]["shape"]] + return None + owner = shape["member"]["shape"] elif match["key"] is not None: if shape["type"] != "map": - return False + return None keys = model["shapes"][shape["key"]["shape"]].get("enum") if match["key"] and keys is not None and match["key"] not in keys: - return False - shape = model["shapes"][shape["value"]["shape"]] - return shape["type"] == "string" + return None + owner = shape["value"]["shape"] + shape = model["shapes"][owner] + return None if walked is None else (*walked, shape) + + +def member_exists(model: dict, operation: str, path: str) -> bool: + """Whether the operation's request has a string member at `path`, a `{KEY}` step naming a key + the map's key enum lists when it has one.""" + walked = _walk(model, operation, path) + return walked is not None and walked[2]["type"] == "string" + + +@functools.cache +def _role_source(namespace: str) -> tuple[dict, ...]: + """The members the namespace's vendored role source (`ROLE_SOURCES`) gives; none for a namespace it is not + granted.""" + path = ROLE_SOURCES.get(namespace) + return () if path is None else tuple(json.loads(path.read_text(encoding="utf-8"))["members"]) + + +def vendored_service(operation: str, path: str, passed_to: list[str], models: dict[str, dict]) -> str | None: + """The one of `passed_to` the role at `path` is for, by the namespace's vendored role source (`ROLE_SOURCES`): + the service a trust policy of the role its member names is for, the member given by its operation when it is the + request's own and by the botocore type holding it otherwise. None for a member the source does not give.""" + name = operation.split(":", 1)[1] + own = PATH_STEP_RE.match(path) is not None + for model in models.values(): + walked = _walk(model, name, path) + if walked is None: + continue + owner, member, _shape = walked + for entry in _role_source(namespace_of(operation)): + if entry["member"] != member or (entry.get("operation") != name if own else entry.get("type") != owner): + continue + services = [service.removesuffix(SERVICE_SUFFIX) for service in entry["trustedBy"]] + chosen = [service for service in services if service in passed_to] + if len(chosen) != 1: + raise ValueError(f"{operation}: the role at {path} is for {services} by {entry['rolePage']}, which " + f"is not one of {passed_to} the reference passes its roles to") + return chosen[0] + return None def load_models(data: Path, clients: set[str]) -> dict[str, dict]: @@ -660,8 +720,11 @@ def entry_for(operation: str, passed_to: list[str], models: dict[str, dict]) -> elif len(passed_to) == 1: role["passedTo"] = passed_to[0] elif passed_to: - raise ValueError(f"{operation}: the role at {path} can go to any of {passed_to}; " - f"say which in MEMBER_SERVICES") + vendored = vendored_service(operation, path, passed_to, models) + if vendored is None: + raise ValueError(f"{operation}: the role at {path} can go to any of {passed_to}; " + f"say which in MEMBER_SERVICES or a vendored role source (ROLE_SOURCES)") + role["passedTo"] = vendored if members[path]: role["byName"] = True roles.append(role) @@ -707,7 +770,8 @@ def build(documents: list[dict], provenance: str, data: Path, botocore: str) -> def _unmatched_corrections(covered: dict[str, dict], namespaces: dict[str, list[str]], data: Path) -> list[str]: - """An exclusion or a member's service that no operation it applies to has, so none outlives its member.""" + """An exclusion, a member's service or a vendored role (`ROLE_SOURCES`) that no operation it applies to has, so + none outlives its member.""" found: dict[str, set[str]] = {} for operation in covered: if operation in BY_HAND or operation in NOT_READ: @@ -723,6 +787,23 @@ def _unmatched_corrections(covered: dict[str, dict], namespaces: dict[str, list[ for path in paths: if path != "*" and not any(path in found[operation] for operation in scope): problems.append(f"{table_name} names {path} for {key}, which no operation there has") + for namespace in ROLE_SOURCES: + held = set() + for operation in found: + if namespace_of(operation) != namespace: + continue + name = operation.split(":", 1)[1] + for model in load_models(data, set(namespaces[namespace])).values(): + for path in found[operation]: + walked = _walk(model, name, path) + if walked is not None: + held.add(("operation", name, walked[1]) if PATH_STEP_RE.match(path) else + ("type", walked[0], walked[1])) + for entry in _role_source(namespace): + kind = "operation" if "operation" in entry else "type" + if (kind, entry[kind], entry["member"]) not in held: + problems.append(f"ROLE_SOURCES gives {namespace}'s {entry[kind]}.{entry['member']}, which no " + f"operation there reads a role from") return problems @@ -834,6 +915,22 @@ def derive(document: dict, data: Path) -> list[str]: return problems +def verify_role_sources() -> list[str]: + """A vendored role source (`ROLE_SOURCES`) whose pages AWS has changed.""" + untrue: list[str] = [] + for namespace, path in sorted(ROLE_SOURCES.items()): + source = json.loads(path.read_text(encoding="utf-8")) + fetcher = ROLE_FETCHERS[namespace] + try: + changed = fetcher.stale(source, *fetcher.fetch_all()) + except (OSError, ValueError) as e: + raise OSError(f"could not read {' and '.join(source['_source']['pages'])} ({e})") from e + if changed: + untrue.append(f"{' and '.join(source['_source']['pages'])} no longer give what {path.name} holds for " + f"{namespace}: run {source['_source']['fetcher']}") + return untrue + + def verify_against(vendored: dict, upstream: dict[str, dict]) -> tuple[list[str], list[str]]: """What the file claims and AWS does not, and the operations AWS has added since.""" untrue: list[str] = [] @@ -891,7 +988,13 @@ def main(argv: list[str] | None = None) -> int: except (OSError, ValueError) as e: print(f"error: could not read the Service Reference ({e})", file=sys.stderr) return 2 + try: + sources = verify_role_sources() + except OSError as e: + print(f"error: {e}", file=sys.stderr) + return 2 untrue, added = verify_against(document, upstream) + untrue += sources for claim in untrue: print(f"error: {claim}", file=sys.stderr) if untrue: diff --git a/tools/aws/sources/eks-roles.json b/tools/aws/sources/eks-roles.json new file mode 100644 index 0000000000..833d457fec --- /dev/null +++ b/tools/aws/sources/eks-roles.json @@ -0,0 +1,39 @@ +{ + "_source": { + "pages": [ + "https://docs.aws.amazon.com/eks/latest/APIReference/API_CreateCluster.html", + "https://docs.aws.amazon.com/eks/latest/userguide/service_IAM_role.html", + "https://docs.aws.amazon.com/eks/latest/APIReference/API_ComputeConfigRequest.html", + "https://docs.aws.amazon.com/eks/latest/userguide/auto-learn-iam.html", + "https://docs.aws.amazon.com/eks/latest/userguide/create-node-role.html" + ], + "fetcher": "tools/aws/fetch_eks_roles.py", + "retrieved": "2026-11-27", + "note": "Each member's description on its API reference page, copied as it stands; where it names the EKS Auto Mode IAM reference, that page's section of its role; and the title of the user guide's page of the role and the service principals its trust policies name." + }, + "members": [ + { + "operation": "CreateCluster", + "member": "roleArn", + "description": "The Amazon Resource Name (ARN) of the IAM role that provides permissions for the Kubernetes control plane to make calls to AWS API operations on your behalf. For more information, see Amazon EKS Service IAM Role in the Amazon EKS User Guide .", + "rolePage": "https://docs.aws.amazon.com/eks/latest/userguide/service_IAM_role.html", + "title": "Amazon EKS cluster IAM role - Amazon EKS", + "trustedBy": [ + "eks.amazonaws.com" + ] + }, + { + "type": "ComputeConfigRequest", + "member": "nodeRoleArn", + "description": "The ARN of the IAM Role EKS will assign to EC2 Managed Instances in your EKS Auto Mode cluster. This value cannot be changed after the compute capability of EKS Auto Mode is enabled. For more information, see the IAM Reference in the Amazon EKS User Guide .", + "reference": "https://docs.aws.amazon.com/eks/latest/userguide/auto-learn-iam.html", + "section": "Node IAM role", + "sectionText": "The Node IAM role is an AWS Identity and Access Management (IAM) role used by Amazon EKS to manage permissions for worker nodes in Kubernetes clusters. This role grants EC2 instances running as Kubernetes nodes the necessary permissions to interact with AWS services and resources, and is automatically configured with Kubernetes RBAC permissions using EKS access entries. You must attach AWS IAM policies to this role. EKS Auto Mode attaches Kubernetes RBAC permissions to this role automatically using EKS access entries. AWS suggests naming this role AmazonEKSAutoNodeRole . With EKS Auto Mode, AWS suggests creating a single Node IAM Role per AWS account. This role has limited permissions. The key permissions include assuming a Pod Identity Role, and pulling images from ECR. AWS suggests the following AWS managed IAM policies: AmazonEKSWorkerNodeMinimalPolicy AmazonEC2ContainerRegistryPullOnly For more information about the Node IAM Role and AWS managed IAM policies, see: AWS managed policies for Amazon Elastic Kubernetes Service Amazon EKS node IAM role For more information about Kubernetes access, see: Review access policy permissions", + "rolePage": "https://docs.aws.amazon.com/eks/latest/userguide/create-node-role.html", + "title": "Amazon EKS node IAM role - Amazon EKS", + "trustedBy": [ + "ec2.amazonaws.com" + ] + } + ] +} diff --git a/tools/aws/test_fetch_eks_roles.py b/tools/aws/test_fetch_eks_roles.py new file mode 100644 index 0000000000..c150ce362e --- /dev/null +++ b/tools/aws/test_fetch_eks_roles.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Tests for fetch_eks_roles.py, on pages in the Amazon EKS API reference's and user guide's markup.""" +from __future__ import annotations + +import pytest + +import fetch_eks_roles as f + +API = f.API_REFERENCE +GUIDE = f.USER_GUIDE + + +def trust(service: str) -> str: + return ('

' + '
{ "Version":"2012-10-17", ' + '"Statement": [ { "Effect": "Allow", "Principal": { "Service": "' + service + '" }, ' + '"Action": "sts:AssumeRole" } ] }
') + + +PAGES = { + API + "API_CreateCluster.html": ( + '
' + 'roleArn

The Amazon Resource Name (ARN) of the IAM role that ' + 'provides permissions for the Kubernetes control plane to make calls to AWS API operations on your behalf. ' + 'For more information, see ' + 'Amazon EKS Service IAM Role in the Amazon EKS User Guide.

Type: String

'), + API + "API_ComputeConfigRequest.html": ( + '
nodeRoleArn' + '

The ARN of the IAM Role EKS will assign to EC2 Managed Instances in your EKS Auto Mode cluster. ' + 'For more information, see the IAM Reference in the Amazon EKS User Guide.

Type: String

' + '
'), + GUIDE + "service_IAM_role.html": "Amazon EKS cluster IAM role" + trust("eks.amazonaws.com"), + GUIDE + "auto-learn-iam.html": ( + '

Cluster IAM role

The Cluster IAM role is used by Amazon EKS.

' + '

Node IAM role

This role grants EC2 instances running as Kubernetes ' + 'nodes the necessary permissions.

See AWS managed policies ' + 'and Amazon EKS node IAM role.

' + '

Service-linked role

Other.

'), + GUIDE + "security-iam-awsmanpol.html": "AWS managed policies

No trust policy here.

", + GUIDE + "create-node-role.html": "Amazon EKS node IAM role" + trust("ec2.amazonaws.com"), +} + + +def test_each_member_gives_its_description_and_the_service_its_roles_page_trusts(): + built = f.build(lambda url: PAGES[url]) + assert built["members"] == [ + {"operation": "CreateCluster", "member": "roleArn", + "description": "The Amazon Resource Name (ARN) of the IAM role that provides permissions for the Kubernetes " + "control plane to make calls to AWS API operations on your behalf. For more information, see " + "Amazon EKS Service IAM Role in the Amazon EKS User Guide .", + "rolePage": GUIDE + "service_IAM_role.html", "title": "Amazon EKS cluster IAM role", + "trustedBy": ["eks.amazonaws.com"]}, + {"type": "ComputeConfigRequest", "member": "nodeRoleArn", + "description": "The ARN of the IAM Role EKS will assign to EC2 Managed Instances in your EKS Auto Mode " + "cluster. For more information, see the IAM Reference in the Amazon EKS User Guide .", + "reference": GUIDE + "auto-learn-iam.html", "section": "Node IAM role", + "sectionText": "This role grants EC2 instances running as Kubernetes nodes the necessary permissions. See " + "AWS managed policies and Amazon EKS node IAM role .", + "rolePage": GUIDE + "create-node-role.html", "title": "Amazon EKS node IAM role", + "trustedBy": ["ec2.amazonaws.com"]}] + + +def test_a_page_whose_layout_changed_is_refused(): + missing = dict(PAGES, **{API + "API_CreateCluster.html": "
"}) + with pytest.raises(ValueError, match="has no entry"): + f.build(lambda url: missing[url]) + untrusted = dict(PAGES, **{GUIDE + "create-node-role.html": "Amazon EKS node IAM role"}) + with pytest.raises(ValueError, match="not one"): + f.build(lambda url: untrusted[url]) + unsectioned = dict(PAGES, **{GUIDE + "auto-learn-iam.html": "

Cluster IAM role

Only.

"}) + with pytest.raises(ValueError, match="no section"): + f.build(lambda url: unsectioned[url]) + + +def test_the_file_is_stale_when_a_page_says_something_else(): + vendored = f.build(lambda url: PAGES[url]) + assert not f.stale(vendored, PAGES) + changed = dict(PAGES, **{GUIDE + "create-node-role.html": "Amazon EKS node IAM role" + + trust("eks.amazonaws.com")}) + assert f.stale(vendored, changed) diff --git a/tools/aws/test_regen_iam_passed_roles.py b/tools/aws/test_regen_iam_passed_roles.py index 4eb6af9744..d1b275868e 100644 --- a/tools/aws/test_regen_iam_passed_roles.py +++ b/tools/aws/test_regen_iam_passed_roles.py @@ -40,8 +40,9 @@ def structure(**members) -> dict: @pytest.fixture def corrections(monkeypatch): """No corrections at all, so a test sees the rule alone and sets what it needs.""" - for name in ("BY_HAND", "NOT_READ", "EXCLUDED_MEMBERS", "EXTRA_MEMBERS", "MEMBER_SERVICES"): + for name in ("BY_HAND", "NOT_READ", "EXCLUDED_MEMBERS", "EXTRA_MEMBERS", "MEMBER_SERVICES", "ROLE_SOURCES"): monkeypatch.setattr(r, name, {}) + r._role_source.cache_clear() monkeypatch.setattr(r, "NAMESPACES", ("svc",)) return monkeypatch @@ -203,6 +204,52 @@ def test_a_role_passed_to_no_named_service_carries_none(corrections): assert r.entry_for("svc:CreateThing", [], SIMPLE)["roles"][0] == {"member": "RoleArn"} +CLUSTER = {"svc": model({"CreateCluster": "In"}, {"In": structure(roleArn="String", computeConfig="Compute"), + "Compute": structure(nodeRoleArn="String")})} + + +def role_source(corrections, tmp_path, members): + path = tmp_path / "svc-roles.json" + path.write_text(json.dumps({"members": members}), encoding="utf-8") + corrections.setattr(r, "ROLE_SOURCES", {"svc": path}) + r._role_source.cache_clear() + + +def test_a_vendored_role_source_gives_each_member_the_service_its_role_is_for(corrections, tmp_path): + # The request's own member by its operation, a member of a type it holds by that type, wherever it sits. + role_source(corrections, tmp_path, [ + {"operation": "CreateCluster", "member": "roleArn", "rolePage": "cluster", "trustedBy": ["svc.amazonaws.com"]}, + {"type": "Compute", "member": "nodeRoleArn", "rolePage": "node", "trustedBy": ["other.amazonaws.com"]}]) + assert r.entry_for("svc:CreateCluster", ["other", "svc"], CLUSTER)["roles"] == [ + {"member": "computeConfig.nodeRoleArn", "passedTo": "other"}, {"member": "roleArn", "passedTo": "svc"}] + + +def test_a_vendored_role_for_a_service_the_reference_does_not_name_fails(corrections, tmp_path): + role_source(corrections, tmp_path, [ + {"operation": "CreateCluster", "member": "roleArn", "rolePage": "cluster", "trustedBy": ["lambda.amazonaws.com"]}, + {"type": "Compute", "member": "nodeRoleArn", "rolePage": "node", "trustedBy": ["other.amazonaws.com"]}]) + with pytest.raises(ValueError, match="not one of"): + r.entry_for("svc:CreateCluster", ["other", "svc"], CLUSTER) + # A member it does not give still needs saying which. + role_source(corrections, tmp_path, [ + {"type": "Compute", "member": "nodeRoleArn", "rolePage": "node", "trustedBy": ["other.amazonaws.com"]}]) + with pytest.raises(ValueError, match="ROLE_SOURCES"): + r.entry_for("svc:CreateCluster", ["other", "svc"], CLUSTER) + + +def test_a_vendored_role_no_operation_reads_is_reported(corrections, tmp_path): + corrections.setattr(r, "load_models", lambda data, clients: CLUSTER) + covered = {"svc:CreateCluster": {"passedTo": ["other", "svc"], "clients": ["svc"]}} + role_source(corrections, tmp_path, [ + {"operation": "CreateCluster", "member": "roleArn", "rolePage": "cluster", "trustedBy": ["svc.amazonaws.com"]}, + {"type": "Compute", "member": "nodeRoleArn", "rolePage": "node", "trustedBy": ["other.amazonaws.com"]}]) + assert r._unmatched_corrections(covered, {"svc": ["svc"]}, tmp_path) == [] + role_source(corrections, tmp_path, [ + {"type": "Compute", "member": "goneRoleArn", "rolePage": "node", "trustedBy": ["other.amazonaws.com"]}]) + assert r._unmatched_corrections(covered, {"svc": ["svc"]}, tmp_path) == [ + "ROLE_SOURCES gives svc's Compute.goneRoleArn, which no operation there reads a role from"] + + def test_several_services_need_a_member_service(corrections): with pytest.raises(ValueError, match="MEMBER_SERVICES"): r.entry_for("svc:CreateThing", ["svc", "other"], SIMPLE)