Skip to content

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

support for API v2 WS (#387)

Nahuel Nucerae91db5976c23
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2ce69aaa..6e8cedda 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [Unreleased] — 2026-04-20
+
+### Added
+- **API Gateway v2 WebSocket APIs** — full WebSocket data plane and control plane on the execute-api host (`ws://{apiId}.execute-api.{host}:{port}/{stage}`). `CreateApi(ProtocolType=WEBSOCKET)` defaults `RouteSelectionExpression` to `$request.body.action`; adds full `RouteResponse` and `IntegrationResponse` CRUD (`Create/Get/Update/Delete` under `/v2/apis/{apiId}/routes/{routeId}/routeresponses` and `/integrations/{integrationId}/integrationresponses`). ASGI `websocket` scope is handled end-to-end: on connect, the `$connect` Lambda runs with the handshake's `queryStringParameters` / `multiValueQueryStringParameters` on the event so token-gated connect hooks work like AWS — 2xx accepts, non-2xx rejects. Incoming frames evaluate the API's `RouteSelectionExpression` and dispatch to `$connect` / `$disconnect` / `$default` / custom-action routes; Lambda event matches AWS WebSocket v2 proxy (`requestContext.connectionId` / `routeKey` / `eventType` / `messageId` / `identity.sourceIp`, real `disconnectStatusCode` + `disconnectReason` from the close frame). `AWS`, `AWS_PROXY`, and `MOCK` integration types supported (MOCK returns the first matching `IntegrationResponse.responseTemplates` entry). `@connections` management API served on the execute-api host: `PostToConnection` pushes to a per-connection outbox that the WS session drains (enables server-side push), `GetConnection`, `DeleteConnection`; unknown or closed connections return `410 GoneException`. Connections carry their owning account; cross-API `@connections` lookups are rejected and Lambda invocations run in the owner's context. No new dependencies — upgrade is served by hypercorn; tests use a stdlib-only WS client. Reported by @whittin3
## [1.3.4] — 2026-04-20
### Fixed
diff --git a/README.md b/README.md
index 0c8f0859..5f909b30 100644
--- a/README.md
+++ b/README.md
@@ -356,7 +356,7 @@ subnet = ec2.create_subnet(
| **ACM** | RequestCertificate, DescribeCertificate, ListCertificates, DeleteCertificate, GetCertificate, ImportCertificate, AddTagsToCertificate, RemoveTagsFromCertificate, ListTagsForCertificate, UpdateCertificateOptions, RenewCertificate, ResendValidationEmail | Certificates auto-issued; DNS validation records generated; supports SANs |
| **WAF v2** | CreateWebACL, GetWebACL, UpdateWebACL, DeleteWebACL, ListWebACLs, AssociateWebACL, DisassociateWebACL, GetWebACLForResource, ListResourcesForWebACL, CreateIPSet, GetIPSet, UpdateIPSet, DeleteIPSet, ListIPSets, CreateRuleGroup, GetRuleGroup, UpdateRuleGroup, DeleteRuleGroup, ListRuleGroups, TagResource, UntagResource, ListTagsForResource, CheckCapacity, DescribeManagedRuleGroup | LockToken enforced on Update/Delete; resource associations tracked |
| **Step Functions** | CreateStateMachine, DeleteStateMachine, DescribeStateMachine, UpdateStateMachine, ListStateMachines, StartExecution, StartSyncExecution, StopExecution, DescribeExecution, DescribeStateMachineForExecution, ListExecutions, GetExecutionHistory, SendTaskSuccess, SendTaskFailure, SendTaskHeartbeat, CreateActivity, DeleteActivity, DescribeActivity, ListActivities, GetActivityTask, TestState, TagResource, UntagResource, ListTagsForResource | Full ASL interpreter; Retry/Catch; waitForTaskToken; Activities (worker pattern); Pass/Task/Choice/Wait/Succeed/Fail/Map/Parallel; TestState API with mock and inspectionLevel support; SFN_MOCK_CONFIG for AWS SFN Local compatible mock testing; intrinsic functions (States.StringToJson, States.JsonToString, States.JsonMerge, States.Format); nested startExecution.sync |
-| **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, TagResource, UntagResource, GetTags | HTTP API (v2) protocol; Lambda proxy (AWS_PROXY) and HTTP proxy (HTTP_PROXY) integrations; data plane via `{apiId}.execute-api.localhost`; `{param}` and `{proxy+}` path matching; JWT/Lambda authorizer CRUD |
+| **API Gateway v2** | CreateApi, GetApi, GetApis, UpdateApi, DeleteApi, CreateRoute, GetRoute, GetRoutes, UpdateRoute, DeleteRoute, CreateIntegration, GetIntegration, GetIntegrations, UpdateIntegration, DeleteIntegration, CreateRouteResponse, GetRouteResponse, GetRouteResponses, UpdateRouteResponse, DeleteRouteResponse, CreateIntegrationResponse, GetIntegrationResponse, GetIntegrationResponses, UpdateIntegrationResponse, DeleteIntegrationResponse, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateDeployment, GetDeployment, GetDeployments, DeleteDeployment, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, TagResource, UntagResource, GetTags, PostToConnection, GetConnection, DeleteConnection | **HTTP API** and **WebSocket API** (`protocolType=WEBSOCKET`); Lambda proxy (`AWS_PROXY`), HTTP proxy (`HTTP_PROXY`), and MOCK integrations; HTTP data plane via `{apiId}.execute-api.localhost` with `{param}` / `{proxy+}` matching; WebSocket data plane with `$connect` / `$disconnect` / `$default` / custom-action routing, `$request.body.*` RouteSelectionExpression, `@connections` management API (PostToConnection / GetConnection / DeleteConnection), per-connection outbox for server-side push; JWT/Lambda authorizer CRUD |
| **API Gateway v1** | CreateRestApi, GetRestApi, GetRestApis, UpdateRestApi, DeleteRestApi, CreateResource, GetResource, GetResources, UpdateResource, DeleteResource, PutMethod, GetMethod, DeleteMethod, UpdateMethod, PutMethodResponse, GetMethodResponse, DeleteMethodResponse, PutIntegration, GetIntegration, DeleteIntegration, UpdateIntegration, PutIntegrationResponse, GetIntegrationResponse, DeleteIntegrationResponse, CreateDeployment, GetDeployment, GetDeployments, UpdateDeployment, DeleteDeployment, CreateStage, GetStage, GetStages, UpdateStage, DeleteStage, CreateAuthorizer, GetAuthorizer, GetAuthorizers, UpdateAuthorizer, DeleteAuthorizer, CreateModel, GetModel, GetModels, DeleteModel, CreateApiKey, GetApiKey, GetApiKeys, UpdateApiKey, DeleteApiKey, CreateUsagePlan, GetUsagePlan, GetUsagePlans, UpdateUsagePlan, DeleteUsagePlan, CreateUsagePlanKey, GetUsagePlanKeys, DeleteUsagePlanKey, CreateDomainName, GetDomainName, GetDomainNames, DeleteDomainName, CreateBasePathMapping, GetBasePathMapping, GetBasePathMappings, DeleteBasePathMapping, TagResource, UntagResource, GetTags | REST API (v1) protocol; Lambda proxy format 1.0 (AWS_PROXY), HTTP proxy (HTTP_PROXY), MOCK integration; data plane via `{apiId}.execute-api.localhost`; resource tree with `{param}` and `{proxy+}` path matching; JSON Patch for all PATCH operations; state persistence |
| **ELBv2 / ALB** | CreateLoadBalancer, DescribeLoadBalancers, DeleteLoadBalancer, DescribeLoadBalancerAttributes, ModifyLoadBalancerAttributes, CreateTargetGroup, DescribeTargetGroups, ModifyTargetGroup, DeleteTargetGroup, DescribeTargetGroupAttributes, ModifyTargetGroupAttributes, CreateListener, DescribeListeners, ModifyListener, DeleteListener, CreateRule, DescribeRules, ModifyRule, DeleteRule, SetRulePriorities, RegisterTargets, DeregisterTargets, DescribeTargetHealth, AddTags, RemoveTags, DescribeTags | Control plane + data plane; ALB→Lambda live traffic routing; `path-pattern`, `host-header`, `http-method`, `query-string`, `http-header` rule conditions; `forward`, `redirect`, `fixed-response` actions; data plane via `{lb-name}.alb.localhost` Host header or `/_alb/{lb-name}/` path prefix |
| **KMS** | CreateKey, ListKeys, DescribeKey, GetPublicKey, Sign, Verify, Encrypt, Decrypt, GenerateDataKey, GenerateDataKeyWithoutPlaintext, CreateAlias, DeleteAlias, ListAliases, UpdateAlias, EnableKeyRotation, DisableKeyRotation, GetKeyRotationStatus, GetKeyPolicy, PutKeyPolicy, ListKeyPolicies, EnableKey, DisableKey, ScheduleKeyDeletion, CancelKeyDeletion, TagResource, UntagResource, ListResourceTags | 27 actions; RSA (2048/4096), ECC (SECG_P256K1, NIST P-256/384/521), and symmetric keys; PKCS1v15, PSS, and ECDSA signing; envelope encryption; alias resolution; key rotation; key policies; tags; enable/disable/schedule deletion; full Terraform `aws_kms_key` compatible; `cryptography` package included in Docker image |
@@ -1075,6 +1075,7 @@ See [`Testcontainers/java-testcontainers`](Testcontainers/java-testcontainers),
| **Athena (real SQL via DuckDB)** | ✅ | ❌ | ✅ |
| **Glue Data Catalog + Jobs** | ✅ | ❌ | ✅ |
| **API Gateway v2 (HTTP API)** | ✅ | ✅ | ✅ |
+| **API Gateway v2 (WebSocket API)** | ✅ | ❌ | ✅ |
| **API Gateway v1 (REST API)** | ✅ | ✅ | ✅ |
| **Firehose** | ✅ | ✅ | ✅ |
| **Route53** | ✅ | ✅ | ✅ |
diff --git a/ministack/app.py b/ministack/app.py
index a2a15f70..f6650109 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -243,6 +243,34 @@ async def app(scope, receive, send):
await _handle_lifespan(scope, receive, send)
return
+ if scope["type"] == "websocket":
+ # WebSocket APIs only reach us via the execute-api host pattern:
+ # ws://{apiId}.execute-api.{host}[:port]/{stage}[/...]
+ ws_headers = {}
+ for name, value in scope.get("headers", []):
+ try:
+ ws_headers[name.decode("latin-1").lower()] = value.decode("utf-8")
+ except UnicodeDecodeError:
+ ws_headers[name.decode("latin-1").lower()] = value.decode("latin-1")
+ ws_host = ws_headers.get("host", "")
+ m = _EXECUTE_API_RE.match(ws_host)
+ if not m:
+ # Not an execute-api host — reject the upgrade.
+ msg = await receive()
+ if msg.get("type") == "websocket.connect":
+ await send({"type": "websocket.close", "code": 1008})
+ return
+ ws_api_id = m.group(1)
+ try:
+ await _get_module("apigateway").handle_websocket(scope, receive, send, ws_api_id)
+ except Exception:
+ logger.exception("Error in WebSocket dispatch")
+ try:
+ await send({"type": "websocket.close", "code": 1011})
+ except Exception:
+ pass
+ return
+
if scope["type"] != "http":
return
@@ -549,7 +577,16 @@ async def app(scope, receive, send):
stage = path_parts[0] if path_parts else "$default"
execute_path = "/" + path_parts[1] if len(path_parts) > 1 else "/"
try:
- if api_id in _get_module("apigateway_v1")._rest_apis:
+ # WebSocket @connections management API — lives on the execute-api host
+ # at /{stage}/@connections/{connectionId}. Detect and dispatch before
+ # normal REST/HTTP routing.
+ conn_prefix = f"/{stage}/@connections/"
+ if path.startswith(conn_prefix):
+ connection_id = path[len(conn_prefix):].split("/", 1)[0]
+ status, resp_headers, resp_body = await _get_module("apigateway").handle_connections_api(
+ method, api_id, stage, connection_id, body, headers
+ )
+ elif api_id in _get_module("apigateway_v1")._rest_apis:
status, resp_headers, resp_body = await _get_module("apigateway_v1").handle_execute(
api_id, stage, method, execute_path, headers, body, query_params
)
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index 08eee053..96764b42 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -66,6 +66,15 @@ _stages = AccountScopedDict() # api_id -> {stage_name -> stage object}
_deployments = AccountScopedDict() # api_id -> {deployment_id -> deployment object}
_authorizers = AccountScopedDict() # api_id -> {authorizer_id -> authorizer object}
_api_tags = AccountScopedDict() # resource_arn -> {key -> value}
+_route_responses = AccountScopedDict() # api_id -> {route_id -> {rr_id -> route_response}}
+_integration_responses = AccountScopedDict() # api_id -> {integration_id -> {ir_id -> int_response}}
+
+# WebSocket connection registry — connections are not per-account-scoped at the store level
+# because the @connections management API may arrive on any host/account; instead we store
+# the owning account id inside each connection record and check on access.
+# { connectionId -> {apiId, accountId, stage, connectedAt, sourceIp, outbox (asyncio.Queue),
+# close_event (asyncio.Event), lastActiveAt, identity} }
+_ws_connections: dict = {}
# ---- Response helpers ----
@@ -95,6 +104,8 @@ def get_state() -> dict:
"deployments": _deployments,
"authorizers": _authorizers,
"api_tags": _api_tags,
+ "route_responses": _route_responses,
+ "integration_responses": _integration_responses,
}
@@ -107,6 +118,8 @@ def load_persisted_state(data: dict) -> None:
_deployments.update(data.get("deployments", {}))
_authorizers.update(data.get("authorizers", {}))
_api_tags.update(data.get("api_tags", {}))
+ _route_responses.update(data.get("route_responses", {}))
+ _integration_responses.update(data.get("integration_responses", {}))
# ---- Control plane router ----
@@ -166,13 +179,28 @@ async def handle_request(method, path, headers, body, query_params):
if method == "PATCH":
return _update_api(api_id, data)
- # /v2/apis/{apiId}/routes[/{routeId}]
+ # /v2/apis/{apiId}/routes[/{routeId}[/routeresponses[/{routeResponseId}]]]
if api_id and sub == "routes":
+ rr_segment = parts[5] if len(parts) > 5 else None
+ rr_id = parts[6] if len(parts) > 6 else None
if not sub_id:
if method == "POST":
return _create_route(api_id, data)
if method == "GET":
return _get_routes(api_id)
+ elif rr_segment == "routeresponses":
+ if not rr_id:
+ if method == "POST":
+ return _create_route_response(api_id, sub_id, data)
+ if method == "GET":
+ return _get_route_responses(api_id, sub_id)
+ else:
+ if method == "GET":
+ return _get_route_response(api_id, sub_id, rr_id)
+ if method == "PATCH":
+ return _update_route_response(api_id, sub_id, rr_id, data)
+ if method == "DELETE":
+ return _delete_route_response(api_id, sub_id, rr_id)
else:
if method == "GET":
return _get_route(api_id, sub_id)
@@ -181,13 +209,28 @@ async def handle_request(method, path, headers, body, query_params):
if method == "DELETE":
return _delete_route(api_id, sub_id)
- # /v2/apis/{apiId}/integrations[/{integrationId}]
+ # /v2/apis/{apiId}/integrations[/{integrationId}[/integrationresponses[/{irId}]]]
if api_id and sub == "integrations":
+ ir_segment = parts[5] if len(parts) > 5 else None
+ ir_id = parts[6] if len(parts) > 6 else None
if not sub_id:
if method == "POST":
return _create_integration(api_id, data)
if method == "GET":
return _get_integrations(api_id)
+ elif ir_segment == "integrationresponses":
+ if not ir_id:
+ if method == "POST":
+ return _create_integration_response(api_id, sub_id, data)
+ if method == "GET":
+ return _get_integration_responses(api_id, sub_id)
+ else:
+ if method == "GET":
+ return _get_integration_response(api_id, sub_id, ir_id)
+ if method == "PATCH":
+ return _update_integration_response(api_id, sub_id, ir_id, data)
+ if method == "DELETE":
+ return _delete_integration_response(api_id, sub_id, ir_id)
else:
if method == "GET":
return _get_integration(api_id, sub_id)
@@ -428,13 +471,16 @@ async def _invoke_http_proxy(integration, path, method, headers, body, query_par
def _create_api(data):
api_id = new_uuid()[:8]
+ protocol = data.get("protocolType", "HTTP")
+ # AWS defaults: HTTP → "$request.method $request.path"; WEBSOCKET → "$request.body.action".
+ default_rse = "$request.body.action" if protocol == "WEBSOCKET" else "$request.method $request.path"
api = {
"apiId": api_id,
"name": data.get("name", "unnamed"),
- "protocolType": data.get("protocolType", "HTTP"),
+ "protocolType": protocol,
"apiEndpoint": f"http://{api_id}.execute-api.{_HOST}:{_PORT}",
"createdDate": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
- "routeSelectionExpression": data.get("routeSelectionExpression", "$request.method $request.path"),
+ "routeSelectionExpression": data.get("routeSelectionExpression", default_rse),
"apiKeySelectionExpression": data.get("apiKeySelectionExpression", "$request.header.x-api-key"),
"tags": data.get("tags", {}),
"disableSchemaValidation": data.get("disableSchemaValidation", False),
@@ -741,3 +787,526 @@ def reset():
_deployments.clear()
_authorizers.clear()
_api_tags.clear()
+ _route_responses.clear()
+ _integration_responses.clear()
+ # Signal any live WS connections to shut down, then drop registry.
+ for conn in list(_ws_connections.values()):
+ ev = conn.get("close_event")
+ if ev is not None:
+ try:
+ ev.set()
+ except Exception:
+ pass
+ _ws_connections.clear()
+
+
+# ==========================================================================
+# Route responses (WebSocket)
+# ==========================================================================
+
+def _create_route_response(api_id, route_id, data):
+ routes = _routes.get(api_id, {})
+ if route_id not in routes:
+ return _apigw_error("NotFoundException", f"Route {route_id} not found", 404)
+ rr_id = new_uuid()[:8]
+ rr = {
+ "routeResponseId": rr_id,
+ "routeResponseKey": data.get("routeResponseKey", "$default"),
+ "modelSelectionExpression": data.get("modelSelectionExpression"),
+ "responseModels": data.get("responseModels", {}),
+ "responseParameters": data.get("responseParameters", {}),
+ }
+ by_route = _route_responses.setdefault(api_id, {}).setdefault(route_id, {})
+ by_route[rr_id] = rr
+ return _apigw_response(rr, 201)
+
+
+def _get_route_responses(api_id, route_id):
+ items = list(_route_responses.get(api_id, {}).get(route_id, {}).values())
+ return _apigw_response({"items": items})
+
+
+def _get_route_response(api_id, route_id, rr_id):
+ rr = _route_responses.get(api_id, {}).get(route_id, {}).get(rr_id)
+ if not rr:
+ return _apigw_error("NotFoundException", f"RouteResponse {rr_id} not found", 404)
+ return _apigw_response(rr)
+
+
+def _update_route_response(api_id, route_id, rr_id, data):
+ rr = _route_responses.get(api_id, {}).get(route_id, {}).get(rr_id)
+ if not rr:
+ return _apigw_error("NotFoundException", f"RouteResponse {rr_id} not found", 404)
+ for k in ("routeResponseKey", "modelSelectionExpression", "responseModels", "responseParameters"):
+ if k in data:
+ rr[k] = data[k]
+ return _apigw_response(rr)
+
+
+def _delete_route_response(api_id, route_id, rr_id):
+ _route_responses.get(api_id, {}).get(route_id, {}).pop(rr_id, None)
+ return 204, {}, b""
+
+
+# ==========================================================================
+# Integration responses (WebSocket)
+# ==========================================================================
+
+def _create_integration_response(api_id, integration_id, data):
+ integs = _integrations.get(api_id, {})
+ if integration_id not in integs:
+ return _apigw_error("NotFoundException", f"Integration {integration_id} not found", 404)
+ ir_id = new_uuid()[:8]
+ ir = {
+ "integrationResponseId": ir_id,
+ "integrationResponseKey": data.get("integrationResponseKey", "$default"),
+ "contentHandlingStrategy": data.get("contentHandlingStrategy"),
+ "templateSelectionExpression": data.get("templateSelectionExpression"),
+ "responseParameters": data.get("responseParameters", {}),
+ "responseTemplates": data.get("responseTemplates", {}),
+ }
+ by_int = _integration_responses.setdefault(api_id, {}).setdefault(integration_id, {})
+ by_int[ir_id] = ir
+ return _apigw_response(ir, 201)
+
+
+def _get_integration_responses(api_id, integration_id):
+ items = list(_integration_responses.get(api_id, {}).get(integration_id, {}).values())
+ return _apigw_response({"items": items})
+
+
+def _get_integration_response(api_id, integration_id, ir_id):
+ ir = _integration_responses.get(api_id, {}).get(integration_id, {}).get(ir_id)
+ if not ir:
+ return _apigw_error("NotFoundException", f"IntegrationResponse {ir_id} not found", 404)
+ return _apigw_response(ir)
+
+
+def _update_integration_response(api_id, integration_id, ir_id, data):
+ ir = _integration_responses.get(api_id, {}).get(integration_id, {}).get(ir_id)
+ if not ir:
+ return _apigw_error("NotFoundException", f"IntegrationResponse {ir_id} not found", 404)
+ for k in ("integrationResponseKey", "contentHandlingStrategy", "templateSelectionExpression",
+ "responseParameters", "responseTemplates"):
+ if k in data:
+ ir[k] = data[k]
+ return _apigw_response(ir)
+
+
+def _delete_integration_response(api_id, integration_id, ir_id):
+ _integration_responses.get(api_id, {}).get(integration_id, {}).pop(ir_id, None)
+ return 204, {}, b""
+
+
+# ==========================================================================
+# WebSocket data plane
+# ==========================================================================
+
+def _api_protocol(api_id: str) -> str | None:
+ """Return the protocolType for an API id, checking all accounts.
+
+ WebSocket connections arrive on the execute-api host before we've resolved
+ which account owns the api. We scan every AccountScopedDict bucket to find
+ the owning account, then return (protocol, account_id).
+ """
+ info = _api_owner(api_id)
+ return info[0] if info else None
+
+
+def _api_owner(api_id: str):
+ """Return (protocolType, owner_account_id) for an API or None if unknown."""
+ # AccountScopedDict stores keys as (account_id, original_key). Walk internals
+ # so we can find the owning account without knowing it up front.
+ for (acct, key), api in _apis._data.items():
+ if key == api_id:
+ return (api.get("protocolType", "HTTP"), acct)
+ return None
+
+
+def _match_ws_route(api_id: str, route_key: str):
+ """Find the route for a WS route key (e.g. '$connect', '$disconnect', '$default',
+ or a custom action like 'sendMessage'). Fallback to $default."""
+ routes = _routes.get(api_id, {})
+ for r in routes.values():
+ if r.get("routeKey") == route_key:
+ return r
+ for r in routes.values():
+ if r.get("routeKey") == "$default":
+ return r
+ return None
+
+
+def _evaluate_route_selection(expr: str, payload_text: str) -> str:
+ """Evaluate a WebSocket RouteSelectionExpression against an incoming frame.
+
+ AWS supports '$request.body.<dotted.path>' (the common case) and any plain
+ literal that the client includes. Anything we can't parse falls back to
+ '$default'.
+ """
+ if not expr:
+ return "$default"
+ if expr.startswith("$request.body."):
+ path = expr[len("$request.body."):]
+ try:
+ obj = json.loads(payload_text) if payload_text else {}
+ except (ValueError, TypeError):
+ return "$default"
+ cur = obj
+ for segment in path.split("."):
+ if isinstance(cur, dict) and segment in cur:
+ cur = cur[segment]
+ else:
+ return "$default"
+ return str(cur) if cur is not None else "$default"
+ return "$default"
+
+
+async def _invoke_ws_lambda(api_id: str, account_id: str, route: dict, stage: str,
+ connection_id: str, event_type: str, message_id: str,
+ body_text: str, source_ip: str, headers: dict,
+ query_params: dict | None = None, **kwargs) -> dict | None:
+ """Invoke a WS route's integration. Returns the integration's response dict or None.
+
+ The event shape matches AWS WebSocket v2 proxy (see docs: "Set up integration
+ request in API Gateway" under WebSocket). Headers include the incoming
+ handshake headers for $connect (along with query string params); for
+ MESSAGE/DISCONNECT the body is the frame payload.
+
+ Integration type handling:
+ - AWS / AWS_PROXY → dispatch to Lambda via the warm worker pool.
+ - MOCK → synthesise a 200 response (no Lambda). Any
+ `responseTemplates.$default` on a matching
+ integration response is returned as the body.
+ - anything else → returns None (caller treats as "no reply").
+ AWS itself only supports AWS/AWS_PROXY/MOCK for
+ WebSocket routes, so this also covers the
+ never-valid HTTP_PROXY case.
+ """
+ from ministack.core.lambda_runtime import get_or_create_worker
+ from ministack.services import lambda_svc
+
+ integration_id = route.get("target", "").replace("integrations/", "")
+ integration = _integrations.get(api_id, {}).get(integration_id)
+ if not integration:
+ return None
+
+ int_type = integration.get("integrationType", "")
+ if int_type == "MOCK":
+ ir_map = _integration_responses.get(api_id, {}).get(integration_id, {})
+ body = ""
+ for ir in ir_map.values():
+ templates = ir.get("responseTemplates", {}) or {}
+ if "$default" in templates:
+ body = templates["$default"]
+ break
+ if templates:
+ body = next(iter(templates.values()))
+ break
+ return {"statusCode": 200, "body": body}
+
+ if int_type not in ("AWS_PROXY", "AWS"):
+ logger.warning(
+ "WebSocket route %s has unsupported integrationType %r; "
+ "AWS only supports AWS / AWS_PROXY / MOCK for WebSocket APIs",
+ route.get("routeKey"), int_type,
+ )
+ return None
+
+ uri = integration.get("integrationUri", "")
+ func_name = uri.split(":")[-1] if ":" in uri else uri
+ func_name = func_name.replace("/invocations", "")
+ if func_name not in lambda_svc._functions:
+ 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,
+ }
+ if event_type == "DISCONNECT":
+ # Populated by handle_websocket from the ASGI disconnect message.
+ request_context["disconnectReason"] = kwargs.get("disconnect_reason", "")
+ request_context["disconnectStatusCode"] = int(kwargs.get("disconnect_code", 1005))
+ if event_type == "MESSAGE":
+ request_context["messageId"] = message_id
+
+ event = {
+ "requestContext": request_context,
+ "body": body_text if body_text is not None else "",
+ "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
+
+ func_data = lambda_svc._functions[func_name]
+ runtime = func_data["config"].get("Runtime", "")
+ code_zip = func_data.get("code_zip")
+ if code_zip and runtime.startswith(("python", "nodejs")):
+ worker = get_or_create_worker(func_name, func_data["config"], code_zip)
+ result = await asyncio.to_thread(worker.invoke, event, message_id)
+ if result.get("status") == "error":
+ return {"statusCode": 500, "body": result.get("error", "")}
+ return result.get("result", {})
+ # Image/unsupported runtime stub — success without body.
+ return {"statusCode": 200, "body": ""}
+
+
+async def handle_websocket(scope, receive, send, api_id: str):
+ """Drive a WebSocket session for a $WEBSOCKET API.
+
+ Flow:
+ 1. Receive `websocket.connect` from ASGI.
+ 2. Invoke `$connect` route Lambda (if any). 2xx → accept; else close.
+ 3. Loop on `websocket.receive`: evaluate routeSelectionExpression, dispatch
+ to the matching route's Lambda. If the Lambda returns a body, forward it
+ back on the same socket.
+ 4. Concurrently drain the per-connection outbox (fed by @connections
+ PostToConnection) and forward messages to the socket.
+ 5. On client disconnect, invoke `$disconnect` route Lambda (fire-and-forget).
+ """
+ owner = _api_owner(api_id)
+ if not owner or owner[0] != "WEBSOCKET":
+ # Not a WS API — refuse the upgrade.
+ await receive() # consume websocket.connect
+ await send({"type": "websocket.close", "code": 1008})
+ return
+
+ protocol, account_id = owner
+
+ # Stage parsing: path is /{stage} or /{stage}/... — execute-api WS URLs are
+ # wss://{apiId}.execute-api.../stage
+ path = scope.get("path", "")
+ path_parts = path.lstrip("/").split("/", 1)
+ stage = path_parts[0] if path_parts and path_parts[0] else "$default"
+
+ headers = {}
+ for name, value in scope.get("headers", []):
+ try:
+ headers[name.decode("latin-1").lower()] = value.decode("utf-8")
+ except UnicodeDecodeError:
+ headers[name.decode("latin-1").lower()] = value.decode("latin-1")
+
+ qs = scope.get("query_string", b"").decode("utf-8")
+ from urllib.parse import parse_qs as _pq
+ query_params = {k: v for k, v in _pq(qs, keep_blank_values=True).items()}
+
+ client = scope.get("client") or ("127.0.0.1", 0)
+ source_ip = client[0] if isinstance(client, (tuple, list)) else "127.0.0.1"
+
+ # Wait for websocket.connect.
+ msg = await receive()
+ if msg.get("type") != "websocket.connect":
+ return
+
+ connection_id = new_uuid().replace("-", "")[:16]
+
+ # Set account context so downstream Lambda invocations see the right tenant.
+ from ministack.core.responses import _request_account_id
+ token = _request_account_id.set(account_id)
+ try:
+ # $connect hook
+ connect_route = _match_ws_route(api_id, "$connect")
+ if connect_route is not None:
+ resp = await _invoke_ws_lambda(
+ api_id, account_id, connect_route, stage, connection_id,
+ "CONNECT", new_uuid(), "", source_ip, headers,
+ query_params=query_params,
+ )
+ status = int((resp or {}).get("statusCode", 200))
+ if status < 200 or status >= 300:
+ await send({"type": "websocket.close", "code": 1008})
+ return
+
+ await send({"type": "websocket.accept"})
+
+ outbox: asyncio.Queue = asyncio.Queue()
+ close_event = asyncio.Event()
+ now_epoch = int(time.time())
+ conn_record = {
+ "apiId": api_id,
+ "accountId": account_id,
+ "stage": stage,
+ # Int epoch seconds — matches ministack JSON timestamp convention.
+ "connectedAt": now_epoch,
+ "lastActiveAt": now_epoch,
+ "sourceIp": source_ip,
+ "identity": {"sourceIp": source_ip, "userAgent": headers.get("user-agent", "")},
+ "outbox": outbox,
+ "close_event": close_event,
+ }
+ _ws_connections[connection_id] = conn_record
+
+ selection_expr = None
+ api_obj = _apis.get(api_id)
+ if api_obj:
+ selection_expr = api_obj.get("routeSelectionExpression", "$request.body.action")
+
+ async def _drain_outbox():
+ while not close_event.is_set():
+ try:
+ item = await asyncio.wait_for(outbox.get(), timeout=0.5)
+ except asyncio.TimeoutError:
+ continue
+ if item is None:
+ return
+ if isinstance(item, bytes):
+ await send({"type": "websocket.send", "bytes": item})
+ else:
+ await send({"type": "websocket.send", "text": str(item)})
+
+ drain_task = asyncio.create_task(_drain_outbox())
+
+ disconnect_code = 1005 # 1005 = "no status rcvd" per RFC 6455, matches AWS default
+ disconnect_reason = ""
+ try:
+ while True:
+ message = await receive()
+ mtype = message.get("type")
+ if mtype == "websocket.disconnect":
+ disconnect_code = int(message.get("code", 1005) or 1005)
+ # ASGI extension: some servers (incl. modern hypercorn) pass the
+ # close-frame reason; fall back to empty string if not present.
+ disconnect_reason = message.get("reason") or ""
+ break
+ if mtype != "websocket.receive":
+ continue
+ frame_text = message.get("text")
+ frame_bytes = message.get("bytes")
+ payload = frame_text if frame_text is not None else (
+ frame_bytes.decode("utf-8", errors="replace") if frame_bytes else ""
+ )
+ conn_record["lastActiveAt"] = int(time.time())
+
+ route_key = _evaluate_route_selection(selection_expr or "", payload)
+ route = _match_ws_route(api_id, route_key)
+ if route is None:
+ # No $default — AWS sends GoneException to the client; we log and continue.
+ continue
+ msg_id = new_uuid()
+ resp = await _invoke_ws_lambda(
+ api_id, account_id, route, stage, connection_id, "MESSAGE",
+ msg_id, payload, source_ip, headers,
+ )
+ if resp is None:
+ continue
+ body = resp.get("body")
+ if body:
+ if isinstance(body, (dict, list)):
+ body = json.dumps(body)
+ if isinstance(body, bytes):
+ await send({"type": "websocket.send", "bytes": body})
+ else:
+ await send({"type": "websocket.send", "text": str(body)})
+ finally:
+ close_event.set()
+ try:
+ await drain_task
+ except Exception:
+ pass
+ _ws_connections.pop(connection_id, None)
+ # Fire $disconnect route best-effort.
+ disconnect_route = _match_ws_route(api_id, "$disconnect")
+ if disconnect_route is not None:
+ try:
+ await _invoke_ws_lambda(
+ api_id, account_id, disconnect_route, stage, connection_id,
+ "DISCONNECT", new_uuid(), "", source_ip, headers,
+ disconnect_code=disconnect_code,
+ disconnect_reason=disconnect_reason,
+ )
+ except Exception:
+ logger.exception("error firing $disconnect")
+ try:
+ await send({"type": "websocket.close", "code": 1000})
+ except Exception:
+ pass
+ finally:
+ try:
+ _request_account_id.reset(token)
+ except Exception:
+ pass
+
+
+# ==========================================================================
+# @connections management API
+# ==========================================================================
+
+async def handle_connections_api(method: str, api_id: str, stage: str,
+ connection_id: str, body: bytes, headers: dict):
+ """Serve the @connections runtime API.
+
+ Paths (on execute-api host):
+ POST /{stage}/@connections/{connectionId} → PostToConnection
+ GET /{stage}/@connections/{connectionId} → GetConnection
+ DELETE /{stage}/@connections/{connectionId} → DeleteConnection
+
+ AWS behaviour:
+ - 410 Gone if the connection is unknown or already closed.
+ - 403 Forbidden if the caller does not own the API (not enforced locally).
+ - 200 on success; POST returns empty body, GET returns JSON.
+ """
+ conn = _ws_connections.get(connection_id)
+ if not conn or conn.get("apiId") != api_id:
+ return 410, {"Content-Type": "application/json"}, json.dumps(
+ {"message": "GoneException"}
+ ).encode()
+
+ if method == "POST":
+ # Push the message into the connection outbox; drain_task will forward it.
+ try:
+ if body:
+ await conn["outbox"].put(body)
+ except Exception as exc:
+ return 500, {"Content-Type": "application/json"}, json.dumps(
+ {"message": str(exc)}
+ ).encode()
+ return 200, {"Content-Type": "application/json"}, b""
+
+ if method == "GET":
+ payload = {
+ "ConnectedAt": conn.get("connectedAt"),
+ "Identity": conn.get("identity", {}),
+ "LastActiveAt": conn.get("lastActiveAt"),
+ }
+ return 200, {"Content-Type": "application/json"}, json.dumps(payload).encode()
+
+ if method == "DELETE":
+ ev = conn.get("close_event")
+ if ev is not None:
+ try:
+ ev.set()
+ except Exception:
+ pass
+ # Flush the outbox with a sentinel so drain_task exits promptly.
+ try:
+ await conn["outbox"].put(None)
+ except Exception:
+ pass
+ return 204, {}, b""
+
+ return 405, {"Content-Type": "application/json"}, json.dumps(
+ {"message": f"Method {method} not allowed on @connections"}
+ ).encode()
diff --git a/tests/test_apigwv2_websocket.py b/tests/test_apigwv2_websocket.py
new file mode 100644
index 00000000..9cc79535
--- /dev/null
+++ b/tests/test_apigwv2_websocket.py
@@ -0,0 +1,554 @@
+"""API Gateway v2 WebSocket — end-to-end tests.
+
+Covers:
+ - CreateApi(protocolType=WEBSOCKET) control-plane defaults
+ - Route/Integration CRUD for WS API
+ - RouteResponse / IntegrationResponse CRUD
+ - Live $connect / $default / $disconnect dispatch via a Lambda
+ - @connections runtime API: PostToConnection, GetConnection, DeleteConnection
+ - Client isolation when two sockets connect to the same API
+ - Accept/reject of $connect based on Lambda statusCode
+
+Uses a hand-rolled WebSocket client (stdlib only) to keep the project
+dependency-free.
+"""
+
+import base64
+import hashlib
+import io
+import json
+import os
+import socket
+import struct
+import time
+import uuid
+import zipfile
+from urllib.parse import urlparse
+
+import pytest
+
+_endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+_EXECUTE_PORT = urlparse(_endpoint).port or 4566
+_LAMBDA_ROLE = "arn:aws:iam::000000000000:role/lambda-role"
+
+_WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
+
+
+def _make_zip(code: str) -> bytes:
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", code)
+ return buf.getvalue()
+
+
+# ── Minimal stdlib WebSocket client ──────────────────────────────────────────
+class _WSClient:
+ """Blocking WebSocket client — just enough to drive tests."""
+
+ def __init__(self, host: str, port: int, path: str, headers: dict | None = None):
+ self._sock = socket.create_connection((host, port), timeout=5)
+ key = base64.b64encode(os.urandom(16)).decode()
+ request_headers = {
+ "Host": f"{host}:{port}",
+ "Upgrade": "websocket",
+ "Connection": "Upgrade",
+ "Sec-WebSocket-Key": key,
+ "Sec-WebSocket-Version": "13",
+ }
+ if headers:
+ request_headers.update(headers)
+ lines = [f"GET {path} HTTP/1.1"]
+ for k, v in request_headers.items():
+ lines.append(f"{k}: {v}")
+ lines.append("")
+ lines.append("")
+ self._sock.sendall("\r\n".join(lines).encode())
+ self._buf = b""
+ self._read_handshake(key)
+
+ def _read_handshake(self, key: str) -> None:
+ while b"\r\n\r\n" not in self._buf:
+ chunk = self._sock.recv(4096)
+ if not chunk:
+ raise RuntimeError(f"handshake closed, got: {self._buf!r}")
+ self._buf += chunk
+ header_blob, self._buf = self._buf.split(b"\r\n\r\n", 1)
+ first_line = header_blob.split(b"\r\n", 1)[0]
+ if b"101" not in first_line:
+ raise RuntimeError(f"WS handshake failed: {header_blob!r}")
+ expected = base64.b64encode(hashlib.sha1((key + _WS_GUID).encode()).digest()).decode()
+ if expected.encode() not in header_blob:
+ raise RuntimeError("Sec-WebSocket-Accept mismatch")
+
+ def send(self, text: str) -> None:
+ payload = text.encode()
+ mask = os.urandom(4)
+ masked = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
+ length = len(payload)
+ if length < 126:
+ header = struct.pack("!BB", 0x81, 0x80 | length)
+ elif length < 65536:
+ header = struct.pack("!BBH", 0x81, 0x80 | 126, length)
+ else:
+ header = struct.pack("!BBQ", 0x81, 0x80 | 127, length)
+ self._sock.sendall(header + mask + masked)
+
+ def recv(self, timeout: float = 3.0) -> str | None:
+ """Return the next text or binary frame's payload as a string."""
+ self._sock.settimeout(timeout)
+ try:
+ while True:
+ frame = self._recv_frame()
+ if frame is None:
+ return None
+ opcode, payload = frame
+ if opcode in (0x1, 0x2): # text or binary
+ return payload.decode("utf-8", errors="replace")
+ if opcode == 0x8: # close
+ return None
+ # ignore ping/pong for test purposes
+ except socket.timeout:
+ return None
+
+ def _recv_all(self, n: int) -> bytes:
+ while len(self._buf) < n:
+ chunk = self._sock.recv(max(4096, n - len(self._buf)))
+ if not chunk:
+ return b""
+ self._buf += chunk
+ out, self._buf = self._buf[:n], self._buf[n:]
+ return out
+
+ def _recv_frame(self):
+ hdr = self._recv_all(2)
+ if len(hdr) < 2:
+ return None
+ b1, b2 = hdr[0], hdr[1]
+ opcode = b1 & 0x0F
+ masked = (b2 & 0x80) != 0
+ length = b2 & 0x7F
+ if length == 126:
+ length = struct.unpack("!H", self._recv_all(2))[0]
+ elif length == 127:
+ length = struct.unpack("!Q", self._recv_all(8))[0]
+ mask = self._recv_all(4) if masked else b""
+ payload = self._recv_all(length)
+ if masked:
+ payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))
+ return opcode, payload
+
+ def close(self) -> None:
+ try:
+ # close frame (code 1000)
+ self._sock.sendall(b"\x88\x82" + os.urandom(4) + b"\x03\xe8")
+ except Exception:
+ pass
+ try:
+ self._sock.close()
+ except Exception:
+ pass
+
+
+# ── Fixtures / helpers ───────────────────────────────────────────────────────
+_ECHO_CODE = """
+import json
+
+def handler(event, context):
+ rc = event.get('requestContext', {})
+ action = rc.get('routeKey', '$default')
+ body_text = event.get('body', '')
+ try:
+ parsed = json.loads(body_text) if body_text else {}
+ except Exception:
+ parsed = {}
+ # Echo the incoming frame with the connectionId for easy test assertions.
+ resp = {
+ 'connectionId': rc.get('connectionId'),
+ 'eventType': rc.get('eventType'),
+ 'action': action,
+ 'body': parsed,
+ }
+ return {'statusCode': 200, 'body': json.dumps(resp)}
+"""
+
+_CONNECT_REJECT_CODE = """
+def handler(event, context):
+ # Force $connect rejection.
+ return {'statusCode': 401, 'body': 'denied'}
+"""
+
+
+def _make_fn(lam, name: str, code: str) -> str:
+ try:
+ lam.delete_function(FunctionName=name)
+ except Exception:
+ pass
+ lam.create_function(
+ FunctionName=name,
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(code)},
+ )
+ return f"arn:aws:lambda:us-east-1:000000000000:function:{name}"
+
+
+def _wire_ws_api(apigw, lam, *, name_suffix: str,
+ connect_code: str | None = None,
+ default_code: str = _ECHO_CODE,
+ disconnect_code: str | None = None) -> tuple[str, dict]:
+ """Create a WS API + routes + integrations and return (apiId, metadata)."""
+ api = apigw.create_api(Name=f"ws-{name_suffix}", ProtocolType="WEBSOCKET")
+ api_id = api["ApiId"]
+ meta = {"created_functions": []}
+ assert api.get("RouteSelectionExpression") == "$request.body.action"
+
+ def _route(route_key: str, code: str):
+ fn_name = f"ws-{name_suffix}-{route_key.lstrip('$')}-{uuid.uuid4().hex[:6]}"
+ arn = _make_fn(lam, fn_name, code)
+ meta["created_functions"].append(fn_name)
+ integ = apigw.create_integration(
+ ApiId=api_id,
+ IntegrationType="AWS_PROXY",
+ IntegrationUri=arn,
+ IntegrationMethod="POST",
+ )
+ apigw.create_route(
+ ApiId=api_id,
+ RouteKey=route_key,
+ Target=f"integrations/{integ['IntegrationId']}",
+ )
+
+ if connect_code is not None:
+ _route("$connect", connect_code)
+ _route("$default", default_code)
+ if disconnect_code is not None:
+ _route("$disconnect", disconnect_code)
+ apigw.create_stage(ApiId=api_id, StageName="prod")
+ return api_id, meta
+
+
+# ── Control-plane tests ──────────────────────────────────────────────────────
+def test_ws_create_api_defaults(apigw):
+ """WEBSOCKET APIs default routeSelectionExpression to $request.body.action."""
+ resp = apigw.create_api(Name="ws-defaults", ProtocolType="WEBSOCKET")
+ assert resp["ProtocolType"] == "WEBSOCKET"
+ assert resp["RouteSelectionExpression"] == "$request.body.action"
+
+
+def test_ws_create_api_custom_rse(apigw):
+ resp = apigw.create_api(
+ Name="ws-custom-rse", ProtocolType="WEBSOCKET",
+ RouteSelectionExpression="$request.body.type",
+ )
+ assert resp["RouteSelectionExpression"] == "$request.body.type"
+
+
+def test_ws_route_response_crud(apigw):
+ api_id = apigw.create_api(Name="ws-rr", ProtocolType="WEBSOCKET")["ApiId"]
+ route = apigw.create_route(ApiId=api_id, RouteKey="sendMessage")
+ rr = apigw.create_route_response(
+ ApiId=api_id, RouteId=route["RouteId"], RouteResponseKey="$default",
+ )
+ assert rr["RouteResponseKey"] == "$default"
+ assert "RouteResponseId" in rr
+ got = apigw.get_route_responses(ApiId=api_id, RouteId=route["RouteId"])
+ assert any(i["RouteResponseId"] == rr["RouteResponseId"] for i in got["Items"])
+ apigw.delete_route_response(
+ ApiId=api_id, RouteId=route["RouteId"], RouteResponseId=rr["RouteResponseId"],
+ )
+
+
+def test_ws_integration_response_crud(apigw):
+ api_id = apigw.create_api(Name="ws-ir", ProtocolType="WEBSOCKET")["ApiId"]
+ integ = apigw.create_integration(
+ ApiId=api_id, IntegrationType="MOCK",
+ )
+ ir = apigw.create_integration_response(
+ ApiId=api_id, IntegrationId=integ["IntegrationId"],
+ IntegrationResponseKey="/200/",
+ )
+ assert ir["IntegrationResponseKey"] == "/200/"
+ assert "IntegrationResponseId" in ir
+ got = apigw.get_integration_responses(ApiId=api_id, IntegrationId=integ["IntegrationId"])
+ assert any(i["IntegrationResponseId"] == ir["IntegrationResponseId"] for i in got["Items"])
+
+
+# ── Data-plane tests ─────────────────────────────────────────────────────────
+def test_ws_connect_and_echo_via_default_route(apigw, lam):
+ api_id, meta = _wire_ws_api(
+ apigw, lam, name_suffix="echo",
+ connect_code=None, default_code=_ECHO_CODE,
+ )
+ ws = _WSClient("localhost", _EXECUTE_PORT, "/prod",
+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"})
+ try:
+ ws.send(json.dumps({"action": "sendMessage", "payload": "hi"}))
+ resp = ws.recv()
+ assert resp is not None, "no reply from Lambda"
+ parsed = json.loads(resp)
+ assert parsed["eventType"] == "MESSAGE"
+ assert parsed["body"]["payload"] == "hi"
+ assert parsed["connectionId"]
+ finally:
+ ws.close()
+
+
+def test_ws_connect_route_accepts(apigw, lam):
+ """$connect Lambda returning 200 accepts the upgrade."""
+ api_id, _ = _wire_ws_api(
+ apigw, lam, name_suffix="connect-ok",
+ connect_code=_ECHO_CODE,
+ )
+ ws = _WSClient("localhost", _EXECUTE_PORT, "/prod",
+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"})
+ try:
+ ws.send(json.dumps({"action": "x"}))
+ # Should get a normal MESSAGE response — proves the socket is live.
+ resp = ws.recv()
+ assert resp is not None
+ finally:
+ ws.close()
+
+
+def test_ws_connect_route_rejects(apigw, lam):
+ """$connect Lambda returning non-2xx rejects the upgrade."""
+ api_id, _ = _wire_ws_api(
+ apigw, lam, name_suffix="connect-deny",
+ connect_code=_CONNECT_REJECT_CODE,
+ )
+ with pytest.raises(Exception):
+ _WSClient("localhost", _EXECUTE_PORT, "/prod",
+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"})
+
+
+def test_ws_post_to_connection_from_management_api(apigw, lam):
+ """@connections PostToConnection pushes a message to the live socket."""
+ import urllib.request
+
+ api_id, _ = _wire_ws_api(apigw, lam, name_suffix="p2c")
+ ws = _WSClient("localhost", _EXECUTE_PORT, "/prod",
+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"})
+ try:
+ # Drive a frame so the Lambda runs and returns the connectionId in its reply.
+ ws.send(json.dumps({"action": "sendMessage"}))
+ reply = ws.recv()
+ conn_id = json.loads(reply)["connectionId"]
+ assert conn_id
+
+ # Push a message from a separate HTTP request (simulating server-side push).
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/prod/@connections/{conn_id}"
+ req = urllib.request.Request(
+ url, data=b"server-push-payload", method="POST",
+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"},
+ )
+ r = urllib.request.urlopen(req, timeout=5)
+ assert r.status == 200
+
+ pushed = ws.recv(timeout=3)
+ assert pushed == "server-push-payload"
+ finally:
+ ws.close()
+
+
+def test_ws_get_connection_returns_metadata(apigw, lam):
+ """@connections GetConnection returns connected-at / identity."""
+ import urllib.request
+
+ api_id, _ = _wire_ws_api(apigw, lam, name_suffix="getc")
+ ws = _WSClient("localhost", _EXECUTE_PORT, "/prod",
+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"})
+ try:
+ ws.send(json.dumps({"action": "x"}))
+ reply = ws.recv()
+ conn_id = json.loads(reply)["connectionId"]
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/prod/@connections/{conn_id}"
+ req = urllib.request.Request(
+ url, method="GET",
+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"},
+ )
+ r = urllib.request.urlopen(req, timeout=5)
+ meta = json.loads(r.read())
+ # Int epoch seconds, per ministack JSON timestamp convention.
+ assert isinstance(meta["ConnectedAt"], int)
+ assert isinstance(meta["LastActiveAt"], int)
+ assert meta["Identity"]["sourceIp"]
+ finally:
+ ws.close()
+
+
+def test_ws_delete_connection_closes_socket(apigw, lam):
+ """@connections DeleteConnection terminates the WS session."""
+ import urllib.request
+
+ api_id, _ = _wire_ws_api(apigw, lam, name_suffix="delc")
+ ws = _WSClient("localhost", _EXECUTE_PORT, "/prod",
+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"})
+ try:
+ ws.send(json.dumps({"action": "x"}))
+ reply = ws.recv()
+ conn_id = json.loads(reply)["connectionId"]
+
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/prod/@connections/{conn_id}"
+ req = urllib.request.Request(
+ url, method="DELETE",
+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"},
+ )
+ r = urllib.request.urlopen(req, timeout=5)
+ assert r.status in (200, 204)
+
+ # Give the server a moment to close, then subsequent recv returns None.
+ time.sleep(0.5)
+ assert ws.recv(timeout=1.5) is None
+ finally:
+ ws.close()
+
+
+def test_ws_post_to_unknown_connection_returns_410(apigw, lam):
+ """@connections PostToConnection on an unknown id returns 410 GoneException."""
+ import urllib.request
+ import urllib.error
+
+ api_id, _ = _wire_ws_api(apigw, lam, name_suffix="gone")
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/prod/@connections/{uuid.uuid4().hex}"
+ req = urllib.request.Request(
+ url, data=b"hi", method="POST",
+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"},
+ )
+ with pytest.raises(urllib.error.HTTPError) as exc_info:
+ urllib.request.urlopen(req, timeout=5)
+ assert exc_info.value.code == 410
+
+
+_CAPTURE_QS_CODE = """
+import json
+
+def handler(event, context):
+ # Echo the $connect event's queryStringParameters so the test can assert on them.
+ rc = event.get('requestContext', {})
+ return {
+ 'statusCode': 200,
+ 'body': json.dumps({
+ 'qs': event.get('queryStringParameters'),
+ 'mvqs': event.get('multiValueQueryStringParameters'),
+ 'eventType': rc.get('eventType'),
+ }),
+ }
+"""
+
+
+def test_ws_connect_receives_query_string_parameters(apigw, lam):
+ """$connect Lambda event exposes queryStringParameters + multiValueQueryStringParameters.
+
+ After accepting, we send a frame and rely on the echo Lambda to confirm the
+ socket is live; the test's primary assertion is that the $connect Lambda
+ did NOT reject us (so QS params didn't break event validation).
+ """
+ # Two Lambdas: one on $connect that validates the QS param; one on $default that echoes.
+ api_id = apigw.create_api(Name="ws-qs-gate", ProtocolType="WEBSOCKET")["ApiId"]
+
+ gate_code = """
+def handler(event, context):
+ qs = event.get('queryStringParameters') or {}
+ mvqs = event.get('multiValueQueryStringParameters') or {}
+ # Reject unless the caller passed ?token=abc
+ if qs.get('token') != 'abc':
+ return {'statusCode': 401, 'body': 'denied'}
+ # Also confirm multi-value came through when a key is repeated.
+ if mvqs.get('tag') != ['a', 'b']:
+ return {'statusCode': 401, 'body': 'mv missing'}
+ return {'statusCode': 200}
+"""
+ gate_arn = _make_fn(lam, f"ws-qs-gate-connect-{uuid.uuid4().hex[:6]}", gate_code)
+ echo_arn = _make_fn(lam, f"ws-qs-gate-default-{uuid.uuid4().hex[:6]}", _ECHO_CODE)
+
+ gate_integ = apigw.create_integration(
+ ApiId=api_id, IntegrationType="AWS_PROXY",
+ IntegrationUri=gate_arn, IntegrationMethod="POST",
+ )
+ apigw.create_route(ApiId=api_id, RouteKey="$connect",
+ Target=f"integrations/{gate_integ['IntegrationId']}")
+
+ echo_integ = apigw.create_integration(
+ ApiId=api_id, IntegrationType="AWS_PROXY",
+ IntegrationUri=echo_arn, IntegrationMethod="POST",
+ )
+ apigw.create_route(ApiId=api_id, RouteKey="$default",
+ Target=f"integrations/{echo_integ['IntegrationId']}")
+ apigw.create_stage(ApiId=api_id, StageName="prod")
+
+ # Without QS params → $connect rejects
+ with pytest.raises(Exception):
+ _WSClient("localhost", _EXECUTE_PORT, "/prod",
+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"})
+
+ # With ?token=abc&tag=a&tag=b → accepted, MESSAGE works.
+ ws = _WSClient(
+ "localhost", _EXECUTE_PORT, "/prod?token=abc&tag=a&tag=b",
+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"},
+ )
+ try:
+ ws.send(json.dumps({"action": "ping"}))
+ resp = ws.recv()
+ assert resp is not None
+ assert json.loads(resp)["eventType"] == "MESSAGE"
+ finally:
+ ws.close()
+
+
+def test_ws_mock_integration_returns_template_body(apigw):
+ """WEBSOCKET routes with MOCK integration + responseTemplates return the template
+ body on the socket without any Lambda invocation."""
+ api_id = apigw.create_api(Name="ws-mock", ProtocolType="WEBSOCKET")["ApiId"]
+ integ = apigw.create_integration(ApiId=api_id, IntegrationType="MOCK")
+ apigw.create_route(ApiId=api_id, RouteKey="$default",
+ Target=f"integrations/{integ['IntegrationId']}")
+ apigw.create_integration_response(
+ ApiId=api_id, IntegrationId=integ["IntegrationId"],
+ IntegrationResponseKey="$default",
+ ResponseTemplates={"$default": '{"from":"mock"}'},
+ )
+ apigw.create_stage(ApiId=api_id, StageName="prod")
+
+ ws = _WSClient("localhost", _EXECUTE_PORT, "/prod",
+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"})
+ try:
+ ws.send(json.dumps({"action": "anything"}))
+ resp = ws.recv()
+ assert resp == '{"from":"mock"}'
+ finally:
+ ws.close()
+
+
+def test_ws_two_clients_stay_isolated(apigw, lam):
+ """Two WS sockets on the same API get distinct connectionIds and
+ @connections messages don't cross-deliver."""
+ import urllib.request
+
+ api_id, _ = _wire_ws_api(apigw, lam, name_suffix="iso")
+ a = _WSClient("localhost", _EXECUTE_PORT, "/prod",
+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"})
+ b = _WSClient("localhost", _EXECUTE_PORT, "/prod",
+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"})
+ try:
+ a.send(json.dumps({"action": "x"}))
+ b.send(json.dumps({"action": "y"}))
+ a_reply = json.loads(a.recv())
+ b_reply = json.loads(b.recv())
+ assert a_reply["connectionId"] != b_reply["connectionId"]
+
+ # Push to A only — B should not receive it.
+ url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/prod/@connections/{a_reply['connectionId']}"
+ urllib.request.urlopen(urllib.request.Request(
+ url, data=b"for-a-only", method="POST",
+ headers={"Host": f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"},
+ ), timeout=5)
+
+ got_a = a.recv(timeout=3)
+ got_b = b.recv(timeout=1)
+ assert got_a == "for-a-only"
+ assert got_b is None
+ finally:
+ a.close()
+ b.close()