Files
floci/tools/aws/fetch_secretsmanager_required_permissions.py
T
Priamo Germosen 96819a87fd fix(iam): check a Secrets Manager request for the actions its required permissions give (#9758)
The Service Reference lists the actions each Secrets Manager operation is authorized by without saying when each is
needed, so a request was checked as its own action alone: a BatchGetSecretValue using Filters without
secretsmanager:ListSecrets, a CreateSecret adding replica Regions without secretsmanager:ReplicateSecretToRegions and
a ValidateResourcePolicy without secretsmanager:PutResourcePolicy were all let through.

Each operation's page in the API reference says it, in its required permissions: "If you use filters, you must also
have secretsmanager:ListSecrets", "To add replica Regions, you must also have secretsmanager:ReplicateSecretToRegions",
"Required permissions: secretsmanager:ValidateResourcePolicy and secretsmanager:PutResourcePolicy".
tools/aws/fetch_secretsmanager_required_permissions.py copies that paragraph for each operation the Service Reference
lists as authorized by another of its actions, with each clause's action and what it is needed for or on, into
tools/aws/sources/secretsmanager-required-permissions.json. Two generators read it:

- regen_iam_authorized_actions.py: an action needed when the request does something is a companion of the request
  member the clause's words name as the generators' names go (filters is Filters, add replica Regions
  AddReplicaRegions), where the Service Reference lists it for the operation and does not mark it as tagging, which
  the tag-on-create table checks. A companion a request member sets may now carry no session key.
- regen_iam_request_resources.py: actions an operation always needs beside its own are each checked on what the rules
  read for it (ValidateResourcePolicy and PutResourcePolicy on the secret its SecretId names). A request checked by
  parts that names nothing is now checked on * as each action the table checks on the same resources as its own, not
  as its own alone, so a ValidateResourcePolicy naming no secret still needs PutResourcePolicy.

The fetcher refuses a sentence naming a secretsmanager: action in a wording it does not read, so a reworded page fails
rather than dropping a check, and the enforcement test runs on the AWS SDK.

Not read: GetSecretValue for each secret of a batch, which AWS reports per secret in Errors rather than refusing the
call; PutResourcePolicy for a cross-account replica and DeleteResourcePolicy for one stopped replicating, whose words
name no member of the request; and the KMS permissions of a secret on a customer managed key.
2026-11-29 13:12:46 -04:00

188 lines
9.9 KiB
Python

#!/usr/bin/env python3
"""Vendor what the AWS Secrets Manager API reference says each operation's request needs into
tools/aws/sources/secretsmanager-required-permissions.json, a source of the IAM tables.
The Service Reference lists the actions an operation is authorized by, BatchGetSecretValue by
secretsmanager:BatchGetSecretValue, secretsmanager:GetSecretValue and secretsmanager:ListSecrets, without saying when
each is needed, and botocore does not say it either. Each operation's page in the API reference does, in a paragraph
of its own:
Required permissions: secretsmanager:BatchGetSecretValue, and you must have secretsmanager:GetSecretValue for
each secret. If you use filters, you must also have secretsmanager:ListSecrets.
https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_BatchGetSecretValue.html
This script reads the Service Reference for the operations it lists as authorized by an action beside their own, and
copies each one's paragraph as it stands, with each clause it gives an action in: what the operation always needs
("Required permissions: A and B"), what it needs for each thing it names ("A for each secret") or on one ("A on the
primary secret"), and what it needs when the request does something ("If you use filters, you must also have A",
"To add replica Regions, you must also have A"), with the words that say so. A sentence naming no secretsmanager:
action, as the KMS ones, is copied with the paragraph but not read, and one naming one in any other wording is
refused, so a reworded page fails rather than dropping a check. Nothing in the output is written by hand, and the
generators read it against the Service Reference's authorized actions and botocore's requests.
Run from anywhere in the repo:
python3 tools/aws/fetch_secretsmanager_required_permissions.py # rewrite the vendored file
python3 tools/aws/fetch_secretsmanager_required_permissions.py --verify # online: the file still says it
"""
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
REFERENCE = "https://servicereference.us-east-1.amazonaws.com/v1/secretsmanager/secretsmanager.json"
API_PAGE = "https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_{operation}.html"
REPO_ROOT = Path(__file__).resolve().parents[2]
OUTPUT = REPO_ROOT / "tools/aws/sources/secretsmanager-required-permissions.json"
NAMESPACE = "secretsmanager"
ACTION = r"secretsmanager:[A-Za-z]+"
# The paragraph giving an operation's required permissions, and each of its sentences.
PARAGRAPH_RE = re.compile(r"^Required permissions: ")
SENTENCE_RE = re.compile(r"(?<=\.)\s+(?=[A-Z])")
# What the operation always needs, and what it needs for each thing or on one thing it names.
ALWAYS_RE = re.compile(rf"^Required permissions: (?P<clauses>{ACTION}.*)\.$")
EACH_RE = re.compile(rf"^(?:and )?(?:you must have )?(?P<action>{ACTION}) for each (?P<words>[a-z]+(?: [a-z]+)*)$")
ON_RE = re.compile(rf"^(?:and )?(?P<action>{ACTION}) on the (?P<words>[a-z]+(?: [a-z]+)*)$")
BARE_RE = re.compile(rf"^(?:and )?(?P<action>{ACTION})$")
# What the operation needs when its request does what the words say.
WHEN_RES = (
re.compile(rf"^If you use (?P<words>[^,]+), you must also have (?P<action>{ACTION})(?: permissions?)?\.$"),
re.compile(rf"^If you include (?P<words>.+?) in the secret, you also need (?P<action>{ACTION})\.$"),
re.compile(rf"^To (?P<words>[^,]+), you must also have (?P<action>{ACTION})(?: permissions?)?\.$"),
)
# What the operation needs when what it acts on is what the words say.
FOR_RE = re.compile(rf"^For (?P<words>[^,]+), you must also have (?P<action>{ACTION})(?: permissions?)?\.$")
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 operations(reference: dict) -> list[str]:
"""The operations the Service Reference lists as authorized by an action of the namespace beside their own."""
found = []
for operation in reference.get("Operations", []):
actions = {f"{action['Service']}:{action['Name']}" for action in operation.get("AuthorizedActions") or []}
if any(action.startswith(NAMESPACE + ":") and action != f"{NAMESPACE}:{operation['Name']}"
for action in actions):
found.append(operation["Name"])
return sorted(found)
def clauses(sentence: str) -> list[dict]:
"""Each action a sentence of the paragraph gives, with what it is needed for."""
always = ALWAYS_RE.match(sentence)
if always:
found = []
for clause in re.split(r",? and (?=you must have|secretsmanager:)|, ", always.group("clauses")):
each, on, bare = EACH_RE.match(clause), ON_RE.match(clause), BARE_RE.match(clause)
if each:
found.append({"action": each.group("action"), "each": each.group("words")})
elif on:
found.append({"action": on.group("action"), "on": on.group("words")})
elif bare:
found.append({"action": bare.group("action")})
else:
raise ValueError(f"the required permissions '{sentence}' give '{clause}', which names no action as "
f"they did: their wording changed")
return found
for when in WHEN_RES:
matched = when.match(sentence)
if matched:
return [{"action": matched.group("action"), "when": matched.group("words")}]
matched = FOR_RE.match(sentence)
if matched:
return [{"action": matched.group("action"), "for": matched.group("words")}]
# A sentence naming an action of the namespace in no wording above would drop that action from the generated
# checks on a refresh, so the page has to be read again; one naming none, as the KMS ones, says nothing here.
if re.search(ACTION, sentence):
raise ValueError(f"the required permissions say '{sentence}', which gives a {NAMESPACE}: action in no wording "
f"they used: their wording changed")
return []
def read_required(operation: str, page: str) -> dict:
"""The operation's paragraph of required permissions and each action it gives."""
for paragraph in re.findall(r"<p>(.*?)</p>", body(page), re.S):
said = text(paragraph)
if PARAGRAPH_RE.match(said):
permissions = [found for sentence in SENTENCE_RE.split(said) for found in clauses(sentence)]
return {"operation": operation, "paragraph": said, "permissions": permissions}
raise ValueError(f"{API_PAGE.format(operation=operation)} gives no required permissions: its layout changed")
def build(reference: dict, pages: dict[str, str]) -> dict:
named = operations(reference)
return {
"_source": {
"pages": [REFERENCE, *(API_PAGE.format(operation=operation) for operation in named)],
"fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)),
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
"note": "The required permissions paragraph of each operation's API reference page the Service Reference "
"lists as authorized by an action beside its own, copied as it stands, with each action it gives "
"and what it is needed for.",
},
"required": [read_required(operation, pages[operation]) for operation in named],
}
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[dict, dict[str, str]]:
"""The Service Reference and the page of each operation it lists as authorized by another action."""
reference = json.loads(fetch(REFERENCE))
return reference, {operation: fetch(API_PAGE.format(operation=operation)) for operation in operations(reference)}
def stale(vendored: dict, reference: dict, pages: dict[str, str]) -> bool:
"""Whether the reference and the pages now give something other than the vendored file, its date aside."""
built = build(reference, pages)
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:
reference, pages = fetch_all(fetch)
except OSError as e:
print(f"error: could not read the AWS Secrets Manager documentation ({e})", file=sys.stderr)
return 2
if args.verify:
vendored = json.loads(OUTPUT.read_text(encoding="utf-8"))
if stale(vendored, reference, pages):
print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the AWS Secrets Manager API reference "
f"does: run tools/aws/fetch_secretsmanager_required_permissions.py and then make "
f"iam-authorized-actions-sync and iam-request-resources-sync", file=sys.stderr)
return 1
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the AWS Secrets Manager API reference")
return 0
built = build(reference, pages)
OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8")
print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['required'])} operations)")
return 0
if __name__ == "__main__":
sys.exit(main())