mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
The Service Reference ends every DMS resource type's ARN format in a wildcard where the resource goes
(arn:${Partition}:dms:${Region}:${Account}:endpoint:*), which the table reader matches as written, so no DMS request
was checked on the resource it names: one naming an endpoint, an instance or a task by its ARN stayed on *, and no
aws:ResourceTag condition on a DMS resource could match.
The DMS User Guide gives what goes there: "An ARN for an AWS DMS resource uses the following syntax:
arn:aws:dms:region:account number:resourcetype:resourcename". tools/aws/fetch_dms_arn_formats.py vendors that page
(the syntax, the sentence saying what its resource name is, and its table of formats) into
tools/aws/sources/dms-arn-formats.json, pairs the syntax with each Service Reference DMS format ending in a wildcard
by its resource type, and writes that format with the page's placeholder where the wildcard was
(arn:${Partition}:dms:${Region}:${Account}:endpoint:${resourcename}). A reworded page, or a table row whose type no
such format has, is refused. regen_iam_request_resources.py takes those formats as they stand (ARN_FORMAT_SOURCES,
granted for dms alone), each checked to differ from the Service Reference's only where its wildcard was, and verifies
the source against the live pages beside the other vendored sources.
The generator's existing machinery then names a DMS resource by the ARN a request passes, or fills the format from
the identifier a request names it by. DmsStoredResourceArns finds such an identifier, or an ARN DMS holds, as DMS
stores it (an endpoint's, an instance's or a task's ARN ends in the id DMS minted, not in its identifier; one stored before keys carried the account is the default account's and found too), and reads
the tags of an endpoint, instance, task or subnet group for aws:ResourceTag, both in place. A subnet group's ARN
ends in its identifier as DMS stores it, in lower case ("This value is stored as a lowercase string"), so the reader
resolves an ARN naming one in another case to that one (resolveStoredArn). A request leaving out
an optional ARN names the resource DMS uses for one naming none, of which it has none. A replication instance whose create
names no subnet group goes into the account's default replication subnet group, so the reader answers that group as
the one such a create acts on (findImplicitDefault), and the create is checked on subgrp:default.
The fetcher also copies what AWS answers each DMS create with, from AWS's recorded exchanges with DMS (the AWS
Emulator evaluation suite's wire tests, "a recorded exchange with AWS") and botocore's examples: whether the ARN of
what the create makes ends in a member of its request (a subnet group's in its ReplicationSubnetGroupIdentifier, an
event subscription's in its SubscriptionName) or in a value the request does not give (an endpoint's, an instance's,
a task's, a certificate's: botocore's example answers EndpointIdentifier "test-endpoint-1" with
endpoint:RAAR3R22XSH46S3PWLC3NJAWKM). The generator's rule for a variable a create's response answers, which stays open
whatever member a rule would fill it from, reads that too (with_recorded_mints), both for what a create is checked
on and for what its tags are checked on: CreateEndpoint, CreateReplicationInstance and ImportCertificate are checked on
what they make with its id open (rep:*), the tags of CreateReplicationTask, CreateDataProvider and
CreateInstanceProfile on what they make likewise, and no other row of the table changes. The creates of data
migrations, migration projects, replication configs and assessment runs have no recorded answer and keep their
fills. A modify renaming an instance is still checked on rep:<new name> beside its own ARN, nothing
being recorded for it.
The regeneration also takes the Service Reference's new SageMaker candidate, leaderboard and model monitor config
actions.
298 lines
17 KiB
Python
298 lines
17 KiB
Python
#!/usr/bin/env python3
|
|
"""Vendor what the AWS DMS User Guide says a DMS ARN is into tools/aws/sources/dms-arn-formats.json, a source of the
|
|
IAM tables.
|
|
|
|
The Service Reference gives every DMS resource type an ARN format ending in a wildcard where the resource goes
|
|
(`arn:${Partition}:dms:${Region}:${Account}:endpoint:*`), which no ARN a request names matches as written, so no DMS
|
|
action is checked on the resource its request names. The User Guide's page on DMS ARNs says what goes there:
|
|
|
|
An ARN for an AWS DMS resource uses the following syntax:
|
|
|
|
arn:aws:dms:region:account number:resourcetype:resourcename
|
|
|
|
resourcename is the resource name assigned to the AWS DMS resource. This is a generated arbitrary string.
|
|
|
|
https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Introduction.AWS.ARN.html
|
|
|
|
This script copies that syntax, the sentence saying what its resource name is and the page's table of ARN formats, as
|
|
they stand, and pairs the syntax with each DMS format of the Service Reference whose resource is a resource type and a
|
|
wildcard, by that resource type (the syntax's `resourcetype`): the format it writes is the Service Reference's, with
|
|
the page's placeholder for the resource name where the wildcard was
|
|
(`arn:${Partition}:dms:${Region}:${Account}:endpoint:${resourcename}`). A page whose syntax or table reads any other
|
|
way is refused, as is a row of the table whose resource type no such format has, so a reworded page, or a reference
|
|
that no longer agrees with it, fails rather than giving a format. Nothing in the output is written by hand, and the
|
|
generator takes the formats as they stand, for DMS alone.
|
|
|
|
It also copies what AWS answers a DMS create with: AWS's recorded exchanges with DMS (the AWS Emulator evaluation
|
|
suite's wire tests, "a recorded exchange with AWS") and botocore's examples of DMS requests. For each create that
|
|
answers the ARN of the type named as the operation is past its verb (CreateEndpoint, an Endpoint), it records whether
|
|
that ARN ends in the value of a member of the request (a subnet group's in its ReplicationSubnetGroupIdentifier,
|
|
asserted as `subgrp:{{subnet_group_id}}`) or in one no member of the request gives (an endpoint's: the recording leaves
|
|
it unasserted, and botocore's example answers `EndpointIdentifier` "test-endpoint-1" with
|
|
`endpoint:RAAR3R22XSH46S3PWLC3NJAWKM`), each with the request and the answer it rests on. A create the evidence gives
|
|
both ways is refused.
|
|
|
|
Run from anywhere in the repo:
|
|
python3 tools/aws/fetch_dms_arn_formats.py # rewrite the vendored file
|
|
python3 tools/aws/fetch_dms_arn_formats.py --verify # online: the file still says what the pages do
|
|
"""
|
|
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/dms/latest/userguide/CHAP_Introduction.AWS.ARN.html"
|
|
REFERENCE = "https://servicereference.us-east-1.amazonaws.com/v1/dms/dms.json"
|
|
REPO_ROOT = Path(__file__).resolve().parents[2]
|
|
OUTPUT = REPO_ROOT / "tools/aws/sources/dms-arn-formats.json"
|
|
|
|
# The sentence introducing the syntax, and the syntax as the page writes it, its placeholders in angle brackets.
|
|
SYNTAX_SENTENCE = "An ARN for an AWS DMS resource uses the following syntax:"
|
|
SYNTAX_RE = re.compile(r"^arn:aws:dms:<region>:<account number>:<resourcetype>:<(?P<name>[a-z]+)>$")
|
|
# A row of the page's table of formats: a resource type and its resource name.
|
|
ROW_RE = re.compile(r"^arn:aws:dms:<region>:<account>:(?P<type>[a-z][a-z-]*):<(?P<name>[a-z]+)>$")
|
|
# A Service Reference DMS format whose resource is a resource type and a wildcard.
|
|
WILDCARD_RE = re.compile(r"^(?P<prefix>arn:\$\{Partition}:dms:\$\{Region}:\$\{Account}:(?P<type>[a-z][a-z-]*):)\*$")
|
|
# AWS's recorded exchanges with DMS whose creates answer the ARN of what they make, and botocore's examples of DMS
|
|
# requests, at the botocore version tools/aws/requirements.txt pins.
|
|
WIRE = "https://raw.githubusercontent.com/aws/aws-emulator-evaluation-suite/main/wire/dms/"
|
|
WIRE_TESTS = ("b1-endpoint-lifecycle", "data-provider-lifecycle", "endpoint-delete-identifier-release",
|
|
"event-subscription-certificate-and-account-reads", "instance-profile-and-subnet-group-lifecycle",
|
|
"subnet-group-tags-and-repeated-delete")
|
|
REQUIREMENTS = REPO_ROOT / "tools/aws/requirements.txt"
|
|
# A create, and the type it makes: the operation past its verb.
|
|
CREATE_RE = re.compile(r"^(?:Create|Import)(?P<type>[A-Z][A-Za-z]+)$")
|
|
# What a recording answers for a value it does not tie to the request, and the ARN it asserts from a request's value.
|
|
NOT_ASSERTED = "<shaped-not-asserted>"
|
|
ASSERTED_RE = re.compile(r"^arn:aws:dms:\{\{region}}:\{\{account}}:[a-z][a-z-]*:(?P<value>\{\{\w+}})$")
|
|
# An example's ARN, and the name it ends in.
|
|
EXAMPLE_ARN_RE = re.compile(r"^arn:aws:dms:[a-z0-9-]+:[0-9]{12}:[a-z][a-z-]*:(?P<value>[^:]+)$")
|
|
|
|
|
|
def text(fragment: str) -> str:
|
|
"""A fragment of a page as text, spaces collapsed."""
|
|
return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip()
|
|
|
|
|
|
def template(fragment: str) -> str:
|
|
"""A code fragment of the page with each placeholder it marks replaceable in angle brackets and no space left
|
|
around the colons the markup breaks lines at: `arn:aws:dms:<region>:<account>:rep:<resourcename>`."""
|
|
marked = re.sub(r'<code class="replaceable">(.*?)</code>', lambda m: "\0" + text(m.group(1)) + "\1", fragment,
|
|
flags=re.S)
|
|
return re.sub(r"\s*:\s*", ":", text(marked)).replace("\0", "<").replace("\1", ">")
|
|
|
|
|
|
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_page(page: str) -> dict:
|
|
"""The syntax the page gives a DMS ARN, the sentence saying what its resource name is, and its table of formats."""
|
|
content = body(page)
|
|
found = re.search(r"<p>\s*" + re.escape(SYNTAX_SENTENCE) + r"\s*</p>\s*<p>\s*(?P<code><code class=\"code\">.*?)"
|
|
r"</p>", content, re.S)
|
|
if found is None:
|
|
raise ValueError(f"{PAGE} no longer says '{SYNTAX_SENTENCE}' before a syntax: its wording or layout changed")
|
|
syntax = template(found.group("code"))
|
|
matched = SYNTAX_RE.match(syntax)
|
|
if matched is None:
|
|
raise ValueError(f"{PAGE} gives the syntax '{syntax}', in no shape it used: its wording changed")
|
|
name = matched.group("name")
|
|
sentences = [text(p) for p in re.findall(r"<p>(.*?)</p>", content, re.S)]
|
|
said = next((s for s in sentences if s.startswith(f"{name} is the resource name assigned to the AWS DMS resource")),
|
|
None)
|
|
if said is None:
|
|
raise ValueError(f"{PAGE} no longer says what {name} is: its wording changed")
|
|
table = re.search(r"<th>\s*AWS DMS resource type\s*</th>\s*<th>\s*ARN format\s*</th>(?P<rows>.*?)</table>",
|
|
content, re.S)
|
|
if table is None:
|
|
raise ValueError(f"{PAGE} has no table of AWS DMS resource types and their ARN formats: its layout changed")
|
|
rows = []
|
|
for kind, code in re.findall(r"<tr>\s*<td[^>]*>(.*?)</td>\s*<td[^>]*>(.*?)</td>\s*</tr>", table.group("rows"),
|
|
re.S):
|
|
written = template(code)
|
|
row = ROW_RE.match(written)
|
|
if row is None or row.group("name") != name:
|
|
raise ValueError(f"{PAGE} gives {text(kind)} the format '{written}', in no shape its syntax has: its "
|
|
f"wording changed")
|
|
rows.append({"resourceType": text(kind), "format": written})
|
|
if not rows:
|
|
raise ValueError(f"{PAGE} lists no resource type: its layout changed")
|
|
return {"syntax": {"sentence": SYNTAX_SENTENCE, "format": syntax}, "resourceName": said, "table": rows}
|
|
|
|
|
|
def arn_formats(said: dict, reference: dict) -> dict[str, str]:
|
|
"""Each DMS resource type whose Service Reference format ends in a wildcard where the syntax has the resource name,
|
|
as that format with the page's placeholder for the name there; a row of the page's table whose resource type no such
|
|
format has is refused."""
|
|
name = SYNTAX_RE.match(said["syntax"]["format"]).group("name")
|
|
formats, types = {}, set()
|
|
for resource in reference.get("Resources", []):
|
|
written = (resource.get("ARNFormats") or [""])[0]
|
|
wildcard = WILDCARD_RE.match(written)
|
|
if wildcard is not None:
|
|
formats[resource["Name"]] = wildcard.group("prefix") + "${" + name + "}"
|
|
types.add(wildcard.group("type"))
|
|
for row in said["table"]:
|
|
kind = ROW_RE.match(row["format"]).group("type")
|
|
if kind not in types:
|
|
raise ValueError(f"{PAGE} gives {row['resourceType']} the resource type {kind}, which no format of "
|
|
f"{REFERENCE} ending in a wildcard has: the page and the reference no longer agree")
|
|
if not formats:
|
|
raise ValueError(f"{REFERENCE} gives no DMS format ending in a wildcard")
|
|
return dict(sorted(formats.items()))
|
|
|
|
|
|
def _naming(request: dict) -> dict[str, str]:
|
|
"""The members of a request that name something, as an identifier or a name."""
|
|
return {member: value for member, value in sorted(request.items())
|
|
if isinstance(value, str) and re.search(r"(Identifier|Name)$", member)}
|
|
|
|
|
|
def create_answers(types: set[str], recordings: list[tuple[str, str]], examples: tuple[str, str]) -> dict:
|
|
"""Each DMS create that AWS's recorded exchanges or botocore's examples show answering the ARN of the type named as
|
|
the operation is past its verb, with what that ARN ends in: the value of one member of the request (`named`), or
|
|
a value no member of the request gives (`minted`), and the request and the answer each rests on. A create the
|
|
evidence gives both ways is refused."""
|
|
found: dict[str, dict] = {}
|
|
|
|
def add(operation: str, kind: str, how: str, member: str | None, evidence: dict) -> None:
|
|
entry = found.setdefault(operation, {"type": kind, "arn": how, **({"member": member} if member else {}),
|
|
"evidence": []})
|
|
if entry["arn"] != how or entry.get("member") != member:
|
|
raise ValueError(f"AWS's evidence answers {operation} both with an ARN in {entry.get('member') or 'a value '
|
|
f'the request does not give'} and in {member or 'a value the request does not give'}")
|
|
entry["evidence"].append(evidence)
|
|
|
|
for url, text in recordings:
|
|
for step in json.loads(text).get("steps", []):
|
|
created = CREATE_RE.match(step.get("operation", ""))
|
|
output = step.get("output") or {}
|
|
if step.get("service") != "dms" or created is None or created.group("type") not in types \
|
|
or output.get("status") != 200:
|
|
continue
|
|
kind = created.group("type")
|
|
answered = (output.get("body") or {}).get(kind) or {}
|
|
value = answered.get(kind + "Arn") if isinstance(answered, dict) else None
|
|
if value is None:
|
|
continue
|
|
request = (step.get("input") or {}).get("body") or {}
|
|
if value == NOT_ASSERTED:
|
|
how, member = "minted", None
|
|
else:
|
|
asserted = ASSERTED_RE.match(value)
|
|
members = [m for m, v in request.items() if asserted and v == asserted.group("value")]
|
|
if len(members) != 1:
|
|
raise ValueError(f"{url} answers {step['operation']} with {value}, which ends in no one member of "
|
|
f"its request: its shape changed")
|
|
how, member = "named", members[0]
|
|
add(step["operation"], kind, how, member,
|
|
{"source": url, "request": _naming(request), "answered": {kind + "Arn": value}})
|
|
url, text = examples
|
|
for operation, shown in sorted(json.loads(text).get("examples", {}).items()):
|
|
created = CREATE_RE.match(operation)
|
|
if created is None or created.group("type") not in types:
|
|
continue
|
|
kind = created.group("type")
|
|
for example in shown:
|
|
answered = (example.get("output") or {}).get(kind) or {}
|
|
value = answered.get(kind + "Arn") if isinstance(answered, dict) else None
|
|
arn = EXAMPLE_ARN_RE.match(value or "")
|
|
if arn is None:
|
|
continue
|
|
request = example.get("input") or {}
|
|
members = [m for m, v in request.items() if isinstance(v, str) and v == arn.group("value")]
|
|
member = members[0] if len(members) == 1 else None
|
|
add(operation, kind, "named" if member else "minted", member,
|
|
{"source": url, "request": _naming(request), "answered": {kind + "Arn": value}})
|
|
return dict(sorted(found.items()))
|
|
|
|
|
|
def build(page: str, reference: str, examples: str = "", *recordings: str) -> dict:
|
|
said = read_page(page)
|
|
document = json.loads(reference)
|
|
types = {resource["Name"] for resource in document.get("Resources", [])}
|
|
return {
|
|
"_source": {
|
|
"pages": [PAGE, REFERENCE, examples_url(), *wire_urls()],
|
|
"fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)),
|
|
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
|
"note": "The User Guide's syntax of a DMS ARN, the sentence saying what its resource name is and its "
|
|
"table of formats, copied as they stand; each Service Reference DMS format ending in a wildcard "
|
|
"where the syntax has the resource name, with the page's placeholder for the name there; and what "
|
|
"AWS's recorded exchanges and botocore's examples answer each DMS create with, the ARN of what it "
|
|
"makes ending in a member of the request or in a value the request does not give.",
|
|
},
|
|
**said,
|
|
"arnFormats": arn_formats(said, document),
|
|
"creates": create_answers(types, list(zip(wire_urls(), recordings)), (examples_url(), examples or "{}")),
|
|
}
|
|
|
|
|
|
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 examples_url() -> str:
|
|
"""botocore's examples of DMS requests, at the version tools/aws/requirements.txt pins."""
|
|
version = re.search(r"^botocore==(\S+)$", REQUIREMENTS.read_text(encoding="utf-8"), re.M).group(1)
|
|
return f"https://raw.githubusercontent.com/boto/botocore/{version}/botocore/data/dms/2016-01-01/examples-1.json"
|
|
|
|
|
|
def wire_urls() -> list[str]:
|
|
"""AWS's recorded exchanges with DMS whose creates answer the ARN of what they make."""
|
|
return [f"{WIRE}{name}.json" for name in WIRE_TESTS]
|
|
|
|
|
|
def fetch_all(fetch=fetch_url) -> tuple[str, ...]:
|
|
"""The User Guide's page on DMS ARNs, the Service Reference's DMS document, botocore's DMS examples and AWS's
|
|
recorded exchanges with DMS."""
|
|
return (fetch(PAGE), fetch(REFERENCE), fetch(examples_url()), *(fetch(url) for url in wire_urls()))
|
|
|
|
|
|
def stale(vendored: dict, page: str, reference: str, examples: str = "", *recordings: str) -> bool:
|
|
"""Whether the pages now give something other than the vendored file, its date aside."""
|
|
built = build(page, reference, examples, *recordings)
|
|
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:
|
|
pages = fetch_all(fetch)
|
|
except OSError as e:
|
|
print(f"error: could not read the AWS DMS User Guide, the Service Reference, botocore's examples or "
|
|
f"AWS's recorded exchanges ({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 AWS DMS User Guide, the Service "
|
|
f"Reference, botocore's examples and AWS's recorded exchanges do: run "
|
|
f"tools/aws/fetch_dms_arn_formats.py and then make iam-request-resources-sync", file=sys.stderr)
|
|
return 1
|
|
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the AWS DMS User Guide, the Service Reference, botocore's "
|
|
f"examples and AWS's recorded exchanges")
|
|
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['arnFormats'])} formats, "
|
|
f"{len(built['creates'])} creates)")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|