mirror of
https://github.com/floci-io/floci.git
synced 2026-12-03 10:17:48 -05:00
The generated IAM condition key table had iam:AccountPropertyNamespaces in notRead on both actions the Service Reference lists it on, so a policy keyed on it matched nothing: the IAM user guide's DenyRoleManagerEnablement statement, ForAnyValue:StringEquals on RoleManager, let a caller enable role manager, and an Allow requiring the namespace refused every call. Neither botocore nor the Service Reference says where the value is; AWS's pages do. The IAM user guide's condition key table: iam:AccountPropertyNamespaces "Specifies the account property namespaces being read or modified in the request ... When you call PutAccountProperties or GetAccountProperties". The API reference on PutAccountProperties' Properties: "Each key uses the format Namespace/PropertyName. The key must contain exactly one / separating the namespace from the property name". tools/aws/fetch_iam_account_property_namespaces.py copies both sentences into tools/aws/sources/iam-account-property-namespaces.json with what they name: the key, the operation, the parameter, the format, its separator and the part that is the namespace. regen_iam_condition_keys.py takes that entry as it stands, refusing it unless the Service Reference lists the pair and botocore models the parameter as a map of strings, and writes it to a new fromMapKeys section, which the IAM context resolver reads from the request's map as the operation's handler does. GetAccountProperties names no properties, so it stays in notRead.
154 lines
8.4 KiB
Python
154 lines
8.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Vendor what the IAM user guide and the IAM API reference say about iam:AccountPropertyNamespaces into
|
|
tools/aws/sources/iam-account-property-namespaces.json, a source of the IAM condition key table.
|
|
|
|
AWS's Service Reference gives PutAccountProperties and GetAccountProperties the key `iam:AccountPropertyNamespaces`,
|
|
typed `ArrayOfString`, without saying where its values are, and botocore models PutAccountProperties' `Properties` as
|
|
a map of strings without naming the key. The IAM user guide's table of IAM condition keys says what the key is:
|
|
|
|
iam:AccountPropertyNamespaces. Specifies the account property namespaces being read or modified in the request.
|
|
... When you call PutAccountProperties or GetAccountProperties, use this condition key to restrict which property
|
|
namespaces a principal can access.
|
|
|
|
https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html
|
|
|
|
and the API reference's page on PutAccountProperties says where in the request each namespace is:
|
|
|
|
Each key uses the format Namespace/PropertyName. The key must contain exactly one / separating the namespace from
|
|
the property name, and cannot start or end with /.
|
|
|
|
https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutAccountProperties.html
|
|
|
|
This script copies those sentences as they stand, with what each names: the key, the operations the guide names for
|
|
it, the request parameter whose keys carry the namespaces, the format of those keys, the separator between its parts
|
|
and the part that is the namespace. The operation page's operation must be one the guide names for the key. Nothing
|
|
in the output is written by hand; regen_iam_condition_keys.py reads it.
|
|
|
|
Run from anywhere in the repo:
|
|
python3 tools/aws/fetch_iam_account_property_namespaces.py # rewrite the vendored file from the pages
|
|
python3 tools/aws/fetch_iam_account_property_namespaces.py --verify # online: the file still says what they 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
|
|
|
|
KEYS_PAGE = "https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html"
|
|
OPERATION_PAGE = "https://docs.aws.amazon.com/IAM/latest/APIReference/API_PutAccountProperties.html"
|
|
REPO_ROOT = Path(__file__).resolve().parents[2]
|
|
OUTPUT = REPO_ROOT / "tools/aws/sources/iam-account-property-namespaces.json"
|
|
|
|
KEY_RE = re.compile(r"\b(?P<key>iam:[A-Za-z]+) Works with string operators\. Specifies the account property "
|
|
r"namespaces being read or modified in the request\. Account properties are organized into "
|
|
r"namespaces \(for example, [A-Za-z]+\)\. When you call (?P<first>[A-Za-z]+) or "
|
|
r"(?P<second>[A-Za-z]+), use this condition key to restrict which property namespaces a principal "
|
|
r"can access\.")
|
|
OPERATION_RE = re.compile(r'<h1 class="topictitle" id="API_(?P<operation>[A-Za-z]+)">(?P=operation)</h1>')
|
|
REQUEST_PARAMETERS_RE = re.compile(r'<h2 id="API_[A-Za-z]+_RequestParameters">(?P<section>.*?)(?:<h2|$)', re.S)
|
|
# A parameter of the section: its name in bold in the first term, its other terms naming its wire form, then its
|
|
# description.
|
|
PARAMETER_RE = re.compile(r'<dt><span class="term">\s*<b>(?P<member>[A-Za-z0-9]+)</b>\s*</span></dt>'
|
|
r'(?:\s*<dt>(?:(?!<dd>).)*?</dt>)*\s*<dd>(?P<description>.*?)</dd>', re.S)
|
|
FORMAT_RE = re.compile(r"\bEach key uses the format (?P<format>(?P<namespace>[A-Za-z]+)(?P<separator>\S)[A-Za-z]+)\. "
|
|
r"The key must contain exactly one (?P=separator) separating the namespace from the property "
|
|
r"name\b[^.]*\.")
|
|
|
|
|
|
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'<div id="main-col-body">(?P<body>.*?)(?:<div class="prev-next"|$)', page, re.S)
|
|
return match.group("body") if match else page
|
|
|
|
|
|
def _found(match: re.Match | None, page: str, what: str) -> re.Match:
|
|
if match is None:
|
|
raise ValueError(f"{page} no longer says {what}: its layout or its wording changed")
|
|
return match
|
|
|
|
|
|
def build(fetch) -> dict:
|
|
named = _found(KEY_RE.search(text(body(fetch(KEYS_PAGE)))), KEYS_PAGE,
|
|
"what iam:AccountPropertyNamespaces is and which operations it is for")
|
|
content = body(fetch(OPERATION_PAGE))
|
|
operation = _found(OPERATION_RE.search(content), OPERATION_PAGE, "which operation it is for").group("operation")
|
|
if operation not in (named.group("first"), named.group("second")):
|
|
raise ValueError(f"{KEYS_PAGE} gives {named.group('key')} to {named.group('first')} and "
|
|
f"{named.group('second')}, not to {operation}")
|
|
section = _found(REQUEST_PARAMETERS_RE.search(content), OPERATION_PAGE, "its request parameters")
|
|
keys = []
|
|
for parameter in PARAMETER_RE.finditer(section.group("section")):
|
|
described = FORMAT_RE.search(text(parameter.group("description")))
|
|
if described is not None:
|
|
keys.append({"operation": operation, "member": parameter.group("member"), "key": named.group("key"),
|
|
"format": described.group("format"), "separator": described.group("separator"),
|
|
"part": described.group("namespace"), "row": described.group(0)})
|
|
if len(keys) != 1:
|
|
raise ValueError(f"{OPERATION_PAGE} gives {len(keys)} request parameters keys holding a namespace, not one: "
|
|
f"its layout or its wording changed")
|
|
return {
|
|
"_source": {
|
|
"pages": [KEYS_PAGE, OPERATION_PAGE],
|
|
"fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)),
|
|
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
|
"note": "The guide's sentence on iam:AccountPropertyNamespaces and the API reference's on the keys of "
|
|
"PutAccountProperties' properties, copied as they stand, with what each names: the key and its "
|
|
"operations, the parameter, its keys' format, the separator and the part that is the namespace.",
|
|
},
|
|
"key": {"key": named.group("key"), "operations": sorted([named.group("first"), named.group("second")]),
|
|
"sentence": named.group(0)},
|
|
"keys": keys,
|
|
}
|
|
|
|
|
|
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, fetch) -> bool:
|
|
"""Whether the pages now give something other than the vendored file, its date aside."""
|
|
built = build(fetch)
|
|
return {key: value for key, value in vendored.items() if key != "_source"} != {
|
|
key: value for key, value in built.items() 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:
|
|
pages = {url: fetch(url) for url in (KEYS_PAGE, OPERATION_PAGE)}
|
|
except OSError as e:
|
|
print(f"error: could not read the IAM user guide or API reference ({e})", file=sys.stderr)
|
|
return 2
|
|
if args.verify:
|
|
vendored = json.loads(OUTPUT.read_text(encoding="utf-8"))
|
|
if stale(vendored, pages.__getitem__):
|
|
print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the IAM user guide and API reference "
|
|
f"do: run tools/aws/fetch_iam_account_property_namespaces.py and then make iam-condition-keys-sync",
|
|
file=sys.stderr)
|
|
return 1
|
|
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the IAM user guide and API reference")
|
|
return 0
|
|
built = build(pages.__getitem__)
|
|
OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8")
|
|
print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['keys'])} operations)")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|