Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(apigateway): authorize AWS_IAM WebSocket $connect as execute-api:Invoke (#1975)

iot-rocketed4750b28f3b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ed565ffc..329cbedf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Fixed
+- **API Gateway v2 (WebSocket API) — `$connect` with `AWS_IAM`** — an unsigned handshake is refused with 403 `Missing Authentication Token`, and under `AUTH=true` the caller needs `execute-api:Invoke` on `arn:aws:execute-api:<region>:<account>:<api-id>/<stage>/$connect`. Contributed by @iot-rocket.
- **SNS — `CreateTopic` keeps its tags** — the handler read `Tag.member.N` where the API sends `Tags.member.N`, so tags given at creation were dropped. Contributed by @iot-rocket.
## [1.5.21] — 2026-10-03
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index 09097c72..2d6ef0b8 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -3037,6 +3037,25 @@ _WS_DENY_REASONS = {
}
+def _authorize_ws_iam(connect_arn, headers, query_params, region):
+ """``(status, message)`` refusing an AWS_IAM $connect, or None; the policy check runs under AUTH=true."""
+ from ministack.app import AUTH
+ from ministack.core.iam_evaluator import AuthError, enforce
+ from ministack.core.router import extract_access_key_id
+
+ access_key = extract_access_key_id(headers, query_params)
+ if not access_key:
+ return 403, "Missing Authentication Token"
+ denied = AUTH and enforce(access_key, "execute-api:Invoke", "apigateway", region, resource_arn=connect_arn)
+ if isinstance(denied, AuthError):
+ return 403, denied.message
+ if denied:
+ reason = _WS_DENY_REASONS["Deny" if denied.decision == "Deny" else "NoMatch"]
+ return 403, (f"User: {denied.principal_arn} is not authorized to perform: execute-api:Invoke "
+ f"on resource: {connect_arn} {reason}")
+ return None
+
+
async def _authorize_ws_connect(api_id, route, request_context, headers, query_params, account_id, region):
"""Run the $connect REQUEST authorizer: ``(refusal, context)``, a refusal being ``(status, message)``."""
from ministack.services.apigateway_v1 import _stringify_context
@@ -3164,6 +3183,11 @@ async def handle_websocket(scope, receive, send, api_id: str, path_override: str
connect_request_id, source_ip, headers),
headers, query_params, account_id, owner_region,
)
+ elif auth_type == "AWS_IAM":
+ refusal = _authorize_ws_iam(
+ execute_api_route_arn(owner_region, account_id, api_id, stage, "$connect"),
+ headers, query_params, owner_region,
+ )
elif auth_type == "JWT":
# only a route restored from state saved before the route checks existed
logger.warning(
diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.py
index c8aea99d..2045f638 100644
--- a/tests/test_apigatewayv2.py
+++ b/tests/test_apigatewayv2.py
@@ -3184,6 +3184,21 @@ def test_ws_connect_request_authorizer_context_reaches_the_routes(apigw, lam):
}
+def test_ws_connect_aws_iam_needs_a_signed_request(apigw, lam):
+ """An AWS_IAM $connect refuses an unsigned handshake with 403 and accepts a SigV4-signed one."""
+ api_id, _ = _wire_ws_api(apigw, lam, name_suffix=f"iam-{uuid.uuid4().hex[:6]}", connect_code=_ECHO_CODE)
+ connect = next(r for r in apigw.get_routes(ApiId=api_id)["Items"] if r["RouteKey"] == "$connect")
+ apigw.update_route(ApiId=api_id, RouteId=connect["RouteId"], AuthorizationType="AWS_IAM")
+
+ status, body = _ws_handshake(api_id, "/prod")
+ assert (status, body["message"]) == (403, "Missing Authentication Token")
+ signed = {"Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/execute-api/aws4_request, "
+ "SignedHeaders=host;x-amz-date, Signature=0"}
+ assert _ws_handshake(api_id, "/prod", signed)[0] == 101
+ presigned = "/prod?X-Amz-Credential=test%2F20260101%2Fus-east-1%2Fexecute-api%2Faws4_request&X-Amz-Signature=0"
+ assert _ws_handshake(api_id, presigned)[0] == 101
+
+
@pytest.mark.parametrize("resource, message", [
({"Type": "AWS::ApiGatewayV2::Authorizer", "Properties": {
"AuthorizerType": "JWT", "Name": "jwt", "IdentitySource": ["route.request.querystring.token"],
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 666a0efa..0e933afc 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -2107,6 +2107,75 @@ class TestResourceArn:
))
assert seen["action"] == "execute-api:Invoke"
+ @pytest.mark.parametrize("granted,refusal", [
+ ("d9506af4/prod/$connect", None),
+ ("d9506af4/prod/$default", (403, (
+ "User: arn:aws:iam::000000000000:user/ws-user is not authorized to perform: execute-api:Invoke "
+ "on resource: arn:aws:execute-api:eu-central-1:000000000000:d9506af4/prod/$connect "
+ "because no identity-based policy allows the execute-api:Invoke action"))),
+ ], ids=["connect", "other-route"])
+ def test_websocket_aws_iam_connect_asks_for_invoke_on_connect(self, monkeypatch, granted, refusal):
+ """A handshake on an AWS_IAM $connect route is authorized as execute-api:Invoke on <api>/<stage>/$connect."""
+ import ministack.app as app
+ from ministack.services import apigateway as apigw_svc
+ from ministack.services import iam as iam_svc
+
+ fake_key = "AKIATESTWSCONNECT01"
+ iam_svc._access_keys[fake_key] = {
+ "UserName": "ws-user", "AccessKeyId": fake_key,
+ "SecretAccessKey": "s", "Status": "Active", "CreateDate": "2024-01-01",
+ }
+ iam_svc._users["ws-user"] = {
+ "UserName": "ws-user", "Arn": "arn:aws:iam::000000000000:user/ws-user",
+ "UserId": "AIDAWSCONN1", "CreateDate": "2024-01-01", "Path": "/",
+ "AttachedPolicies": [], "Tags": [],
+ }
+ iam_svc._user_inline_policies["ws-user"] = {"p": json.dumps({"Statement": [{
+ "Effect": "Allow", "Action": "execute-api:Invoke",
+ "Resource": f"arn:aws:execute-api:eu-central-1:000000000000:{granted}",
+ }]})}
+ monkeypatch.setattr(app, "AUTH", True)
+ monkeypatch.setattr(apigw_svc, "_api_owner", lambda api_id: ("WEBSOCKET", "000000000000", "eu-central-1"))
+ monkeypatch.setattr(apigw_svc, "_match_ws_route",
+ lambda api_id, key: {"routeKey": "$connect", "authorizationType": "AWS_IAM"})
+ stages = apigw_svc.AccountRegionScopedDict()
+ stages.set_scoped("000000000000", "eu-central-1", "d9506af4", {"prod": {}})
+ monkeypatch.setattr(apigw_svc, "_stages", stages)
+ connected = []
+
+ async def connect_integration(*args, **kwargs):
+ connected.append(args[4])
+ return {"statusCode": 403}
+
+ monkeypatch.setattr(apigw_svc, "_invoke_ws_lambda", connect_integration)
+
+ async def receive():
+ return {"type": "websocket.connect"}
+
+ def handshake(query):
+ sent = []
+
+ async def send(message):
+ sent.append(message)
+
+ scope = {"type": "websocket", "path": "/prod", "query_string": query.encode(), "headers": [],
+ "extensions": {"websocket.http.response": {}}}
+ asyncio.run(apigw_svc.handle_websocket(scope, receive, send, "d9506af4"))
+ return sent[0].get("status"), json.loads(sent[1]["body"])["message"] if len(sent) > 1 else None
+
+ try:
+ unsigned = handshake("")
+ signed = handshake(f"X-Amz-Credential={fake_key}%2F20260101%2Feu-central-1%2Fexecute-api%2Faws4_request")
+ finally:
+ iam_svc._access_keys.pop(fake_key, None)
+ iam_svc._users.pop("ws-user", None)
+ iam_svc._user_inline_policies.pop("ws-user", None)
+ assert unsigned == (403, "Missing Authentication Token")
+ if refusal is None:
+ assert connected == ["prod"]
+ else:
+ assert (connected, signed) == ([], refusal)
+
# --- Lambda Function URLs ---
@pytest.mark.parametrize("resolved,arn,context", [
(("000000000000", "eu-central-1", "notify", None, {"AuthType": "AWS_IAM"}),