mirror of
https://github.com/floci-io/floci.git
synced 2026-12-03 10:17:48 -05:00
#9743 read which queue each action of a message move task is checked on from two parameter sentences of the API reference picked one by one (SourceArn's "only ARNs of dead-letter queues (DLQs)", DestinationArn's "specify the destination queue"), a list of the three operations' pages, and a reading of its own for ListMessageMoveTasks: a queue no parameter named was the one the row named the operation's own action of. The developer guide's steps to configure a redrive's minimum permissions group the actions by queue instead: "Permissions for the DLQ (source queue): sqs:StartMessageMoveTask, ..., sqs:ReceiveMessage, sqs:DeleteMessage, sqs:GetQueueAttributes" and "Permissions for destination queue: sqs:SendMessage". The fetcher now copies those groups, and group_permission_resources places each action the Service Reference lists an operation as authorized by on the queue its group names, the member of the request the group's words name as the generator's names go (the source queue is SourceArn, the destination queue DestinationArn), as CodeArtifact's destination repository is its destinationRepository. The parameter sentences, the list of operations and the own-queue reading are gone. The table is unchanged.
146 lines
7.1 KiB
Python
146 lines
7.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Vendor what the Amazon SQS developer guide says a dead-letter queue redrive is checked as into
|
|
tools/aws/sources/sqs-redrive-permissions.json, a source of the IAM tables.
|
|
|
|
The Service Reference lists the actions each message move task operation is authorized by, StartMessageMoveTask by
|
|
sqs:StartMessageMoveTask, sqs:ReceiveMessage, sqs:DeleteMessage, sqs:GetQueueAttributes and sqs:SendMessage, without
|
|
saying which queue of the request each is checked on, and botocore does not say it either. The developer guide's
|
|
steps to configure a redrive's minimum permissions do, a group of permissions for each queue:
|
|
|
|
Permissions for the DLQ (source queue): sqs:StartMessageMoveTask, sqs:CancelMessageMoveTask,
|
|
sqs:ListMessageMoveTasks, sqs:ReceiveMessage, sqs:DeleteMessage, sqs:GetQueueAttributes,
|
|
sqs:ListDeadLetterSourceQueues. Specify the Resource ARN of the DLQ (source queue).
|
|
|
|
Permissions for destination queue: sqs:SendMessage. Specify the Resource ARN of the destination queue.
|
|
|
|
https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-configure-dead-letter-queue-redrive.html
|
|
|
|
This script copies each group as it stands, with the steps it is in, the resource its heading names (the words in
|
|
its parentheses where it has them, "source queue") and each action it lists. Nothing in the output is written by hand,
|
|
and the generator reads it against the Service Reference's authorized actions and botocore's requests.
|
|
|
|
Run from anywhere in the repo:
|
|
python3 tools/aws/fetch_sqs_redrive_permissions.py # rewrite the vendored file from the page
|
|
python3 tools/aws/fetch_sqs_redrive_permissions.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
|
|
|
|
GUIDE_PAGE = ("https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/"
|
|
"sqs-configure-dead-letter-queue-redrive.html")
|
|
REPO_ROOT = Path(__file__).resolve().parents[2]
|
|
OUTPUT = REPO_ROOT / "tools/aws/sources/sqs-redrive-permissions.json"
|
|
|
|
# A group's heading, naming the resource its permissions are of: "Permissions for the DLQ (source queue):",
|
|
# "Permissions for destination queue:".
|
|
HEADING_RE = re.compile(r"^Permissions for (?:the )?(?:[A-Z]+ \((?P<named>[^)]+)\)|(?P<plain>[^():]+)):$")
|
|
# A group: a list item whose first paragraph is its heading, then the list of what it holds.
|
|
GROUP_RE = re.compile(r'<li class="listitem">\s*<p>(?P<heading>(?:(?!</p>).)*)</p>\s*<div class="itemizedlist">\s*'
|
|
r'<ul class="itemizedlist">(?P<items>.*?)</ul>', re.S)
|
|
# A heading of the page, which says what the groups after it are for.
|
|
SECTION_RE = re.compile(r"<h[1-6][^>]*>(?P<title>.*?)</h[1-6]>", re.S)
|
|
# An action an item of a group lists, alone in its code element.
|
|
ACTION_RE = re.compile(r'<li class="listitem">\s*<p>\s*<code class="code">(?P<action>[a-z0-9-]+:[A-Za-z]+)</code>')
|
|
|
|
|
|
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_groups(page: str) -> list[dict]:
|
|
"""Each group of permissions the guide's steps give, with the steps it is in, the resource its heading names and
|
|
each action it lists, in the page's order."""
|
|
content = body(page)
|
|
sections = [(found.start(), text(found.group("title"))) for found in SECTION_RE.finditer(content)]
|
|
groups = []
|
|
for group in GROUP_RE.finditer(content):
|
|
heading = text(group.group("heading"))
|
|
named = HEADING_RE.match(heading)
|
|
if named is None:
|
|
continue
|
|
actions = [found.group("action") for found in ACTION_RE.finditer(group.group("items"))]
|
|
if not actions:
|
|
raise ValueError(f"{GUIDE_PAGE} gives '{heading}' with no action: its layout changed")
|
|
section = next((title for start, title in reversed(sections) if start < group.start()), None)
|
|
groups.append({"section": section, "heading": heading,
|
|
"resource": named.group("named") or named.group("plain"), "actions": actions})
|
|
if not any(action.startswith("sqs:") for group in groups for action in group["actions"]):
|
|
raise ValueError(f"{GUIDE_PAGE} gives no group of sqs: permissions for a queue: its layout or its wording "
|
|
f"changed")
|
|
return groups
|
|
|
|
|
|
def build(guide_page: str) -> dict:
|
|
return {
|
|
"_source": {
|
|
"pages": [GUIDE_PAGE],
|
|
"fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)),
|
|
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
|
"note": "Each group of permissions the developer guide's steps to configure a dead-letter queue redrive "
|
|
"give, copied as it stands, with the steps it is in, the resource its heading names and each "
|
|
"action it lists.",
|
|
},
|
|
"groups": read_groups(guide_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 guide's page."""
|
|
return (fetch(GUIDE_PAGE),)
|
|
|
|
|
|
def stale(vendored: dict, guide_page: str) -> bool:
|
|
"""Whether the page now gives something other than the vendored file, its date aside."""
|
|
built = build(guide_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:
|
|
pages = fetch_all(fetch)
|
|
except OSError as e:
|
|
print(f"error: could not read the Amazon SQS developer guide ({e})", file=sys.stderr)
|
|
return 2
|
|
if args.verify:
|
|
vendored = json.loads(OUTPUT.read_text(encoding="utf-8"))
|
|
if stale(vendored, *pages):
|
|
print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the Amazon SQS developer guide does: "
|
|
f"run tools/aws/fetch_sqs_redrive_permissions.py and then make iam-request-resources-sync",
|
|
file=sys.stderr)
|
|
return 1
|
|
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the Amazon SQS developer guide")
|
|
return 0
|
|
built = build(*pages)
|
|
OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8")
|
|
print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['groups'])} groups)")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|