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
feat(apigateway): run REQUEST authorizers on WebSocket $connect (#1929)
iot-rocketa13203dbc558
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4a245283..096cdf8c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **API Gateway v2 (WebSocket API) — `$connect` authorization** — a `CUSTOM` `$connect` route ran no authorizer. It now runs its REQUEST authorizer, refuses the handshake with 401, 403 or 500 and passes `principalId` and the context to `requestContext.authorizer` of the connection's events. `CreateAuthorizer`, `CreateRoute`, `UpdateRoute` and the CloudFormation resources refuse a JWT authorizer, JWT route authorization and authorization on a route other than `$connect` with `BadRequestException`, as AWS does; a JWT `$connect` route kept in saved state refuses the handshake with 500 instead of validating the token. `requestContext.stage` names the stage in the connection URL instead of `$default`.+- **CloudFormation — a change set with only new stack tags lists them** — it ended `FAILED` with "didn't contain changes"; it now lists each resource the stack holds, other than a custom resource or wait condition, as a `Modify` with `Scope: Tags`, and stack tags given in another order are no change for a change set or `UpdateStack`. Contributed by @iot-rocket.- **CloudFormation — change sets list what a change reaches** — a resource that references a replaced resource, an attribute of a modified resource or a changed parameter is now listed as a `Modify` whose detail names the cause (`ChangeSource` `ResourceReference`, `ResourceAttribute` or `ParameterReference`, with `CausingEntity`). Contributed by @iot-rocket.diff --git a/ministack/app.py b/ministack/app.pyindex 75eb8160..a8106d9e 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -2609,13 +2609,13 @@ async def app(scope, receive, send):returntry:if parsed:- ws_api_id, _stage, _execute_path = parsed+ ws_api_id, ws_stage, ws_execute_path = parsedawait _get_module("apigateway").handle_websocket(scope,receive,send,ws_api_id,- path_override=_execute_path,+ path_override=f"/{ws_stage}{ws_execute_path}",)elif appsync_rt_m:await _get_module("appsync_events").handle_websocket(scope, receive, send, appsync_rt_m.group(1))diff --git a/ministack/core/arn.py b/ministack/core/arn.pyindex 1709d674..d065b747 100644--- a/ministack/core/arn.py+++ b/ministack/core/arn.py@@ -76,3 +76,8 @@ def execute_api_arn(region: str, account_id: str, api_id: str,f"arn:aws:execute-api:{region}:{account_id}:"f"{api_id}/{stage}/{method}/{path.lstrip('/')}")+++def execute_api_route_arn(region: str, account_id: str, api_id: str, stage: str, route_key: str) -> str:+ """Build the ``execute-api`` ARN of a WebSocket route: ``...:<api-id>/<stage>/<route-key>``."""+ return f"arn:aws:execute-api:{region}:{account_id}:{api_id}/{stage}/{route_key}"diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.pyindex ea7f2339..0a65089a 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, execute_api_arn, parse_arn+from ministack.core.arn import ArnParseError, execute_api_arn, execute_api_route_arn, parse_arnfrom ministack.core.concurrency import run_reentrantfrom ministack.core.responses import (AccountRegionScopedDict,@@ -879,7 +879,8 @@ def _request_authorizer_identity_sources(identity_source, headers, query_params,"""Resolve a REQUEST authorizer's identitySource list to (all_present, values).HTTP API identitySource entries use `$request.header.*` / `$request.querystring.*`- / `$stageVariables.*` (unlike REST's `method.request.*`). Returns whether+ / `$stageVariables.*` (unlike REST's `method.request.*`), WebSocket APIs+ `route.request.header.*` / `route.request.querystring.*` / `stageVariables.*`. Returns whetherevery declared source is present+non-empty and the ordered values (usedfor the cache-key). Mirrors apigateway_v1._request_identity_sources."""@@ -888,6 +889,8 @@ def _request_authorizer_identity_sources(identity_source, headers, query_params,for src in (identity_source or []):if not isinstance(src, str):continue+ if src.startswith(("route.request.", "stageVariables.")):+ src = "$" + src.removeprefix("route.")val = ""if src.startswith("$request.header."):val = headers.get(src[len("$request.header."):].lower()) or ""@@ -940,7 +943,7 @@ def _cache_authorizer_result(key, expires_at, result, context):async def _invoke_request_authorizer_lambda(authorizer, event, account_id, region):- """Invoke a REQUEST authorizer's Lambda and return its raw execution result dict."""+ """Invoke a REQUEST authorizer's Lambda; its response object, or None if it failed or answered no object."""from ministack.services import lambda_svclambda_ref = _extract_lambda_ref_from_integration_uri(authorizer.get("authorizerUri", ""))@@ -950,10 +953,21 @@ async def _invoke_request_authorizer_lambda(authorizer, event, account_id, regioif func_data is None or func_config is None:return Noneexec_record = lambda_svc._execution_record_for_config(func_data, func_config)- return await run_reentrant(+ result = await run_reentrant(lambda_svc._execute_function_with_config_scope, exec_record, event,thread_name="ministack-apigw-authorizer",)+ if not result or result.get("error"):+ return None+ payload = result.get("body")+ if isinstance(payload, bytes):+ payload = payload.decode("utf-8", errors="replace")+ if isinstance(payload, str):+ try:+ payload = json.loads(payload)+ except json.JSONDecodeError:+ return None+ return payload if isinstance(payload, dict) else Noneasync def _authorize_request_v2(@@ -1082,22 +1096,8 @@ async def _authorize_request_v2(cached = (hit[1], hit[2])if cached is None:- result = await _invoke_request_authorizer_lambda(authorizer, event, owner_account_id, owner_region)- if result is None:- # Authorizer Lambda unresolved / not found -> connection failure.- return (500, {"Content-Type": "application/json"}, json.dumps({"message": "Internal Server Error"}).encode()), None- if result.get("error"):- return (500, {"Content-Type": "application/json"}, json.dumps({"message": "Internal Server Error"}).encode()), None-- payload = result.get("body")- if isinstance(payload, (str, bytes)):- if isinstance(payload, bytes):- payload = payload.decode("utf-8", errors="replace")- try:- payload = json.loads(payload)- except json.JSONDecodeError:- payload = None- if not isinstance(payload, dict):+ payload = await _invoke_request_authorizer_lambda(authorizer, event, owner_account_id, owner_region)+ if payload is None:return (500, {"Content-Type": "application/json"}, json.dumps({"message": "Internal Server Error"}).encode()), Noneraw_ctx = payload.get("context") or {}@@ -1907,9 +1907,40 @@ def _delete_cors_configuration(api_id):# ---- Control plane: Routes ----+_WS_AUTHORIZER_TYPE_MESSAGE = (+ "Invalid authorizer type. Only REQUEST authorizer type is supported on WEBSOCKET protocol Apis."+)+++def _ws_authorizer_type_message(api_id, authorizer_type):+ """The BadRequestException message a WebSocket API answers for an authorizer type it does not support."""+ if _apis.get(api_id, {}).get("protocolType") == "WEBSOCKET" and authorizer_type != "REQUEST":+ return _WS_AUTHORIZER_TYPE_MESSAGE+ return None+++def _ws_route_authorization_message(api_id, route_key, authorization_type):+ """The BadRequestException message a WebSocket API answers for route authorization it does not support."""+ if _apis.get(api_id, {}).get("protocolType") != "WEBSOCKET" or (authorization_type or "NONE") == "NONE":+ return None+ if route_key != "$connect":+ return "Currently, authorization is restricted to the $connect route only"+ if authorization_type == "JWT":+ return "Currently, JWT authorization type is restricted to APIs with a protocol type of HTTP"+ return None+++def _ws_route_authorization_error(api_id, route_key, authorization_type):+ """The BadRequestException a WebSocket API answers for route authorization it does not support."""+ message = _ws_route_authorization_message(api_id, route_key, authorization_type)+ return _apigw_error("BadRequestException", message, 400) if message else None++def _create_route(api_id, data):if api_id not in _apis:return _api_not_found(api_id)+ if err := _ws_route_authorization_error(api_id, data.get("routeKey", "$default"), data.get("authorizationType")):+ return errroute_id = new_uuid()[:8]route = {"routeId": route_id,@@ -1952,6 +1983,10 @@ def _update_route(api_id, route_id, data):route = _routes.get(api_id, {}).get(route_id)if not route:return _apigw_error("NotFoundException", f"Route {route_id} not found", 404)+ if err := _ws_route_authorization_error(+ api_id, data.get("routeKey", route["routeKey"]), data.get("authorizationType", route.get("authorizationType")),+ ):+ return errfor k in ("routeKey","target",@@ -2274,6 +2309,8 @@ def _untag_resource(resource_arn: str, tag_keys: list):def _create_authorizer(api_id, data):if api_id not in _apis:return _api_not_found(api_id)+ if message := _ws_authorizer_type_message(api_id, data.get("authorizerType")):+ return _apigw_error("BadRequestException", message, 400)auth_id = new_uuid()[:8]authorizer = {"authorizerId": auth_id,@@ -2553,6 +2590,41 @@ def _evaluate_route_selection(expr: str, payload_text: str) -> str:return "$default"+def _ws_request_context(api_id: str, route_key: str, stage: str, connection_id: str, event_type: str,+ request_id: str, source_ip: str, headers: dict) -> dict:+ """requestContext of a WebSocket event, shared by route integrations and the $connect authorizer."""+ now_ms = int(time.time() * 1000)+ return {+ "routeKey": route_key,+ "eventType": event_type,+ "extendedRequestId": new_uuid(),+ "requestTime": time.strftime("%d/%b/%Y:%H:%M:%S +0000"),+ "stage": stage,+ "connectedAt": now_ms,+ "requestTimeEpoch": now_ms,+ "identity": {"sourceIp": source_ip, "userAgent": headers.get("user-agent", "")},+ "requestId": request_id,+ "domainName": f"{api_id}.execute-api.{_HOST}",+ "connectionId": connection_id,+ "apiId": api_id,+ }+++def _ws_connect_fields(headers: dict, query_params: dict | None) -> dict:+ """Handshake headers and query string as a $connect event carries them."""+ # AWS flattens single-valued QS params to string, keeps multi-valued as lists.+ return {+ "headers": dict(headers),+ "multiValueHeaders": {k: [v] for k, v in headers.items()},+ "queryStringParameters": {+ k: (v[-1] if isinstance(v, list) else v) for k, v in query_params.items()+ } if query_params else None,+ "multiValueQueryStringParameters": {+ k: (v if isinstance(v, list) else [v]) for k, v in query_params.items()+ } if query_params else None,+ }++async def _invoke_ws_lambda(api_id: str, account_id: str, region: str, route: dict, stage: str,connection_id: str, event_type: str, message_id: str,body_text: str, source_ip: str, headers: dict,@@ -2620,20 +2692,11 @@ async def _invoke_ws_lambda(api_id: str, account_id: str, region: str, route: diif func_data is None or func_config is None:return None- request_context = {- "routeKey": route.get("routeKey", "$default"),- "eventType": event_type,- "extendedRequestId": new_uuid(),- "requestTime": time.strftime("%d/%b/%Y:%H:%M:%S +0000"),- "stage": stage,- "connectedAt": int(time.time() * 1000),- "requestTimeEpoch": int(time.time() * 1000),- "identity": {"sourceIp": source_ip, "userAgent": headers.get("user-agent", "")},- "requestId": message_id,- "domainName": f"{api_id}.execute-api.{_HOST}",- "connectionId": connection_id,- "apiId": api_id,- }+ request_context = _ws_request_context(+ api_id, route.get("routeKey", "$default"), stage, connection_id, event_type, message_id, source_ip, headers,+ )+ if kwargs.get("authorizer") is not None:+ request_context["authorizer"] = kwargs["authorizer"]if event_type == "DISCONNECT":# Populated by handle_websocket from the ASGI disconnect message.request_context["disconnectReason"] = kwargs.get("disconnect_reason", "")@@ -2647,29 +2710,7 @@ async def _invoke_ws_lambda(api_id: str, account_id: str, region: str, route: di"isBase64Encoded": False,}if event_type == "CONNECT":- event["headers"] = dict(headers)- event["multiValueHeaders"] = {k: [v] for k, v in headers.items()}- if query_params:- # AWS flattens single-valued QS params to string, keeps multi-valued as lists.- event["queryStringParameters"] = {- k: (v[-1] if isinstance(v, list) else v)- for k, v in query_params.items()- }- event["multiValueQueryStringParameters"] = {- k: (v if isinstance(v, list) else [v])- for k, v in query_params.items()- }- else:- event["queryStringParameters"] = None- event["multiValueQueryStringParameters"] = None- authorizer_claims = kwargs.get("authorizer_claims")- if authorizer_claims is not None:- request_context["authorizer"] = {- "jwt": {- "claims": authorizer_claims,- "scopes": kwargs.get("authorizer_scopes") or [],- }- }+ event.update(_ws_connect_fields(headers, query_params))runtime = func_config.get("Runtime", "")code_zip = func_data.get("code_zip")@@ -2700,6 +2741,58 @@ async def _invoke_ws_lambda(api_id: str, account_id: str, region: str, route: direturn {"statusCode": 200, "body": ""}+_WS_DENY_REASONS = {+ "Deny": "with an explicit deny in an identity-based policy",+ "NoMatch": "because no identity-based policy allows the execute-api:Invoke action",+}+++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++ authorizer = _authorizers.get(api_id, {}).get(route.get("authorizerId") or "")+ if not authorizer:+ return (500, ""), None+ stage = request_context["stage"]+ stage_vars = _get_stage_variables(api_id, stage)+ present, _values = _request_authorizer_identity_sources(+ authorizer.get("identitySource"), headers, query_params, stage_vars,+ )+ if not present:+ return (401, "Unauthorized"), None+ method_arn = execute_api_route_arn(region, account_id, api_id, stage, "$connect")+ event = {+ "type": "REQUEST",+ "methodArn": method_arn,+ **_ws_connect_fields(headers, query_params),+ "stageVariables": stage_vars,+ "requestContext": {**request_context, "messageDirection": "IN"},+ }+ payload = await _invoke_request_authorizer_lambda(authorizer, event, account_id, region)+ policy = (payload or {}).get("policyDocument")+ if not isinstance(policy, dict) or not isinstance(payload.get("context") or {}, dict):+ return (500, ""), None+ decision = _evaluate_authorizer_policy(policy, method_arn)+ if decision != "Allow":+ return (403, f"User is not authorized to access this resource {_WS_DENY_REASONS[decision]}"), None+ context = _stringify_context(payload.get("context"))+ if payload.get("principalId") is not None:+ context["principalId"] = str(payload["principalId"])+ return None, context+++async def _refuse_ws_handshake(scope, send, status, message, connection_id, request_id):+ """Answer the upgrade with an HTTP error response, as API Gateway does."""+ if "websocket.http.response" not in (scope.get("extensions") or {}):+ await send({"type": "websocket.close", "code": 1008})+ return+ body = json.dumps({"message": message, "connectionId": connection_id, "requestId": request_id}).encode()+ await send({"type": "websocket.http.response.start", "status": status,+ "headers": [(b"content-type", b"application/json")]})+ await send({"type": "websocket.http.response.body", "body": body})++async def handle_websocket(scope, receive, send, api_id: str, path_override: str | None = None):"""Drive a WebSocket session for a $WEBSOCKET API.@@ -2769,32 +2862,34 @@ async def handle_websocket(scope, receive, send, api_id: str, path_override: strtry:# $connect hookconnect_route = _match_ws_route(api_id, "$connect")+ authorizer_context = Noneif connect_route is not None:- # JWT authorizer validation (mirrors the HTTP API path).auth_type = (connect_route.get("authorizationType") or "NONE").upper()- ws_authorizer_claims = None- ws_authorizer_scopes = []- if auth_type == "JWT":- authorizer_id = connect_route.get("authorizerId")- authorizer = _authorizers.get(api_id, {}).get(authorizer_id) if authorizer_id else None- if not authorizer:- await send({"type": "websocket.close", "code": 1008})- return- claims, scopes, auth_error = await _validate_jwt_authorizer(- connect_route, authorizer, headers, query_params or {},+ connect_request_id = new_uuid()+ refusal = None+ if auth_type == "CUSTOM":+ refusal, authorizer_context = await _authorize_ws_connect(+ api_id, connect_route,+ _ws_request_context(api_id, "$connect", stage, connection_id, "CONNECT",+ connect_request_id, source_ip, headers),+ headers, query_params, account_id, owner_region,)- if auth_error:- await send({"type": "websocket.close", "code": 1008})- return- ws_authorizer_claims = claims or {}- ws_authorizer_scopes = scopes or []+ elif auth_type == "JWT":+ # only a route restored from state saved before the route checks existed+ logger.warning(+ "WebSocket API %s: JWT authorization on $connect is not supported, refusing the handshake",+ api_id,+ )+ refusal = (500, "")+ if refusal:+ await _refuse_ws_handshake(scope, send, *refusal, connection_id, connect_request_id)+ returnresp = await _invoke_ws_lambda(api_id, account_id, owner_region, connect_route, stage, connection_id,- "CONNECT", new_uuid(), "", source_ip, headers,+ "CONNECT", connect_request_id, "", source_ip, headers,query_params=query_params,- authorizer_claims=ws_authorizer_claims,- authorizer_scopes=ws_authorizer_scopes,+ authorizer=authorizer_context,)status = int((resp or {}).get("statusCode", 200))if status < 200 or status >= 300:@@ -2869,7 +2964,7 @@ async def handle_websocket(scope, receive, send, api_id: str, path_override: strmsg_id = new_uuid()resp = await _invoke_ws_lambda(api_id, account_id, owner_region, route, stage, connection_id, "MESSAGE",- msg_id, payload, source_ip, headers,+ msg_id, payload, source_ip, headers, authorizer=authorizer_context,)if resp is None:continue@@ -2897,6 +2992,7 @@ async def handle_websocket(scope, receive, send, api_id: str, path_override: str"DISCONNECT", new_uuid(), "", source_ip, headers,disconnect_code=disconnect_code,disconnect_reason=disconnect_reason,+ authorizer=authorizer_context,)except Exception:logger.exception("error firing $disconnect")diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 03011ace..7194cc58 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -9616,6 +9616,8 @@ def _apigw_v2_route_create(logical_id, props, stack_name):api_id = props.get("ApiId", "")route_id = new_uuid()[:8]route = {"routeId": route_id, **_apigw_v2_route_props(props)}+ if message := _apigw_v2._ws_route_authorization_message(api_id, route["routeKey"], route["authorizationType"]):+ raise ValueError(message)_apigw_v2._routes.setdefault(api_id, {})[route_id] = routephysical_id = f"{api_id}/{route_id}"return physical_id, {"RouteId": route_id}@@ -9669,6 +9671,8 @@ def _apigw_v2_authorizer_create(logical_id, props, stack_name):.Issuer are translated here rather than passed through PascalCase."""api_id = props.get("ApiId", "")+ if message := _apigw_v2._ws_authorizer_type_message(api_id, props.get("AuthorizerType", "JWT")):+ raise ValueError(message)auth_id = new_uuid()[:8]jwt_cfg = props.get("JwtConfiguration") or {}authorizer = {@@ -9708,6 +9712,8 @@ def _apigw_v2_authorizer_update(physical_id, old_props, new_props, stack_name):authorizer = authorizers.get(physical_id)if not authorizer:return _apigw_v2_authorizer_create(physical_id, new_props, stack_name)+ if message := _apigw_v2._ws_authorizer_type_message(api_id, new_props.get("AuthorizerType", "JWT")):+ raise ValueError(message)jwt_cfg = new_props.get("JwtConfiguration") or {}authorizer.update({"authorizerType": new_props.get("AuthorizerType", "JWT"),diff --git a/tests/test_apigatewayv2.py b/tests/test_apigatewayv2.pyindex 4e20c1d2..df78f2ef 100644--- a/tests/test_apigatewayv2.py+++ b/tests/test_apigatewayv2.py@@ -3054,51 +3054,200 @@ def test_apigwv2_path_based_websocket(apigw, lam):ws.close()-def test_ws_connect_jwt_authorizer_rejects_missing_token(apigw, lam, cognito_idp):- """$connect with a JWT authorizer rejects connections that lack a valid token (#1074)."""+_WS_CONTEXT_CODE = """+import json+def handler(event, context):+ rc = event['requestContext']+ return {'statusCode': 200, 'body': json.dumps({'stage': rc['stage'], 'authorizer': rc.get('authorizer')})}+"""- pool_id = cognito_idp.create_user_pool(PoolName=f"ws-jwt-{_uuid_mod.uuid4().hex[:8]}")["UserPool"]["Id"]- issuer = f"https://cognito-idp.us-east-1.amazonaws.com/{pool_id}"- api = apigw.create_api(Name=f"ws-jwt-deny-{_uuid_mod.uuid4().hex[:8]}", ProtocolType="WEBSOCKET")- api_id = api["ApiId"]- fn_name = f"ws-jwt-con-{_uuid_mod.uuid4().hex[:6]}"- arn = _make_fn(lam, fn_name, _ECHO_CODE)- integ = apigw.create_integration(- ApiId=api_id, IntegrationType="AWS_PROXY",- IntegrationUri=arn, IntegrationMethod="POST",- )[email protected]("path_based", [False, True], ids=["host", "path"])+def test_ws_request_context_names_the_stage(apigw, lam, path_based):+ """requestContext.stage is the stage named in the connection URL."""+ api_id, _ = _wire_ws_api(apigw, lam, name_suffix=f"stage-{uuid.uuid4().hex[:6]}",+ default_code=_WS_CONTEXT_CODE)+ if path_based:+ path, host = f"/_aws/execute-api/{api_id}/prod", f"localhost:{_EXECUTE_PORT}"+ else:+ path, host = "/prod", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"+ ws = _WSClient("localhost", _EXECUTE_PORT, path, headers={"Host": host})+ try:+ ws.send(json.dumps({"action": "x"}))+ assert json.loads(ws.recv())["stage"] == "prod"+ finally:+ ws.close()+++_WS_AUTHORIZER_CODE = """+def handler(event, context):+ tok = {k.lower(): v for k, v in event['headers'].items()}.get('auth', '')+ if tok == 'error':+ raise Exception('authorizer failed')+ arn = event['methodArn']+ return {+ 'principalId': 'alice',+ 'policyDocument': {'Version': '2012-10-17', 'Statement': [{+ 'Action': 'execute-api:Invoke', 'Resource': arn.replace('/prod/', '/other/') if tok == 'other' else arn,+ 'Effect': 'Allow' if tok in ('allow', 'other') else 'Deny'}]},+ 'context': {'user': 'alice', 'n': 7, 'ok': True, 'methodArn': arn, 'type': event['type'],+ 'eventType': event['requestContext']['eventType'],+ 'requestId': event['requestContext']['requestId']},+ }+"""++_WS_CONNECT_NEEDS_AUTHORIZER_CODE = """+def handler(event, context):+ rc = event['requestContext']+ authorizer = rc.get('authorizer') or {}+ same_request = authorizer.get('requestId') == rc['requestId']+ return {'statusCode': 200 if authorizer.get('user') == 'alice' and same_request else 403}+"""+++def _wire_ws_request_authorizer_api(apigw, lam,+ identity_source=("route.request.header.Auth", "route.request.querystring.tok")):+ """WS API whose $connect route uses a REQUEST authorizer, by default on header Auth + querystring tok."""+ api_id, _ = _wire_ws_api(apigw, lam, name_suffix=f"reqauth-{uuid.uuid4().hex[:6]}",+ connect_code=_WS_CONNECT_NEEDS_AUTHORIZER_CODE, default_code=_WS_CONTEXT_CODE)+ fn_arn = _make_fn(lam, f"ws-reqauth-authorizer-{uuid.uuid4().hex[:6]}", _WS_AUTHORIZER_CODE)auth_id = apigw.create_authorizer(- ApiId=api_id, AuthorizerType="JWT", Name="ws-jwt",- IdentitySource=["$request.querystring.token"],- JwtConfiguration={"Audience": ["ws-client"], "Issuer": issuer},+ ApiId=api_id, AuthorizerType="REQUEST", Name="ws-request",+ AuthorizerUri=f"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/{fn_arn}/invocations",+ IdentitySource=list(identity_source),)["AuthorizerId"]- apigw.create_route(- ApiId=api_id, RouteKey="$connect",- Target=f"integrations/{integ['IntegrationId']}",- AuthorizationType="JWT", AuthorizerId=auth_id,- )- apigw.create_route(- ApiId=api_id, RouteKey="$default",- Target=f"integrations/{integ['IntegrationId']}",- )- apigw.create_stage(ApiId=api_id, StageName="prod")+ 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="CUSTOM", AuthorizerId=auth_id)+ return api_id- # Without a token → connection must be rejected (close code 1008).- with pytest.raises(Exception):- _WSClient("localhost", _EXECUTE_PORT, "/prod",- headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"})- # With a valid token → connection must be accepted.- now = int(time.time())- token = _make_signed_token({- "sub": "ws-user", "iss": issuer, "aud": "ws-client",- "iat": now, "nbf": now - 1, "exp": now + 3600,- })- ws = _WSClient("localhost", _EXECUTE_PORT, f"/prod?token={token}",- headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"})- ws.close()- cognito_idp.delete_user_pool(UserPoolId=pool_id)+def _ws_handshake(api_id: str, path: str, headers: dict | None = None) -> tuple[int, dict]:+ """Status and JSON body of a WebSocket upgrade request."""+ import http.client++ conn = http.client.HTTPConnection("localhost", _EXECUTE_PORT, timeout=30)+ try:+ conn.request("GET", path, headers={+ "Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}", "Upgrade": "websocket",+ "Connection": "Upgrade", "Sec-WebSocket-Key": base64.b64encode(os.urandom(16)).decode(),+ "Sec-WebSocket-Version": "13", **(headers or {}),+ })+ resp = conn.getresponse()+ return resp.status, json.loads(resp.read() or b"{}")+ finally:+ conn.close()+++def test_ws_connect_request_authorizer_refuses_the_handshake(apigw, lam):+ """A $connect REQUEST authorizer refuses with 401 (identity source missing), 403 (denied) or 500."""+ api_id = _wire_ws_request_authorizer_api(apigw, lam)+ cases = [+ ("/prod", {}, 401, "Unauthorized"),+ ("/prod", {"Auth": "allow"}, 401, "Unauthorized"),+ ("/prod?tok=1", {"Auth": "deny"}, 403,+ "User is not authorized to access this resource with an explicit deny in an identity-based policy"),+ ("/prod?tok=1", {"Auth": "other"}, 403,+ "User is not authorized to access this resource because no identity-based policy allows "+ "the execute-api:Invoke action"),+ ("/prod?tok=1", {"Auth": "error"}, 500, ""),+ ]+ for path, headers, status, message in cases:+ got_status, body = _ws_handshake(api_id, path, headers)+ assert (got_status, body.get("message")) == (status, message), (path, headers)+ assert body["connectionId"] and body["requestId"]+++def test_ws_connect_request_authorizer_reads_stage_variables(apigw, lam):+ """A stageVariables.* identity source is present once the stage defines that variable."""+ api_id = _wire_ws_request_authorizer_api(apigw, lam, identity_source=("route.request.header.Auth",+ "stageVariables.tier"))+ assert _ws_handshake(api_id, "/prod", {"Auth": "deny"})[0] == 401+ apigw.update_stage(ApiId=api_id, StageName="prod", StageVariables={"tier": "gold"})+ assert _ws_handshake(api_id, "/prod", {"Auth": "deny"})[0] == 403+++def test_ws_connect_request_authorizer_context_reaches_the_routes(apigw, lam):+ """An allowed $connect passes principalId and the stringified context to $connect and later messages."""+ api_id = _wire_ws_request_authorizer_api(apigw, lam)+ ws = _WSClient("localhost", _EXECUTE_PORT, "/prod?tok=1",+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}", "Auth": "allow"})+ try:+ ws.send(json.dumps({"action": "x"}))+ reply = json.loads(ws.recv())+ finally:+ ws.close()+ authorizer = reply["authorizer"]+ assert authorizer.pop("requestId")+ assert authorizer == {+ "principalId": "alice", "user": "alice", "n": "7", "ok": "true", "type": "REQUEST", "eventType": "CONNECT",+ "methodArn": f"arn:aws:execute-api:us-east-1:000000000000:{api_id}/prod/$connect",+ }++[email protected]("resource, message", [+ ({"Type": "AWS::ApiGatewayV2::Authorizer", "Properties": {+ "AuthorizerType": "JWT", "Name": "jwt", "IdentitySource": ["route.request.querystring.token"],+ "JwtConfiguration": {"Audience": ["client"], "Issuer": "https://issuer.example.com"}}},+ "Invalid authorizer type. Only REQUEST authorizer type is supported on WEBSOCKET protocol Apis."),+ ({"Type": "AWS::ApiGatewayV2::Route", "Properties": {"RouteKey": "$connect", "AuthorizationType": "JWT"}},+ "Currently, JWT authorization type is restricted to APIs with a protocol type of HTTP"),+ ({"Type": "AWS::ApiGatewayV2::Route", "Properties": {"RouteKey": "send", "AuthorizationType": "CUSTOM"}},+ "Currently, authorization is restricted to the $connect route only"),+], ids=["jwt-authorizer", "jwt-route", "custom-on-send"])+def test_ws_cfn_refuses_route_authorization_a_websocket_api_does_not_support(cfn, resource, message):+ """A template fails the stack where CreateAuthorizer or CreateRoute would answer BadRequestException."""+ stack = f"ws-cfnauth-{uuid.uuid4().hex[:8]}"+ cfn.create_stack(StackName=stack, TemplateBody=json.dumps({"Resources": {+ "Api": {"Type": "AWS::ApiGatewayV2::Api", "Properties": {+ "Name": stack, "ProtocolType": "WEBSOCKET", "RouteSelectionExpression": "$request.body.action"}},+ "Refused": {"Type": resource["Type"], "Properties": {"ApiId": {"Ref": "Api"}, **resource["Properties"]}},+ }}))+ try:+ for _ in range(60):+ status = cfn.describe_stacks(StackName=stack)["Stacks"][0]["StackStatus"]+ if not status.endswith("_IN_PROGRESS"):+ break+ time.sleep(1)+ assert status == "ROLLBACK_COMPLETE"+ reasons = [e.get("ResourceStatusReason", "") for e in cfn.describe_stack_events(StackName=stack)["StackEvents"]+ if e["LogicalResourceId"] == "Refused"]+ assert any(message in r for r in reasons), reasons+ finally:+ cfn.delete_stack(StackName=stack)+++def test_ws_route_authorization_limited_to_connect_and_request_authorizers(apigw):+ """A WebSocket API takes REQUEST authorizers only, and route authorization on $connect only, never JWT."""+ api_id = apigw.create_api(Name=f"ws-auth-rules-{_uuid_mod.uuid4().hex[:8]}", ProtocolType="WEBSOCKET")["ApiId"]++ def refused(message, call, **kwargs):+ with pytest.raises(ClientError) as exc:+ call(ApiId=api_id, **kwargs)+ assert exc.value.response["Error"]["Code"] == "BadRequestException"+ assert exc.value.response["Error"]["Message"] == message++ refused("Invalid authorizer type. Only REQUEST authorizer type is supported on WEBSOCKET protocol Apis.",+ apigw.create_authorizer, AuthorizerType="JWT", Name="jwt",+ IdentitySource=["route.request.header.Auth"],+ JwtConfiguration={"Audience": ["client"], "Issuer": "https://issuer.example.com"})+ auth_id = apigw.create_authorizer(+ ApiId=api_id, AuthorizerType="REQUEST", Name="request", IdentitySource=["route.request.header.Auth"],+ AuthorizerUri="arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/"+ "arn:aws:lambda:us-east-1:000000000000:function:auth/invocations",+ )["AuthorizerId"]+ jwt_refused = "Currently, JWT authorization type is restricted to APIs with a protocol type of HTTP"+ refused(jwt_refused, apigw.create_route, RouteKey="$connect", AuthorizationType="JWT", AuthorizerId=auth_id)+ connect_id = apigw.create_route(ApiId=api_id, RouteKey="$connect")["RouteId"]+ refused(jwt_refused, apigw.update_route, RouteId=connect_id, AuthorizationType="JWT", AuthorizerId=auth_id)+ assert apigw.update_route(+ ApiId=api_id, RouteId=connect_id, AuthorizationType="CUSTOM", AuthorizerId=auth_id,+ )["AuthorizationType"] == "CUSTOM"++ connect_only = "Currently, authorization is restricted to the $connect route only"+ refused(connect_only, apigw.create_route, RouteKey="sendMessage", AuthorizationType="CUSTOM", AuthorizerId=auth_id)+ refused(connect_only, apigw.create_route, RouteKey="sendMessage", AuthorizationType="AWS_IAM")+ message_id = apigw.create_route(ApiId=api_id, RouteKey="sendMessage")["RouteId"]+ refused(connect_only, apigw.update_route, RouteId=message_id, AuthorizationType="CUSTOM", AuthorizerId=auth_id)def test_apigwv1_path_based_restapi_legacy_user_request(apigw_v1, lam):