Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(apigateway): use HTTP IAM actions and preserve resource paths (#2068)
Adrian-Ryan Acala916a28677407
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4ce6c0a5..935cb6c3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **API Gateway — management IAM actions and resource paths** — with `AUTH=true`, REST and HTTP/WebSocket API management requests use `apigateway:GET`, `POST`, `PUT`, `PATCH` and `DELETE` instead of SDK operation names. Resource ARNs preserve stage names, nested resources and collection paths, and ignore trailing slashes as AWS does, so scoped grants and explicit stage denies apply to the requested resource.- **AppConfig — `GetLatestConfiguration` returns an empty body when nothing changed** — it returned the full configuration on every poll. It now also returns `Version-Label` and uses `RequiredMinimumPollIntervalInSeconds` as the poll interval, and `CreateHostedConfigurationVersion` stores `VersionLabel`. Contributed by @Jolley71717.- **AppConfig — `StopDeployment` follows the documented states** — it marked any deployment `ROLLED_BACK`. It now rolls back an in-progress deployment, reverts a completed one only with `AllowRevert` and within 72 hours (`REVERTED`), and returns `BadRequestException` otherwise. Contributed by @Jolley71717.diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex 4fe197ac..1c2120b4 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -681,6 +681,12 @@ def extract_iam_action(service: str, method: str, path: str,logger.debug("AUTH: no IAM namespace for service %s — allowing", service)return None+ # API Gateway management authorizes HTTP verbs, not SDK operation names.+ # Handle it before Query/JSON extraction: those protocols cannot override+ # the action of a REST management request (v1 and v2 share this namespace).+ if service == "apigateway":+ return f"apigateway:{method}" if method in {"GET", "POST", "PUT", "PATCH", "DELETE"} else None+# Tier 1: Action query param (query-protocol services)action_name = _action_from_query(query_params, body,headers.get("content-type", ""))@@ -1544,22 +1550,13 @@ def extract_resource_arn(service: str, method: str, path: str,# --- API Gateway (REST path-based) ---if service == "apigateway":- parts = [p for p in path.split("/") if p]- # v2: /v2/apis/{apiId}- if "apis" in parts:- ai = parts.index("apis")- if ai + 1 < len(parts):- api_id = parts[ai + 1]- return f"arn:aws:apigateway:{region}::/apis/{api_id}"- return f"arn:aws:apigateway:{region}::/apis/*"- # v1: /restapis/{restApiId}- if "restapis" in parts:- ri = parts.index("restapis")- if ri + 1 < len(parts):- api_id = parts[ri + 1]- return f"arn:aws:apigateway:{region}::/restapis/{api_id}"- return f"arn:aws:apigateway:{region}::/restapis/*"- return "*"+ # Management ARNs retain the complete resource/collection path and+ # have an empty account component. The v2 endpoint prefix is not part+ # of the ARN. Decode URI labels, including the HTTP API $default stage.+ # AWS ignores trailing slashes when authorizing management resources,+ # as our control-plane handlers do when resolving the target resource.+ resource_path = unquote(path[3:] if path.startswith("/v2/") else path).rstrip("/")+ return f"arn:aws:apigateway:{region}::{resource_path}"# --- Bedrock (REST path-based, multiple sub-services) ---diff --git a/tests/test_apigateway_iam.py b/tests/test_apigateway_iam.pynew file mode 100644index 00000000..26fdf6c7--- /dev/null+++ b/tests/test_apigateway_iam.py@@ -0,0 +1,103 @@+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).+"""API Gateway management authorization through request dispatch and IAM policies."""++import asyncio+import json++import pytest++from ministack.core.iam_actions import extract_iam_action, extract_resource_arn+from ministack.core.iam_evaluator import EvalContext, evaluate, parse_policy_document++[email protected]("path", ["/restapis/api/stages/prod", "/v2/apis/api/stages/prod"])[email protected]("method", ["GET", "POST", "PUT", "PATCH", "DELETE"])+def test_management_actions_use_http_verbs(path, method):+ # Neither query-protocol parameters nor JSON-protocol headers may override+ # the action of this REST-only service.+ assert extract_iam_action(+ "apigateway", method, path,+ {"x-amz-target": "ApiGateway.GetStage"}, b"", {"Action": "GetStage"},+ ) == f"apigateway:{method}"++[email protected]("path, resource", [+ ("/restapis", "/restapis"),+ ("/restapis/api", "/restapis/api"),+ ("/restapis/api/stages", "/restapis/api/stages"),+ ("/restapis/api/stages/prod", "/restapis/api/stages/prod"),+ ("/restapis/api/stages/prod/", "/restapis/api/stages/prod"),+ ("/restapis/api/stages/", "/restapis/api/stages"),+ ("/restapis/api/resources/root/methods/GET/integration", "/restapis/api/resources/root/methods/GET/integration"),+ ("/v2/apis", "/apis"),+ ("/v2/apis/api", "/apis/api"),+ ("/v2/apis/api/stages", "/apis/api/stages"),+ ("/v2/apis/api/stages/", "/apis/api/stages"),+ ("/v2/apis/api/stages/prod/", "/apis/api/stages/prod"),+ ("/v2/apis/api/stages/%24default", "/apis/api/stages/$default"),+ ("/v2/apis/api/stages/%24default/", "/apis/api/stages/$default"),+ ("/v2/apis/api/routes/route", "/apis/api/routes/route"),+ ("/domainnames/example.com/basepathmappings", "/domainnames/example.com/basepathmappings"),+ ("/v2/domainnames/example.com/apimappings", "/domainnames/example.com/apimappings"),+ ("/account", "/account"),+])+def test_management_resource_preserves_path(path, resource):+ assert extract_resource_arn(+ "apigateway", "GET", path, {}, b"", {}, "us-east-2", "000000000000",+ ) == f"arn:aws:apigateway:us-east-2::{resource}"++[email protected]("prefix", ["/restapis/api", "/v2/apis/api"])[email protected]("suffix", ["", "/"])[email protected]("case, method, stage, expected", [+ ("stage-grant", "GET", "prod", 200),+ ("stage-grant", "PATCH", "prod", 200),+ ("stage-grant", "GET", "dev", 403),+ ("parent-grant", "GET", "prod", 403),+ ("operation-grant", "GET", "prod", 403),+ ("stage-deny", "GET", "prod", 403),+ ("stage-deny", "GET", "dev", 200),+])+def test_stage_policy_is_enforced_on_dispatch(monkeypatch, prefix, suffix, case, method, stage, expected):+ import ministack.app as app+ from ministack.core import iam_evaluator++ parent = f"arn:aws:apigateway:us-east-2::{prefix.removeprefix('/v2')}"+ grants = {+ "stage-grant": [{"Effect": "Allow", "Action": ["apigateway:GET", "apigateway:PATCH"],+ "Resource": f"{parent}/stages/prod"}],+ "parent-grant": [{"Effect": "Allow", "Action": "apigateway:GET", "Resource": parent}],+ "operation-grant": [{"Effect": "Allow", "Action": "apigateway:GetStage", "Resource": "*"}],+ "stage-deny": [+ {"Effect": "Allow", "Action": "apigateway:*", "Resource": f"{parent}/*"},+ {"Effect": "Deny", "Action": "apigateway:GET", "Resource": f"{parent}/stages/prod"},+ ],+ }+ statements = parse_policy_document({"Statement": grants[case]})+ dispatched = []++ def enforce_policy(access_key, action, service, region, resource_arn="*", service_context=None):+ result = evaluate(EvalContext(+ principal_arn="arn:aws:iam::000000000000:user/caller",+ principal_type="User", principal_account="000000000000",+ action=action, resource_arn=resource_arn, region=region,+ ), [statements])+ return None if result.decision == "Allow" else result++ async def handler(*args):+ dispatched.append(args)+ return 200, {}, b"{}"++ monkeypatch.setattr(app, "AUTH", True)+ monkeypatch.setattr(iam_evaluator, "enforce", enforce_policy)+ monkeypatch.setattr(iam_evaluator, "pin_request_caller", lambda *args: None)+ monkeypatch.setitem(app.SERVICE_HANDLERS, "apigateway", handler)+ headers = {"authorization": "AWS4-HMAC-SHA256 Credential=test/20261006/us-east-2/apigateway/aws4_request"}+ status, _, body = asyncio.run(app._dispatch_service_request(+ method, f"{prefix}/stages/{stage}{suffix}", headers, b"", {}, "request-stage",+ ))+ assert status == expected+ assert bool(dispatched) == (expected == 200)+ if expected == 403:+ assert f"apigateway:{method}" in json.loads(body)["message"]