mirror of
https://github.com/floci-io/floci.git
synced 2026-11-29 08:31:53 -05:00
Under enforcement a VPC association call scoped by route53:VPCs was refused for every VPC, as #8367 reports: the request condition key table never filled the key, so a condition on it never saw a value. Neither botocore nor the Service Reference says where a request carries the key or in what form. Route 53's developer guide says both, in its table of condition keys: route53:VPCs "Represents a list of VPCs in the request of AssociateVPCWithHostedZone, DisassociateVPCFromHostedZone, ListHostedZonesByVPC, CreateHostedZone, CreateVPCAssociationAuthorization, and DeleteVPCAssociationAuthorization, in the format of "VPCId=<vpc-id>,VPCRegion=<region>". A vendored source, tools/aws/sources/route53-condition-keys.json, written by tools/aws/fetch_route53_conditions.py from that page, gives each key the table gives in a format of request members, with its operations and members, and the generator reads it for route53 (CONDITION_SOURCES) beside the record keys it already reads. The table writes a key a format composes as that format with each member's place holding where the request carries it (VPCId={VPC.VPCId},VPCRegion={VPC.VPCRegion}), and a member of the query string as ? and its name (ListHostedZonesByVPC's ?vpcid and ?vpcregion), and the request condition reader fills the format from them, read from an XML body or the query string, when each member holds one value. A request naming no VPC, as a public CreateHostedZone does, carries none. Route 53 reads the VPC only where its schema puts it, the VPC below the request's root, where IAM reads it, and refuses a second VPC, a second VPCId or VPCRegion, or a repeated vpcid or vpcregion query parameter with InvalidInput, as it already refuses a change batch naming an element twice. It used to take the first VPC anywhere in the body, so a request naming a denied VPC beside another carried no value for the Deny to match and still acted on the denied one. Closes #8367.
134 lines
6.5 KiB
Python
134 lines
6.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Vendor which request members a Route 53 condition key composes into tools/aws/sources/route53-condition-keys.json,
|
|
a source of the request condition key table.
|
|
|
|
AWS's Service Reference gives AssociateVPCWithHostedZone, DisassociateVPCFromHostedZone, ListHostedZonesByVPC,
|
|
CreateHostedZone, CreateVPCAssociationAuthorization and DeleteVPCAssociationAuthorization the key `route53:VPCs`
|
|
without saying where a request carries it, or in what form, and botocore does not say it either. Route 53's developer
|
|
guide does, in its table of the condition keys Route 53 defines:
|
|
|
|
route53:VPCs AssociateVPCWithHostedZone DisassociateVPCFromHostedZone ListHostedZonesByVPC CreateHostedZone
|
|
CreateVPCAssociationAuthorization DeleteVPCAssociationAuthorization Multi-valued
|
|
Represents a list of VPCs in the request of AssociateVPCWithHostedZone, ..., in the format of
|
|
"VPCId=<vpc-id>,VPCRegion=<region>
|
|
|
|
https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/specifying-conditions-route53.html
|
|
|
|
This script copies the row of each key the table gives in a format of request members, `<Member>=<value>` pairs, as
|
|
it stands, with the operations it names and the members of its format, in order. A row giving no such format is not
|
|
read here. Nothing in the output is written by hand; regen_request_condition_keys.py reads it to give the table each
|
|
key as its format composes those members of each operation's request.
|
|
|
|
Run from anywhere in the repo:
|
|
python3 tools/aws/fetch_route53_conditions.py # rewrite the vendored file from the page
|
|
python3 tools/aws/fetch_route53_conditions.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/Route53/latest/DeveloperGuide/specifying-conditions-route53.html"
|
|
REPO_ROOT = Path(__file__).resolve().parents[2]
|
|
OUTPUT = REPO_ROOT / "tools/aws/sources/route53-condition-keys.json"
|
|
|
|
# The header of the page's table of condition keys.
|
|
HEADER = ["Route 53 Condition Key", "API operations", "Value type", "Description"]
|
|
# A description giving the key's value in a format of request members.
|
|
FORMAT_RE = re.compile(r'\bin the format of "?(?P<format>[A-Za-z]+=<[a-z-]+>(?:,[A-Za-z]+=<[a-z-]+>)+)')
|
|
MEMBER_RE = re.compile(r"(?P<member>[A-Za-z]+)=<[a-z-]+>")
|
|
KEY_RE = re.compile(r"^route53:[A-Za-z]+$")
|
|
OPERATION_RE = re.compile(r"^[A-Z][A-Za-z]+$")
|
|
|
|
|
|
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 body(page: str) -> str:
|
|
"""The page's own content, its navigation left out."""
|
|
match = re.search(r'<div id="main-col-body">(?P<body>.*?)(?:<div class="prev-next"|$)', page, re.S)
|
|
return match.group("body") if match else page
|
|
|
|
|
|
def key_rows(page: str) -> list[list[str]]:
|
|
"""The rows of the page's table of condition keys, each its key, operations, value type and description."""
|
|
for table in re.findall(r"<table[^>]*>(.*?)</table>", body(page), re.S):
|
|
rows = [[text(cell) for cell in re.findall(r"<t[dh][^>]*>(.*?)</t[dh]>", row, re.S)]
|
|
for row in re.findall(r"<tr>(.*?)</tr>", table, re.S)]
|
|
if rows and rows[0] == HEADER:
|
|
return [row for row in rows[1:] if len(row) == len(HEADER) and KEY_RE.match(row[0])]
|
|
raise ValueError(f"{PAGE} has no table of Route 53 condition keys: its layout changed")
|
|
|
|
|
|
def build(fetch) -> dict:
|
|
keys = []
|
|
for key, operations, value_type, description in key_rows(fetch(PAGE)):
|
|
found = FORMAT_RE.search(description)
|
|
if found is None:
|
|
continue
|
|
named = operations.split()
|
|
if not named or not all(OPERATION_RE.match(name) for name in named):
|
|
raise ValueError(f"{PAGE} names {key}'s operations as '{operations}': its layout changed")
|
|
keys.append({"key": key, "operations": named, "format": found.group("format"),
|
|
"members": MEMBER_RE.findall(found.group("format")), "valueType": value_type,
|
|
"row": description})
|
|
if not keys:
|
|
raise ValueError(f"{PAGE} gives no key in a format of request members: its layout changed")
|
|
return {
|
|
"_source": {
|
|
"page": PAGE,
|
|
"fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)),
|
|
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
|
"note": "Each Route 53 key whose row of the page's table of condition keys gives its value in a format of "
|
|
"request members, with the operations the row names, the format and its members in order, and "
|
|
"the row's description, copied as it stands.",
|
|
},
|
|
"keys": sorted(keys, key=lambda entry: entry["key"]),
|
|
}
|
|
|
|
|
|
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 stale(vendored: dict, page: str) -> bool:
|
|
"""Whether the page now gives something other than the vendored file, its date aside."""
|
|
return vendored.get("keys") != build(lambda url: page)["keys"]
|
|
|
|
|
|
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(PAGE)
|
|
except OSError as e:
|
|
print(f"error: could not read the Route 53 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 Route 53 developer guide does: run "
|
|
f"tools/aws/fetch_route53_conditions.py and then make request-condition-keys-sync", file=sys.stderr)
|
|
return 1
|
|
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the Route 53 developer guide")
|
|
return 0
|
|
built = build(lambda url: page)
|
|
OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8")
|
|
print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['keys'])} keys)")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|