Files
floci/tools/aws/fetch_sts_source_identity.py
T
Priamo Germosen 7d3049d218 fix(iam): read a federated assume's source identity from its assertion or token (#9708)
Under enforcement a role whose trust policy conditions AssumeRoleWithSAML or AssumeRoleWithWebIdentity on sts:SourceIdentity refused every assume, and one that withheld sts:SetSourceIdentity was never consulted: neither operation read the source identity its identity provider sets, so the session carried none, the response returned none and its requests carried no aws:SourceIdentity. The Service Reference gives both actions sts:SourceIdentity but lists no authorized actions for either operation, and botocore models the value only in the response.

The IAM user guide's page on source identity, which tools/aws/fetch_sts_source_identity.py already vendors, says where each carries it, "to set a SAML attribute for source identity, include the Attribute element with the Name attribute set to https://aws.amazon.com/SAML/Attributes/SourceIdentity" and "include source identity in the https://aws.amazon.com/source_identity namespace in the token", and what it needs, "trust policies for all roles connected to an identity provider (IdP) must have the sts:SetSourceIdentity permission". The fetcher now copies those sentences too, and regen_iam_authorized_actions.py gives each operation a companion naming the attribute or the claim and the key it is read as, where the reference's action of the operation's name takes sts:SourceIdentity.

STS reads the value the table names, holds it to botocore's sourceIdentityType (the shape botocore gives the response's SourceIdentity, as it does AssumeRole's member), and refuses several values or one outside it with InvalidIdentityToken. The trust policy reads it as sts:SourceIdentity, through the keys the federated trust evaluators already read in full, and is checked for sts:SetSourceIdentity before the assume, as for AssumeRole. The session records it under aws:SourceIdentity, which a session assumed from it carries on, and the response returns it.

Part of #6640.
2026-11-28 23:02:42 -04:00

203 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Vendor what the IAM user guide says about setting a source identity into tools/aws/sources/sts-source-identity.json,
a source of the request condition key table and the authorized actions table.
AWS's Service Reference gives AssumeRole the key `sts:SourceIdentity` and lists `sts:SetSourceIdentity` among the
actions the operation is authorized by, beside `sts:AssumeRole` and `sts:TagSession`, without saying which request
member carries the key or when the action is needed, and botocore does not say either. The IAM user guide's page on
source identity does:
To pass source identity while assuming a role, use the -–source-identity AWS CLI option or the SourceIdentity
AWS API parameter.
To specify a source identity, principals (IAM users and roles) must have permissions to sts:SetSourceIdentity.
When you assume a role with another role, called role chaining, permissions for sts:SetSourceIdentity are
required in both the permissions policy of the principal who is assuming the role and in the role trust policy
of the target role.
https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html
To set a SAML attribute for source identity, include the Attribute element with the Name attribute set to
https://aws.amazon.com/SAML/Attributes/SourceIdentity.
Include source identity in the https://aws.amazon.com/source_identity namespace in the token when you submit the
AssumeRoleWithWebIdentity request.
Trust policies for all roles connected to an identity provider (IdP) must have the sts:SetSourceIdentity
permission.
This script copies those sentences as they stand, with what each names: the operation of each "Using source identity
with <Operation>" section that names the API parameter carrying the value (`keys`), or the SAML attribute or the token
claim carrying it (`federated`), the action setting a source identity needs, alone, when chaining and for a role an
identity provider is connected to, the key a request setting one carries and the key the session's later requests carry,
and the sentences saying the value persists through a chain. A section naming none of them is not read here. Nothing in
the output is written by hand; regen_request_condition_keys.py and regen_iam_authorized_actions.py read it.
Run from anywhere in the repo:
python3 tools/aws/fetch_sts_source_identity.py # rewrite the vendored file from the page
python3 tools/aws/fetch_sts_source_identity.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/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html"
REPO_ROOT = Path(__file__).resolve().parents[2]
OUTPUT = REPO_ROOT / "tools/aws/sources/sts-source-identity.json"
OPERATION_HEADING_RE = re.compile(r"^Using source identity with (?P<operation>[A-Z][A-Za-z]+)$")
MEMBER_RE = re.compile(r"\bTo pass source identity while assuming a role, use the \S+ AWS CLI option or the "
r"(?P<member>[A-Z][A-Za-z]+) AWS API parameter\.")
PERMISSION_RE = re.compile(r"\bTo specify a source identity, principals \(IAM users and roles\) must have permissions "
r"to (?P<action>sts:[A-Za-z]+)\.")
CHAINING_RE = re.compile(r"\bWhen you assume a role with another role, called role chaining, permissions for "
r"(?P<action>sts:[A-Za-z]+) are required in both the permissions policy of the principal "
r"who is assuming the role and in the role trust policy of the target role\.")
KEYS_RE = re.compile(r"\bWhen an identity sets a source identity, the (?P<request>sts:[A-Za-z]+) key is present in the "
r"request\. For subsequent actions taken during the role session, the "
r"(?P<session>aws:[A-Za-z]+) key is present in the request\.")
ATTRIBUTE_RE = re.compile(r"\bTo set a SAML attribute for source identity, include the Attribute element with the "
r"Name attribute set to (?P<attribute>https://[^\s]+?)\.(?:\s|$)")
# The claim is read from the markup, where the page links the namespace's host inside the code element naming it.
CLAIM_RE = re.compile(r"\bInclude source identity in the <code[^>]*>(?P<claim>.*?)</code>\s+namespace in the token",
re.S)
IDP_RE = re.compile(r"\bTrust policies for all roles connected to an identity provider \(IdP\) must have the "
r"(?P<action>sts:[A-Za-z]+) permission\.")
PERSISTS_RE = re.compile(r"\bThe value that is set persists when a role is used to assume another role[^.]*\. "
r"The value that is set cannot be changed during the role session\.")
CHAINED_KEYS_RE = re.compile(r"\bTherefore, both the (?P<session>aws:[A-Za-z]+) and (?P<request>sts:[A-Za-z]+) keys "
r"are present in the request context\.")
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 sections(page: str) -> dict[str, str]:
"""Each second-level section of the page as its markup, under its heading as text."""
parts = re.split(r"<h2[^>]*>(.*?)</h2>", body(page), flags=re.S)
return {text(parts[i]): parts[i + 1] for i in range(1, len(parts) - 1, 2)}
def _sentence(pattern: re.Pattern, where: str, what: str) -> re.Match:
found = pattern.search(where)
if found is None:
raise ValueError(f"{PAGE} no longer says {what}: its layout or its wording changed")
return found
def build(fetch) -> dict:
page = fetch(PAGE)
by_heading = sections(page)
whole = text(body(page))
keys, federated = [], []
for heading, markup in by_heading.items():
operation = OPERATION_HEADING_RE.match(heading)
if operation is None:
continue
section = text(markup)
member = MEMBER_RE.search(section)
attribute = ATTRIBUTE_RE.search(section)
claim = CLAIM_RE.search(markup)
if member is not None:
keys.append({"operation": operation.group("operation"), "member": member.group("member"),
"row": member.group(0)})
elif attribute is not None:
federated.append({"operation": operation.group("operation"), "attribute": attribute.group("attribute"),
"row": attribute.group(0).strip()})
elif claim is not None:
named_claim = re.sub(r"<[^>]+>|\s+", "", claim.group("claim"))
federated.append({"operation": operation.group("operation"), "claim": named_claim,
"row": text(claim.group(0).replace(claim.group("claim"), named_claim))})
if not keys:
raise ValueError(f"{PAGE} names no API parameter a source identity is passed in: its layout changed")
permission = _sentence(PERMISSION_RE, whole, "which action specifying a source identity needs")
chaining = _sentence(CHAINING_RE, whole, "which action a chained assume of a source identity needs")
if chaining.group("action") != permission.group("action"):
raise ValueError(f"{PAGE} names {permission.group('action')} for setting a source identity and "
f"{chaining.group('action')} for chaining one")
named = _sentence(KEYS_RE, whole, "which keys a source identity is present in the request as")
chained = _sentence(CHAINED_KEYS_RE, whole, "which keys a chained request carries a source identity as")
if (chained.group("request"), chained.group("session")) != (named.group("request"), named.group("session")):
raise ValueError(f"{PAGE} names other keys for a chained request than for one setting a source identity")
persists = _sentence(PERSISTS_RE, whole, "that a source identity persists through a chain")
idp = _sentence(IDP_RE, whole, "which action a role an identity provider is connected to needs of its trust")
if idp.group("action") != permission.group("action"):
raise ValueError(f"{PAGE} names {permission.group('action')} for setting a source identity and "
f"{idp.group('action')} for a role an identity provider is connected to")
for entry in keys + federated:
entry["key"] = named.group("request")
return {
"_source": {
"page": PAGE,
"fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)),
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
"note": "The page's sentences on setting a source identity, copied as they stand, with what each names: "
"the API parameter each operation's section passes it in, the action setting one needs and its "
"chained form, the keys a request carries it as, and its persistence through a chain.",
},
"keys": sorted(keys, key=lambda entry: entry["operation"]),
"federated": sorted(federated, key=lambda entry: entry["operation"]),
"permission": {"action": permission.group("action"), "sentence": permission.group(0),
"chaining": chaining.group(0), "identityProvider": idp.group(0)},
"sessionKey": {"key": named.group("session"), "sentence": named.group(0), "chained": chained.group(0)},
"persists": persists.group(0),
}
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."""
built = build(lambda url: page)
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 page")
args = parser.parse_args(argv)
try:
page = fetch(PAGE)
except OSError as e:
print(f"error: could not read the IAM user guide's source identity page ({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 IAM user guide does: run "
f"tools/aws/fetch_sts_source_identity.py and then make request-condition-keys-sync and "
f"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(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'])} operations)")
return 0
if __name__ == "__main__":
sys.exit(main())