Files
floci/tools/aws/fetch_rds_cluster_group_permissions.py
T
Priamo Germosen 7064800c45 chore(deps): bump botocore to 1.44.18 (#10128)
Bumps botocore from 1.44.17 to 1.44.18 with its regenerated data. 1.44.18 adds
RDS data groups and DB cluster groups, whose operations the IAM tables now
read from the model rather than marking them as missing from the pinned
botocore.

The Service Reference lists two tagging actions for rds:CreateDataGroup,
rds:AddTagsToDataGroup and rds:AddTagsToResource, without saying whether the
tags a create carries need one or both, so the tag-on-create generator stopped
on it. The Aurora User Guide's prerequisites for data groups answer it: "To add
tags when you create a data group, grant rds:AddTagsToResource and
rds:AddTagsToDataGroup on *". fetch_rds_tag_actions.py vendors that page into
tools/aws/sources/rds-tag-actions.json, and the generator, granted it for RDS
alone (TAG_ACTION_SOURCES), lists both actions for the operation when they are
the ones the reference lists. --verify reads the page again.

That sentence grants both actions "on *", where the guide grants adding
tags to a data group that exists "on data-group:*", so the fetcher copies
that resource too and the table marks the operation anyResource: Floci
checks the create's tagging actions on *, not on the DB cluster the create
itself is checked on.

The tag-on-create table and TagOnCreate now carry each operation's tagging
actions as a list, and the enforcement filter, RequestChecks and STS's trust
policy check every action an operation's tags need. An operation with one
tagging action is checked as before. verify_role_sources' body becomes
verify_vendored_sources, which both generators use to verify their vendored
sources.

The guide's IAM page for database cluster groups authorizes
rds:CreateDBClusterGroup against "* (the group doesn't exist yet)", where the
Service Reference lists cluster-group for it and a group's ARN holds a
resource ID the request does not carry. fetch_rds_cluster_group_permissions.py
vendors that page's table as RDS's permission source, and the request
resources generator checks an action its row authorizes against * alone
there.

fetch_dms_arn_formats.py refreshes its botocore examples at the new pin, and
the authorized-actions table takes the Service Reference's new mapping of
budgets:DescribeBudgetSpendForPrincipal to budgets:ViewBudget.
2026-12-04 08:28:12 -04:00

147 lines
6.8 KiB
Python

#!/usr/bin/env python3
"""Vendor what the Aurora User Guide says each database cluster group action is authorized against into
tools/aws/sources/rds-cluster-group-permissions.json, a source of the IAM tables.
The Service Reference lists cluster-group as the resource rds:CreateDBClusterGroup acts on, and botocore's request
names the group it creates by its DBClusterGroupIdentifier, while a group's ARN holds a resource ID its service mints.
The guide's IAM page for database cluster groups says what each group action is authorized against, in a table:
Action Authorized against
rds:CreateDBClusterGroup * (the group doesn't exist yet). Restrict creates with condition keys such as
aws:RequestTag, rds:DeletionProtection, and rds:BackupRetentionPeriod.
https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/databaseclustergroups-iam.html, its section
databaseclustergroups-iam-actions
This script copies each row of that table as it stands, the actions its first cell names and the text of its second,
and marks a row whose second cell names `*` alone ahead of anything else it says (`on`), as the create's does. A table
laid out otherwise, or a row naming no RDS action, is refused, so a reworded page fails rather than dropping a check.
Nothing in the output is written by hand, and the generator reads it against the Service Reference's actions.
Run from anywhere in the repo:
python3 tools/aws/fetch_rds_cluster_group_permissions.py # rewrite the vendored file
python3 tools/aws/fetch_rds_cluster_group_permissions.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/AmazonRDS/latest/AuroraUserGuide/databaseclustergroups-iam.html"
# The section of the page holding the table of what each group action is authorized against.
SECTION = "databaseclustergroups-iam-actions"
REPO_ROOT = Path(__file__).resolve().parents[2]
OUTPUT = REPO_ROOT / "tools/aws/sources/rds-cluster-group-permissions.json"
# The table's header, as the page gives it.
HEADER = ["Action", "Authorized against"]
ACTION_RE = re.compile(r"rds:[A-Za-z]+")
# A second cell naming `*` alone ahead of whatever else it says: "* (the group doesn't exist yet)".
ANY_RE = re.compile(r"^\*(?=\s|\.|$)")
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 section(page: str) -> str:
"""The section's markup, up to the next heading."""
found = re.search(r'<h(?P<level>[1-6])[^>]*\bid="' + re.escape(SECTION) + r'"[^>]*>(?P<body>.*?)(?=<h[1-6]\b|$)',
page, re.S)
if found is None:
raise ValueError(f"{PAGE} has no section {SECTION}: its layout changed")
return found.group("body")
def read_rows(page: str) -> list[dict]:
"""Each row of the section's table: the actions its first cell names, the text of its second, and `on` where
that text names `*` alone first."""
table = re.search(r"<table\b.*?</table>", section(page), re.S)
if table is None:
raise ValueError(f"{PAGE} has no table in its section {SECTION}: its layout changed")
header = [text(cell) for cell in re.findall(r"<th\b[^>]*>(.*?)</th>", table.group(0), re.S)]
if header != HEADER:
raise ValueError(f"{PAGE} heads its table {header}, not {HEADER}: its layout changed")
rows = []
for row in re.findall(r"<tr\b[^>]*>(.*?)</tr>", table.group(0), re.S):
cells = [text(cell) for cell in re.findall(r"<td\b[^>]*>(.*?)</td>", row, re.S)]
if not cells:
continue
actions = ACTION_RE.findall(cells[0])
if len(cells) != 2 or not actions or ACTION_RE.sub("", cells[0]).strip(" ,") != "":
raise ValueError(f"{PAGE} has a row {cells}, which is not RDS actions and what they are authorized "
f"against: its layout changed")
entry = {"actions": actions, "authorizedAgainst": cells[1]}
if ANY_RE.match(cells[1]):
entry["on"] = "*"
rows.append(entry)
if not rows:
raise ValueError(f"{PAGE} has no rows in its table: its layout changed")
return rows
def build(page: str) -> dict:
return {
"_source": {
"pages": [f"{PAGE}#{SECTION}"],
"fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)),
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
"note": "Each row of the Aurora User Guide's table of what each database cluster group action is "
"authorized against, copied as it stands, a row authorized against * alone marked so.",
},
"authorizedAgainst": read_rows(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 Aurora User Guide's IAM page for database cluster groups."""
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 Aurora User 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 Aurora User Guide does: run "
f"tools/aws/fetch_rds_cluster_group_permissions.py and then make iam-request-resources-sync",
file=sys.stderr)
return 1
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the Aurora User 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['authorizedAgainst'])} rows)")
return 0
if __name__ == "__main__":
sys.exit(main())