#!/usr/bin/env python3 """Vendor what the AWS Lambda Developer Guide says adding a layer to a function needs into tools/aws/sources/lambda-layer-permissions.json, a source of the IAM tables. The Service Reference lists lambda:GetLayerVersion among the actions CreateFunction and UpdateFunctionConfiguration are authorized by, without saying what it is checked on, and botocore does not say it either. The guide's page on adding layers does, at the head of its section: Make sure that you have permission to call the GetLayerVersion API on the layer version. For Event Functions in your AWS account, you must have this permission in your user policy. To use a layer in another account, the owner of that account must grant your account permission in a resource-based policy. https://docs.aws.amazon.com/lambda/latest/dg/adding-layers.html This script copies that paragraph as it stands, with the action each sentence of it naming an API gives and the resource it gives it on ("the GetLayerVersion API on the layer version": lambda:GetLayerVersion, on the layer version). A sentence asking for permission to call an API 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 resource types and botocore's requests. Run from anywhere in the repo: python3 tools/aws/fetch_lambda_layer_permissions.py # rewrite the vendored file python3 tools/aws/fetch_lambda_layer_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 PAGE = "https://docs.aws.amazon.com/lambda/latest/dg/adding-layers.html" REPO_ROOT = Path(__file__).resolve().parents[2] OUTPUT = REPO_ROOT / "tools/aws/sources/lambda-layer-permissions.json" NAMESPACE = "lambda" # A sentence asking for permission to call an API, and the wording the page gives it in: the API and the resource. ASKS_RE = re.compile(r"\bpermission to call the\b") API_RE = re.compile(r"^Make sure that you have permission to call the (?P[A-Z][A-Za-z]+) API on the " r"(?P[a-z]+(?: [a-z]+)*)\.$") SENTENCE_RE = re.compile(r"(?<=\.)\s+(?=[A-Z])") 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[dict]: """Each paragraph asking for permission to call an API, as it stands, with the action and the resource each such sentence of it gives.""" found = [] for paragraph in re.findall(r"

(.*?)

", body(page), re.S): said = text(paragraph) if not ASKS_RE.search(said): continue for sentence in SENTENCE_RE.split(said): if not ASKS_RE.search(sentence): continue matched = API_RE.match(sentence) if matched is None: raise ValueError(f"{PAGE} says '{sentence}', which asks for permission to call an API in no wording " f"it used: its wording changed") found.append({"paragraph": said, "sentence": sentence, "action": f"{NAMESPACE}:{matched.group('api')}", "on": matched.group("words")}) if not found: raise ValueError(f"{PAGE} asks for permission to call no API: its layout or wording changed") return found def build(page: str) -> dict: return { "_source": { "pages": [PAGE], "fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)), "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), "note": "Each sentence of the adding-layers page asking for permission to call an API, copied as it " "stands with its paragraph, with the action it names and the resource it names it on.", }, "apiPermissions": read_permissions(page), } 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[str]: """The adding-layers page.""" return (fetch(PAGE),) def stale(vendored: dict, page: str) -> bool: """Whether the page now gives something other than the vendored file, its date aside.""" built = build(page) 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 page") args = parser.parse_args(argv) try: (page,) = fetch_all(fetch) except OSError as e: print(f"error: could not read the AWS Lambda Developer Guide ({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 AWS Lambda Developer Guide does: " f"run tools/aws/fetch_lambda_layer_permissions.py and then make iam-request-resources-sync", file=sys.stderr) return 1 print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the AWS Lambda Developer Guide") return 0 built = build(page) OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8") print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['apiPermissions'])} permissions)") return 0 if __name__ == "__main__": sys.exit(main())