diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.yml index 5a68565393..31d850d864 100644 --- a/.github/workflows/iam-data-drift.yml +++ b/.github/workflows/iam-data-drift.yml @@ -97,6 +97,9 @@ on: - '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' - 'src/main/resources/aws/rest-routes.json' - 'tools/aws/regen_rest_routes.py' - 'tools/aws/test_regen_rest_routes.py' diff --git a/Makefile b/Makefile index 9a009d28c7..718b5b1ad2 100644 --- a/Makefile +++ b/Makefile @@ -646,7 +646,8 @@ REQUEST_CONDITION_KEYS_PATHS := src/main/resources/aws/request-condition-keys.js 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 $(IAM_PASSED_ROLES_GENERATOR) \ tools/aws/sources/eventbridge-condition-keys.json tools/aws/fetch_eventbridge_conditions.py \ - tools/aws/test_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 DOCUMENTED_ROUTES_PATHS := src/main/resources/aws/rest-routes.json tools/aws/regen_rest_routes.py \ tools/aws/test_regen_rest_routes.py tools/aws/regen_partitions.py tools/aws/regen_query_services.py IAM_REQUEST_RESOURCES_PATHS := src/main/resources/aws/iam-request-resources.json \ @@ -988,7 +989,7 @@ s3control-tag-condition-keys-verify: ## Check the S3 Control tag condition actio $(PYTHON) tools/aws/regen_s3control_tag_condition_keys.py --verify .PHONY: request-condition-keys-sync request-condition-keys-check request-condition-keys-verify -request-condition-keys-sync: ## Regenerate the EventBridge, Lambda Web, Redshift, Route 53 and STS request condition keys from AWS and botocore +request-condition-keys-sync: ## Regenerate the EKS, EventBridge, Lambda Web, Redshift, Route 53 and STS request condition keys from AWS and botocore $(PYTHON) tools/aws/regen_request_condition_keys.py request-condition-keys-check: ## Check the request condition key members against pinned botocore $(PYTHON) tools/aws/regen_request_condition_keys.py --check diff --git a/docs/services/iam.md b/docs/services/iam.md index 28835236c1..5fce55b657 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -4195,6 +4195,21 @@ floci populates: given a JSON null is absent, never the cluster's stored value. The actions, members and protocol come from the same `request-condition-keys.json`. A boolean member given anything but a boolean or its text is refused before it is read (see [EKS](eks.md)), so the key never misses a value the cluster takes. +- `eks:principalArn`, `eks:accessEntryType`, `eks:kubernetesGroups` and `eks:username`: the `principalArn`, + `type`, each of the `kubernetesGroups` and the `username` a `CreateAccessEntry` request names; `eks:policyArn` + and `eks:namespaces`: the `policyArn` and each namespace of the `accessScope` an `AssociateAccessPolicy` request + names. A member the request leaves out names nothing: an entry created without a `type` carries no + `eks:accessEntryType`, and a `cluster` scope no `eks:namespaces`, so a `Null` check on it refuses that scope. + Neither botocore nor the Service Reference says which member carries these keys, so a vendored source, + `tools/aws/sources/eks-condition-keys.json`, written by `tools/aws/fetch_eks_conditions.py` from the + [Service Authorization Reference](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonelastickubernetesservice.html), + gives each: "the principalArn present in the access entry requests", "the access entry type", "the Kubernetes + username". It is read where the Service Reference lists the key on the action itself. `eks:accessScope` is not + read: the page names the `accessScope` structure, not which of its values the key holds. Nor is + `DisassociateAccessPolicy`'s `eks:policyArn`, which its request carries in its path. The keys the Service + 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. - `sts:RoleSessionName` and `sts:ExternalId`: the `RoleSessionName` and `ExternalId` an `AssumeRole` request passes, as given, for the caller's identity-based policies, permissions boundary, session policy and SCPs, as the role's trust policy reads them (see [STS](sts.md)); `sts:ExternalId` is absent when the request passes none. diff --git a/src/main/resources/aws/request-condition-keys.json b/src/main/resources/aws/request-condition-keys.json index 71bf9e13a1..851142d4c3 100644 --- a/src/main/resources/aws/request-condition-keys.json +++ b/src/main/resources/aws/request-condition-keys.json @@ -11,12 +11,28 @@ "ec2-instance-connect:privateIpAddress", "ec2-instance-connect:remotePort" ], + "eks:AssociateAccessPolicy": [ + "eks:accessScope", + "eks:namespaces", + "eks:policyArn" + ], + "eks:CreateAccessEntry": [ + "eks:accessEntryType", + "eks:kubernetesGroups", + "eks:principalArn", + "eks:username" + ], "eks:CreateCluster": [ "eks:authenticationMode", "eks:bootstrapClusterCreatorAdminPermissions", "eks:endpointPrivateAccess", "eks:endpointPublicAccess" ], + "eks:DisassociateAccessPolicy": [ + "eks:accessScope", + "eks:namespaces", + "eks:policyArn" + ], "eks:UpdateClusterConfig": [ "eks:authenticationMode", "eks:endpointPrivateAccess", @@ -95,6 +111,28 @@ "remotePort" ] }, + "eks:AssociateAccessPolicy": { + "eks:namespaces": [ + "accessScope.namespaces.*" + ], + "eks:policyArn": [ + "policyArn" + ] + }, + "eks:CreateAccessEntry": { + "eks:accessEntryType": [ + "type" + ], + "eks:kubernetesGroups": [ + "kubernetesGroups.*" + ], + "eks:principalArn": [ + "principalArn" + ], + "eks:username": [ + "username" + ] + }, "eks:CreateCluster": { "eks:authenticationMode": [ "accessConfig.authenticationMode" @@ -188,6 +226,16 @@ } }, "memberShapes": { + "eks:AssociateAccessPolicy": { + "accessScope.namespaces.*": "String", + "policyArn": "String" + }, + "eks:CreateAccessEntry": { + "type": "String", + "kubernetesGroups.*": "String", + "principalArn": "String", + "username": "String" + }, "eks:CreateCluster": { "accessConfig.authenticationMode": "AuthenticationMode", "accessConfig.bootstrapClusterCreatorAdminPermissions": "BoxedBoolean", diff --git a/src/test/java/io/floci/aws/core/common/EksAccessEntryConditionsIntegrationTest.java b/src/test/java/io/floci/aws/core/common/EksAccessEntryConditionsIntegrationTest.java new file mode 100644 index 0000000000..e3f33b81e7 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/EksAccessEntryConditionsIntegrationTest.java @@ -0,0 +1,156 @@ +package io.floci.aws.core.common; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.EnforcementFixtures.UserCredentials; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.eks.EksClient; +import software.amazon.awssdk.services.eks.model.AccessScopeType; +import software.amazon.awssdk.services.eks.model.EksException; + +import java.net.URI; +import java.util.List; +import java.util.UUID; + +import static io.floci.aws.testing.EnforcementFixtures.auth; +import static io.floci.aws.testing.IamTestPolicies.EMPTY_POLICY_DOCUMENT; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * An access entry request is checked with the members the Service Authorization Reference says its keys hold: a + * CreateAccessEntry with its {@code principalArn}, {@code type}, {@code kubernetesGroups} and {@code username} as + * {@code eks:principalArn}, {@code eks:accessEntryType}, {@code eks:kubernetesGroups} and {@code eks:username}, and an + * AssociateAccessPolicy with its {@code policyArn} and each namespace of its scope as {@code eks:policyArn} and + * {@code eks:namespaces}, a member the request leaves out naming nothing. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class EksAccessEntryConditionsIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + private static final String VIEW = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSViewPolicy"; + private static final String ADMIN = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSAdminPolicy"; + + @TestHTTPResource("/") + URI endpoint; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void anAccessEntryIsCreatedOnlyForThePrincipalTypeGroupsAndUsernameAPolicyAllows() { + try (Fixture f = new Fixture()) { + String allowed = f.role("allowed"); + String other = f.role("other"); + f.policy(""" + {"Effect":"Allow","Action":"eks:CreateAccessEntry","Resource":"*","Condition":{ + "ArnEquals":{"eks:principalArn":"%s"},"StringEquals":{"eks:accessEntryType":"STANDARD"}, + "ForAllValues:StringEquals":{"eks:kubernetesGroups":["viewers"]}}}""".formatted(allowed)); + denied(() -> f.client.createAccessEntry(r -> r.clusterName(f.cluster).principalArn(other).type("STANDARD"))); + denied(() -> f.client.createAccessEntry(r -> r.clusterName(f.cluster).principalArn(allowed) + .type("STANDARD").kubernetesGroups("viewers", "admins"))); + // A request naming no type carries no eks:accessEntryType for StringEquals to match. + denied(() -> f.client.createAccessEntry(r -> r.clusterName(f.cluster).principalArn(allowed))); + f.client.createAccessEntry(r -> r.clusterName(f.cluster).principalArn(allowed).type("STANDARD") + .kubernetesGroups("viewers")); + + // An explicit deny on a username holds against an allow of every entry. + String named = f.role("named"); + f.policy(""" + {"Effect":"Allow","Action":"eks:CreateAccessEntry","Resource":"*"}, + {"Effect":"Deny","Action":"eks:CreateAccessEntry","Resource":"*", + "Condition":{"StringEquals":{"eks:username":"cluster-admin"}}}"""); + denied(() -> f.client.createAccessEntry(r -> r.clusterName(f.cluster).principalArn(named) + .username("cluster-admin"))); + f.client.createAccessEntry(r -> r.clusterName(f.cluster).principalArn(named).username("viewer")); + } + } + + @Test + void anAccessPolicyIsAssociatedOnlyAsThePolicyAndNamespacesAPolicyAllows() { + try (Fixture f = new Fixture()) { + String principal = f.role("associated"); + f.admin.createAccessEntry(r -> r.clusterName(f.cluster).principalArn(principal)); + f.policy(""" + {"Effect":"Allow","Action":"eks:AssociateAccessPolicy","Resource":"*","Condition":{ + "ArnEquals":{"eks:policyArn":"%s"}, + "ForAllValues:StringEquals":{"eks:namespaces":["team-a","team-b"]}}}""".formatted(VIEW)); + denied(() -> f.associate(principal, ADMIN, "team-a")); + denied(() -> f.associate(principal, VIEW, "team-a", "kube-system")); + f.associate(principal, VIEW, "team-a", "team-b"); + + // A cluster scope names no namespace, so a Null check on eks:namespaces refuses it. + f.policy(""" + {"Effect":"Allow","Action":"eks:AssociateAccessPolicy","Resource":"*", + "Condition":{"Null":{"eks:namespaces":"false"}}}"""); + denied(() -> f.client.associateAccessPolicy(r -> r.clusterName(f.cluster).principalArn(principal) + .policyArn(VIEW).accessScope(s -> s.type(AccessScopeType.CLUSTER)))); + f.associate(principal, VIEW, "team-a"); + } + } + + private static void denied(Runnable call) { + EksException error = assertThrows(EksException.class, call::run); + assertEquals(403, error.statusCode()); + assertEquals("AccessDeniedException", error.awsErrorDetails().errorCode()); + } + + /** A user, its clients and an API-mode cluster an administrator creates, removed afterwards. */ + private final class Fixture implements AutoCloseable { + final String user = "eks-access-" + UUID.randomUUID(); + final String cluster = "access-" + UUID.randomUUID(); + final EksClient admin; + final EksClient client; + + Fixture() { + UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), + auth(ACCOUNT, "iam"), user); + String clusterRole = EnforcementFixtures.createRole(cleanup, endpoint.getPort(), ACCOUNT, "/", + user + "-cluster", EMPTY_POLICY_DOCUMENT); + admin = AwsTestClients.create(EksClient.builder(), ACCOUNT, Region.US_EAST_1, endpoint); + try { + client = AwsTestClients.create(EksClient.builder(), credentials.accessKeyId(), + credentials.secretAccessKey(), Region.US_EAST_1, endpoint); + admin.createCluster(r -> r.name(cluster).roleArn(clusterRole) + .accessConfig(a -> a.authenticationMode("API_AND_CONFIG_MAP"))); + } catch (RuntimeException e) { + admin.close(); + throw e; + } + } + + /** A role of a name made from {@code name}, removed afterwards; its ARN. */ + String role(String name) { + return EnforcementFixtures.createRole(cleanup, endpoint.getPort(), ACCOUNT, "/", + name + "-" + UUID.randomUUID().toString().substring(0, 8), EMPTY_POLICY_DOCUMENT); + } + + void policy(String statements) { + EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth(ACCOUNT, "iam"), user, "conditions", + "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}"); + } + + void associate(String principal, String policy, String... namespaces) { + client.associateAccessPolicy(r -> r.clusterName(cluster).principalArn(principal).policyArn(policy) + .accessScope(s -> s.type(AccessScopeType.NAMESPACE).namespaces(List.of(namespaces)))); + } + + @Override + public void close() { + try { + admin.deleteCluster(r -> r.name(cluster)); + } finally { + client.close(); + admin.close(); + } + } + } +} diff --git a/tools/aws/fetch_eks_conditions.py b/tools/aws/fetch_eks_conditions.py new file mode 100644 index 0000000000..68825a4c55 --- /dev/null +++ b/tools/aws/fetch_eks_conditions.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""Vendor which request member carries each Amazon EKS access entry condition key into +tools/aws/sources/eks-condition-keys.json, a source of the request condition key table. + +AWS's Service Reference gives CreateAccessEntry the keys `eks:principalArn`, `eks:accessEntryType`, +`eks:kubernetesGroups` and `eks:username`, and AssociateAccessPolicy and DisassociateAccessPolicy `eks:policyArn`, +`eks:accessScope` and `eks:namespaces`, without saying where a request carries them, and botocore does not say it +either. The Service Authorization Reference's table of the keys EKS defines does, naming the request member each +holds: + + eks:principalArn Filters access by the principalArn present in the access entry requests the user makes to + the EKS service + eks:accessEntryType Filters access by the access entry type present in the access entry requests ... + + https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonelastickubernetesservice.html + +This script copies the row of each key the access entry and access policy requests carry, as it stands, with the +member it names: the one its row names by its name, or, where the row names it in words, the member those words name +(`PHRASES`), checked against the row. Nothing in the output is written by hand; regen_request_condition_keys.py reads +it to give the table those members, where botocore says the request carries one. + +Run from anywhere in the repo: + python3 tools/aws/fetch_eks_conditions.py # rewrite the vendored file from the page + python3 tools/aws/fetch_eks_conditions.py --verify # online: the file still says what the page does +""" +from __future__ import annotations + +import argparse +import html +import json +import re +import sys +import urllib.request +from datetime import datetime, timezone +from pathlib import Path + +PAGE = "https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonelastickubernetesservice.html" +REPO_ROOT = Path(__file__).resolve().parents[2] +OUTPUT = REPO_ROOT / "tools/aws/sources/eks-condition-keys.json" + +# The requests whose keys this file reads, as the rows name them. +REQUESTS = ("access entry requests", "associate / disassociate access policy requests") +# A row naming the member it filters on and the requests that carry it. +ROW_RE = re.compile(r"^Filters access by the (?P.+?) present in the (?P.+?) the user makes to the " + r"EKS service$") +# A member a row names by its name. +MEMBER_RE = re.compile(r"^[a-z][A-Za-z0-9]*$") +# The members rows name in words: the access entry's type and its Kubernetes username, botocore's `type` and +# `username` of the access entry requests. +PHRASES = {"access entry type": "type", "Kubernetes username": "username"} +KEY_RE = re.compile(r"^eks:[A-Za-z]+$") + + +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 key_rows(page: str) -> list[tuple[str, str]]: + """Each EKS key of the page's table of condition keys, with its row's description as text.""" + rows = [] + for row in re.findall(r"(.*?)", page, re.S): + cells = [text(cell) for cell in re.findall(r"]*>(.*?)", row, re.S)] + if len(cells) > 1 and KEY_RE.match(cells[0]): + rows.append((cells[0], cells[1])) + if not rows: + raise ValueError(f"{PAGE} has no table of EKS condition keys: its layout changed") + return rows + + +def build(fetch) -> dict: + keys = [] + for key, row in key_rows(fetch(PAGE)): + # The page doubles a word now and then ("requests requests"); the row is copied as it stands. + found = ROW_RE.match(re.sub(r"\b(\w+) \1\b", r"\1", row)) + if found is None or found.group("requests") not in REQUESTS: + continue + named = found.group("named") + member = named if MEMBER_RE.match(named) else PHRASES.get(named) + if member is None: + raise ValueError(f"{PAGE} names {key}'s member as '{named}', which is no member's name nor one of the " + f"words PHRASES gives a member: its layout changed") + keys.append({"key": key, "member": member, "requests": found.group("requests"), "row": row}) + if not keys: + raise ValueError(f"{PAGE} names no access entry key's member: its layout changed") + return { + "_source": { + "page": PAGE, + "fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)), + "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), + "note": "Each EKS key whose row of the page's table of condition keys filters on what the access entry or " + "access policy requests carry, with the member the row names and the row, copied as it stands.", + }, + "keys": sorted(keys, key=lambda entry: entry["key"]), + } + + +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 stale(vendored: dict, page: str) -> bool: + """Whether the page now gives something other than the vendored file, its date aside.""" + return vendored.get("keys") != build(lambda url: page)["keys"] + + +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 page") + args = parser.parse_args(argv) + try: + page = fetch(PAGE) + except OSError as e: + print(f"error: could not read the Service Authorization Reference ({e})", file=sys.stderr) + return 2 + if args.verify: + vendored = json.loads(OUTPUT.read_text(encoding="utf-8")) + if stale(vendored, page): + print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the Service Authorization Reference " + f"does: run tools/aws/fetch_eks_conditions.py and then make request-condition-keys-sync", + file=sys.stderr) + return 1 + print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the Service Authorization Reference") + return 0 + built = build(lambda url: page) + OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8") + print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['keys'])} keys)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/regen_request_condition_keys.py b/tools/aws/regen_request_condition_keys.py index 9f181fbfe2..c9a327a1f7 100644 --- a/tools/aws/regen_request_condition_keys.py +++ b/tools/aws/regen_request_condition_keys.py @@ -6,7 +6,11 @@ it. `SERVICES` names, for each namespace, the keys read and where: - `eks`: a CreateCluster or UpdateClusterConfig request is checked with the access configuration and endpoint flags it names in its JSON body, as `eks:authenticationMode`, `eks:bootstrapClusterCreatorAdminPermissions`, - `eks:endpointPrivateAccess` and `eks:endpointPublicAccess`; a member it leaves out names nothing. + `eks:endpointPrivateAccess` and `eks:endpointPublicAccess`; a member it leaves out names nothing. A + CreateAccessEntry request is checked with its principal, type, Kubernetes groups and username, and an + AssociateAccessPolicy request with its policy and each namespace of its scope, as the Service Authorization + Reference gives them (`CONDITION_SOURCES`); `eks:accessScope`, a structure the page does not say which value of + holds the key, and a member the request carries in its path are not read. - `lambda`: a Lambda Web Functions request is checked with the endpoint's authType as `lambda:Request/WebFunctionAuthType`, the one the request names, and `lambda:Resource/WebFunctionAuthType`, the one the endpoint has before the request, read from the stored endpoint. @@ -77,6 +81,7 @@ import sys import urllib.request from pathlib import Path +import fetch_eks_conditions import fetch_eventbridge_conditions from regen_dynamodb_condition_keys import member_paths from regen_iam_tag_on_create import _condition_keys, _resource_keys @@ -152,29 +157,44 @@ SERVICES = { # for EventBridge: its user guide's table of condition keys gives `events:source`, `events:detail-type` and the # `events:detail.*` keys as "the literal string for the field of the event", which a rule's "event pattern" # gives ("EventPattern is a mandatory argument to PutRule"), and `events:TargetArn` as "the ARN of the target for the -# rule"; tools/aws/fetch_eventbridge_conditions.py vendors that page and `vendored_service` reads it. Each file is -# written by its own script from the page, unchanged, and nothing about an operation is stated here. +# rule"; tools/aws/fetch_eventbridge_conditions.py vendors that page and `vendored_service` reads it. And granted for +# EKS: the Service Authorization Reference's table of the keys EKS defines gives `eks:principalArn`, +# `eks:kubernetesGroups`, `eks:policyArn` and `eks:namespaces` as "the present in the access entry requests" +# or in "the associate / disassociate access policy requests", and `eks:accessEntryType` and `eks:username` as "the +# access entry type" and "the Kubernetes username" present in them; tools/aws/fetch_eks_conditions.py vendors that +# page and `vendored_service` reads it. Each file is written by its own script from the page, unchanged, and nothing +# about an operation is stated here. CONDITION_SOURCES: dict[str, dict] = { + "eks": {"model": "eks", "source": REPO_ROOT / "tools/aws/sources/eks-condition-keys.json", + "fetcher": fetch_eks_conditions}, "events": {"model": "events", "source": REPO_ROOT / "tools/aws/sources/eventbridge-condition-keys.json", "fetcher": fetch_eventbridge_conditions}, } def vendored_service(namespace: str) -> dict: - """The `SERVICES` entry of a namespace a vendored page gives (`CONDITION_SOURCES`): each key read from the member - the page says carries it, a field of a JSON document after `#`, in the one operation the page names for it.""" + """The `SERVICES` entry of a namespace a vendored page gives (`CONDITION_SOURCES`), beside any it has: each key + read from the member the page says carries it, a field of a JSON document after `#`, in the one operation the + page names for it where it names one (`operations`). The page gives what a request carries, so a key is read + from an action's request only where the reference lists it on that action, not only on a resource type, whose + key is the stored resource's value (`vendored`).""" granted = CONDITION_SOURCES[namespace] document = json.loads(granted["source"].read_text(encoding="utf-8")) - request, operations = {}, {} + base = SERVICES.get(namespace, {"request": {}, "stored": (), "not_in_request": {}}) + request, operations = dict(base["request"]), {} for entry in document["keys"]: request[entry["key"]] = entry["member"] + (f"#{entry['field']}.*" if "field" in entry else "") - operations[entry["key"]] = entry["operation"] - return {"model": granted["model"], "request": request, "stored": (), "not_in_request": {}, - "operations": operations} + if "operation" in entry: + operations[entry["key"]] = entry["operation"] + return {**base, "model": granted["model"], "request": request, "operations": operations, + "vendored": frozenset(entry["key"] for entry in document["keys"])} SERVICES.update({namespace: vendored_service(namespace) for namespace in CONDITION_SOURCES}) +# The locations a request carries a member outside its body in, which the request condition reader does not read. +OUTSIDE_THE_BODY = {"uri", "querystring", "header", "headers"} + def url(namespace: str) -> str: return f"{REFERENCE}v1/{namespace}/{namespace}.json" @@ -184,10 +204,13 @@ def action_keys(namespace: str, reference: dict) -> dict[str, list[str]]: """Every action of the namespace that takes a key it reads, with the ones it takes.""" service = SERVICES[namespace] read = set(service["request"]) | set(service["stored"]) + vendored = service.get("vendored", frozenset()) resource_keys = _resource_keys([reference]) found = {} for action in sorted(reference["Actions"], key=lambda entry: entry["Name"]): - keys = read & _condition_keys(namespace, action, resource_keys) + own = set(action.get("ActionConditionKeys") or ()) + keys = {key for key in read & _condition_keys(namespace, action, resource_keys) + if key not in vendored or key in own} if keys: found[f"{namespace}:{action['Name']}"] = sorted(keys) return found @@ -235,6 +258,14 @@ def _located(namespace: str, model: dict | None, actions: dict[str, list[str]]): raise ValueError(f"{action} takes {key} but botocore has no request for it") # A vendored page gives a member by its path; `SERVICES` by its name, wherever it is. paths = [name] if "." in name else member_paths(model, operation["input"]["shape"], {name}) + vendored = key in service.get("vendored", ()) + if vendored and "." not in name and not document: + # A request carrying the member a vendored page names outside its body, or as a structure, which + # the page does not say which value of holds the key, carries no value read here. + paths = [path for path in paths if _in_the_body(model, operation["input"]["shape"], path) + and _scalar_or_list(model, operation["input"]["shape"], path)] + if not paths: + continue if not paths: raise ValueError(f"{action} takes {key} but its request has no {name} member") nested = [path for path in paths if protocol in FLAT_PROTOCOLS and "." in path] @@ -247,9 +278,28 @@ def _located(namespace: str, model: dict | None, actions: dict[str, list[str]]): raise ValueError(f"{action} takes {key} from {path}, which its request does not have") from e if document and model["shapes"][shape].get("type") != "string": raise ValueError(f"{action} takes {key} from a document in {path}, which is not a string") + if model["shapes"][shape].get("type") == "list" and not document: + # Each value of a list of them, as an ArrayOfString key holds them. + carried, shape = carried + ".*", model["shapes"][shape]["member"]["shape"] yield action, key, carried + (f"#{document}" if document else ""), shape +def _in_the_body(model: dict, shape: str, path: str) -> bool: + """Whether the request carries the member at `path` in its body, not in its URI, query string or headers.""" + return model["shapes"][shape]["members"][path.split(".", 1)[0]].get("location") not in OUTSIDE_THE_BODY + + +def _scalar_or_list(model: dict, shape: str, path: str) -> bool: + """Whether the member at `path` holds a value or a list of them, not a structure or a map.""" + for step in path.split("."): + spec = model["shapes"][shape] + shape = (spec.get("member") or spec.get("value"))["shape"] if step == "*" else spec["members"][step]["shape"] + spec = model["shapes"][shape] + return spec.get("type") not in ("structure", "map") and ( + spec.get("type") != "list" or model["shapes"][spec["member"]["shape"]].get("type") not in ("structure", "map", + "list")) + + def carried_member(model: dict, shape: str, path: str, xml: bool) -> tuple[str, str]: """The member at `path`, as `member_paths` spells it, as the request carries it, with its botocore shape: the same path in a form or a JSON body; in an XML body the elements botocore names, a list's own by the name of its diff --git a/tools/aws/sources/eks-condition-keys.json b/tools/aws/sources/eks-condition-keys.json new file mode 100644 index 0000000000..afce77947b --- /dev/null +++ b/tools/aws/sources/eks-condition-keys.json @@ -0,0 +1,58 @@ +{ + "_source": { + "page": "https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonelastickubernetesservice.html", + "fetcher": "tools/aws/fetch_eks_conditions.py", + "retrieved": "2026-11-28", + "note": "Each EKS key whose row of the page's table of condition keys filters on what the access entry or access policy requests carry, with the member the row names and the row, copied as it stands." + }, + "keys": [ + { + "key": "eks:accessEntryType", + "member": "type", + "requests": "access entry requests", + "row": "Filters access by the access entry type present in the access entry requests the user makes to the EKS service" + }, + { + "key": "eks:accessScope", + "member": "accessScope", + "requests": "associate / disassociate access policy requests", + "row": "Filters access by the accessScope present in the associate / disassociate access policy requests the user makes to the EKS service" + }, + { + "key": "eks:clusterName", + "member": "clusterName", + "requests": "access entry requests", + "row": "Filters access by the clusterName present in the access entry requests the user makes to the EKS service" + }, + { + "key": "eks:kubernetesGroups", + "member": "kubernetesGroups", + "requests": "access entry requests", + "row": "Filters access by the kubernetesGroups present in the access entry requests the user makes to the EKS service" + }, + { + "key": "eks:namespaces", + "member": "namespaces", + "requests": "associate / disassociate access policy requests", + "row": "Filters access by the namespaces present in the associate / disassociate access policy requests the user makes to the EKS service" + }, + { + "key": "eks:policyArn", + "member": "policyArn", + "requests": "access entry requests", + "row": "Filters access by the policyArn present in the access entry requests the user makes to the EKS service" + }, + { + "key": "eks:principalArn", + "member": "principalArn", + "requests": "access entry requests", + "row": "Filters access by the principalArn present in the access entry requests requests the user makes to the EKS service" + }, + { + "key": "eks:username", + "member": "username", + "requests": "access entry requests", + "row": "Filters access by the Kubernetes username present in the access entry requests the user makes to the EKS service" + } + ] +} diff --git a/tools/aws/test_fetch_eks_conditions.py b/tools/aws/test_fetch_eks_conditions.py new file mode 100644 index 0000000000..c6f190b286 --- /dev/null +++ b/tools/aws/test_fetch_eks_conditions.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""Tests for fetch_eks_conditions.py, on a page in the Service Authorization Reference's markup.""" +from __future__ import annotations + +import pytest + +import fetch_eks_conditions as f + +SERVICE = " the user makes to the EKS service" + + +def row(key: str, description: str) -> str: + return f'{key}{description}String' + + +ROWS = (row("eks:principalArn", "Filters access by the principalArn present in the access entry requests requests" + + SERVICE) + + row("eks:accessEntryType", "Filters access by the access entry type present in the access entry requests" + + SERVICE) + + row("eks:namespaces", "Filters access by the namespaces present in the associate / disassociate access " + "policy requests" + SERVICE) + + row("eks:authenticationMode", "Filters access by the authenticationMode present in the create / update " + "cluster request")) + + +def page(rows: str = ROWS) -> str: + return f"{rows}
Condition keysDescriptionType
" + + +def test_each_access_entry_key_is_read_from_the_member_its_row_names(): + keys = {entry["key"]: entry for entry in f.build(lambda url: page())["keys"]} + assert keys["eks:principalArn"]["member"] == "principalArn" + # A member named in words is the one those words name. + assert keys["eks:accessEntryType"]["member"] == "type" + assert keys["eks:namespaces"]["requests"] == "associate / disassociate access policy requests" + # A key of another request is not read here. + assert "eks:authenticationMode" not in keys + assert keys["eks:principalArn"]["row"].endswith("requests requests the user makes to the EKS service") + + +def test_a_page_whose_layout_changed_is_refused(): + with pytest.raises(ValueError, match="no table"): + f.build(lambda url: "
") + with pytest.raises(ValueError, match="no member's name"): + f.build(lambda url: page(row("eks:principalArn", "Filters access by the principal ARN of the entry present " + "in the access entry requests" + SERVICE))) + + +def test_the_file_is_stale_when_the_page_says_something_else(): + vendored = f.build(lambda url: page()) + assert not f.stale(vendored, page()) + assert f.stale(vendored, page(ROWS.replace("the principalArn present", "the principal present"))) diff --git a/tools/aws/test_regen_request_condition_keys.py b/tools/aws/test_regen_request_condition_keys.py index db004fa64b..8326fffa7a 100644 --- a/tools/aws/test_regen_request_condition_keys.py +++ b/tools/aws/test_regen_request_condition_keys.py @@ -145,6 +145,9 @@ def test_the_vendored_table_covers_its_namespaces(): "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", @@ -262,3 +265,51 @@ def test_the_vendored_table_reads_eventbridge_rules_and_targets(): 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"]