diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.yml index 7b985b7ba3..61ca5c3c4c 100644 --- a/.github/workflows/iam-data-drift.yml +++ b/.github/workflows/iam-data-drift.yml @@ -9,7 +9,8 @@ name: IAM Data Drift # operation's request names, the DynamoDB condition key table, the IAM condition key table, the # S3 Control tag condition key table, and the request condition key table (Lambda Web and Redshift). It # also checks the routes rest-routes.json takes from the AWS page that documents an endpoint botocore does -# not model (Glue's Iceberg REST endpoint). That +# not model (Glue's Iceberg REST endpoint) and the legacy routes it takes from the botocore release whose +# model still gave them (SES v2's list GETs). That # needs the live service reference index, so unlike every other check here it can # fail without anything in the repository having changed: an AWS outage, or a namespace AWS has # retired. It therefore runs on its own, never as part of a job that ordinary changes trigger. diff --git a/Makefile b/Makefile index 232d39022e..8c974e8a2d 100644 --- a/Makefile +++ b/Makefile @@ -1022,10 +1022,12 @@ request-condition-keys-check: ## Check the request condition key members against request-condition-keys-verify: ## Check the request condition action keys against AWS $(PYTHON) tools/aws/regen_request_condition_keys.py --verify -.PHONY: documented-routes-sync documented-routes-verify +.PHONY: documented-routes-sync legacy-routes-sync documented-routes-verify documented-routes-sync: ## Read the REST routes AWS documents for endpoints botocore does not model again (commit the result) $(PYTHON) tools/aws/regen_rest_routes.py --fetch-documented -documented-routes-verify: ## CI gate (online): the vendored documented REST routes must still be the ones AWS's pages give +legacy-routes-sync: ## Read the legacy REST routes again from the botocore release each model's are read from (commit the result) + $(PYTHON) tools/aws/regen_rest_routes.py --fetch-legacy +documented-routes-verify: ## CI gate (online): the vendored documented and legacy REST routes must still be what their sources give $(PYTHON) tools/aws/regen_rest_routes.py --verify cloudtrail-s3-data-events-sync: ## Regenerate src/main/resources/aws/cloudtrail-s3-data-events.json (online; commit the result) diff --git a/docs/services/iam.md b/docs/services/iam.md index 270000b89b..d5b949a1df 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -2955,8 +2955,9 @@ endpoint is. Amazon SES v2's and Amazon Pinpoint Email's routes are checked by their routes, on the resources the table reads, as SES v1's Query requests are by their `Action`. Two `GET` routes an SDK built before botocore moved `ListConfigurationSets` and `ListEmailIdentities` to `POST /v2/email/list-configuration-sets` and `POST /v2/email/list-identities` still sends, -`GET /v2/email/configuration-sets` and `GET /v2/email/identities`, are served but match no route of the model, so -they are not checked. +`GET /v2/email/configuration-sets` and `GET /v2/email/identities`, are checked as the same actions. The generator +reads them from botocore 1.43.104's own model, which still gave them (`make legacy-routes-sync`), rather than +having them typed by hand. AWS AppConfig (with its data plane), AWS CodeArtifact and Amazon CodeGuru Reviewer are checked by their routes on the resources the table of request resources reads. Nine of AppConfig's operations act on a type the Service Authorization Reference marks required that diff --git a/docs/services/ses.md b/docs/services/ses.md index 9c6777d887..40dc3759bf 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -587,8 +587,8 @@ for its own API's members alone: a v1 `SendEmail` names its identity by its `Sou `FromEmailAddressIdentityArn`, and neither is read for the other's. A v2 templated send is checked on the template its `Content.Template` (`DefaultContent.Template` for `SendBulkEmail`) names by `TemplateName` or `TemplateArn`; one with inline `TemplateContent` names none. `ListConfigurationSets` and `ListEmailIdentities` are -`POST /v2/email/list-configuration-sets` and `POST /v2/email/list-identities` in the model; the `GET` routes -an SDK built before that still sends are served but match no route of the model, so they are not checked. +`POST /v2/email/list-configuration-sets` and `POST /v2/email/list-identities` in the model; an SDK built before +that move still sends the `GET` routes the model carried, and they are checked as the same actions. SES publishes to an SNS topic as `ses.amazonaws.com`, so the topic's policy decides whether it may, whatever the sender's own SNS permissions: an event destination's events with the configuration set's diff --git a/src/main/resources/aws/rest-routes.json b/src/main/resources/aws/rest-routes.json index 755b19f833..ff263cc692 100644 --- a/src/main/resources/aws/rest-routes.json +++ b/src/main/resources/aws/rest-routes.json @@ -3391,6 +3391,7 @@ "sesv2": { "credentialScope": "ses", "apiVersion": "2019-09-27", + "legacyRoutes": {"release": "1.43.104", "routes": {"ListConfigurationSets": [{"method": "GET", "requestUri": "/v2/email/configuration-sets"}], "ListEmailIdentities": [{"method": "GET", "requestUri": "/v2/email/identities"}]}, "retrieved": "2026-11-30"}, "operations": { "AssociateEmailIdentityCertificate": {"method": "POST", "requestUri": "/v2/email/identity/certificates"}, "BatchGetMetricData": {"method": "POST", "requestUri": "/v2/email/metrics/batch"}, @@ -3449,14 +3450,14 @@ "GetReputationEntity": {"method": "GET", "requestUri": "/v2/email/reputation/entities/{ReputationEntityType}/{ReputationEntityReference}"}, "GetSuppressedDestination": {"method": "GET", "requestUri": "/v2/email/suppression/addresses/{EmailAddress}"}, "GetTenant": {"method": "POST", "requestUri": "/v2/email/tenants/get"}, - "ListConfigurationSets": {"method": "POST", "requestUri": "/v2/email/list-configuration-sets"}, + "ListConfigurationSets": {"method": "POST", "requestUri": "/v2/email/list-configuration-sets", "alternatives": [{"method": "GET", "requestUri": "/v2/email/configuration-sets", "located": {}}]}, "ListContactLists": {"method": "GET", "requestUri": "/v2/email/contact-lists"}, "ListContacts": {"method": "POST", "requestUri": "/v2/email/contact-lists/{ContactListName}/contacts/list"}, "ListCustomVerificationEmailTemplates": {"method": "GET", "requestUri": "/v2/email/custom-verification-email-templates"}, "ListDedicatedIpPools": {"method": "GET", "requestUri": "/v2/email/dedicated-ip-pools"}, "ListDeliverabilityTestReports": {"method": "GET", "requestUri": "/v2/email/deliverability-dashboard/test-reports"}, "ListDomainDeliverabilityCampaigns": {"method": "GET", "requestUri": "/v2/email/deliverability-dashboard/domains/{SubscribedDomain}/campaigns"}, - "ListEmailIdentities": {"method": "POST", "requestUri": "/v2/email/list-identities"}, + "ListEmailIdentities": {"method": "POST", "requestUri": "/v2/email/list-identities", "alternatives": [{"method": "GET", "requestUri": "/v2/email/identities", "located": {}}]}, "ListEmailIdentityCertificates": {"method": "POST", "requestUri": "/v2/email/identity/certificates/list"}, "ListEmailTemplates": {"method": "GET", "requestUri": "/v2/email/templates"}, "ListExportJobs": {"method": "POST", "requestUri": "/v2/email/list-export-jobs"}, diff --git a/src/test/java/io/floci/aws/services/iam/IamActionRegistryTest.java b/src/test/java/io/floci/aws/services/iam/IamActionRegistryTest.java index 30f7c84f57..75de51ec86 100644 --- a/src/test/java/io/floci/aws/services/iam/IamActionRegistryTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamActionRegistryTest.java @@ -505,8 +505,9 @@ class IamActionRegistryTest { /** * SES v2 is routed by its vendored model, every route checked as its operation's action by the route coverage * test: a route names its whole path, not one below it. {@code ListConfigurationSets} is - * {@code POST /v2/email/list-configuration-sets} there; the {@code GET /v2/email/configuration-sets} an SDK built - * before the model moved it still sends matches no route, so it is not checked. + * {@code POST /v2/email/list-configuration-sets} there, and the {@code GET /v2/email/configuration-sets} an SDK + * built before the model moved it sends is its alternative, checked as the same action, as + * {@code GET /v2/email/identities} is of {@code ListEmailIdentities}. */ @Test void sesV2IsRoutedByItsModelsWholePaths() { @@ -519,9 +520,12 @@ class IamActionRegistryTest { assertNull(registry.resolve("ses", mockCtx("GET", "/v2/email/configuration-sets/my-set/unknown", new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}"))); - assertNull(registry.resolve("ses", + assertEquals("ses:ListConfigurationSets", registry.resolve("ses", mockCtx("GET", "/v2/email/configuration-sets", new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}"))); + assertEquals("ses:ListEmailIdentities", registry.resolve("ses", + mockCtx("GET", "/v2/email/identities", new MultivaluedHashMap<>(), + MediaType.APPLICATION_JSON_TYPE, "{}"))); } @Test diff --git a/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java index 367e0d4109..5567e62722 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java @@ -669,6 +669,26 @@ class IamRestRouteEnforcementIntegrationTest { return eksCluster(name, "{}"); } + /** + * The legacy GET routes an SDK built on the sesv2 model before it moved its list operations to the POST + * {@code /v2/email/list-*} routes still sends are checked as the same actions: a caller with no SES grant is + * refused, an allow on everything lists, and a deny on the action holds under an allow on everything. + */ + @Test + void aLegacySesListRouteIsCheckedAsItsOperationsAction() { + String user = user("route-ses-legacy-list"); + refused(as(user, "ses").get("/v2/email/identities").then(), "ses:ListEmailIdentities"); + refused(as(user, "ses").get("/v2/email/configuration-sets").then(), "ses:ListConfigurationSets"); + + policy(user, allow("ses:ListEmailIdentities", "*") + "," + allow("ses:ListConfigurationSets", "*")); + as(user, "ses").get("/v2/email/identities").then().statusCode(200); + as(user, "ses").get("/v2/email/configuration-sets").then().statusCode(200); + + policy(user, allow("ses:*", "*") + "," + deny("ses:ListEmailIdentities", "*")); + refused(as(user, "ses").get("/v2/email/identities").then(), "ses:ListEmailIdentities"); + as(user, "ses").get("/v2/email/configuration-sets").then().statusCode(200); + } + /** A cluster an administrator creates with {@code tags}, a JSON map, removed afterwards; its ARN. */ private String eksCluster(String name, String tags) { String arn = eks().body("{\"name\":\"" + name + "\",\"roleArn\":\"arn:aws:iam::" + ACCOUNT diff --git a/tools/aws/regen_rest_routes.py b/tools/aws/regen_rest_routes.py index 753d0aff3b..78575adae7 100644 --- a/tools/aws/regen_rest_routes.py +++ b/tools/aws/regen_rest_routes.py @@ -21,6 +21,11 @@ route requiring all a request carries being its operation (`shared_routes`). The otherwise. Supported shared-controller alternatives are generated beside the modeled URI, with member-location overrides for the bare route, and its own method where that is not the operation's. These alternatives describe existing Floci compatibility paths, not additional botocore operations. +A route SDKs built on an older botocore release still send beside the current one is a legacy alternative +(`LEGACY`), read from that release's own model rather than typed by hand: an operation both models hold, on +another route than the pinned model gives it, has the older route vendored as its alternative, checked as the +same action. Reading them needs the network, so a regeneration carries them over from the vendored file, +`--fetch-legacy` reads them again, and `--verify` checks the vendored ones against the release. The models are botocore's `//service-2.json` (Apache-2.0, https://github.com/boto/botocore), the latest API version of each, located as @@ -38,7 +43,8 @@ Run from anywhere in the repo: python3 tools/aws/regen_rest_routes.py # rewrite the vendored file in place python3 tools/aws/regen_rest_routes.py --check # exit 1 when the vendored file is stale python3 tools/aws/regen_rest_routes.py --fetch-documented # also read the documented endpoints again - python3 tools/aws/regen_rest_routes.py --verify # exit 1 when a documented endpoint's page differs + python3 tools/aws/regen_rest_routes.py --fetch-legacy # also read the legacy routes again + python3 tools/aws/regen_rest_routes.py --verify # exit 1 when a source differs from the vendored """ from __future__ import annotations @@ -144,6 +150,15 @@ DOCUMENTED: dict[str, dict[str, str]] = { }, } +# Each model and the botocore release whose model of it still carries the routes SDKs built before a later move +# send. Nothing here names a route: `build_legacy` reads the release's own model and takes, for an operation both +# models hold on different routes, the older one as its alternative. Botocore's sesv2 model moved its two list +# operations from their `GET` routes to the `POST /v2/email/list-*` ones between 1.43.104 and 1.43.105, and an SDK +# built on the model before that move sends the legacy `GET`s still. +LEGACY: dict[str, str] = { + "sesv2": "1.43.104", +} + # A definition link: https://github.com///blob//#L, the line of the operation's method. DEFINITION_LINK = re.compile(r"https://github\.com/([^/\s]+)/([^/\s]+)/blob/([^/\s]+)/(\S+?)\\?#L(\d+)") DEFINITION_METHOD = re.compile(r"^ (get|post|put|delete|head|patch|options):\s*$") @@ -260,10 +275,14 @@ def documented_route(page_route: str, defined_path: str) -> tuple[str, str, list return page_method, route, prefix, differs -def fetch_url(url: str) -> str: +def fetch_bytes(url: str) -> bytes: request = urllib.request.Request(url, headers={"User-Agent": "floci-aws-data-generator"}) with urllib.request.urlopen(request, timeout=60) as response: - return response.read().decode("utf-8") + return response.read() + + +def fetch_url(url: str) -> str: + return fetch_bytes(url).decode("utf-8") def build_documented(spec: dict[str, str], fetch=fetch_url) -> dict: @@ -341,10 +360,73 @@ def carried_documented(current: str) -> dict[str, dict]: METHODS = ("GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS") +def model_at(name: str, release: str, api_version: str, fetch=fetch_bytes) -> dict: + """The model of `name` as botocore `release` stores it, gunzipped when that release gzips its data.""" + url = f"https://raw.githubusercontent.com/boto/botocore/{release}/botocore/data/{name}/{api_version}/service-2.json" + try: + body = fetch(url) + except OSError as error: + raise SystemExit(f"error: botocore {release} holds no {name} model to read the legacy routes from: {error}") + if body[:2] == b"\x1f\x8b": + body = gzip.decompress(body) + try: + return json.loads(body.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as error: + raise SystemExit(f"error: {url} is no JSON model of {name}: {error}") + + +def build_legacy(name: str, release: str, model: dict, fetch=fetch_bytes) -> dict: + """The legacy routes of `name`, read from botocore `release`: an operation both models hold, on another route + than the pinned model gives it, has the release's route vendored as its alternative, so a request of the route + an SDK built before the move sends is checked as the operation's action. No route is typed by hand.""" + older = model_at(name, release, model["metadata"]["apiVersion"], fetch) + routes = {} + for operation, spec in older.get("operations", {}).items(): + current = model["operations"].get(operation) + if current is None or "http" not in spec: + continue + moved = spec["http"]["method"], spec["http"]["requestUri"] + if moved != (current["http"]["method"], current["http"]["requestUri"]): + routes[operation] = [{"method": moved[0], "requestUri": moved[1]}] + return {"release": release, "routes": dict(sorted(routes.items())), "retrieved": date.today().isoformat()} + + +def carried_legacy(current: str, models: dict[str, dict]) -> dict[str, dict]: + """The legacy routes the vendored file holds, each read from the release `LEGACY` names, so a regeneration + needs no network. The only place a legacy route is checked: `build_legacy` reads routes from a botocore model, + which gives no other, while the vendored block is what anyone can edit.""" + vendored = json.loads(current).get("models", {}) if current.strip() else {} + carried = {} + for name, release in LEGACY.items(): + block = vendored.get(name, {}).get("legacyRoutes") + if block is None: + raise SystemExit(f"error: the vendored file holds no legacy routes of {name}: run with --fetch-legacy") + if block.get("release") != release: + raise SystemExit(f"error: the legacy routes of {name} are read from botocore {block.get('release')}, " + f"not {release}: run with --fetch-legacy") + operations = models.get(name, {}).get("operations", {}) + routes = block.get("routes") + if not isinstance(routes, dict): + raise SystemExit(f"error: the legacy routes of {name} are no operation-to-routes object: run with " + f"--fetch-legacy") + for operation, each in routes.items(): + if operation not in operations: + raise SystemExit(f"error: {name} holds no operation the legacy routes name: {operation}") + if not isinstance(each, list) or not each or not all( + isinstance(route, dict) and route.get("method") in METHODS + and str(route.get("requestUri", "")).startswith("/") for route in each): + raise SystemExit(f"error: a legacy route of {name}.{operation} names no method a REST request " + f"carries or no absolute path: run with --fetch-legacy") + carried[name] = {"release": release, "routes": dict(sorted(routes.items())), + "retrieved": block.get("retrieved", "")} + return carried + + def build(models: dict[str, dict], provenance: str, documented: dict[str, dict] | None = None, - elsewhere: dict[str, dict[str, str]] | None = None) -> dict: - """The vendored document from each loaded model, and the routes of each documented endpoint. `elsewhere` gives - each model's operations signed for another service (`signed_elsewhere`).""" + elsewhere: dict[str, dict[str, str]] | None = None, legacy: dict[str, dict] | None = None) -> dict: + """The vendored document from each loaded model, the routes of each documented endpoint, and the legacy routes + of each model `LEGACY` names. `elsewhere` gives each model's operations signed for another service + (`signed_elsewhere`).""" routes = {} denial_statuses = {} for name in sorted(models): @@ -353,6 +435,7 @@ def build(models: dict[str, dict], provenance: str, documented: dict[str, dict] raise SystemExit(f"error: {name} is not a REST model") shared = SHARED_ROUTES.get(name, frozenset()) signed = (elsewhere or {}).get(name, {}) + held = (legacy or {}).get(name) operations = {} for operation in sorted(model["operations"]): if operation in signed: @@ -364,14 +447,19 @@ def build(models: dict[str, dict], provenance: str, documented: dict[str, dict] # span them or the route matches no tag request at all. request_uri = re.sub(r"\{([^}]*[Aa]rn[^}]*)}", r"{\1+}", request_uri) route = {"method": http["method"], "requestUri": request_uri} + if held and operation in held["routes"]: + route["alternatives"] = [legacy_alternative(each, http["method"]) for each in held["routes"][operation]] if operation in shared: - route["alternatives"] = [bare_tags_route(http["method"])] + route.setdefault("alternatives", []).append(bare_tags_route(http["method"])) operations[operation] = route routes[name] = { "credentialScope": MODELS[name], "apiVersion": model["metadata"]["apiVersion"], "operations": operations, } + if held: + routes[name]["legacyRoutes"] = {"release": held["release"], "routes": held["routes"], + "retrieved": held.get("retrieved", "")} if signed: routes[name]["signedElsewhere"] = dict(sorted(signed.items())) status = access_denied_status(model) @@ -479,6 +567,13 @@ def load_rulesets(data: Path) -> tuple[dict[str, dict], dict | None]: return rulesets, json.loads(partitions.read_text(encoding="utf-8")) if partitions.is_file() else None +def legacy_alternative(legacy: dict[str, str], modelled_method: str) -> dict: + """The alternative a legacy route is checked as: the members its path holds none of, its own method where that + is not the operation's. `carried_legacy` is where a vendored legacy route is checked.""" + alternative = {"requestUri": legacy["requestUri"], "located": {}} + return alternative if legacy["method"] == modelled_method else {"method": legacy["method"], **alternative} + + def bare_tags_route(method: str) -> dict: """The bare `/tags` route SharedTagsController also serves for a shared tags route of the method, with where it reads the ARN: a tagging request is a POST whose body names it, whether the service tags with POST or with @@ -547,6 +642,8 @@ def render(doc: dict) -> str: lines.append(f' "accessDeniedStatus": {model["accessDeniedStatus"]},') if "documented" in model: lines.append(f' "documented": {json.dumps(model["documented"])},') + if "legacyRoutes" in model: + lines.append(f' "legacyRoutes": {json.dumps(model["legacyRoutes"])},') if "signedElsewhere" in model: lines.append(f' "signedElsewhere": {json.dumps(model["signedElsewhere"])},') lines.append(' "operations": {') @@ -579,26 +676,49 @@ def verify_documented(vendored: dict[str, dict], fetch=fetch_url) -> int: return 1 if stale else 0 +def verify_legacy(vendored: dict[str, dict], models: dict[str, dict], fetch=fetch_bytes) -> int: + """Whether each release `LEGACY` names still gives the vendored legacy routes, the retrieval date aside.""" + stale = [] + for name, release in LEGACY.items(): + fresh = build_legacy(name, release, models[name], fetch) + ours = json.loads(json.dumps(vendored.get(name, {}).get("legacyRoutes", {}))) + ours.pop("retrieved", None) + fresh.pop("retrieved", None) + if ours != fresh: + stale.append(name) + for name in stale: + print(f"error: botocore {LEGACY[name]} gives other legacy routes of {name} than the vendored: run with " + f"--fetch-legacy", file=sys.stderr) + if not stale: + print(f"{len(LEGACY)} model(s) match the legacy routes of their botocore release") + return 1 if stale else 0 + + def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--check", action="store_true", help="exit 1 when the vendored file differs from a fresh generation") parser.add_argument("--fetch-documented", action="store_true", help="online: read the documented endpoints' routes again from their AWS pages") + parser.add_argument("--fetch-legacy", action="store_true", + help="online: read the legacy routes again from the botocore release each is read from") parser.add_argument("--verify", action="store_true", - help="online: exit 1 when a documented endpoint's AWS page gives other routes than the vendored") + help="online: exit 1 when a source gives other routes than the vendored") parser.add_argument("--botocore-data", type=Path, help="botocore data directory") parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS) args = parser.parse_args(argv) current = args.output.read_text(encoding="utf-8") if args.output.exists() else "" - if args.verify: - return verify_documented(carried_documented(current)) - documented = {name: build_documented(spec) for name, spec in DOCUMENTED.items()} if args.fetch_documented \ - else carried_documented(current) data, provenance = resolve_botocore_data(args.botocore_data) models = load_models(data) + if args.verify: + vendored = json.loads(current).get("models", {}) if current.strip() else {} + return max(verify_documented(carried_documented(current)), verify_legacy(vendored, models)) + documented = {name: build_documented(spec) for name, spec in DOCUMENTED.items()} if args.fetch_documented \ + else carried_documented(current) + legacy = {name: build_legacy(name, release, models[name]) for name, release in LEGACY.items()} \ + if args.fetch_legacy else carried_legacy(current, models) rulesets, partitions = load_rulesets(data) - fresh = render(build(models, provenance, documented, signed_elsewhere(models, rulesets, partitions))) + fresh = render(build(models, provenance, documented, signed_elsewhere(models, rulesets, partitions), legacy)) if args.check: if strip_source(current) != strip_source(fresh): diff --git a/tools/aws/test_regen_rest_routes.py b/tools/aws/test_regen_rest_routes.py index 46e5ebe2d1..b820872efc 100644 --- a/tools/aws/test_regen_rest_routes.py +++ b/tools/aws/test_regen_rest_routes.py @@ -71,6 +71,7 @@ def test_a_model_that_is_not_rest_is_refused(): def test_check_passes_on_a_fresh_generation_and_fails_on_a_stale_one(tmp_path, monkeypatch): monkeypatch.setattr(r, "DOCUMENTED", {}) + monkeypatch.setattr(r, "LEGACY", {}) for name in r.MODELS: directory = tmp_path / "data" / name / "2020-01-01" directory.mkdir(parents=True) @@ -273,6 +274,149 @@ def test_an_alternative_is_keyed_by_its_own_method(): PutTags=("PUT", "/tags"))}, "test") +def test_a_legacy_route_is_an_alternative_keyed_by_its_own_method(): + # The sesv2 model moved its list operations to the POST /v2/email/list-* routes between botocore 1.43.105 and + # 1.43.104; an SDK built on the model before the move sends the legacy GETs still, checked as the same actions + # (floci-io/floci#9818). + held = {"release": "1.43.104", "routes": { + "ListEmailIdentities": [{"method": "GET", "requestUri": "/v2/email/identities"}], + "ListConfigurationSets": [{"method": "GET", "requestUri": "/v2/email/configuration-sets"}]}} + doc = r.build({"sesv2": model("rest-json", "2019-09-27", ListEmailIdentities=("POST", "/v2/email/list-identities"), + ListConfigurationSets=("POST", "/v2/email/list-configuration-sets"), + CreateEmailIdentity=("POST", "/v2/email/identities"))}, + "botocore test", legacy={"sesv2": held}) + operations = doc["models"]["sesv2"]["operations"] + assert operations["ListEmailIdentities"] == { + "method": "POST", "requestUri": "/v2/email/list-identities", + "alternatives": [{"method": "GET", "requestUri": "/v2/email/identities", "located": {}}]} + assert operations["ListConfigurationSets"] == { + "method": "POST", "requestUri": "/v2/email/list-configuration-sets", + "alternatives": [{"method": "GET", "requestUri": "/v2/email/configuration-sets", "located": {}}]} + assert "alternatives" not in operations["CreateEmailIdentity"] + assert doc["models"]["sesv2"]["legacyRoutes"] == {**held, "retrieved": ""} + assert json.loads(r.render(doc)) == doc + + +def test_a_legacy_route_of_the_operations_own_method_says_nothing_but_its_path(): + held = {"release": "1.43.104", "routes": {"ListContactLists": [{"method": "GET", + "requestUri": "/v2/email/contact-lists"}]}} + doc = r.build({"sesv2": model("rest-json", "2019-09-27", + ListContactLists=("GET", "/v2/email/current-contact-lists"))}, + "test", legacy={"sesv2": held}) + assert doc["models"]["sesv2"]["operations"]["ListContactLists"]["alternatives"] == [ + {"requestUri": "/v2/email/contact-lists", "located": {}}] + + +def vendored_legacy(routes, release="1.43.104"): + """The vendored file holding `routes` as the legacy routes of sesv2, read from `release`.""" + block = {"release": release, "routes": routes, "retrieved": "2026-11-30"} + return json.dumps({"models": {"sesv2": {"credentialScope": "ses", "apiVersion": "2019-09-27", + "legacyRoutes": block, "operations": {}}}}) + + +def test_a_vendored_legacy_route_that_names_no_absolute_path_or_an_unknown_method_is_refused(): + # The vendored block is where a legacy route is checked: build_legacy reads routes from a botocore model, which + # gives no other, so no second copy of these checks is kept where it hands them to the generator. + sesv2 = {"sesv2": model("rest-json", "2019-09-27", ListEmailIdentities=("POST", "/v2/email/list-identities"))} + refused = [[{"method": "GET", "requestUri": "v2/email/identities"}], + [{"method": "FETCH", "requestUri": "/v2/email/identities"}], []] + for routes in refused: + with pytest.raises(SystemExit, match="no method a REST request carries or no absolute path"): + r.carried_legacy(vendored_legacy({"ListEmailIdentities": routes}), sesv2) + + +def test_a_vendored_legacy_route_naming_no_operation_of_the_model_is_refused(): + # An operation the model stopped serving leaves its legacy route stale: the regeneration says so. + sesv2 = {"sesv2": model("rest-json", "2019-09-27", ListEmailIdentities=("POST", "/v2/email/list-identities"))} + with pytest.raises(SystemExit, match="sesv2 holds no operation the legacy routes name"): + r.carried_legacy(vendored_legacy({"ListIdentities": [{"method": "GET", + "requestUri": "/v2/email/identities"}]}), sesv2) + with pytest.raises(SystemExit, match="no operation-to-routes object"): + r.carried_legacy(vendored_legacy([]), sesv2) + + +def sesv2_at(release, operations): + """A fetch giving botocore `release`'s sesv2 model with `operations`, each its method and request URI, reading + the model from that release's own tag and recording the URL it was asked for.""" + modelled = {name: {"http": {"method": method, "requestUri": uri}} for name, (method, uri) in operations.items()} + body = json.dumps({"metadata": {"protocol": "rest-json", "apiVersion": "2019-09-27"}, "operations": modelled}) + + def fetch(url): + fetch.asked.append(url) + return body.encode("utf-8") + + fetch.asked = [] + return fetch + + +def test_legacy_routes_are_read_from_the_release_and_only_an_operation_that_moved_is_one(): + # Nothing names a route: the release's model gives each operation's route, and only an operation whose route the + # two models disagree on takes the older one as its legacy route. + current = model("rest-json", "2019-09-27", ListEmailIdentities=("POST", "/v2/email/list-identities"), + ListConfigurationSets=("POST", "/v2/email/list-configuration-sets"), + CreateEmailIdentity=("POST", "/v2/email/identities"), GetEmailIdentity=("GET", "/x")) + older_model = sesv2_at("1.43.104", { + "ListEmailIdentities": ("GET", "/v2/email/identities"), + "ListConfigurationSets": ("GET", "/v2/email/configuration-sets"), + "CreateEmailIdentity": ("POST", "/v2/email/identities"), + "GetEmailIdentity": ("GET", "/x"), + "DeleteEmailIdentity": ("DELETE", "/v2/email/identities/{EmailIdentity}")}) + older = r.build_legacy("sesv2", "1.43.104", current, older_model) + assert older["release"] == "1.43.104" + assert older["routes"] == { + "ListEmailIdentities": [{"method": "GET", "requestUri": "/v2/email/identities"}], + "ListConfigurationSets": [{"method": "GET", "requestUri": "/v2/email/configuration-sets"}]} + assert older_model.asked == ["https://raw.githubusercontent.com/boto/botocore/1.43.104/botocore/data/sesv2/" + "2019-09-27/service-2.json"] + + +def test_a_gzipped_model_of_the_release_is_read_all_the_same(): + current = model("rest-json", "2019-09-27", ListEmailIdentities=("POST", "/v2/email/list-identities")) + body = json.dumps({"metadata": {"protocol": "rest-json", "apiVersion": "2019-09-27"}, + "operations": {"ListEmailIdentities": {"http": {"method": "GET", + "requestUri": "/v2/email/identities"}}}}) + gzipped = r.build_legacy("sesv2", "1.43.104", current, lambda url: gzip.compress(body.encode("utf-8"))) + assert gzipped["routes"] == {"ListEmailIdentities": [{"method": "GET", "requestUri": "/v2/email/identities"}]} + + +def test_a_release_holding_no_model_or_no_json_of_it_is_refused(): + current = model("rest-json", "2019-09-27", ListEmailIdentities=("POST", "/v2/email/list-identities")) + with pytest.raises(SystemExit, match="holds no sesv2 model"): + r.build_legacy("sesv2", "1.43.104", current, raising(OSError("404 Not Found"))) + with pytest.raises(SystemExit, match="no JSON model"): + r.build_legacy("sesv2", "1.43.104", current, lambda url: b"not json") + + +def raising(error): + def fetch(url): + raise error + return fetch + + +def test_carried_legacy_keeps_the_vendored_routes_of_the_named_release(): + sesv2 = {"sesv2": model("rest-json", "2019-09-27", ListEmailIdentities=("POST", "/v2/email/list-identities"))} + routes = {"ListEmailIdentities": [{"method": "GET", "requestUri": "/v2/email/identities"}]} + assert r.carried_legacy(vendored_legacy(routes), sesv2) == { + "sesv2": {"release": "1.43.104", "routes": routes, "retrieved": "2026-11-30"}} + with pytest.raises(SystemExit, match="read from botocore 1.43.103, not 1.43.104"): + r.carried_legacy(vendored_legacy(routes, "1.43.103"), sesv2) + without = json.dumps({"models": {"sesv2": {"credentialScope": "ses", "apiVersion": "2019-09-27", + "operations": {}}}}) + with pytest.raises(SystemExit, match="no legacy routes of sesv2"): + r.carried_legacy(without, sesv2) + + +def test_verify_legacy_compares_the_vendored_routes_with_the_release(): + current = model("rest-json", "2019-09-27", ListEmailIdentities=("POST", "/v2/email/list-identities")) + vendored = {"sesv2": {"credentialScope": "ses", "apiVersion": "2019-09-27", "operations": {}, "legacyRoutes": { + "release": "1.43.104", "retrieved": "2026-11-30", + "routes": {"ListEmailIdentities": [{"method": "GET", "requestUri": "/v2/email/identities"}]}}}} + same = sesv2_at("1.43.104", {"ListEmailIdentities": ("GET", "/v2/email/identities")}) + assert r.verify_legacy(vendored, {"sesv2": current}, same) == 0 + kept = sesv2_at("1.43.104", {"ListEmailIdentities": ("POST", "/v2/email/list-identities")}) + assert r.verify_legacy(vendored, {"sesv2": current}, kept) == 1 + + def test_a_label_its_controller_lets_span_slashes_keeps_the_models_one_segment(): # API Gateway v2's controller serves /v2/tags/{resourceArn: .+} and EKS's its access entries under # {principalArn: .+}, so an ARN sent unencoded reaches them; the routes keep the model's labels all the same, and @@ -405,6 +549,7 @@ def test_a_link_that_anchors_no_method_or_a_page_with_no_row_of_the_type_is_refu def test_check_carries_the_documented_routes_over_and_verify_compares_them_with_the_page(tmp_path, monkeypatch): monkeypatch.setattr(r, "DOCUMENTED", {"glue-iceberg-rest": GLUE}) + monkeypatch.setattr(r, "LEGACY", {}) for name in r.MODELS: directory = tmp_path / "data" / name / "2020-01-01" directory.mkdir(parents=True)