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(iam): resolve the resource ARN so scoped policies match (#1719)
iot-rocket58c69e05c873
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a818532c..c69791f6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **IAM — a resource-scoped policy matches, instead of denying** — `extract_resource_arn` returned `*` for three whole families of request, and a resource-scoped policy can never match `*`, so under `AUTH=true` the only grant that worked was one written as `Resource: "*"`. First, IoT mapped six path prefixes to ARNs but not `/jobs` or `/provisioning-templates`, and neither data plane had a branch at all: a client signs those with the `iotdata` and `iotjobsdata` scopes, so they arrive as their own service keys and fell through. That rules out what the CDK emits: its `AwsCustomResource` for an IoT job grants `iot:CreateJob` on exactly `job/<jobId>` plus the target `thinggroup/<name>`, the scoping AWS documents, and a CloudFormation stack carrying one failed to deploy here with `is not authorized to perform: iot:CreateJob` while deploying on AWS. A publish and a retained message now resolve to their topic, which carries every level (`topic/sensors/rack-1/temperature`), and a shadow or job execution to its thing. `Publish` also resolves an action again: its URI label is non-greedy, so the SDK percent-encodes the separators and the ASGI server hands them back decoded, and a route compiled as one segment then matched no topic below the first level. Second, the query-protocol services (EC2, CloudFormation, CloudWatch, Auto Scaling, ElastiCache) carry their parameters in a form-encoded body when the SDK POSTs, which botocore does, so nothing reached the query string and every branch reading it resolved nothing: `ec2:AuthorizeSecurityGroupIngress` scoped to one security group was denied for that group. The router already parsed that body to find `Action` and now keeps the rest of it, merged underneath the query string, which still wins. Third, an `execute-api` invoke was authorized against `*` as well, so a policy naming one API and stage, which is what `grantExecute` and every service-to-service grant emit, never matched; it now resolves to `arn:aws:execute-api:<region>:<account>:<api-id>/<stage>/<METHOD>/<path>`, built by the same helper the Lambda authorizer's method ARN uses, and authorized once the stage is known so a v2 API on `$default` is not charged for a stage segment it does not have. Contributed by @iot-rocket.- **CloudFormation — `AWS::IAM::Policy` is provisioned inline, not as a managed policy** — the document was stored as an account-global customer-managed policy and attached to the Roles, Users and Groups the resource named, where CloudFormation embeds it on each of them the way `PutRolePolicy`, `PutUserPolicy` and `PutGroupPolicy` do. The difference is that an inline policy is scoped to its entity, so the same `PolicyName` can exist on many entities at once, and CDK relies on it: it derives `PolicyName` from the construct path, so every stack granting something to a role reached by the same path emits the same name. Twenty of one deployment's twenty-seven policies collapsed onto two records, and each deploy took the grants away from the stacks before it; under `AUTH=true` those roles were then denied the actions their own templates granted. The document now goes onto each entity through the existing inline handlers, so `ListRolePolicies`, `GetRolePolicy` and the `RolePolicyList` of `GetAccountAuthorizationDetails` report it and the IAM evaluator finds it. The physical id is generated rather than being the `PolicyName`, which is what AWS returns: measured against the account, a stack with an explicit `PolicyName` of `ms0049-refprobe-explicit-name` answers `Ref` with `ms0049--Pol-AW24HieEB0iX`, and `list-policies --scope Local` over an estate of forty deployed stacks counts zero. `AWS::IAM::ManagedPolicy` is unchanged. Contributed by @iot-rocket.- **Lambda — dispatch SQS event source batches concurrently** — one thread polled every mapping and waited for each invoke, so a handler that took 10 seconds held a message on an unrelated queue for about 8.6 seconds, and `ScalingConfig.MaximumConcurrency` was stored but ignored. SQS batches are now invoked off the poll thread, up to `MaximumConcurrency` batches per mapping (default 5), lowered to the function's `ReservedConcurrentExecutions` so a mapping does not throttle its own function. Kinesis and DynamoDB Streams mappings still process one batch at a time. Contributed by @ThailerL.- **ECS — a task's `version` counts its state changes** — the counter was minted at `1` and never moved again, so a consumer holding an older `DescribeTasks` copy could not tell it from the current one, which is the comparison the field exists for. It now increments on each transition the record reports: the move to `ACTIVATING`, the move to `RUNNING`, the move to `STOPPED` whether it came from `StopTask`, an essential container exiting or a failed start, and the restore after a restart that stops a task that was running. A real task counts the same way, measured on a Fargate task polled through `DescribeTasks`: `1` at `PROVISIONING`, `2` at `PENDING`, `3` at `RUNNING`, `4` when `StopTask` set `desiredStatus`, `5` at `DEPROVISIONING`, `6` at `STOPPED`. There are no task state change events here, so the counter is what `DescribeTasks`, `RunTask` and `StopTask` report and nothing else. Contributed by @iot-rocket.diff --git a/ministack/app.py b/ministack/app.pyindex 519dc393..f5a6a44b 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -1523,6 +1523,31 @@ def _parse_execute_api_url(host: str, path: str) -> tuple[str, str, str] | None:return None+def _enforce_execute_api(api_id: str, stage: str, method: str, execute_path: str,+ headers: dict, query_params: dict):+ """Authorize an execute-api invoke against its own ARN.++ ``arn:aws:execute-api:<region>:<account>:<api-id>/<stage>/<METHOD>/<path>``,+ the shape AWS documents. Without it every invoke was authorized against+ ``*``, so a policy scoped to one API and stage — which is what the CDK's+ ``grantExecute`` and every hand-written service-to-service grant produce —+ never matched and the call was denied.++ Built by the same helper the Lambda authorizer's method ARN uses, because+ a policy has to match both.+ """+ from ministack.core.arn import execute_api_arn+ from ministack.core.responses import get_account_id++ return _enforce_data_plane(+ "apigateway", "execute-api:Invoke", headers, query_params, "",+ resource_arn=execute_api_arn(+ extract_region(headers, query_params), get_account_id(),+ api_id, stage, method, execute_path,+ ),+ )++def _resolve_stage_and_path(api_id: str, tentative_stage: str, execute_path: str) -> tuple[str, str]:"""Pick (stage, execute_path) based on the API's configured stages.@@ -1597,23 +1622,35 @@ async def _handle_execute_api_request(return Noneapi_id, tentative_stage, execute_path = parsed- denied = _enforce_data_plane("apigateway", "execute-api:Invoke", headers, query_params, "")+ # WebSocket @connections management API — /{stage}/@connections/{id}.+ # The @connections prefix is authoritative; skip $default resolution.+ connections = execute_path.startswith("/@connections/")+ if connections or stage_from_mapping:+ # A base-path mapping names its stage; the whole remainder is API path.+ stage = tentative_stage+ else:+ # Resolved before authorizing, so the ARN names the stage the request+ # actually reaches: a v2 API on $default serves from the root, so the+ # first path segment is not a stage there and naming it one would+ # authorize against a resource that does not exist. The call only reads+ # the API's configured stages, and it answers a caller who is not+ # authorized yet, so it reports nothing about why it failed.+ try:+ stage, execute_path = _resolve_stage_and_path(api_id, tentative_stage, execute_path)+ except Exception as e:+ logger.exception("Error resolving the execute-api stage: %s", e)+ return 500, {"Content-Type": "application/json"}, json.dumps({"message": "Internal Server Error"}).encode()++ denied = _enforce_execute_api(api_id, stage, method, execute_path, headers, query_params)if denied:return deniedtry:- # WebSocket @connections management API — /{stage}/@connections/{id}.- # The @connections prefix is authoritative; skip $default resolution.- if execute_path.startswith("/@connections/"):+ if connections:connection_id = execute_path[len("/@connections/") :].split("/", 1)[0]return await _get_module("apigateway").handle_connections_api(- method, api_id, tentative_stage, connection_id, body, headers+ method, api_id, stage, connection_id, body, headers)- if stage_from_mapping:- # A base-path mapping names its stage; the whole remainder is API path.- stage = tentative_stage- else:- stage, execute_path = _resolve_stage_and_path(api_id, tentative_stage, execute_path)apigw_v1 = _get_module("apigateway_v1")if apigw_v1.find_api_scope(api_id) is not None:return await apigw_v1.handle_execute(api_id, stage, method, execute_path, headers, body, query_params)@@ -2121,15 +2158,26 @@ def _maybe_record_cloudtrail(def _routing_params(method: str, path: str, headers: dict, body: bytes, query_params: dict) -> dict:- """Augment routing params for unsigned form-encoded requests whose Action lives in the body."""- routing_params = query_params- if not query_params.get("Action") and headers.get("content-type", "").startswith(+ """Augment routing params with a query-protocol request's form-encoded body.++ The query-protocol services (EC2, CloudFormation, CloudWatch, Auto Scaling,+ ElastiCache) put every parameter in the body when the SDK POSTs, which+ botocore does. An unsigned request's ``Action`` lives there, and so does the+ resource the caller named: this dict is what ``extract_resource_arn``+ receives, so without the rest of the body it resolves nothing and a+ resource-scoped policy can never match.++ Merged underneath the query string, which still wins, and only for the one+ content type that carries it.+ """+ if not body or not headers.get("content-type", "").startswith("application/x-www-form-urlencoded"):- body_params = parse_qs(body.decode("utf-8", errors="replace"), keep_blank_values=True)- if body_params.get("Action"):- routing_params = {**query_params, "Action": body_params["Action"]}- return routing_params+ return query_params+ body_params = parse_qs(body.decode("utf-8", errors="replace"), keep_blank_values=True)+ if not body_params:+ return query_params+ return {**body_params, **query_params}def _unknown_query_error(body: bytes, request_id: str):diff --git a/ministack/core/arn.py b/ministack/core/arn.pyindex d067fdb3..1709d674 100644--- a/ministack/core/arn.py+++ b/ministack/core/arn.py@@ -62,3 +62,17 @@ def parse_arn(value: str) -> Arn:def is_arn(value: str) -> bool:"""Return whether a value is shaped like an ARN."""return isinstance(value, str) and value.startswith(_ARN_PREFIX) and value.count(":") >= _ARN_SECTIONS - 1+++def execute_api_arn(region: str, account_id: str, api_id: str,+ stage: str, method: str, path: str) -> str:+ """Build the ``execute-api`` ARN for one invoke.++ ``arn:aws:execute-api:<region>:<account>:<api-id>/<stage>/<METHOD>/<path>``.+ Both the Lambda authorizer's method ARN and the IAM evaluator's resource+ have to be this exact string, so they share one builder.+ """+ return (+ f"arn:aws:execute-api:{region}:{account_id}:"+ f"{api_id}/{stage}/{method}/{path.lstrip('/')}"+ )diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex 80a5b333..f17a37e5 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -465,7 +465,22 @@ _BOTOCORE_SERVICE_MAP: dict[str, list[str]] = {_REST_ROUTE_CACHE: dict[str, list[tuple[str, re.Pattern, str, int, dict[str, str]]]] = {}-def _compile_uri(uri_pattern: str) -> tuple[re.Pattern, int, dict[str, str]]:+# A botocore path label is non-greedy ({x}) unless the model marks it greedy+# ({x+}), and the SDK percent-encodes any "/" the value carries so the label+# still matches one segment on the wire. We match against the decoded path the+# ASGI server hands us, where those separators are separators again, so a+# non-greedy label whose value may contain one never matches and the request+# resolves no action at all. An MQTT topic is multi-level by definition, which+# makes iot-data's the case that bites: without this, Publish and+# GetRetainedMessage are not authorized on any topic below the first level.+# Keyed by botocore service name, as _BOTOCORE_SERVICE_MAP's values are.+_GREEDY_URI_LABELS: dict[str, frozenset[str]] = {+ "iot-data": frozenset({"topic"}),+}+++def _compile_uri(uri_pattern: str,+ greedy_labels: frozenset[str] = frozenset()) -> tuple[re.Pattern, int, dict[str, str]]:"""Compile a botocore URI pattern into a regex + specificity score +required query params.@@ -474,7 +489,9 @@ def _compile_uri(uri_pattern: str) -> tuple[re.Pattern, int, dict[str, str]]:(2 literal segments).Query params from the pattern (e.g., ``?mode=import``) are returned- separately for disambiguation.+ separately for disambiguation. Labels named in ``greedy_labels`` match+ across ``/`` as if the model had marked them ``{x+}``; see+ ``_GREEDY_URI_LABELS``."""required_query: dict[str, str] = {}if "?" in uri_pattern:@@ -501,7 +518,7 @@ def _compile_uri(uri_pattern: str) -> tuple[re.Pattern, int, dict[str, str]]:if seg.startswith("{") and seg.endswith("+}"):regex_parts.append(".+")elif seg.startswith("{") and seg.endswith("}"):- regex_parts.append("[^/]+")+ regex_parts.append(".+" if seg[1:-1] in greedy_labels else "[^/]+")else:regex_parts.append(re.escape(seg))specificity += 1@@ -548,6 +565,7 @@ def _load_botocore_routes(botocore_service: str) -> list[tuple[str, re.Pattern,logger.debug("AUTH: failed to load botocore model for %s", botocore_service)return []+ greedy_labels = _GREEDY_URI_LABELS.get(botocore_service, frozenset())routes = []for op_name, op_def in model.get("operations", {}).items():http = op_def.get("http", {})@@ -555,7 +573,7 @@ def _load_botocore_routes(botocore_service: str) -> list[tuple[str, re.Pattern,uri = http.get("requestUri", "")if not method or not uri:continue- compiled, specificity, required_query = _compile_uri(uri)+ compiled, specificity, required_query = _compile_uri(uri, greedy_labels)# Operations with required query params get a specificity boostif required_query:specificity += len(required_query)@@ -787,7 +805,12 @@ def extract_resource_arn(service: str, method: str, path: str,headers: dict, body: bytes,query_params: dict, region: str,account_id: str) -> str:- """Construct the resource ARN for the request, or '*' if unknown."""+ """Construct the resource ARN for the request, or '*' if unknown.++ ``query_params`` is the router's params dict, which for a query-protocol+ POST carries the form-encoded body merged underneath the query string+ (``app._routing_params``). The branches below read it directly.+ """if service == "s3":parts = [p for p in path.split("/") if p]@@ -1397,8 +1420,20 @@ def extract_resource_arn(service: str, method: str, path: str,# --- IoT (REST path-based, multiple resource types) ---- if service == "iot":+ # Both data planes carry iot: actions on iot: ARNs, and their paths are the+ # ones the map below already names: a publish is /topics/{topic}, a shadow+ # and a job execution are /things/{thingName}/... . Routed by credential+ # scope, they arrive here as their own service keys.+ if service in ("iot", "iot-data", "iot-jobs-data"):parts = [p for p in path.split("/") if p]+ # Publish and the retained-message calls take everything after the+ # prefix as the topic, and a topic is multi-level: the ARN is+ # topic/sensors/a/temperature, not topic/sensors. The separators arrive+ # percent-encoded from the SDK, which is why iot_data._publish unquotes+ # as well.+ if len(parts) > 1 and parts[0] in ("topics", "retainedMessage"):+ topic = unquote("/".join(parts[1:]))+ return f"arn:aws:iot:{region}:{account_id}:topic/{topic}"_IOT_RESOURCES = {"things": "thing","thing-types": "thingtype",@@ -1406,15 +1441,14 @@ def extract_resource_arn(service: str, method: str, path: str,"policies": "policy","certificates": "cert","rules": "rule",+ "jobs": "job",+ "provisioning-templates": "provisioningtemplate",}for segment, rtype in _IOT_RESOURCES.items():if segment in parts:si = parts.index(segment)if si + 1 < len(parts):- name = parts[si + 1]- if rtype == "cert":- return f"arn:aws:iot:{region}:{account_id}:{rtype}/{name}"- return f"arn:aws:iot:{region}:{account_id}:{rtype}/{name}"+ return f"arn:aws:iot:{region}:{account_id}:{rtype}/{parts[si + 1]}"return "*"# --- API Gateway (REST path-based) ---diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.pyindex e8aa80e1..adcfc36e 100644--- a/ministack/services/apigateway.py+++ b/ministack/services/apigateway.py@@ -53,7 +53,7 @@ import urllib.errorimport urllib.parseimport urllib.request-from ministack.core.arn import ArnParseError, parse_arn+from ministack.core.arn import ArnParseError, execute_api_arn, parse_arnfrom ministack.core.concurrency import run_reentrantfrom ministack.core.responses import (AccountRegionScopedDict,@@ -850,13 +850,6 @@ def _evaluate_authorizer_policy(policy_doc, route_arn):return "Allow" if allow else "NoMatch"-def _build_route_arn(region, account_id, api_id, stage, method, path):- return (- f"arn:aws:execute-api:{region}:{account_id}:"- f"{api_id}/{stage}/{method}/{path.lstrip('/')}"- )--def _request_authorizer_identity_sources(identity_source, headers, query_params, stage_vars):"""Resolve a REQUEST authorizer's identitySource list to (all_present, values).@@ -964,7 +957,7 @@ async def _authorize_request_v2(if not authorizer:return (500, {"Content-Type": "application/json"}, json.dumps({"message": "Internal Server Error"}).encode()), None- route_arn = _build_route_arn(owner_region, owner_account_id, api_id, stage, method, path)+ route_arn = execute_api_arn(owner_region, owner_account_id, api_id, stage, method, path)payload_version = str(authorizer.get("authorizerPayloadFormatVersion") or "2.0")simple_response = payload_version == "2.0" and bool(authorizer.get("enableSimpleResponses"))ttl = _authorizer_ttl(authorizer)diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.pyindex e26115e3..f38eb2ca 100644--- a/ministack/services/apigateway_v1.py+++ b/ministack/services/apigateway_v1.py@@ -102,7 +102,7 @@ import urllib.requestimport yaml-from ministack.core.arn import ArnParseError, parse_arn+from ministack.core.arn import ArnParseError, execute_api_arn, parse_arnfrom ministack.core.concurrency import run_reentrantfrom ministack.core.responses import (AccountRegionScopedDict,@@ -1396,13 +1396,6 @@ def _deny_error(explicit):)-def _build_method_arn(region, account_id, api_id, stage_name, method, request_path):- return (- f"arn:aws:execute-api:{region}:{account_id}:"- f"{api_id}/{stage_name}/{method}/{request_path.lstrip('/')}"- )--def _arn_matches(pattern, arn):"""Match an IAM policy Resource against a method ARN, honoring `*`/`?` globs."""regex = "^" + re.escape(pattern).replace(r"\*", ".*").replace(r"\?", ".") + "$"@@ -1758,7 +1751,7 @@ async def _authorize_request_v1(if not authorizer:return _gw_error(500, "Internal server error"), None- method_arn = _build_method_arn(+ method_arn = execute_api_arn(owner_region, owner_account_id, api_id, stage_name, method, request_path)atype = (authorizer.get("type") or "TOKEN").upper()diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex ddb77b8f..033a3a5a 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -893,6 +893,44 @@ class TestSeededAwsManagedPolicies:# Resource ARN construction# ---------------------------------------------------------------------------+_FORM = {"content-type": "application/x-www-form-urlencoded"}+++def _sigv4_headers(credential_scope: str, host: str) -> dict:+ """Headers shaped like a signed request, which is how the router decides+ the service: the credential scope wins over the host and the path."""+ return {+ "authorization": (+ f"AWS4-HMAC-SHA256 Credential=test/20260101/eu-central-1/{credential_scope}"+ "/aws4_request, SignedHeaders=host, Signature=deadbeef"+ ),+ "host": host,+ }+++def _capture_enforced_arn(monkeypatch) -> dict:+ """Record the resource ARN the data-plane check was handed, and allow."""+ import ministack.app as app++ seen: dict[str, str] = {}++ def _capture(service, iam_action, headers, query_params, request_id, resource_arn="*"):+ seen["arn"] = resource_arn+ return None++ monkeypatch.setattr(app, "_enforce_data_plane", _capture)+ monkeypatch.setattr(app, "extract_region", lambda h, q=None: "eu-central-1")+ return seen+++class _NoApiModule:+ """Stands in for the apigateway modules so dispatch stops at the 404."""++ @staticmethod+ def find_api_scope(api_id):+ return None++class TestResourceArn:def test_s3_bucket(self):from ministack.core.iam_actions import extract_resource_arn@@ -1204,6 +1242,258 @@ class TestResourceArn:from ministack.core.iam_actions import extract_resource_arnassert extract_resource_arn("iot", "GET", "/rules/my-rule", {}, b"", {}, "us-east-1", "123") == "arn:aws:iot:us-east-1:123:rule/my-rule"+ def test_iot_job(self):+ from ministack.core.iam_actions import extract_resource_arn+ assert extract_resource_arn("iot", "PUT", "/jobs/rollout-2024", {}, b"", {}, "us-east-1", "123") == "arn:aws:iot:us-east-1:123:job/rollout-2024"++ def test_iot_provisioning_template(self):+ from ministack.core.iam_actions import extract_resource_arn+ assert extract_resource_arn("iot", "GET", "/provisioning-templates/fleet", {}, b"", {}, "us-east-1", "123") == "arn:aws:iot:us-east-1:123:provisioningtemplate/fleet"++ def test_iot_publish_topic_keeps_every_level(self):+ """A topic ARN carries the whole topic, not its first segment:+ arn:aws:iot:...:topic/sensors/rack-1/temperature. Truncating it to+ topic/sensors would authorize a publish against the wrong resource."""+ from ministack.core.iam_actions import extract_resource_arn+ assert extract_resource_arn(+ "iot", "POST", "/topics/sensors/rack-1/temperature", {}, b"", {}, "us-east-1", "123"+ ) == "arn:aws:iot:us-east-1:123:topic/sensors/rack-1/temperature"++ def test_iot_shadow_resolves_to_its_thing(self):+ from ministack.core.iam_actions import extract_resource_arn+ assert extract_resource_arn(+ "iot", "GET", "/things/my-thing/shadow", {}, b"", {}, "us-east-1", "123"+ ) == "arn:aws:iot:us-east-1:123:thing/my-thing"++ def test_iot_collection_call_has_no_resource(self):+ from ministack.core.iam_actions import extract_resource_arn+ assert extract_resource_arn("iot", "GET", "/jobs", {}, b"", {}, "us-east-1", "123") == "*"++ def test_iot_job_policy_from_the_cdk_actually_allows_the_call(self):+ """The two halves together, which is where this showed up. The CDK's+ AwsCustomResource emits exactly this policy for an IoT job, and every+ such stack failed to deploy under AUTH because the request carried no+ job ARN to match it against: only Resource "*" got through."""+ from ministack.core.iam_actions import extract_resource_arn++ arn = extract_resource_arn(+ "iot", "PUT", "/jobs/hawkbit_rollout-2024", {}, b"", {}, "eu-central-1", "000000000000"+ )+ stmts = parse_policy_document({"Statement": [{+ "Effect": "Allow",+ "Action": "iot:CreateJob",+ "Resource": [+ "arn:aws:iot:eu-central-1:000000000000:job/hawkbit_rollout-2024",+ "arn:aws:iot:eu-central-1:000000000000:thinggroup/hawkbit_rollout",+ ],+ }]})+ ctx = EvalContext(+ principal_arn="arn:aws:sts::000000000000:assumed-role/deployer/session",+ principal_type="AssumedRole",+ principal_account="000000000000",+ action="iot:CreateJob", resource_arn=arn, region="eu-central-1",+ )+ assert evaluate(ctx, [stmts]).decision == "Allow"++ def test_iot_retained_message_is_its_topic(self):+ from ministack.core.iam_actions import extract_resource_arn+ assert extract_resource_arn(+ "iot-data", "GET", "/retainedMessage/sensors/rack-1", {}, b"", {}, "us-east-1", "123"+ ) == "arn:aws:iot:us-east-1:123:topic/sensors/rack-1"++ # --- The data planes route by credential scope, not as "iot" ---+ def test_publish_resolves_through_the_router(self):+ """The branch above is reached only if the router agrees. A boto3+ iot-data client signs with the iotdata scope, so detect_service answers+ "iot-data" and not "iot": a branch keyed on "iot" alone is dead code+ that a test calling extract_resource_arn("iot", ...) cannot see."""+ from ministack.core.iam_actions import extract_iam_action, extract_resource_arn+ from ministack.core.router import detect_service++ path = "/topics/sensors/rack-1/temperature"+ headers = _sigv4_headers("iotdata", "data-ats.iot.eu-central-1.amazonaws.com")+ service = detect_service("POST", path, headers, {})+ assert service == "iot-data"+ assert extract_iam_action(service, "POST", path, headers, b"", {}) == "iot:Publish"+ assert extract_resource_arn(+ service, "POST", path, headers, b"", {}, "eu-central-1", "123"+ ) == "arn:aws:iot:eu-central-1:123:topic/sensors/rack-1/temperature"++ def test_publish_resolves_the_same_topic_however_the_sdk_sent_it(self):+ """Publish's URI label is non-greedy, so botocore percent-encodes the+ separators and the ASGI server hands them back decoded. Both spellings+ have to name one resource, or the grant matches on one path only."""+ from ministack.core.iam_actions import extract_iam_action, extract_resource_arn+ from ministack.core.router import detect_service++ headers = _sigv4_headers("iotdata", "data-ats.iot.eu-central-1.amazonaws.com")+ expected = "arn:aws:iot:eu-central-1:123:topic/sensors/rack-1/temperature"+ for path in ("/topics/sensors/rack-1/temperature",+ "/topics/sensors%2Frack-1%2Ftemperature"):+ service = detect_service("POST", path, headers, {})+ assert extract_iam_action(service, "POST", path, headers, b"", {}) == "iot:Publish"+ assert extract_resource_arn(+ service, "POST", path, headers, b"", {}, "eu-central-1", "123"+ ) == expected++ def test_create_job_resolves_through_the_router(self):+ from ministack.core.iam_actions import extract_iam_action, extract_resource_arn+ from ministack.core.router import detect_service++ headers = _sigv4_headers("iot", "iot.eu-central-1.amazonaws.com")+ service = detect_service("PUT", "/jobs/rollout-2024", headers, {})+ assert service == "iot"+ assert extract_iam_action(service, "PUT", "/jobs/rollout-2024", headers, b"", {}) == "iot:CreateJob"+ assert extract_resource_arn(+ service, "PUT", "/jobs/rollout-2024", headers, b"", {}, "eu-central-1", "123"+ ) == "arn:aws:iot:eu-central-1:123:job/rollout-2024"++ def test_job_execution_on_the_jobs_data_plane_is_its_thing(self):+ """AWS scopes the jobs data plane on the thing, not the job."""+ from ministack.core.iam_actions import extract_resource_arn+ assert extract_resource_arn(+ "iot-jobs-data", "GET", "/things/dev-01/jobs/j1", {}, b"", {}, "us-east-1", "123"+ ) == "arn:aws:iot:us-east-1:123:thing/dev-01"++ # --- Query-protocol services put their parameters in the body ---+ def test_ec2_reads_a_form_encoded_body(self):+ """botocore POSTs EC2 as application/x-www-form-urlencoded, so nothing+ reaches the query string and the branch below resolved nothing. The+ router merges that body in, which is why this goes through it."""+ from ministack.app import _routing_params+ from ministack.core.iam_actions import extract_resource_arn++ body = b"Action=AuthorizeSecurityGroupIngress&GroupId=sg-0abc&Version=2016-11-15"+ params = _routing_params("POST", "/", _FORM, body, {})+ assert extract_resource_arn(+ "ec2", "POST", "/", _FORM, body, params, "eu-central-1", "123"+ ) == "arn:aws:ec2:eu-central-1:123:security-group/sg-0abc"++ def test_cloudformation_reads_a_form_encoded_body(self):+ from ministack.app import _routing_params+ from ministack.core.iam_actions import extract_resource_arn++ body = b"Action=DescribeStacks&StackName=my-stack"+ params = _routing_params("POST", "/", _FORM, body, {})+ assert extract_resource_arn(+ "cloudformation", "POST", "/", _FORM, body, params, "us-east-1", "123",+ ) == "arn:aws:cloudformation:us-east-1:123:stack/my-stack/*"++ def test_query_params_win_over_the_body(self):+ from ministack.app import _routing_params+ from ministack.core.iam_actions import extract_resource_arn++ body = b"GroupId=sg-body"+ params = _routing_params("POST", "/", _FORM, body, {"GroupId": ["sg-query"]})+ assert extract_resource_arn(+ "ec2", "POST", "/", _FORM, body, params, "us-east-1", "123",+ ) == "arn:aws:ec2:us-east-1:123:security-group/sg-query"++ def test_body_is_read_even_when_the_action_was_lifted_out_of_it(self):+ """The router already lifted Action out of this same body, so a merge+ that fired only on an empty dict would be a no-op on exactly the+ requests it exists for."""+ from ministack.app import _routing_params+ from ministack.core.iam_actions import extract_resource_arn++ body = b"Action=AuthorizeSecurityGroupIngress&GroupId=sg-0abc&Version=2016-11-15"+ params = _routing_params(+ "POST", "/", _FORM, body, {"Action": ["AuthorizeSecurityGroupIngress"]}+ )+ assert params["GroupId"] == ["sg-0abc"]+ assert extract_resource_arn(+ "ec2", "POST", "/", _FORM, body, params, "eu-central-1", "123",+ ) == "arn:aws:ec2:eu-central-1:123:security-group/sg-0abc"++ @pytest.mark.parametrize("content_type, body", [+ ("application/x-amz-json-1.1", b'{"TableName":"users"}'),+ ("application/xml", b"<Response>a=b</Response>"),+ ("application/x-www-form-urlencoded", b""),+ ("", b"Action=DescribeStacks&StackName=my-stack"),+ ])+ def test_only_a_form_encoded_body_is_merged(self, content_type, body):+ """A body of any other content type is left alone, which is what keeps+ this off the S3 upload path: extract_resource_arn runs on every+ authenticated request, and a PutObject body can be very large."""+ from ministack.app import _routing_params+ assert _routing_params("POST", "/", {"content-type": content_type}, body, {}) == {}++ def test_a_json_body_still_resolves_its_own_resource(self):+ from ministack.core.iam_actions import extract_resource_arn+ assert extract_resource_arn(+ "dynamodb", "POST", "/", {}, b'{"TableName":"users"}', {}, "us-east-1", "123"+ ) == "arn:aws:dynamodb:us-east-1:123:table/users"++ # --- No false allows ---+ def test_a_scoped_grant_denies_the_resource_it_does_not_name(self):+ """The other half of the fix: the request now resolves to its own ARN,+ so a grant naming a different one has to stop matching."""+ from ministack.core.iam_actions import extract_resource_arn++ arn = extract_resource_arn(+ "iot", "PUT", "/jobs/rollout-2025", {}, b"", {}, "eu-central-1", "000000000000"+ )+ stmts = parse_policy_document({"Statement": [{+ "Effect": "Allow", "Action": "iot:CreateJob",+ "Resource": "arn:aws:iot:eu-central-1:000000000000:job/rollout-2024",+ }]})+ ctx = EvalContext(+ principal_arn="arn:aws:sts::000000000000:assumed-role/deployer/session",+ principal_type="AssumedRole", principal_account="000000000000",+ action="iot:CreateJob", resource_arn=arn, region="eu-central-1",+ )+ assert evaluate(ctx, [stmts]).decision == "ImplicitDeny"++ def test_a_wildcard_grant_still_matches_a_resolved_arn(self):+ from ministack.core.iam_actions import extract_resource_arn++ arn = extract_resource_arn(+ "iot", "PUT", "/jobs/rollout-2024", {}, b"", {}, "eu-central-1", "000000000000"+ )+ stmts = parse_policy_document({"Statement": [{+ "Effect": "Allow", "Action": "iot:CreateJob", "Resource": "*",+ }]})+ ctx = EvalContext(+ principal_arn="arn:aws:sts::000000000000:assumed-role/deployer/session",+ principal_type="AssumedRole", principal_account="000000000000",+ action="iot:CreateJob", resource_arn=arn, region="eu-central-1",+ )+ assert evaluate(ctx, [stmts]).decision == "Allow"++ # --- execute-api ---+ def test_execute_api_invoke_is_authorized_against_its_own_arn(self, monkeypatch):+ """Every invoke used to be authorized against "*", so a grant scoped to+ one API and stage — what the CDK's grantExecute and every hand-written+ service-to-service policy produce — never matched."""+ import ministack.app as app++ seen = _capture_enforced_arn(monkeypatch)+ app._enforce_execute_api("d9506af4", "dev", "POST", "/commands/delete", {}, {})+ assert seen["arn"] == (+ "arn:aws:execute-api:eu-central-1:000000000000:d9506af4/dev/POST/commands/delete"+ )++ def test_execute_api_default_stage_is_not_taken_from_the_path(self, monkeypatch):+ """Why the call sits after the stage is resolved. A v2 API on $default+ serves from the root, so the first path segment is a path segment, and+ authorizing on it would name a resource that does not exist."""+ import ministack.app as app++ seen = _capture_enforced_arn(monkeypatch)+ monkeypatch.setattr(app, "_parse_execute_api_url",+ lambda host, path: ("d9506af4", "commands", "/delete"))+ monkeypatch.setattr(app, "_resolve_stage_and_path",+ lambda api_id, tentative, path: ("$default", f"/{tentative}{path}"))+ monkeypatch.setattr(app, "_get_module", lambda name: _NoApiModule)++ asyncio.run(app._handle_execute_api_request(+ "d9506af4.execute-api.eu-central-1.amazonaws.com",+ "/commands/delete", "POST", {}, b"", {},+ ))+ assert seen["arn"] == (+ "arn:aws:execute-api:eu-central-1:000000000000:d9506af4/$default/POST/commands/delete"+ )+# --- API Gateway ---def test_apigateway_v2(self):from ministack.core.iam_actions import extract_resource_arn