Files
floci/tools/aws/fetch_lambda_response_permissions.py
T
Priamo Germosen 1dc6478108 fix(iam): return GetFunction's tags only to a caller allowed lambda:ListTags (#9782)
The Lambda API reference says of GetFunction's Tags "Lambda returns tag data only if you have explicit allow
permissions for lambda:ListTags", and the Service Reference lists lambda:ListTags among the actions GetFunction is
authorized by. Floci returned a function's tags to every caller allowed lambda:GetFunction.

tools/aws/fetch_lambda_response_permissions.py vendors, from the API reference page of each operation the Service
Reference lists as authorized by an action beside its own and the reference's operations page documents, each
response element's sentence saying it is returned only with a permission, with the element and the action. It
refuses a sentence naming a permission and a lambda: action in any other wording, and a page whose response elements
section is missing or lists no element without saying the response is empty, so a reworded or relaid page fails
rather than dropping the check. The authorized-actions generator reads it into a returnedOnlyIf
section, where botocore's response of the operation has a member of the element's name and the Service Reference
lists the action among the operation's: GetFunction returns Tags only with lambda:ListTags. IamAuthorizedActions
reads it, and LambdaController leaves the member out of a GetFunction response to a caller not allowed the action on
the function, checked with the function's tags through IamEnforcementFilter.authorizeEntryResource. TagsError is not
set, as no recording of AWS's answer for that case gives its code and message.

IamEnforcementFilter.requestAuthorization, which hands a handler the caller the filter evaluated, now treats a blank
Authorization header as no credential, as the filter itself does, and falls back to the presigned X-Amz-Credential;
before, a request with a blank header and a query credential passed the filter as that credential and the handler's
check as unsigned, so GetFunction returned Tags to a caller not allowed lambda:ListTags.
2026-11-29 22:09:26 -04:00

190 lines
9.9 KiB
Python

#!/usr/bin/env python3
"""Vendor what the AWS Lambda API reference says a response returns only with a permission into
tools/aws/sources/lambda-response-permissions.json, a source of the IAM tables.
The Service Reference lists lambda:ListTags among the actions GetFunction is authorized by, without saying what for,
and botocore's model is not a source the generators read sentences from. The operation's page in the API reference
says it of one of its response elements:
Tags
The function's tags. Lambda returns tag data only if you have explicit allow permissions for lambda:ListTags.
https://docs.aws.amazon.com/lambda/latest/api/API_GetFunction.html
This script reads the Service Reference for the operations it lists as authorized by an action beside their own,
keeps those the API reference's operations page lists, and copies each response element's sentence saying the
element is returned only with an action's permission, with the element and the action. A sentence saying so 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 responses.
Run from anywhere in the repo:
python3 tools/aws/fetch_lambda_response_permissions.py # rewrite the vendored file
python3 tools/aws/fetch_lambda_response_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/lambda/lambda.json"
OPERATIONS_PAGE = "https://docs.aws.amazon.com/lambda/latest/api/API_Operations.html"
API_PAGE = "https://docs.aws.amazon.com/lambda/latest/api/API_{operation}.html"
REPO_ROOT = Path(__file__).resolve().parents[2]
OUTPUT = REPO_ROOT / "tools/aws/sources/lambda-response-permissions.json"
NAMESPACE = "lambda"
ACTION = rf"{NAMESPACE}:[A-Za-z]+"
# A sentence about a permission an element needs, which names an action of the namespace and a permission, and the
# wording the reference gives it in.
PERMISSION_RE = re.compile(rf"\bpermissions?\b.*\b{ACTION}|\b{ACTION}.*\bpermissions?\b|\bonly (?:if|when) you have\b")
RETURNED_RE = re.compile(rf"^Lambda returns (?P<what>[a-z]+(?: [a-z]+)*) only if you have explicit allow "
rf"permissions for (?P<action>{ACTION})\.$")
SENTENCE_RE = re.compile(r"(?<=\.)\s+(?=[A-Z])")
# An operation's page's response elements, up to the next section; and what one with none says instead.
SECTION_RE = '<h2 id="API_{operation}_ResponseElements"'
EMPTY_BODY_RE = re.compile(r"the service sends back an HTTP \d{3} response with an empty HTTP body")
# A response element of an operation's page: its name, and its description up to the next element.
ELEMENT_RE = re.compile(r'<dt id="lambda-(?P<operation>[A-Za-z]+)-response-(?P<element>[A-Za-z]+)">.*?</dt>\s*'
r'<dd>(?P<description>.*?)</dd>', re.S)
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 listed(index: str) -> set[str]:
"""The operations the API reference's operations page links to."""
found = set(re.findall(r'href="\./API_([A-Za-z]+)\.html"', body(index)))
if not found:
raise ValueError(f"{OPERATIONS_PAGE} links to no operation: its layout changed")
return found
def operations(reference: dict, index: str) -> list[str]:
"""The operations the Service Reference lists as authorized by an action of the namespace beside their own and
the API reference documents."""
documented = listed(index)
found = []
for operation in reference.get("Operations", []):
actions = {f"{action['Service']}:{action['Name']}" for action in operation.get("AuthorizedActions") or []}
if operation["Name"] in documented and any(action.startswith(NAMESPACE + ":")
and action != f"{NAMESPACE}:{operation['Name']}"
for action in actions):
found.append(operation["Name"])
return sorted(found)
def response_section(operation: str, page: str) -> str:
"""The operation's page's response elements section, refused when the page has none or it lists no element and
does not say the response is empty."""
content = body(page)
start = content.find(SECTION_RE.format(operation=operation))
if start < 0:
raise ValueError(f"{API_PAGE.format(operation=operation)} has no response elements section: its layout "
f"changed")
end = content.find("<h2", start + 1)
section = content[start:] if end < 0 else content[start:end]
if not ELEMENT_RE.search(section) and not EMPTY_BODY_RE.search(text(section)):
raise ValueError(f"{API_PAGE.format(operation=operation)} lists no response element and does not say its "
f"response is empty: its layout changed")
return section
def read_returned(operation: str, page: str) -> list[dict]:
"""Each response element of the operation's page returned only with a permission, with its sentence and action. A
sentence naming a permission and an action of the namespace in any other wording is refused, as is a page whose
response elements cannot be read, so a reworded or relaid page fails rather than dropping a check."""
found = []
for element in ELEMENT_RE.finditer(response_section(operation, page)):
if element.group("operation") != operation:
raise ValueError(f"{API_PAGE.format(operation=operation)} lists the response element "
f"{element.group('element')} of {element.group('operation')}: its layout changed")
for sentence in SENTENCE_RE.split(text(element.group("description"))):
if not PERMISSION_RE.search(sentence):
continue
matched = RETURNED_RE.match(sentence)
if matched is None:
raise ValueError(f"{API_PAGE.format(operation=operation)} says of {element.group('element')} "
f"'{sentence}', which returns it only with a permission in no wording it used: its "
f"wording changed")
found.append({"operation": operation, "element": element.group("element"), "sentence": sentence,
"action": matched.group("action")})
return found
def build(reference: dict, index: str, pages: dict[str, str]) -> dict:
named = operations(reference, index)
return {
"_source": {
"pages": [REFERENCE, OPERATIONS_PAGE, *(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": "Each response element the API reference page of an operation the Service Reference lists as "
"authorized by an action beside its own says is returned only with a permission, with the "
"sentence that says so and the action.",
},
"returnedOnlyIf": [found for operation in named for found in read_returned(operation, pages[operation])],
}
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, str, dict[str, str]]:
"""The Service Reference, the operations page and the page of each operation `operations` keeps."""
reference = json.loads(fetch(REFERENCE))
index = fetch(OPERATIONS_PAGE)
return reference, index, {operation: fetch(API_PAGE.format(operation=operation))
for operation in operations(reference, index)}
def stale(vendored: dict, reference: dict, index: str, 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, index, 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, index, pages = fetch_all(fetch)
except OSError as e:
print(f"error: could not read the AWS Lambda API reference ({e})", file=sys.stderr)
return 2
if args.verify:
vendored = json.loads(OUTPUT.read_text(encoding="utf-8"))
if stale(vendored, reference, index, pages):
print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the AWS Lambda API reference does: "
f"run tools/aws/fetch_lambda_response_permissions.py and then make iam-authorized-actions-sync",
file=sys.stderr)
return 1
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the AWS Lambda API reference")
return 0
built = build(reference, index, pages)
OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8")
print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['returnedOnlyIf'])} elements)")
return 0
if __name__ == "__main__":
sys.exit(main())