Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

17.0 KB
Raw Blame
#!/usr/bin/env python3
"""Regenerate the AWS managed-policy catalog under src/main/resources/iam/ from iam-dataset.

Three files back `AwsManagedPolicies`, all keyed by policy name and sorted by it:

- `managed-policies.yaml`: the catalog, each policy's name and path (and, for a few, a
  description).
- `managed-policy-documents.json`: the document of each policy's current default version.
- `managed-policy-versions.json`: that version's id, the policy's creation date and the date
  of its current default version.

The source is https://github.com/iann0036/iam-dataset (MIT), read from the `local/aws/iam-dataset`
checkout: `aws/managed_policies.json` lists every policy with its ARN, default version and
update date, and `aws/managedpolicies/<name>.json` holds its document. A policy the dataset marks
deprecated has no ARN there and leaves the catalog, except the names in `RETAINED`.

Two fields are not in the dataset and are carried over from the vendored files instead of being
regenerated:

- `createDate`, the "Creation time" published on each policy's page of the AWS managed policy
  reference (https://docs.aws.amazon.com/aws-managed-policy/latest/reference/). A policy new to
  the catalog takes the dataset's date when it is on `v1`, which is then its creation date too;
  on a later version it has no recorded creation date until one is sourced from its reference
  page (`--fetch-create-dates` reads the page of every policy past `v1` that still has none).
- `description`, kept for the policies Floci seeded before the catalog was generated.

Nothing is hand-typed. When the checkout is absent (CI), `--check` only verifies the vendored
files parse, agree with each other and keep their shape; a regeneration needs `local/aws`.

Run from anywhere in the repo:
    python3 tools/aws/regen_managed_policies.py            # rewrite the vendored files in place
    python3 tools/aws/regen_managed_policies.py --check    # exit 1 when the vendored files are stale
"""
from __future__ import annotations

import argparse
import json
import re
import sys
import urllib.error
import urllib.request
from datetime import datetime, timezone
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[2]
RESOURCES = REPO_ROOT / "src/main/resources/iam"
CATALOG = "managed-policies.yaml"
DOCUMENTS = "managed-policy-documents.json"
VERSIONS = "managed-policy-versions.json"
LOCAL_DATASET = REPO_ROOT / "local/aws/iam-dataset"
DATASET_LIST = "aws/managed_policies.json"
DATASET_DOCUMENTS = "aws/managedpolicies"
REFERENCE_PAGE = "https://docs.aws.amazon.com/aws-managed-policy/latest/reference/{name}.html"

# Deprecated policies that stay resolvable. AWS keeps a deprecated policy attachable to the
# entities that already had it, and Floci resolved AWSLambdaFullAccess before the catalog was
# generated (#2194), so dropping it would break configurations that work today.
RETAINED = ("AWSLambdaFullAccess",)

HEADER = """\
# AWS managed policy catalog.
#
# Floci resolves arn:aws:iam::aws:policy/* ARNs against this list, so an ARN absent here
# returns NoSuchEntity exactly as it does on real AWS. Seeding the real catalog is what
# keeps that check faithful in both directions: policies AWS publishes attach cleanly, and
# typos are still rejected.
#
# Policy documents are stored in iam/managed-policy-documents.json, keyed by policy name.
# The documents are generated from the public AWS managed policy dataset cited below.
#
# Each document is the policy's current default version. The version id AWS reports for it
# (e.g. v3 for AmazonS3ReadOnlyAccess) is stored in iam/managed-policy-versions.json, also
# keyed by policy name, together with the policy's creation date (createDate) and the date
# of its current default version (updateDate), the two dates GetPolicy reports. The version
# id and updateDate come from the same dataset (the "version" and "updatedate" fields of
# aws/managed_policies.json); createDate comes from the "Creation time" published on each
# policy's page of the AWS managed policy reference,
# https://docs.aws.amazon.com/aws-managed-policy/latest/reference/, which is minute-precise.
# A policy that entered the catalog on v1 takes the dataset's date instead, which is then its
# creation date too. A policy past v1 whose page cannot be read has no createDate. Only the
# default version's document is bundled, so superseded version ids resolve to NoSuchEntity.
#
# Names and paths derive from the public AWS managed policy list, via
# https://github.com/iann0036/iam-dataset (MIT). To refresh against a real account:
#   aws iam list-policies --scope AWS
#
# Generated by tools/aws/regen_managed_policies.py (make aws-data-sync); do not edit by hand.
"""

NAME_RE = re.compile(r"[\w+=,.@-]{1,128}")
PATH_RE = re.compile(r"/(?:[\x21-\x7e]+/)?")
VERSION_RE = re.compile(r"v[1-9][0-9]*")
INSTANT_RE = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z")
CATALOG_ENTRY_RE = re.compile(r'^  - name: (".*")\n    path: (".*")\n(?:    description: (".*")\n)?', re.MULTILINE)
CREATION_TIME_RE = re.compile(r"Creation time\s*:\s*([A-Z][a-z]+ \d{1,2}, \d{4}, \d{2}:\d{2}) UTC")


# --------------------------------------------------------------------------- #
# Reading
# --------------------------------------------------------------------------- #
def parse_catalog(text: str) -> list[dict]:
    """The `policies:` entries of managed-policies.yaml, in file order. The file is generated, so
    its layout is fixed: every value is a JSON-compatible double-quoted YAML scalar."""
    entries = []
    for match in CATALOG_ENTRY_RE.finditer(text):
        entry = {"name": json.loads(match.group(1)), "path": json.loads(match.group(2))}
        if match.group(3) is not None:
            entry["description"] = json.loads(match.group(3))
        entries.append(entry)
    return entries


def read_vendored(resources: Path) -> tuple[list[dict], dict, dict]:
    catalog_path = resources / CATALOG
    catalog = parse_catalog(catalog_path.read_text(encoding="utf-8")) if catalog_path.exists() else []
    documents_path = resources / DOCUMENTS
    documents = json.loads(documents_path.read_text(encoding="utf-8")) if documents_path.exists() else {}
    versions_path = resources / VERSIONS
    versions = json.loads(versions_path.read_text(encoding="utf-8")) if versions_path.exists() else {}
    return catalog, documents, versions


def instant(value: str | None) -> str | None:
    """`2026-02-12T17:57:39+00:00` or `...Z` -> `2026-02-12T17:57:39Z`."""
    if not value:
        return None
    parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
    return parsed.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def name_and_path(arn: str) -> tuple[str, str]:
    """`arn:aws:iam::aws:policy/service-role/X` -> (`X`, `/service-role/`)."""
    resource = arn.split(":policy", 1)[1]
    name = resource.rsplit("/", 1)[1]
    return name, resource[: len(resource) - len(name)]


def parse_creation_time(html: str) -> str | None:
    match = CREATION_TIME_RE.search(re.sub(r"<[^>]+>", " ", html))
    if match is None:
        return None
    parsed = datetime.strptime(match.group(1), "%B %d, %Y, %H:%M").replace(tzinfo=timezone.utc)
    return parsed.strftime("%Y-%m-%dT%H:%M:%SZ")


def fetch_creation_time(name: str) -> str | None:
    """The creation time on the policy's reference page, or None when the page cannot be read:
    a policy AWS no longer documents has none, and it must not stop the other policies."""
    request = urllib.request.Request(REFERENCE_PAGE.format(name=name), headers={"User-Agent": "floci-regen"})
    try:
        with urllib.request.urlopen(request, timeout=30) as response:
            return parse_creation_time(response.read().decode("utf-8", "replace"))
    except (urllib.error.URLError, TimeoutError) as e:
        print(f"warning: no creation date for {name}: its reference page could not be read ({e})", file=sys.stderr)
        return None


# --------------------------------------------------------------------------- #
# Generation
# --------------------------------------------------------------------------- #
def build(dataset: Path, vendored_catalog: list[dict], vendored_versions: dict,
          fetch_create_date=None) -> tuple[list[dict], dict, dict]:
    listing = json.loads((dataset / DATASET_LIST).read_text(encoding="utf-8"))["policies"]
    by_name = {policy["name"]: policy for policy in listing}
    previous = {entry["name"]: entry for entry in vendored_catalog}

    selected: dict[str, tuple[str, dict]] = {}
    for policy in listing:
        if policy.get("arn"):
            name, path = name_and_path(policy["arn"])
            if name != policy["name"]:
                raise ValueError(f"{DATASET_LIST}: {policy['name']} has the ARN of {name}")
            selected[name] = (path, policy)
    for name in RETAINED:
        if name not in selected:
            if name not in by_name:
                raise ValueError(f"{DATASET_LIST}: retained policy {name} is not in the dataset")
            if name not in previous:
                raise ValueError(f"retained policy {name} has no vendored path to keep")
            selected[name] = (previous[name]["path"], by_name[name])

    catalog, documents, versions = [], {}, {}
    for name in sorted(selected):
        path, policy = selected[name]
        entry = {"name": name, "path": path}
        if previous.get(name, {}).get("description"):
            entry["description"] = previous[name]["description"]
        catalog.append(entry)

        document_file = dataset / DATASET_DOCUMENTS / f"{name}.json"
        if not document_file.exists():
            raise ValueError(f"{DATASET_DOCUMENTS}: no document for {name}")
        documents[name] = json.loads(document_file.read_text(encoding="utf-8"))["document"]

        version_id = policy.get("version")
        update_date = instant(policy.get("updatedate")) or instant(policy.get("createdate"))
        version = {"defaultVersionId": version_id}
        create_date = vendored_versions.get(name, {}).get("createDate")
        if create_date is None:
            if version_id == "v1":
                if name not in vendored_versions:
                    create_date = instant(policy.get("createdate"))
            elif fetch_create_date is not None:
                create_date = fetch_create_date(name)
        if create_date is not None:
            version["createDate"] = create_date
        version["updateDate"] = update_date
        versions[name] = version
    return catalog, documents, versions


def render_catalog(catalog: list[dict]) -> str:
    lines = [HEADER, "policies:\n"]
    for entry in catalog:
        lines.append(f"  - name: {json.dumps(entry['name'])}\n    path: {json.dumps(entry['path'])}\n")
        if "description" in entry:
            lines.append(f"    description: {json.dumps(entry['description'])}\n")
    return "".join(lines)


def render_documents(documents: dict) -> str:
    return json.dumps(documents, separators=(",", ":"), sort_keys=True) + "\n"


def render_versions(versions: dict) -> str:
    return json.dumps(versions, indent=2) + "\n"


def render(catalog: list[dict], documents: dict, versions: dict) -> dict[str, str]:
    return {CATALOG: render_catalog(catalog), DOCUMENTS: render_documents(documents), VERSIONS: render_versions(versions)}


# --------------------------------------------------------------------------- #
# Offline shape check
# --------------------------------------------------------------------------- #
def self_check(resources: Path) -> list[str]:
    """Problems with the vendored files that need no dataset: the three agree on one sorted set
    of names, and every value has the shape of what it claims to be. It cannot tell a stale
    value from a current one; only a regeneration against local/aws can."""
    problems: list[str] = []
    for file_name in (CATALOG, DOCUMENTS, VERSIONS):
        if not (resources / file_name).exists():
            problems.append(f"{resources / file_name} is missing")
    if problems:
        return problems
    try:
        catalog, documents, versions = read_vendored(resources)
    except json.JSONDecodeError as e:
        return [f"{resources}: a vendored file is not valid JSON ({e})"]

    names = [entry["name"] for entry in catalog]
    catalog_text = (resources / CATALOG).read_text(encoding="utf-8")
    policy_lines = sum(1 for line in catalog_text.splitlines() if line.startswith("  - name: "))
    if policy_lines != len(catalog):
        problems.append(f"{CATALOG}: {policy_lines - len(catalog)} entries do not have the generated layout")
    elif render_catalog(catalog) != catalog_text:
        problems.append(f"{CATALOG}: has content other than the generated header and policy entries")
    if not catalog:
        problems.append(f"{CATALOG}: no policies")
    if names != sorted(names):
        problems.append(f"{CATALOG}: policies are not sorted by name")
    if len(set(names)) != len(names):
        problems.append(f"{CATALOG}: duplicate policy names")
    if list(documents) != sorted(documents) or list(versions) != sorted(versions):
        problems.append(f"{DOCUMENTS} and {VERSIONS} must be sorted by name")
    for other, label in ((documents, DOCUMENTS), (versions, VERSIONS)):
        missing, extra = set(names) - set(other), set(other) - set(names)
        if missing:
            problems.append(f"{label}: no entry for {sorted(missing)[:5]}")
        if extra:
            problems.append(f"{label}: entries not in {CATALOG}: {sorted(extra)[:5]}")

    for entry in catalog:
        if not NAME_RE.fullmatch(entry["name"]):
            problems.append(f"{CATALOG}: {entry['name']!r} is not a policy name")
        if not PATH_RE.fullmatch(entry["path"]):
            problems.append(f"{CATALOG}: {entry['name']} has a malformed path {entry['path']!r}")
    for name, document in documents.items():
        if not isinstance(document, dict) or not isinstance(document.get("Statement"), (list, dict)):
            problems.append(f"{DOCUMENTS}: {name} is not a policy document")
    for name, version in versions.items():
        if not isinstance(version, dict) or set(version) - {"defaultVersionId", "createDate", "updateDate"}:
            problems.append(f"{VERSIONS}: {name} has unexpected fields")
            continue
        if not VERSION_RE.fullmatch(str(version.get("defaultVersionId"))):
            problems.append(f"{VERSIONS}: {name} has a malformed defaultVersionId")
        for field in ("createDate", "updateDate"):
            if field in version and not INSTANT_RE.fullmatch(str(version[field])):
                problems.append(f"{VERSIONS}: {name}.{field} is not an ISO-8601 instant")
        if "updateDate" not in version:
            problems.append(f"{VERSIONS}: {name} has no updateDate")
    return problems


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--check", action="store_true", help="exit 1 when the vendored files differ from a fresh generation")
    parser.add_argument("--dataset", type=Path, default=LOCAL_DATASET, help="iam-dataset checkout")
    parser.add_argument("--fetch-create-dates", action="store_true",
                        help="read the AWS managed policy reference page of each policy past v1 that has no creation time")
    parser.add_argument("--resources", type=Path, default=RESOURCES, help=argparse.SUPPRESS)
    args = parser.parse_args(argv)
    rel = args.resources.relative_to(REPO_ROOT) if args.resources.is_relative_to(REPO_ROOT) else args.resources

    problems = self_check(args.resources) if args.check else []
    for problem in problems:
        print(f"error: {problem}")
    if problems:
        return 1

    if not (args.dataset / DATASET_LIST).exists():
        if args.check:
            print(f"{rel}: iam-dataset not checked out, managed-policy catalog shape verified only")
            return 0
        raise SystemExit("error: regenerating needs the iam-dataset checkout under local/aws")

    vendored_catalog, _, vendored_versions = read_vendored(args.resources)
    catalog, documents, versions = build(args.dataset, vendored_catalog, vendored_versions,
                                         fetch_creation_time if args.fetch_create_dates else None)
    rendered = render(catalog, documents, versions)
    if args.check:
        stale = [name for name, text in rendered.items()
                 if not (args.resources / name).exists() or (args.resources / name).read_text(encoding="utf-8") != text]
        if stale:
            print(f"error: {', '.join(stale)} under {rel} differ from a fresh generation. "
                  "Run 'make aws-data-sync' and commit the result.")
            return 1
        print(f"{rel}: managed-policy catalog is up to date ({len(catalog)} policies)")
        return 0
    args.resources.mkdir(parents=True, exist_ok=True)
    for name, text in rendered.items():
        (args.resources / name).write_text(text, encoding="utf-8")
    undated = [name for name, version in versions.items() if "createDate" not in version]
    print(f"wrote {rel}/{{{CATALOG},{DOCUMENTS},{VERSIONS}}}: {len(catalog)} policies"
          + (f"; no creation date for {', '.join(undated)}" if undated else ""))
    return 0


if __name__ == "__main__":
    sys.exit(main())