mirror of
https://github.com/floci-io/floci.git
synced 2026-12-06 11:38:06 -05:00
A role's trust policy read a web identity token as two keys Floci built by hand, <issuer>:sub and <issuer>:aud, the latter always from the aud claim. The IAM User Guide's Default mapping, for every IdP it gives no tab of its own, also gives amr, email and oaud, and reads aud from azp where the token sets one; its page on creating an OIDC provider says AWS STS uses azp as the audience the provider's client IDs are checked against. A fetcher vendors the Default tab's rows and the provider page's azp sentence. The authorized-actions generator writes them as webIdentityClaims, and AssumeRoleWithWebIdentity reads the trust policy's keys and the token's audience from that section.
206 lines
11 KiB
Python
206 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Vendor how the IAM User Guide maps an OIDC token's claims to the condition keys a role's trust policy reads into
|
|
tools/aws/sources/sts-oidc-claim-keys.json, a source of the IAM authorized actions table.
|
|
|
|
The IAM User Guide's page on condition keys has, under "Available keys for AWS OIDC federation", a Default tab, which
|
|
"lists the standard OIDC claims and how they map to AWS STS condition context keys in AWS", and says "Use this mapping if
|
|
your IdP is not listed in the tab options". Its table gives each key, the claim it is read from and whether it is
|
|
available in session:
|
|
|
|
AWS STS condition key IdP JWT claim Available in session
|
|
amr amr Yes
|
|
aud azp Yes
|
|
If no value is set for azp, the aud condition key maps to the aud claim.
|
|
email email No
|
|
oaud aud No
|
|
sub sub Yes
|
|
|
|
https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#condition-keys-wif
|
|
|
|
The page on creating an OIDC identity provider says which claim a token's audience, the client ID the provider is
|
|
registered with, is read from:
|
|
|
|
If your OIDC identity provider is setting both aud and azp claims in the token, AWS STS will use the value in the
|
|
azp claim as the aud claim.
|
|
|
|
https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html
|
|
|
|
This script copies the tab's sentence, each row of its table and the provider page's sentence as they stand, with what
|
|
they name: a row's key, its claim, the claim the row's own sentence says the key is read from when that claim has no
|
|
value, and whether it is available in session; the claim the provider page names the audience and the one AWS STS uses
|
|
in its place. A page whose table has other columns, or that words either sentence otherwise, is refused, so a reworded
|
|
page fails rather than giving a key. Nothing in the output is written by hand.
|
|
|
|
Run from anywhere in the repo:
|
|
python3 tools/aws/fetch_sts_oidc_claim_keys.py # rewrite the vendored file
|
|
python3 tools/aws/fetch_sts_oidc_claim_keys.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
|
|
|
|
KEYS_PAGE = "https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html"
|
|
PROVIDER_PAGE = "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html"
|
|
# The section of the condition keys page on OIDC federation, and the tab of it for an IdP no other tab names.
|
|
SECTION = "condition-keys-wif"
|
|
TAB = "default"
|
|
REPO_ROOT = Path(__file__).resolve().parents[2]
|
|
OUTPUT = REPO_ROOT / "tools/aws/sources/sts-oidc-claim-keys.json"
|
|
|
|
# The table's columns, as the page heads them.
|
|
COLUMNS = ["AWS STS condition key", "IdP JWT claim", "Available in session"]
|
|
NAME_RE = re.compile(r"^[a-z][a-z0-9_]*$")
|
|
# The tab's sentence saying which IdPs its mapping is for.
|
|
APPLIES_RE = re.compile(r"^Use this mapping if your IdP is not listed in the tab options\.$")
|
|
# A row's sentence naming the claim its key is read from when the row's claim has no value.
|
|
OTHERWISE_RE = re.compile(r"^If no value is set for (?P<claim>[a-z][a-z0-9_]*), the (?P<key>[a-z][a-z0-9_]*) condition "
|
|
r"key maps to the (?P<otherwise>[a-z][a-z0-9_]*) claim\.$")
|
|
# The provider page's sentence naming the claim AWS STS reads a token's audience from in place of another.
|
|
AUDIENCE_RE = re.compile(r"^If your OIDC identity provider is setting both (?P<claim>[a-z]+) and (?P<preferred>[a-z]+) "
|
|
r"claims in the token, AWS STS will use the value in the (?P=preferred) claim as the "
|
|
r"(?P=claim) claim\.$")
|
|
|
|
|
|
def _text(fragment: str) -> str:
|
|
return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", "", fragment))).strip()
|
|
|
|
|
|
def _paragraphs(fragment: str) -> list[str]:
|
|
"""Each paragraph of the fragment as one line of text."""
|
|
return [text for text in (_text(body) for body in re.findall(r"<p\b[^>]*>(.*?)</p>", fragment, re.S)) if text]
|
|
|
|
|
|
def _sentences(paragraph: str) -> list[str]:
|
|
return [sentence for sentence in re.split(r"(?<=\.)\s+", paragraph) if sentence]
|
|
|
|
|
|
def tab(page: str) -> str:
|
|
"""The tab's markup, up to the next tab of the section that is not a nested code example's."""
|
|
section = re.search(r'\bid="' + re.escape(SECTION) + r'"(?P<body>.*?)(?=<h[1-3]\b|$)', page, re.S)
|
|
if section is None:
|
|
raise ValueError(f"{KEYS_PAGE} has no section {SECTION}: its layout changed")
|
|
starts = list(re.finditer(r'<dd tab-id="(?P<id>[^"]*)"', section.group("body")))
|
|
for index, start in enumerate(starts):
|
|
if start.group("id") == TAB:
|
|
end = next((later.start() for later in starts[index + 1:] if later.group("id") != "json"),
|
|
len(section.group("body")))
|
|
return section.group("body")[start.end():end]
|
|
raise ValueError(f"{KEYS_PAGE} has no {TAB} tab under {SECTION}: its layout changed")
|
|
|
|
|
|
def _one(pattern: re.Pattern, sentences: list[str], what: str, page: str) -> re.Match:
|
|
found = [match for match in map(pattern.match, sentences) if match is not None]
|
|
if len(found) != 1:
|
|
raise ValueError(f"{page} no longer says in one sentence {what}: its wording changed")
|
|
return found[0]
|
|
|
|
|
|
def keys(markup: str) -> list[dict]:
|
|
"""The rows of the tab's table: each key, its claim, the claim its sentence reads it from otherwise, and whether it
|
|
is available in session."""
|
|
table = re.search(r"<table\b.*?</table>", markup, re.S)
|
|
if table is None:
|
|
raise ValueError(f"{KEYS_PAGE}'s {TAB} tab has no table: its layout changed")
|
|
header = [_text(cell) for cell in re.findall(r"<th\b[^>]*>(.*?)</th>", table.group(0), re.S)]
|
|
if header != COLUMNS:
|
|
raise ValueError(f"{KEYS_PAGE}'s {TAB} tab heads its table {header}, not {COLUMNS}")
|
|
rows = []
|
|
for row in re.findall(r"<tr>(.*?)</tr>", table.group(0), re.S):
|
|
cells = [_paragraphs(cell) for cell in re.findall(r"<td\b[^>]*>(.*?)</td>", row, re.S)]
|
|
if not cells:
|
|
continue
|
|
if len(cells) != 3 or len(cells[0]) != 1 or len(cells[2]) != 1 or not 1 <= len(cells[1]) <= 2:
|
|
raise ValueError(f"{KEYS_PAGE}'s {TAB} tab has a row {cells} that is not a key, its claim and whether "
|
|
f"it is available in session")
|
|
key, claim, session = cells[0][0], cells[1][0], cells[2][0]
|
|
if not NAME_RE.match(key) or not NAME_RE.match(claim) or session not in ("Yes", "No"):
|
|
raise ValueError(f"{KEYS_PAGE}'s {TAB} tab maps '{key}' to '{claim}' in session '{session}', which is "
|
|
f"not a key, a claim and Yes or No")
|
|
entry = {"key": key, "claim": claim, "inSession": session == "Yes"}
|
|
if len(cells[1]) == 2:
|
|
otherwise = OTHERWISE_RE.match(cells[1][1])
|
|
if otherwise is None or otherwise.group("claim") != claim or otherwise.group("key") != key:
|
|
raise ValueError(f"{KEYS_PAGE}'s {TAB} tab says of {key} '{cells[1][1]}', which no longer names "
|
|
f"the claim {key} is read from when {claim} has no value")
|
|
entry["otherwise"] = otherwise.group("otherwise")
|
|
entry["otherwiseSentence"] = otherwise.group(0)
|
|
rows.append(entry)
|
|
if not rows or len({row["key"] for row in rows}) != len(rows):
|
|
raise ValueError(f"{KEYS_PAGE}'s {TAB} tab gives no keys, or one twice: its layout changed")
|
|
return rows
|
|
|
|
|
|
def audience(page: str) -> dict:
|
|
"""The claim the provider page names a token's audience, the one AWS STS uses in its place, and the sentence."""
|
|
sentences = [sentence for paragraph in _paragraphs(page) for sentence in _sentences(paragraph)]
|
|
found = _one(AUDIENCE_RE, sentences, "which claim AWS STS reads a token's audience from", PROVIDER_PAGE)
|
|
return {"claim": found.group("claim"), "preferred": found.group("preferred"), "sentence": found.group(0)}
|
|
|
|
|
|
def build(keys_page: str, provider_page: str) -> dict:
|
|
markup = tab(keys_page)
|
|
sentences = [sentence for paragraph in _paragraphs(markup) for sentence in _sentences(paragraph)]
|
|
applies = _one(APPLIES_RE, sentences, f"which IdPs its {TAB} mapping is for", KEYS_PAGE)
|
|
return {
|
|
"_source": {
|
|
"pages": [f"{KEYS_PAGE}#{SECTION}", PROVIDER_PAGE],
|
|
"fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)),
|
|
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
|
"note": "The IAM User Guide's Default mapping of OIDC claims to condition keys, each row as the page gives "
|
|
"it, and its sentence naming the claim AWS STS reads a token's audience from, copied as they stand.",
|
|
},
|
|
"default": {"sentence": applies.group(0), "keys": keys(markup)},
|
|
"audience": audience(provider_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, str]:
|
|
"""The IAM User Guide's page on condition keys and its page on creating an OIDC identity provider."""
|
|
return fetch(KEYS_PAGE), fetch(PROVIDER_PAGE)
|
|
|
|
|
|
def stale(vendored: dict, keys_page: str, provider_page: str) -> bool:
|
|
"""Whether the pages now give something other than the vendored file, its date aside."""
|
|
built = build(keys_page, provider_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 pages")
|
|
args = parser.parse_args(argv)
|
|
try:
|
|
pages = fetch_all(fetch)
|
|
except OSError as e:
|
|
print(f"error: could not read the IAM User Guide ({e})", file=sys.stderr)
|
|
return 2
|
|
if args.verify:
|
|
vendored = json.loads(OUTPUT.read_text(encoding="utf-8"))
|
|
if stale(vendored, *pages):
|
|
print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the IAM User Guide does: run "
|
|
f"tools/aws/fetch_sts_oidc_claim_keys.py and then make iam-authorized-actions-sync", file=sys.stderr)
|
|
return 1
|
|
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the IAM User Guide")
|
|
return 0
|
|
built = build(*pages)
|
|
OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8")
|
|
print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['default']['keys'])} key(s))")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|