#!/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())