mirror of
https://github.com/floci-io/floci.git
synced 2026-11-30 00:45:17 -05:00
The Service Reference lists lambda:GetLayerVersion among the actions CreateFunction and UpdateFunctionConfiguration are authorized by, and the Lambda Developer Guide says what it is checked on: "Make sure that you have permission to call the GetLayerVersion API on the layer version". Floci checked neither operation as it, so a caller allowed to create or update functions added any layer version of its account, whatever its policies said about reading it. tools/aws/fetch_lambda_layer_permissions.py vendors that sentence from the adding-layers page, with the action and the resource it names, and refuses a page asking for permission to call an API in any other wording. The request-resources generator reads it (api_permission_resources): an operation the Service Reference lists as authorized by that action is also checked as it on each value of the request's member holding botocore's ARN shape for the type the words name (`<Type>Arn`, as minted_types reads it; `Layers`, a list of `LayerVersionArn`, for a `layerVersion`). CreateFunction and UpdateFunctionConfiguration now check lambda:GetLayerVersion on each layer version their Layers give, and a request giving none is not checked as it; no other operation changes. --verify reports an operation checked so whose action the Service Reference stops listing (verify_api_actions). CreateFunction is the first operation checked by parts that also tags what it creates, so IamEnforcementFilter now checks an operation's own action, where it is one of the parts, as it would be alone: with the request's tags (aws:RequestTag, aws:TagKeys) and carried values, not the bare part context. The checks made after it, the tagging action a create also needs, a companion and a forwarded action, are made on the resources that action was checked on, not on *, so lambda:TagResource is again checked on the function a tagged create makes. Another account's layer version is checked on its ARN alone: LambdaStoredResourceArns answers reachedInItsAccount for it, as Lambda reads such a layer in its owner's account through the owner's policy and never as the caller's layer of that name, where IAM also checked the caller's same-named layer before (GetLayerVersionByArn too). The table is regenerated against today's Service Reference too, which the online gate this change runs requires: AWS added SageMaker's leaderboard and model-monitor-config types (their ARN formats and tag keys, and the types of AddTags, DeleteTags and ListTags) and lists a backup-external namespace the table does not read. The docs and two comments in LambdaService and LambdaLayerService no longer say Floci implements no layer permissions.
138 lines
6.2 KiB
Python
138 lines
6.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Vendor what the AWS Lambda Developer Guide says adding a layer to a function needs into
|
|
tools/aws/sources/lambda-layer-permissions.json, a source of the IAM tables.
|
|
|
|
The Service Reference lists lambda:GetLayerVersion among the actions CreateFunction and UpdateFunctionConfiguration
|
|
are authorized by, without saying what it is checked on, and botocore does not say it either. The guide's page on
|
|
adding layers does, at the head of its section:
|
|
|
|
Make sure that you have permission to call the GetLayerVersion API on the layer version. For Event Functions in
|
|
your AWS account, you must have this permission in your user policy. To use a layer in another account, the owner
|
|
of that account must grant your account permission in a resource-based policy.
|
|
|
|
https://docs.aws.amazon.com/lambda/latest/dg/adding-layers.html
|
|
|
|
This script copies that paragraph as it stands, with the action each sentence of it naming an API gives and the
|
|
resource it gives it on ("the GetLayerVersion API on the layer version": lambda:GetLayerVersion, on the layer
|
|
version). A sentence asking for permission to call an API 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 resource types and botocore's requests.
|
|
|
|
Run from anywhere in the repo:
|
|
python3 tools/aws/fetch_lambda_layer_permissions.py # rewrite the vendored file
|
|
python3 tools/aws/fetch_lambda_layer_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
|
|
|
|
PAGE = "https://docs.aws.amazon.com/lambda/latest/dg/adding-layers.html"
|
|
REPO_ROOT = Path(__file__).resolve().parents[2]
|
|
OUTPUT = REPO_ROOT / "tools/aws/sources/lambda-layer-permissions.json"
|
|
NAMESPACE = "lambda"
|
|
|
|
# A sentence asking for permission to call an API, and the wording the page gives it in: the API and the resource.
|
|
ASKS_RE = re.compile(r"\bpermission to call the\b")
|
|
API_RE = re.compile(r"^Make sure that you have permission to call the (?P<api>[A-Z][A-Za-z]+) API on the "
|
|
r"(?P<words>[a-z]+(?: [a-z]+)*)\.$")
|
|
SENTENCE_RE = re.compile(r"(?<=\.)\s+(?=[A-Z])")
|
|
|
|
|
|
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 read_permissions(page: str) -> list[dict]:
|
|
"""Each paragraph asking for permission to call an API, as it stands, with the action and the resource each such
|
|
sentence of it gives."""
|
|
found = []
|
|
for paragraph in re.findall(r"<p>(.*?)</p>", body(page), re.S):
|
|
said = text(paragraph)
|
|
if not ASKS_RE.search(said):
|
|
continue
|
|
for sentence in SENTENCE_RE.split(said):
|
|
if not ASKS_RE.search(sentence):
|
|
continue
|
|
matched = API_RE.match(sentence)
|
|
if matched is None:
|
|
raise ValueError(f"{PAGE} says '{sentence}', which asks for permission to call an API in no wording "
|
|
f"it used: its wording changed")
|
|
found.append({"paragraph": said, "sentence": sentence,
|
|
"action": f"{NAMESPACE}:{matched.group('api')}", "on": matched.group("words")})
|
|
if not found:
|
|
raise ValueError(f"{PAGE} asks for permission to call no API: its layout or wording changed")
|
|
return found
|
|
|
|
|
|
def build(page: str) -> dict:
|
|
return {
|
|
"_source": {
|
|
"pages": [PAGE],
|
|
"fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)),
|
|
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
|
"note": "Each sentence of the adding-layers page asking for permission to call an API, copied as it "
|
|
"stands with its paragraph, with the action it names and the resource it names it on.",
|
|
},
|
|
"apiPermissions": read_permissions(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]:
|
|
"""The adding-layers page."""
|
|
return (fetch(PAGE),)
|
|
|
|
|
|
def stale(vendored: dict, page: str) -> bool:
|
|
"""Whether the page now gives something other than the vendored file, its date aside."""
|
|
built = build(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 page")
|
|
args = parser.parse_args(argv)
|
|
try:
|
|
(page,) = fetch_all(fetch)
|
|
except OSError as e:
|
|
print(f"error: could not read the AWS Lambda Developer Guide ({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 AWS Lambda Developer Guide does: "
|
|
f"run tools/aws/fetch_lambda_layer_permissions.py and then make iam-request-resources-sync",
|
|
file=sys.stderr)
|
|
return 1
|
|
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the AWS Lambda Developer Guide")
|
|
return 0
|
|
built = build(page)
|
|
OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8")
|
|
print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['apiPermissions'])} permissions)")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|