mirror of
https://github.com/floci-io/floci.git
synced 2026-12-06 03:28:18 -05:00
Under IAM enforcement a VPC peering request carried neither key, so a policy scoped by either side of the peering refused what it should allow. Each key is now the ARN of the VPC on that side, in its own Region and account: from the connection EC2 holds for Accept, Reject, Delete and ModifyVpcPeeringConnectionOptions, and from the request for the connection CreateVpcPeeringConnection makes. The generator reads an ARN key named as another type with a word before it from the structure member that begins with the key's name, opted in for EC2. Create's parameters are joined to the record's sides by AWS's own sample request and response on the API reference page, vendored by tools/aws/fetch_ec2_request_samples.py. Closes #8366
134 lines
5.4 KiB
Python
134 lines
5.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Copy the sample requests and their sample responses from pages of the EC2 API reference.
|
|
|
|
Each page's examples give a Query request ("Sample Request") and, for some, what EC2 answered to it ("Sample
|
|
Response"). A request directly followed by its response is copied as a pair: the request's parameters with their
|
|
values, and every leaf of the response with its XML element path. The generator joins a request parameter to the
|
|
member of the record the request makes that holds the same value in AWS's own sample, which botocore does not say
|
|
(`CreateVpcPeeringConnection`'s `PeerVpcId` is the accepter VPC's id, documented only as "The ID of the VPC with which
|
|
you are creating the VPC peering connection"). The fetched data says nothing of its own about any parameter.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import html
|
|
import json
|
|
import re
|
|
import sys
|
|
import urllib.parse
|
|
import urllib.request
|
|
import xml.etree.ElementTree as ET
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
REPO_ROOT = Path(__file__).resolve().parents[2]
|
|
OUTPUT = REPO_ROOT / "tools/aws/sources/ec2-request-samples.json"
|
|
PAGES = {"CreateVpcPeeringConnection":
|
|
"https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVpcPeeringConnection.html"}
|
|
# Query parameters every EC2 request carries, which name nothing of the operation's own.
|
|
COMMON_PARAMETERS = {"Action", "Version"}
|
|
|
|
|
|
def _blocks(page: str) -> list[str]:
|
|
return [html.unescape(re.sub(r"<[^>]+>", "", block)).strip()
|
|
for block in re.findall(r"<pre\b[^>]*>(.*?)</pre>", page, re.S)]
|
|
|
|
|
|
def _request(operation: str, text: str) -> dict[str, str] | None:
|
|
"""The parameters of a sample Query request for `operation`, or None when the block is not one."""
|
|
joined = "".join(line.strip() for line in text.splitlines())
|
|
if not joined.startswith("https://"):
|
|
return None
|
|
query = urllib.parse.urlsplit(joined).query
|
|
parameters = dict(urllib.parse.parse_qsl(query, keep_blank_values=True))
|
|
if parameters.get("Action") != operation:
|
|
return None
|
|
return {name: value for name, value in parameters.items()
|
|
if name not in COMMON_PARAMETERS and name != "AUTHPARAMS" and value != ""}
|
|
|
|
|
|
def _response(operation: str, text: str) -> list[dict] | None:
|
|
"""Every leaf of a sample response to `operation`, with its element path below the root, or None when the block
|
|
is not one."""
|
|
if not re.match(r"<" + re.escape(operation) + r"Response(?:\s|>)", text):
|
|
return None
|
|
try:
|
|
root = ET.fromstring(text)
|
|
except ET.ParseError as error:
|
|
raise ValueError(f"{operation} has a malformed XML response example") from error
|
|
leaves = []
|
|
|
|
def walk(node: ET.Element, path: list[str]) -> None:
|
|
if not len(node) and (node.text or "").strip():
|
|
leaves.append({"path": path, "value": node.text.strip()})
|
|
for child in node:
|
|
walk(child, path + [child.tag.rsplit("}", 1)[-1]])
|
|
|
|
walk(root, [])
|
|
return leaves
|
|
|
|
|
|
def read_samples(operation: str, page: str) -> list[dict]:
|
|
"""Each sample request of `operation` the page follows with its sample response, in the page's order."""
|
|
samples = []
|
|
blocks = _blocks(page)
|
|
for index, text in enumerate(blocks[:-1]):
|
|
request = _request(operation, text)
|
|
response = _response(operation, blocks[index + 1]) if request is not None else None
|
|
if request and response:
|
|
samples.append({"request": request, "response": response})
|
|
if not samples:
|
|
raise ValueError(f"{operation} has no sample request followed by its response: the page layout changed")
|
|
return samples
|
|
|
|
|
|
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 build(pages: dict[str, str]) -> dict:
|
|
return {
|
|
"_source": {"fetcher": "tools/aws/fetch_ec2_request_samples.py",
|
|
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
|
"pages": list(PAGES.values())},
|
|
"namespace": "ec2",
|
|
"operations": {operation: {"page": url, "samples": read_samples(operation, pages[url])}
|
|
for operation, url in PAGES.items()},
|
|
}
|
|
|
|
|
|
def stale(vendored: dict, pages: dict[str, str]) -> bool:
|
|
built = build(pages)
|
|
return any(vendored.get(key) != built[key] for key in ("namespace", "operations"))
|
|
|
|
|
|
def fetch_all(fetch=None) -> tuple[dict[str, str]]:
|
|
fetch = fetch or fetch_url
|
|
return ({url: fetch(url) for url in PAGES.values()},)
|
|
|
|
|
|
def main(argv: list[str] | None = None, fetch=fetch_url) -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--verify", action="store_true")
|
|
args = parser.parse_args(argv)
|
|
try:
|
|
pages, = fetch_all(fetch)
|
|
result = build(pages)
|
|
if args.verify:
|
|
if stale(json.loads(OUTPUT.read_text()), pages):
|
|
print("error: EC2 request samples changed; rerun tools/aws/fetch_ec2_request_samples.py",
|
|
file=sys.stderr)
|
|
return 1
|
|
else:
|
|
OUTPUT.write_text(json.dumps(result, indent=2) + "\n")
|
|
except (OSError, ValueError, ET.ParseError) as error:
|
|
print(f"error: could not read EC2 request samples ({error})", file=sys.stderr)
|
|
return 2
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|