mirror of
https://github.com/floci-io/floci.git
synced 2026-11-29 08:31:53 -05:00
Under enforcement an AssumeRole passing a SourceIdentity was neither held to sts:SetSourceIdentity nor read as sts:SourceIdentity, so a trust policy requiring a source identity refused every assume and one granting the permission was never consulted. The session kept no source identity either: the response returned none, its requests carried no aws:SourceIdentity, and a session assumed from it could set another. botocore gives the member and the Service Reference the key and the action, listing sts:SetSourceIdentity among the actions AssumeRole is authorized by, without saying when it is needed or which member carries the key. The IAM user guide's page on source identity says both: "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", and when chaining it is "required in both the permissions policy of the principal who is assuming the role and in the role trust policy of the target role". tools/aws/fetch_sts_source_identity.py vendors it into tools/aws/sources/sts-source-identity.json. regen_request_condition_keys.py reads it for sts (CONDITION_SOURCES), so sts:SourceIdentity is read from AssumeRole's SourceIdentity, and regen_iam_authorized_actions.py crosses it with the reference's AuthorizedActions and botocore's request members into a new companions section of iam-authorized-actions.json: AssumeRole needs sts:SetSourceIdentity when it names SourceIdentity or its caller carries aws:SourceIdentity. Enforcement checks the companion action on the role with the request's keys, and for a caller that is itself a role session checks it of the caller's own permissions alone too, since a trust policy naming the caller's role would otherwise stand in for them in the same account (the table's callerPolicyWhenChained, from the page's sentence on role chaining). STS checks it in the trust policy before the assume, as AWS names it where a statement granting both is conditioned on another sts:SourceIdentity. The session records the value under the key the table gives, aws:SourceIdentity, which its requests carry and a session assumed from it carries on, read there as sts:SourceIdentity too, and the response returns it. A chained request naming another value is refused with ValidationError, "The source identity is already set for this assume role session", and an AssumeRole naming a session tag key twice with InvalidParameterValue, "Duplicate tag keys found. Please note that Tag keys are case insensitive.", both as AWS's evaluation suite records them. Part of #6640.
170 lines
9.2 KiB
Python
170 lines
9.2 KiB
Python
#!/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
|
||
|
||
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, the action setting a source identity needs,
|
||
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 no API parameter 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\.")
|
||
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 text, under its heading."""
|
||
parts = re.split(r"<h2[^>]*>(.*?)</h2>", body(page), flags=re.S)
|
||
return {text(parts[i]): text(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 = []
|
||
for heading, section in by_heading.items():
|
||
operation = OPERATION_HEADING_RE.match(heading)
|
||
member = MEMBER_RE.search(section) if operation else None
|
||
if member is None:
|
||
continue
|
||
keys.append({"operation": operation.group("operation"), "member": member.group("member"),
|
||
"row": member.group(0)})
|
||
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")
|
||
for entry in keys:
|
||
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"]),
|
||
"permission": {"action": permission.group("action"), "sentence": permission.group(0),
|
||
"chaining": chaining.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())
|