#!/usr/bin/env python3 """Vendor what the AWS Secrets Manager API reference says each operation's request needs into tools/aws/sources/secretsmanager-required-permissions.json, a source of the IAM tables. The Service Reference lists the actions an operation is authorized by, BatchGetSecretValue by secretsmanager:BatchGetSecretValue, secretsmanager:GetSecretValue and secretsmanager:ListSecrets, without saying when each is needed, and botocore does not say it either. Each operation's page in the API reference does, in a paragraph of its own: Required permissions: secretsmanager:BatchGetSecretValue, and you must have secretsmanager:GetSecretValue for each secret. If you use filters, you must also have secretsmanager:ListSecrets. https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_BatchGetSecretValue.html This script reads the Service Reference for the operations it lists as authorized by an action beside their own, and copies each one's paragraph as it stands, with each clause it gives an action in: what the operation always needs ("Required permissions: A and B"), what it needs for each thing it names ("A for each secret") or on one ("A on the primary secret"), and what it needs when the request does something ("If you use filters, you must also have A", "To add replica Regions, you must also have A"), with the words that say so. A sentence naming no secretsmanager: action, as the KMS ones, is copied with the paragraph but not read, and one naming one in any other wording is refused, so a reworded page fails rather than dropping a check. Nothing in the output is written by hand, and the generators read it against the Service Reference's authorized actions and botocore's requests. Run from anywhere in the repo: python3 tools/aws/fetch_secretsmanager_required_permissions.py # rewrite the vendored file python3 tools/aws/fetch_secretsmanager_required_permissions.py --verify # online: the file still says it """ 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 REFERENCE = "https://servicereference.us-east-1.amazonaws.com/v1/secretsmanager/secretsmanager.json" API_PAGE = "https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_{operation}.html" REPO_ROOT = Path(__file__).resolve().parents[2] OUTPUT = REPO_ROOT / "tools/aws/sources/secretsmanager-required-permissions.json" NAMESPACE = "secretsmanager" ACTION = r"secretsmanager:[A-Za-z]+" # The paragraph giving an operation's required permissions, and each of its sentences. PARAGRAPH_RE = re.compile(r"^Required permissions: ") SENTENCE_RE = re.compile(r"(?<=\.)\s+(?=[A-Z])") # What the operation always needs, and what it needs for each thing or on one thing it names. ALWAYS_RE = re.compile(rf"^Required permissions: (?P{ACTION}.*)\.$") EACH_RE = re.compile(rf"^(?:and )?(?:you must have )?(?P{ACTION}) for each (?P[a-z]+(?: [a-z]+)*)$") ON_RE = re.compile(rf"^(?:and )?(?P{ACTION}) on the (?P[a-z]+(?: [a-z]+)*)$") BARE_RE = re.compile(rf"^(?:and )?(?P{ACTION})$") # What the operation needs when its request does what the words say. WHEN_RES = ( re.compile(rf"^If you use (?P[^,]+), you must also have (?P{ACTION})(?: permissions?)?\.$"), re.compile(rf"^If you include (?P.+?) in the secret, you also need (?P{ACTION})\.$"), re.compile(rf"^To (?P[^,]+), you must also have (?P{ACTION})(?: permissions?)?\.$"), ) # What the operation needs when what it acts on is what the words say. FOR_RE = re.compile(rf"^For (?P[^,]+), you must also have (?P{ACTION})(?: permissions?)?\.$") def text(fragment: str) -> str: """A fragment of a page as text, spaces collapsed, and none left before a mark an inline tag ends ahead of.""" collapsed = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip() return re.sub(r" (?=[.,;:)])", "", re.sub(r"\( ", "(", collapsed)) def body(page: str) -> str: """The page's own content, its navigation left out.""" match = re.search(r'
(?P.*?)(?:
list[str]: """The operations the Service Reference lists as authorized by an action of the namespace beside their own.""" found = [] for operation in reference.get("Operations", []): actions = {f"{action['Service']}:{action['Name']}" for action in operation.get("AuthorizedActions") or []} if any(action.startswith(NAMESPACE + ":") and action != f"{NAMESPACE}:{operation['Name']}" for action in actions): found.append(operation["Name"]) return sorted(found) def clauses(sentence: str) -> list[dict]: """Each action a sentence of the paragraph gives, with what it is needed for.""" always = ALWAYS_RE.match(sentence) if always: found = [] for clause in re.split(r",? and (?=you must have|secretsmanager:)|, ", always.group("clauses")): each, on, bare = EACH_RE.match(clause), ON_RE.match(clause), BARE_RE.match(clause) if each: found.append({"action": each.group("action"), "each": each.group("words")}) elif on: found.append({"action": on.group("action"), "on": on.group("words")}) elif bare: found.append({"action": bare.group("action")}) else: raise ValueError(f"the required permissions '{sentence}' give '{clause}', which names no action as " f"they did: their wording changed") return found for when in WHEN_RES: matched = when.match(sentence) if matched: return [{"action": matched.group("action"), "when": matched.group("words")}] matched = FOR_RE.match(sentence) if matched: return [{"action": matched.group("action"), "for": matched.group("words")}] # A sentence naming an action of the namespace in no wording above would drop that action from the generated # checks on a refresh, so the page has to be read again; one naming none, as the KMS ones, says nothing here. if re.search(ACTION, sentence): raise ValueError(f"the required permissions say '{sentence}', which gives a {NAMESPACE}: action in no wording " f"they used: their wording changed") return [] def read_required(operation: str, page: str) -> dict: """The operation's paragraph of required permissions and each action it gives.""" for paragraph in re.findall(r"

(.*?)

", body(page), re.S): said = text(paragraph) if PARAGRAPH_RE.match(said): permissions = [found for sentence in SENTENCE_RE.split(said) for found in clauses(sentence)] return {"operation": operation, "paragraph": said, "permissions": permissions} raise ValueError(f"{API_PAGE.format(operation=operation)} gives no required permissions: its layout changed") def build(reference: dict, pages: dict[str, str]) -> dict: named = operations(reference) return { "_source": { "pages": [REFERENCE, *(API_PAGE.format(operation=operation) for operation in named)], "fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)), "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), "note": "The required permissions paragraph of each operation's API reference page the Service Reference " "lists as authorized by an action beside its own, copied as it stands, with each action it gives " "and what it is needed for.", }, "required": [read_required(operation, pages[operation]) for operation in named], } 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[dict, dict[str, str]]: """The Service Reference and the page of each operation it lists as authorized by another action.""" reference = json.loads(fetch(REFERENCE)) return reference, {operation: fetch(API_PAGE.format(operation=operation)) for operation in operations(reference)} def stale(vendored: dict, reference: dict, pages: dict[str, str]) -> bool: """Whether the reference and the pages now give something other than the vendored file, its date aside.""" built = build(reference, pages) return any(vendored.get(key) != built[key] for key in built if key != "_source") 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: reference, pages = fetch_all(fetch) except OSError as e: print(f"error: could not read the AWS Secrets Manager documentation ({e})", file=sys.stderr) return 2 if args.verify: vendored = json.loads(OUTPUT.read_text(encoding="utf-8")) if stale(vendored, reference, pages): print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the AWS Secrets Manager API reference " f"does: run tools/aws/fetch_secretsmanager_required_permissions.py and then make " f"iam-authorized-actions-sync and iam-request-resources-sync", file=sys.stderr) return 1 print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the AWS Secrets Manager API reference") return 0 built = build(reference, pages) OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8") print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['required'])} operations)") return 0 if __name__ == "__main__": sys.exit(main())