Files
floci/tools/aws/fetch_backup_arn_formats.py
T
Priamo Germosen 16bdd60072 fix(iam): check an AWS Backup recovery point on the ARN its request names (#9884)
The Service Reference gives AWS Backup's recovery point the format
arn:${Partition}:${Vendor}:${Region}:*:${ResourceType}:${RecoveryPointId}, a wildcard where the account goes, which
no ARN a request names matches as written, so every request naming a recovery point by its ARN
(DescribeRecoveryPoint, DeleteRecoveryPoint, StartRestoreJob and the rest) was checked on *.

The AWS Backup Developer Guide's table of resource ARNs gives each kind of recovery point's ARN with the account, or
nothing, in that place. tools/aws/fetch_backup_arn_formats.py vendors the table's recovery point rows as they stand
into tools/aws/sources/backup-arn-formats.json, refusing a row with anything else there, and writes the Service
Reference's format with the account variable in place of the wildcard. ARN_FORMAT_SOURCES grants it for backup, and
with_vendored_formats now takes a vendored format that has a variable for each of the reference's wildcards and
nothing else changed. The table's recovery point format becomes
arn:${Partition}:${Vendor}:${Region}:${Account}:${ResourceType}:${RecoveryPointId}.

Some rows give a recovery point no colon between its type and id, which that format does not fit (an EBS snapshot's
arn:aws:ec2:region::snapshot/*, a DynamoDB backup's table/*/backup/*). The fetcher also writes each row as a format
of its own, the last wildcard as ${RecoveryPointId} and one before it as ${Resource}, and the table gives the
recovery point those its format does not fit already (alternateFormats): EBS snapshots, EC2 images, FSx backups and
DynamoDB backups. RequestResourceMembers matches a type's ARN against its format or any of them.

The generic recovery point format also fits an IAM role whose path holds a colon, and the rule for an ARN member had
typed the roles StartRestoreJob, StartCopyJob and StartScanJob pass as recovery points. The generator now reads the
generated passed-roles table, as it reads the authorized-actions one, and reads no resource of an action from a
member it gives as a role the operation passes, whose ARN iam:PassRole is checked on: 98 rows in 83 operations go,
of which only those five could fit a role's ARN.

test_fetch_backup_arn_formats.py checks the fetcher's copy, its formats and refusals;
test_regen_iam_request_resources.py the account wildcard's replacement, the alternates kept and the passed-role rows
dropped; RequestResourceMembersTest the alternates' read and refusals; ResourceArnBuilderTest that DescribeRecoveryPoint
is checked on the ARN in its path, a Backup one sent encoded or not and an EBS one as an SDK encodes it, and
StartRestoreJob on its recovery point and not on the role it passes; IamRequestResourceEnforcementIntegrationTest that a
grant on one recovery point's ARN lets the caller describe that one and not another.
2026-12-01 07:44:42 -04:00

197 lines
10 KiB
Python

#!/usr/bin/env python3
"""Vendor what the AWS Backup Developer Guide says a recovery point's ARN is into
tools/aws/sources/backup-arn-formats.json, a source of the IAM tables.
The Service Reference gives AWS Backup's recovery point the ARN format
`arn:${Partition}:${Vendor}:${Region}:*:${ResourceType}:${RecoveryPointId}`, a wildcard where the account goes,
which no ARN a request names matches as written, so no request naming a recovery point by its ARN is checked on it.
The Developer Guide's table of AWS Backup resource ARNs gives each kind of recovery point's ARN, the account in that
place or nothing:
Recovery point for Amazon EBS arn:aws:ec2:region::snapshot/*
Recovery point for Amazon RDS arn:aws:rds:region:account-id:snapshot:awsbackup:*
Recovery point for Amazon EFS arn:aws:backup:region:account-id:recovery-point:*
https://docs.aws.amazon.com/aws-backup/latest/devguide/access-control.html
This script copies the table's recovery point rows as they stand and, where every one of them has the account or
nothing in the place of the Service Reference's account wildcard, writes the Service Reference's format with the
account variable there (`arn:${Partition}:${Vendor}:${Region}:${Account}:${ResourceType}:${RecoveryPointId}`). A
row with anything else there is refused, as is a page with no such table or a reference whose recovery point format
has no wildcard there, so a reworded page, or a reference that no longer agrees with it, fails rather than giving a
format.
Some rows name a recovery point no colon parts from its id, which that format does not fit (an EBS snapshot's
`snapshot/*`, a DynamoDB backup's `table/*/backup/*`). Each row is also written as a format of its own
(`alternateFormats`): the partition, Region and account placeholders as the Service Reference's variables, and in
the resource part the last wildcard or placeholder as the recovery point's id, `${RecoveryPointId}` as the Service
Reference names it, one before it as `${Resource}`, as the guide's Redshift rows name the part before the id
(`<resource>`). A row with more is refused. Nothing in the output is written by hand, and the generator takes the
formats as they stand, for AWS Backup alone.
Run from anywhere in the repo:
python3 tools/aws/fetch_backup_arn_formats.py # rewrite the vendored file
python3 tools/aws/fetch_backup_arn_formats.py --verify # online: the file still says what the pages do
"""
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/aws-backup/latest/devguide/access-control.html"
REFERENCE = "https://servicereference.us-east-1.amazonaws.com/v1/backup/backup.json"
REPO_ROOT = Path(__file__).resolve().parents[2]
OUTPUT = REPO_ROOT / "tools/aws/sources/backup-arn-formats.json"
# The table of resource ARNs, by its id, and a row of it naming a kind of recovery point.
TABLE_RE = re.compile(r'<div class="table-container" id="resource-arns-table">.*?<table.*?</table>', re.S)
RECOVERY_POINT = "Recovery point"
# A recovery point's ARN as the page writes it, its account place holding the account or nothing.
ROW_RE = re.compile(r"^arn:(?:aws|<aws-partition>):[a-z][a-z0-9-]*:<region>:(?P<account><account-id>|):.+$")
# The Service Reference's recovery point format, its account place a wildcard.
WILDCARD_RE = re.compile(r"^(?P<head>arn:\$\{Partition}:\$\{\w+}:\$\{Region}:)\*(?P<tail>:.+)$")
ACCOUNT = "${Account}"
# The page's partition, Region and account as the Service Reference's variables.
ROW_VARIABLES = {"aws": "${Partition}", "<aws-partition>": "${Partition}", "<region>": "${Region}",
"<account-id>": "${Account}", "": ""}
# A wildcard or a placeholder in a row's resource part.
ROW_WILDCARD_RE = re.compile(r"\*|<[a-z-]+>")
ROW_IDS = ("${Resource}", "${RecoveryPointId}")
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 template(fragment: str) -> str:
"""A code fragment of the page with each placeholder it marks replaceable in angle brackets and no space left
around the colons the markup breaks lines at: `arn:aws:ec2:<region>::snapshot/*`."""
marked = re.sub(r'<code class="replaceable">(.*?)</code>', lambda m: "\0" + text(m.group(1)) + "\1", fragment,
flags=re.S)
return re.sub(r"\s*:\s*", ":", text(marked)).replace("\0", "<").replace("\1", ">")
def read_page(page: str) -> list[dict]:
"""The table's recovery point rows, each as the page writes its ARN; a row with anything but the account or
nothing in the account's place is refused."""
table = TABLE_RE.search(page)
if table is None:
raise ValueError(f"{PAGE} has no table of AWS Backup resource ARNs: its layout changed")
rows = []
for row in re.findall(r"<tr>(.*?)</tr>", table.group(0), re.S):
cells = re.findall(r"<td[^>]*>(.*?)</td>", row, re.S)
if len(cells) < 2 or not text(cells[0]).startswith(RECOVERY_POINT):
continue
written = template(cells[1])
if ROW_RE.match(written) is None:
raise ValueError(f"{PAGE} gives {text(cells[0])} the ARN '{written}', with neither the account nor "
f"nothing in the account's place: its wording changed")
rows.append({"resourceType": text(cells[0]), "format": written})
if not rows:
raise ValueError(f"{PAGE} lists no recovery point: its layout changed")
return rows
def row_format(written: str) -> str:
"""A recovery point row's ARN as a format: its partition, Region and account as the Service Reference's variables,
and in its resource part the last wildcard or placeholder as the recovery point's id, one before it as the resource
the guide's Redshift rows name (`arn:aws:dynamodb:<region>:<account-id>:table/*/backup/*` is
`arn:${Partition}:dynamodb:${Region}:${Account}:table/${Resource}/backup/${RecoveryPointId}`)."""
_, partition, service, region, account, resource = written.split(":", 5)
wildcards = ROW_WILDCARD_RE.findall(resource)
if not wildcards or len(wildcards) > len(ROW_IDS):
raise ValueError(f"{PAGE} gives a recovery point the ARN '{written}', with {len(wildcards)} wildcards past its "
f"account where its rows have one or two: its wording changed")
names = iter(ROW_IDS[len(ROW_IDS) - len(wildcards):])
return ":".join(["arn", ROW_VARIABLES[partition], service, ROW_VARIABLES[region], ROW_VARIABLES[account],
ROW_WILDCARD_RE.sub(lambda wildcard: next(names), resource)])
def alternate_formats(rows: list[dict]) -> dict[str, list[str]]:
"""Each recovery point row's ARN as a format, once each, for the recovery point type."""
return {"recoveryPoint": sorted({row_format(row["format"]) for row in rows})}
def arn_formats(reference: dict) -> dict[str, str]:
"""Each Service Reference AWS Backup format with a wildcard in the account's place, with the account there."""
formats = {}
for resource in reference.get("Resources", []):
written = (resource.get("ARNFormats") or [""])[0]
wildcard = WILDCARD_RE.match(written)
if wildcard is not None:
formats[resource["Name"]] = wildcard.group("head") + ACCOUNT + wildcard.group("tail")
if not formats:
raise ValueError(f"{REFERENCE} gives no AWS Backup format with a wildcard in the account's place")
return dict(sorted(formats.items()))
def build(page: str, reference: str) -> dict:
rows = read_page(page)
return {
"_source": {
"pages": [PAGE, REFERENCE],
"fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)),
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
"note": "The Developer Guide's recovery point ARNs, copied as they stand, each with the account or "
"nothing in the account's place; each Service Reference AWS Backup format with a wildcard "
"there, with the account variable in its place; and each recovery point ARN as a format.",
},
"recoveryPoints": rows,
"arnFormats": arn_formats(json.loads(reference)),
"alternateFormats": alternate_formats(rows),
}
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, str]:
"""The Developer Guide's page on access control and the Service Reference's AWS Backup document."""
return fetch(PAGE), fetch(REFERENCE)
def stale(vendored: dict, page: str, reference: str) -> bool:
"""Whether the pages now give something other than the vendored file, its date aside."""
built = build(page, reference)
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:
page, reference = fetch_all(fetch)
except OSError as e:
print(f"error: could not read the AWS Backup Developer Guide or the Service Reference ({e})",
file=sys.stderr)
return 2
if args.verify:
vendored = json.loads(OUTPUT.read_text(encoding="utf-8"))
if stale(vendored, page, reference):
print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the AWS Backup Developer Guide and the "
f"Service Reference do: run tools/aws/fetch_backup_arn_formats.py and then make "
f"iam-request-resources-sync", file=sys.stderr)
return 1
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the AWS Backup Developer Guide and the Service Reference")
return 0
built = build(page, reference)
OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8")
print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['recoveryPoints'])} recovery points, "
f"{len(built['arnFormats'])} formats)")
return 0
if __name__ == "__main__":
sys.exit(main())