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
adding data plane for v1 v2 (#402)
Nahuel Nuceraebfbaf960269
diff --git a/README.md b/README.mdindex 70cd26ea..b91c89bf 100644--- a/README.md+++ b/README.md@@ -356,8 +356,8 @@ 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, 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 |+| **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` Host header or path-based `/_aws/execute-api/{apiId}/{stage}/{path}` (no DNS/Host override needed — works from browsers on macOS and strict clients); WebSocket data plane on the same two URL forms, with `$connect` / `$disconnect` / `$default` / custom-action routing, `$request.body.*` RouteSelectionExpression, `@connections` management API (PostToConnection / GetConnection / DeleteConnection), per-connection outbox for server-side push; `{param}` / `{proxy+}` matching; 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` Host header, path-based `/_aws/execute-api/{apiId}/{stage}/{path}`, or legacy `/restapis/{apiId}/{stage}/_user_request_/{path}`; 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 || **CloudFront** | CreateDistribution, GetDistribution, GetDistributionConfig, ListDistributions, UpdateDistribution, DeleteDistribution, CreateInvalidation, ListInvalidations, GetInvalidation, CreateOriginAccessControl, GetOriginAccessControl, GetOriginAccessControlConfig, ListOriginAccessControls, UpdateOriginAccessControl, DeleteOriginAccessControl, TagResource, UntagResource, ListTagsForResource | REST/XML API; ETag-based optimistic concurrency; Origin Access Control (OAC) with SigV4 signing for S3, MediaStore, Lambda, MediaPackageV2 origins; field validation and name uniqueness enforcement |diff --git a/ministack/app.py b/ministack/app.pyindex 7cb61ac9..965fde46 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -592,23 +592,59 @@ async def _handle_ses_v2_request(method: str, path: str, headers: dict, body: byreturn await _get_module("ses_v2").handle_request(method, path, headers, body, query_params)+def _parse_execute_api_url(host: str, path: str) -> tuple[str, str, str] | None:+ """Resolve an execute-api request into (api_id, stage, execute_path).++ Supports three addressing modes, in priority order:+ 1. Host-based (AWS-native): {apiId}.execute-api.<host>[:port]/{stage}/{path}+ 2. LocalStack-compat (new): <host>[:port]/_aws/execute-api/{apiId}/{stage}/{path}+ 3. LocalStack-compat (v1): <host>[:port]/restapis/{apiId}/{stage}/_user_request_/{path}++ The path-based forms exist because (a) browsers on macOS don't resolve+ `*.localhost` and (b) many HTTP clients can't override the `Host` header+ (issue #401). Returns ``None`` if none of the three patterns match."""+ m = _EXECUTE_API_RE.match(host)+ if m:+ api_id = m.group(1)+ parts = path.lstrip("/").split("/", 1)+ stage = parts[0] if parts and parts[0] else "$default"+ execute_path = "/" + parts[1] if len(parts) > 1 else "/"+ return api_id, stage, execute_path++ # LocalStack-compat: /_aws/execute-api/{apiId}/{stage}/{path...}+ if path.startswith("/_aws/execute-api/"):+ rest = path[len("/_aws/execute-api/"):]+ parts = rest.split("/", 2)+ if len(parts) >= 2 and parts[0]:+ api_id = parts[0]+ stage = parts[1] if parts[1] else "$default"+ execute_path = "/" + parts[2] if len(parts) > 2 else "/"+ return api_id, stage, execute_path++ # LocalStack v1 legacy: /restapis/{apiId}/{stage}/_user_request_/{path...}+ if path.startswith("/restapis/"):+ rest = path[len("/restapis/"):]+ parts = rest.split("/", 3)+ if len(parts) >= 3 and parts[2] == "_user_request_":+ api_id = parts[0]+ stage = parts[1] if parts[1] else "$default"+ execute_path = "/" + parts[3] if len(parts) > 3 else "/"+ return api_id, stage, execute_path++ return None++async def _handle_execute_api_request(host: str, path: str, method: str, headers: dict, body: bytes, query_params: dict):- """Handle API Gateway execute-api data plane requests."""- execute_match = _EXECUTE_API_RE.match(host)- if not execute_match:+ """Handle API Gateway execute-api data plane requests (Host-based + path-based)."""+ parsed = _parse_execute_api_url(host, path)+ if parsed is None:return None-- api_id = execute_match.group(1)- path_parts = path.lstrip("/").split("/", 1)- stage = path_parts[0] if path_parts else "$default"- execute_path = "/" + path_parts[1] if len(path_parts) > 1 else "/"+ api_id, stage, execute_path = parsedtry:- # 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]+ # WebSocket @connections management API — /{stage}/@connections/{id} in+ # the Host-based form resolves to execute_path == "/@connections/{id}".+ if execute_path.startswith("/@connections/"):+ connection_id = execute_path[len("/@connections/"):].split("/", 1)[0]return await _get_module("apigateway").handle_connections_api(method, api_id, stage, connection_id, body, headers)@@ -782,8 +818,9 @@ async def app(scope, receive, send):returnif scope["type"] == "websocket":- # WebSocket APIs only reach us via the execute-api host pattern:- # ws://{apiId}.execute-api.{host}[:port]/{stage}[/...]+ # WebSocket APIs are reachable two ways:+ # ws://{apiId}.execute-api.{host}[:port]/{stage}[/...] (Host-based)+ # ws://<host>[:port]/_aws/execute-api/{apiId}/{stage}[/...] (LocalStack-compat path)ws_headers = {}for name, value in scope.get("headers", []):try:@@ -791,15 +828,18 @@ async def app(scope, receive, send):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:+ ws_path = scope.get("path", "")+ parsed = _parse_execute_api_url(ws_host, ws_path)+ if not parsed:msg = await receive()if msg.get("type") == "websocket.connect":await send({"type": "websocket.close", "code": 1008})return- ws_api_id = m.group(1)+ ws_api_id, _stage, _execute_path = parsedtry:- await _get_module("apigateway").handle_websocket(scope, receive, send, ws_api_id)+ await _get_module("apigateway").handle_websocket(+ scope, receive, send, ws_api_id, path_override=_execute_path,+ )except Exception:logger.exception("Error in WebSocket dispatch")try:diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.pyindex b8bb90a5..25557b07 100644--- a/ministack/services/apigateway.py+++ b/ministack/services/apigateway.py@@ -1074,7 +1074,7 @@ async def _invoke_ws_lambda(api_id: str, account_id: str, route: dict, stage: streturn {"statusCode": 200, "body": ""}-async def handle_websocket(scope, receive, send, api_id: str):+async def handle_websocket(scope, receive, send, api_id: str, path_override: str | None = None):"""Drive a WebSocket session for a $WEBSOCKET API.Flow:@@ -1086,6 +1086,10 @@ async def handle_websocket(scope, receive, send, api_id: str):4. Concurrently drain the per-connection outbox (fed by @connectionsPostToConnection) and forward messages to the socket.5. On client disconnect, invoke `$disconnect` route Lambda (fire-and-forget).++ ``path_override`` is used when the caller addressed us via the LocalStack-+ compat path form (``/_aws/execute-api/{apiId}/{stage}``) so we read the+ stage from the rewritten path instead of the raw URL."""owner = _api_owner(api_id)if not owner or owner[0] != "WEBSOCKET":@@ -1096,9 +1100,9 @@ async def handle_websocket(scope, receive, send, api_id: str):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", "")+ # Stage parsing: Host-based URLs look like wss://{apiId}.execute-api.../stage;+ # path-based compat URLs (#401) use path_override with the rewritten path.+ path = path_override if path_override is not None else scope.get("path", "")path_parts = path.lstrip("/").split("/", 1)stage = path_parts[0] if path_parts and path_parts[0] else "$default"diff --git a/tests/test_apigwv1.py b/tests/test_apigatewayv1.pysimilarity index 100%rename from tests/test_apigwv1.pyrename to tests/test_apigatewayv1.pydiff --git a/tests/test_apigw.py b/tests/test_apigatewayv2.pysimilarity index 57%rename from tests/test_apigw.pyrename to tests/test_apigatewayv2.pyindex af318640..beb8333c 100644--- a/tests/test_apigw.py+++ b/tests/test_apigatewayv2.py@@ -1,12 +1,15 @@+"""API Gateway v2 tests — HTTP API + WebSocket + common lifecycle."""+import ioimport jsonimport os+import pytestimport time+import uuid as _uuid_modimport zipfile-from urllib.parse import urlparse-import pytestfrom botocore.exceptions import ClientError-import uuid as _uuid_mod+from urllib.parse import urlparse+_endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")@@ -806,3 +809,636 @@ def test_apigw_v2_stage_timestamps(apigw):assert isinstance(stage["CreatedDate"], datetime), f"CreatedDate should be datetime, got {type(stage['CreatedDate'])}"assert isinstance(stage["LastUpdatedDate"], datetime), f"LastUpdatedDate should be datetime, got {type(stage['LastUpdatedDate'])}"apigw.delete_api(ApiId=api_id)+++# ========== from test_apigwv2.py ==========++def test_apigwv2_created_date_is_unix_timestamp(apigw):+ resp = apigw.create_api(Name="tf-date-test-v2", ProtocolType="HTTP")+ created = resp["CreatedDate"]+ import datetime++ assert isinstance(created, datetime.datetime), (+ f"CreatedDate should be datetime (parsed from Unix int), got {type(created)}"+ )+ apigw.delete_api(ApiId=resp["ApiId"])+++# ========== from test_apigwv2_websocket.py ==========++"""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+++_WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"+++++# ── 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()+++# ========== Path-based data plane (issue #401) ==========++def test_apigwv2_path_based_execute_api_http(apigw, lam):+ """HTTP API reachable via /_aws/execute-api/{apiId}/{stage}/{path} without Host override."""+ api_id, _ = _wire_ws_api(apigw, lam, name_suffix="pb-http") # creates a WS API — reuse for wiring+ # But we need an HTTP API for this test. Build one explicitly.+ http_api_id = apigw.create_api(Name="pb-http-api", ProtocolType="HTTP")["ApiId"]+ fn_name = f"pb-http-fn-{uuid.uuid4().hex[:6]}"+ arn = _make_fn(lam, fn_name, _ECHO_CODE)+ integ = apigw.create_integration(+ ApiId=http_api_id, IntegrationType="AWS_PROXY",+ IntegrationUri=arn, IntegrationMethod="POST",+ )+ apigw.create_route(+ ApiId=http_api_id, RouteKey="GET /hello",+ Target=f"integrations/{integ['IntegrationId']}",+ )+ apigw.create_stage(ApiId=http_api_id, StageName="prod")++ import urllib.request+ url = f"http://localhost:{_EXECUTE_PORT}/_aws/execute-api/{http_api_id}/prod/hello"+ r = urllib.request.urlopen(url, timeout=5)+ assert r.status == 200+ payload = json.loads(r.read())+ assert payload["eventType"] == "MESSAGE" or payload.get("action") == "GET /hello" or "hello" in str(payload)+++def test_apigwv2_path_based_websocket(apigw, lam):+ """WebSocket reachable via ws://localhost/_aws/execute-api/{apiId}/{stage}."""+ api_id, _ = _wire_ws_api(apigw, lam, name_suffix="pb-ws")+ ws = _WSClient(+ "localhost", _EXECUTE_PORT,+ f"/_aws/execute-api/{api_id}/prod",+ headers={"Host": f"localhost:{_EXECUTE_PORT}"},+ )+ try:+ ws.send(json.dumps({"action": "sendMessage", "payload": "path-based"}))+ resp = ws.recv()+ assert resp is not None+ parsed = json.loads(resp)+ assert parsed["body"]["payload"] == "path-based"+ finally:+ ws.close()+++def test_apigwv1_path_based_restapi_legacy_user_request(apigw_v1, lam):+ """REST API v1 reachable via /restapis/{apiId}/{stage}/_user_request_/{path} (LocalStack legacy)."""+ import urllib.request++ api_id = apigw_v1.create_rest_api(name="pb-v1-api")["id"]+ root = apigw_v1.get_resources(restApiId=api_id)["items"][0]["id"]+ res_id = apigw_v1.create_resource(restApiId=api_id, parentId=root, pathPart="hello")["id"]+ apigw_v1.put_method(+ restApiId=api_id, resourceId=res_id, httpMethod="GET", authorizationType="NONE",+ )++ fn_name = f"pb-v1-fn-{uuid.uuid4().hex[:6]}"+ arn = _make_fn(lam, fn_name, _ECHO_CODE)+ apigw_v1.put_integration(+ restApiId=api_id, resourceId=res_id, httpMethod="GET",+ type="AWS_PROXY", integrationHttpMethod="POST",+ uri=f"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/{arn}/invocations",+ )+ apigw_v1.create_deployment(restApiId=api_id, stageName="prod")++ url = f"http://localhost:{_EXECUTE_PORT}/restapis/{api_id}/prod/_user_request_/hello"+ r = urllib.request.urlopen(url, timeout=5)+ assert r.status == 200diff --git a/tests/test_apigwv2.py b/tests/test_apigwv2.pydeleted file mode 100644index 235b0b76..00000000--- a/tests/test_apigwv2.py+++ /dev/null@@ -1,19 +0,0 @@-import io-import json-import os-import time-import zipfile-from urllib.parse import urlparse-import pytest-from botocore.exceptions import ClientError-import uuid as _uuid_mod--def test_apigwv2_created_date_is_unix_timestamp(apigw):- resp = apigw.create_api(Name="tf-date-test-v2", ProtocolType="HTTP")- created = resp["CreatedDate"]- import datetime-- assert isinstance(created, datetime.datetime), (- f"CreatedDate should be datetime (parsed from Unix int), got {type(created)}"- )- apigw.delete_api(ApiId=resp["ApiId"])diff --git a/tests/test_apigwv2_websocket.py b/tests/test_apigwv2_websocket.pydeleted file mode 100644index 9cc79535..00000000--- a/tests/test_apigwv2_websocket.py+++ /dev/null@@ -1,554 +0,0 @@-"""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()diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex 1097cf1e..fed9ea75 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -1,15 +1,20 @@+"""Cognito tests — user pools, identity pools, OAuth2/OIDC flows."""+import base64import ioimport jsonimport os+import pytestimport time-import urllib.requestimport urllib.error+import urllib.request+import uuid as _uuid_modimport zipfile-from urllib.parse import urlparse, parse_qs as _parse_qs, urlencode as _urlencode-import pytestfrom botocore.exceptions import ClientError-import uuid as _uuid_mod+from urllib.parse import urlparse, parse_qs as _parse_qs, urlencode as _urlencode+++# ========== from test_cognito.py ==========def test_cognito_create_and_describe_user_pool(cognito_idp):resp = cognito_idp.create_user_pool(PoolName="TestPool")@@ -1581,3 +1586,604 @@ def test_cognito_admin_disable_by_sub(cognito_idp):cognito_idp.admin_disable_user(UserPoolId=pid, Username=sub)user2 = cognito_idp.admin_get_user(UserPoolId=pid, Username=sub)assert user2["Enabled"] is False++# ========== from test_cognito_oauth2.py ==========++"""+Integration tests for Cognito OAuth2/OIDC IdP endpoints.++Tests the full OAuth2 authorization code flow including:+ /oauth2/authorize, /login, /oauth2/token, /oauth2/userInfo, /logout+"""+import base64+import hashlib+import json+import os+import secrets+import urllib.error+import urllib.parse+import urllib.request++from conftest import ENDPOINT, make_client+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def _setup_pool_with_user(cognito_idp, generate_secret=True):+ """Create a user pool with a confirmed user and an OAuth-enabled client."""+ pool = cognito_idp.create_user_pool(PoolName='OAuth2TestPool')+ pool_id = pool['UserPool']['Id']++ client_kwargs = {+ 'UserPoolId': pool_id,+ 'ClientName': 'oauth2-test-client',+ 'GenerateSecret': generate_secret,+ 'AllowedOAuthFlows': ['code'],+ 'AllowedOAuthScopes': ['openid', 'email', 'profile'],+ 'AllowedOAuthFlowsUserPoolClient': True,+ 'CallbackURLs': ['http://localhost:3000/callback'],+ 'LogoutURLs': ['http://localhost:3000/logout'],+ 'DefaultRedirectURI': 'http://localhost:3000/callback',+ 'ExplicitAuthFlows': ['ALLOW_USER_PASSWORD_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],+ }+ client_resp = cognito_idp.create_user_pool_client(**client_kwargs)+ client = client_resp['UserPoolClient']++ cognito_idp.admin_create_user(+ UserPoolId=pool_id,+ Username='testuser',+ TemporaryPassword='TempPass1!',+ UserAttributes=[+ {'Name': 'email', 'Value': '[email protected]'},+ {'Name': 'email_verified', 'Value': 'true'},+ {'Name': 'name', 'Value': 'Test User'},+ ],+ )+ cognito_idp.admin_set_user_password(+ UserPoolId=pool_id, Username='testuser', Password='TestPass1!', Permanent=True,+ )++ return pool_id, client+++def _lower_headers(h):+ """Return a plain dict with all header names lowercased."""+ return {k.lower(): v for k, v in h.items()}+++def _get(url, follow_redirects=True):+ """GET request, optionally not following redirects."""+ req = urllib.request.Request(url, method='GET')+ if not follow_redirects:+ opener = urllib.request.build_opener(_NoRedirectHandler)+ else:+ opener = urllib.request.build_opener()+ try:+ resp = opener.open(req, timeout=10)+ return resp.status, _lower_headers(resp.headers), resp.read()+ except urllib.error.HTTPError as e:+ return e.code, _lower_headers(e.headers), e.read()+++def _post_form(url, data, headers=None, follow_redirects=True):+ """POST form-encoded data."""+ body = urllib.parse.urlencode(data).encode()+ req = urllib.request.Request(url, data=body, method='POST')+ req.add_header('Content-Type', 'application/x-www-form-urlencoded')+ if headers:+ for k, v in headers.items():+ req.add_header(k, v)+ if not follow_redirects:+ opener = urllib.request.build_opener(_NoRedirectHandler)+ else:+ opener = urllib.request.build_opener()+ try:+ resp = opener.open(req, timeout=10)+ return resp.status, _lower_headers(resp.headers), resp.read()+ except urllib.error.HTTPError as e:+ return e.code, _lower_headers(e.headers), e.read()+++class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):+ def redirect_request(self, req, fp, code, msg, headers, newurl):+ raise urllib.error.HTTPError(newurl, code, msg, headers, fp)+++# ---------------------------------------------------------------------------+# Tests — /oauth2/authorize+# ---------------------------------------------------------------------------++def test_oauth2_authorize_shows_login_form():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp)+ client_id = client['ClientId']++ url = (f'{ENDPOINT}/oauth2/authorize?response_type=code'+ f'&client_id={client_id}'+ f'&redirect_uri=http://localhost:3000/callback'+ f'&scope=openid+email'+ f'&state=abc123')+ status, headers, body = _get(url)+ html = body.decode('utf-8')++ assert status == 200+ assert 'text/html' in headers.get('content-type', '')+ assert '<form' in html+ assert 'username' in html+ assert 'password' in html+ assert client_id in html+++def test_oauth2_authorize_invalid_client():+ url = (f'{ENDPOINT}/oauth2/authorize?response_type=code'+ f'&client_id=nonexistent'+ f'&redirect_uri=http://localhost:3000/callback')+ status, headers, body = _get(url)+ resp = json.loads(body)++ assert status == 400+ assert resp['error'] == 'invalid_client'+++def test_oauth2_authorize_invalid_redirect_uri():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp)+ client_id = client['ClientId']++ url = (f'{ENDPOINT}/oauth2/authorize?response_type=code'+ f'&client_id={client_id}'+ f'&redirect_uri=http://evil.com/callback')+ status, headers, body = _get(url)+ resp = json.loads(body)++ assert status == 400+ assert resp['error'] == 'invalid_request'+++def test_oauth2_authorize_unsupported_response_type():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp)+ client_id = client['ClientId']++ url = (f'{ENDPOINT}/oauth2/authorize?response_type=token'+ f'&client_id={client_id}'+ f'&redirect_uri=http://localhost:3000/callback')+ status, headers, body = _get(url)+ resp = json.loads(body)++ assert status == 400+ assert resp['error'] == 'unsupported_response_type'+++# ---------------------------------------------------------------------------+# Tests — /login+# ---------------------------------------------------------------------------++def test_oauth2_login_success_redirects_with_code():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp)+ client_id = client['ClientId']++ status, headers, body = _post_form(+ f'{ENDPOINT}/login',+ {+ 'username': 'testuser',+ 'password': 'TestPass1!',+ 'client_id': client_id,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'scope': 'openid email',+ 'state': 'mystate',+ 'response_type': 'code',+ },+ follow_redirects=False,+ )++ assert status == 302+ location = headers.get('location', '')+ assert location.startswith('http://localhost:3000/callback')+ parsed = urllib.parse.urlparse(location)+ qs = urllib.parse.parse_qs(parsed.query)+ assert 'code' in qs+ assert qs['state'] == ['mystate']+++def test_oauth2_login_failure_shows_error():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp)+ client_id = client['ClientId']++ status, headers, body = _post_form(+ f'{ENDPOINT}/login',+ {+ 'username': 'testuser',+ 'password': 'WrongPass!',+ 'client_id': client_id,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'scope': 'openid',+ 'state': 'xyz',+ 'response_type': 'code',+ },+ )++ assert status == 200+ html = body.decode('utf-8')+ assert 'Incorrect username or password' in html+++# ---------------------------------------------------------------------------+# Tests — /oauth2/token+# ---------------------------------------------------------------------------++def _do_login_and_get_code(cognito_idp, client_id, extra_form=None):+ """Helper: submit login form, return the authorization code."""+ form = {+ 'username': 'testuser',+ 'password': 'TestPass1!',+ 'client_id': client_id,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'scope': 'openid email',+ 'state': 'test',+ 'response_type': 'code',+ }+ if extra_form:+ form.update(extra_form)+ status, headers, body = _post_form(f'{ENDPOINT}/login', form, follow_redirects=False)+ assert status == 302+ location = headers.get('location', '')+ qs = urllib.parse.parse_qs(urllib.parse.urlparse(location).query)+ return qs['code'][0]+++def test_oauth2_token_authorization_code():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp)+ client_id = client['ClientId']+ client_secret = client.get('ClientSecret', '')+ code = _do_login_and_get_code(cognito_idp, client_id)++ status, headers, body = _post_form(f'{ENDPOINT}/oauth2/token', {+ 'grant_type': 'authorization_code',+ 'code': code,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'client_id': client_id,+ 'client_secret': client_secret,+ })++ assert status == 200+ resp = json.loads(body)+ assert 'access_token' in resp+ assert 'id_token' in resp+ assert 'refresh_token' in resp+ assert resp['token_type'] == 'Bearer'+ assert resp['expires_in'] == 3600+++def test_oauth2_token_authorization_code_with_pkce():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp, generate_secret=False)+ client_id = client['ClientId']++ # Generate PKCE pair+ code_verifier = secrets.token_urlsafe(64)+ digest = hashlib.sha256(code_verifier.encode('ascii')).digest()+ code_challenge = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii')++ code = _do_login_and_get_code(cognito_idp, client_id, {+ 'code_challenge': code_challenge,+ 'code_challenge_method': 'S256',+ })++ status, headers, body = _post_form(f'{ENDPOINT}/oauth2/token', {+ 'grant_type': 'authorization_code',+ 'code': code,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'client_id': client_id,+ 'code_verifier': code_verifier,+ })++ assert status == 200+ resp = json.loads(body)+ assert 'access_token' in resp+ assert 'id_token' in resp+++def test_oauth2_token_invalid_pkce_verifier():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp, generate_secret=False)+ client_id = client['ClientId']++ code_verifier = secrets.token_urlsafe(64)+ digest = hashlib.sha256(code_verifier.encode('ascii')).digest()+ code_challenge = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii')++ code = _do_login_and_get_code(cognito_idp, client_id, {+ 'code_challenge': code_challenge,+ 'code_challenge_method': 'S256',+ })++ status, headers, body = _post_form(f'{ENDPOINT}/oauth2/token', {+ 'grant_type': 'authorization_code',+ 'code': code,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'client_id': client_id,+ 'code_verifier': 'wrong-verifier',+ })++ assert status == 400+ resp = json.loads(body)+ assert resp['error'] == 'invalid_grant'+++def test_oauth2_token_code_reuse():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp)+ client_id = client['ClientId']+ client_secret = client.get('ClientSecret', '')+ code = _do_login_and_get_code(cognito_idp, client_id)++ # First use — should succeed+ status1, _, body1 = _post_form(f'{ENDPOINT}/oauth2/token', {+ 'grant_type': 'authorization_code',+ 'code': code,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'client_id': client_id,+ 'client_secret': client_secret,+ })+ assert status1 == 200++ # Second use — should fail+ status2, _, body2 = _post_form(f'{ENDPOINT}/oauth2/token', {+ 'grant_type': 'authorization_code',+ 'code': code,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'client_id': client_id,+ 'client_secret': client_secret,+ })+ assert status2 == 400+ resp2 = json.loads(body2)+ assert resp2['error'] == 'invalid_grant'+++def test_oauth2_token_refresh_token():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp)+ client_id = client['ClientId']+ client_secret = client.get('ClientSecret', '')+ code = _do_login_and_get_code(cognito_idp, client_id)++ # Get initial tokens+ status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {+ 'grant_type': 'authorization_code',+ 'code': code,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'client_id': client_id,+ 'client_secret': client_secret,+ })+ assert status == 200+ tokens = json.loads(body)+ refresh_token = tokens['refresh_token']++ # Refresh+ status2, _, body2 = _post_form(f'{ENDPOINT}/oauth2/token', {+ 'grant_type': 'refresh_token',+ 'refresh_token': refresh_token,+ 'client_id': client_id,+ 'client_secret': client_secret,+ })+ assert status2 == 200+ resp2 = json.loads(body2)+ assert 'access_token' in resp2+ assert 'id_token' in resp2+++def test_oauth2_token_client_credentials():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp, generate_secret=True)+ client_id = client['ClientId']+ client_secret = client['ClientSecret']++ status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {+ 'grant_type': 'client_credentials',+ 'client_id': client_id,+ 'client_secret': client_secret,+ 'scope': 'openid',+ })++ assert status == 200+ resp = json.loads(body)+ assert 'access_token' in resp+ assert resp['token_type'] == 'Bearer'+ # client_credentials should NOT return id_token or refresh_token+ assert 'id_token' not in resp+ assert 'refresh_token' not in resp+++def test_oauth2_token_client_auth_basic():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp, generate_secret=True)+ client_id = client['ClientId']+ client_secret = client['ClientSecret']++ basic = base64.b64encode(f'{client_id}:{client_secret}'.encode()).decode()++ status, _, body = _post_form(+ f'{ENDPOINT}/oauth2/token',+ {+ 'grant_type': 'client_credentials',+ 'scope': 'openid',+ },+ headers={'Authorization': f'Basic {basic}'},+ )++ assert status == 200+ resp = json.loads(body)+ assert 'access_token' in resp+++# ---------------------------------------------------------------------------+# Tests — /oauth2/userInfo+# ---------------------------------------------------------------------------++def test_oauth2_userinfo():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp)+ client_id = client['ClientId']+ client_secret = client.get('ClientSecret', '')+ code = _do_login_and_get_code(cognito_idp, client_id)++ # Get tokens+ _, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {+ 'grant_type': 'authorization_code',+ 'code': code,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'client_id': client_id,+ 'client_secret': client_secret,+ })+ tokens = json.loads(body)+ access_token = tokens['access_token']++ # Call userInfo+ req = urllib.request.Request(+ f'{ENDPOINT}/oauth2/userInfo',+ headers={'Authorization': f'Bearer {access_token}'},+ )+ resp = urllib.request.urlopen(req, timeout=10)+ assert resp.status == 200+ claims = json.loads(resp.read())++ assert 'sub' in claims+ assert claims.get('email') == '[email protected]'+ assert claims.get('cognito:username') == 'testuser'+ assert claims.get('name') == 'Test User'+++def test_oauth2_userinfo_invalid_token():+ req = urllib.request.Request(+ f'{ENDPOINT}/oauth2/userInfo',+ headers={'Authorization': 'Bearer invalid-token'},+ )+ try:+ urllib.request.urlopen(req, timeout=10)+ assert False, 'Expected 401'+ except urllib.error.HTTPError as e:+ assert e.code == 401+ resp = json.loads(e.read())+ assert resp['error'] == 'invalid_token'+++def test_oauth2_userinfo_missing_token():+ req = urllib.request.Request(f'{ENDPOINT}/oauth2/userInfo')+ try:+ urllib.request.urlopen(req, timeout=10)+ assert False, 'Expected 401'+ except urllib.error.HTTPError as e:+ assert e.code == 401+++# ---------------------------------------------------------------------------+# Tests — /logout+# ---------------------------------------------------------------------------++def test_oauth2_logout_redirects():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp)+ client_id = client['ClientId']++ url = (f'{ENDPOINT}/logout'+ f'?client_id={client_id}'+ f'&logout_uri=http://localhost:3000/logout')+ status, headers, body = _get(url, follow_redirects=False)++ assert status == 302+ assert headers.get('location', '') == 'http://localhost:3000/logout'+++def test_oauth2_logout_invalid_uri():+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp)+ client_id = client['ClientId']++ url = (f'{ENDPOINT}/logout'+ f'?client_id={client_id}'+ f'&logout_uri=http://evil.com/logout')+ status, headers, body = _get(url, follow_redirects=False)++ assert status == 400+ resp = json.loads(body)+ assert resp['error'] == 'invalid_request'+++# ---------------------------------------------------------------------------+# Tests — E2E flow+# ---------------------------------------------------------------------------++def test_oauth2_full_flow():+ """End-to-end: authorize -> login -> token -> userInfo."""+ cognito_idp = make_client('cognito-idp')+ pool_id, client = _setup_pool_with_user(cognito_idp)+ client_id = client['ClientId']+ client_secret = client.get('ClientSecret', '')++ # 1. GET /oauth2/authorize — get login form+ url = (f'{ENDPOINT}/oauth2/authorize?response_type=code'+ f'&client_id={client_id}'+ f'&redirect_uri=http://localhost:3000/callback'+ f'&scope=openid+email'+ f'&state=e2e-state')+ status, headers, body = _get(url)+ assert status == 200+ assert '<form' in body.decode('utf-8')++ # 2. POST /login — submit credentials+ status, headers, body = _post_form(+ f'{ENDPOINT}/login',+ {+ 'username': 'testuser',+ 'password': 'TestPass1!',+ 'client_id': client_id,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'scope': 'openid email',+ 'state': 'e2e-state',+ 'response_type': 'code',+ },+ follow_redirects=False,+ )+ assert status == 302+ location = headers.get('location', '')+ qs = urllib.parse.parse_qs(urllib.parse.urlparse(location).query)+ code = qs['code'][0]+ assert qs['state'] == ['e2e-state']++ # 3. POST /oauth2/token — exchange code for tokens+ status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {+ 'grant_type': 'authorization_code',+ 'code': code,+ 'redirect_uri': 'http://localhost:3000/callback',+ 'client_id': client_id,+ 'client_secret': client_secret,+ })+ assert status == 200+ tokens = json.loads(body)+ assert 'access_token' in tokens+ assert 'id_token' in tokens+ assert 'refresh_token' in tokens++ # 4. GET /oauth2/userInfo — verify user claims+ req = urllib.request.Request(+ f'{ENDPOINT}/oauth2/userInfo',+ headers={'Authorization': f'Bearer {tokens["access_token"]}'},+ )+ resp = urllib.request.urlopen(req, timeout=10)+ claims = json.loads(resp.read())+ assert claims['email'] == '[email protected]'+ assert claims['cognito:username'] == 'testuser'++ # 5. GET /logout — redirect to logout URI+ logout_url = (f'{ENDPOINT}/logout'+ f'?client_id={client_id}'+ f'&logout_uri=http://localhost:3000/logout')+ status, headers, _ = _get(logout_url, follow_redirects=False)+ assert status == 302+ assert headers.get('location', '') == 'http://localhost:3000/logout'diff --git a/tests/test_cognito_oauth2.py b/tests/test_cognito_oauth2.pydeleted file mode 100644index 061b3d8c..00000000--- a/tests/test_cognito_oauth2.py+++ /dev/null@@ -1,598 +0,0 @@-"""-Integration tests for Cognito OAuth2/OIDC IdP endpoints.--Tests the full OAuth2 authorization code flow including:- /oauth2/authorize, /login, /oauth2/token, /oauth2/userInfo, /logout-"""-import base64-import hashlib-import json-import os-import secrets-import urllib.error-import urllib.parse-import urllib.request--from conftest import ENDPOINT, make_client---# ----------------------------------------------------------------------------# Helpers-# -----------------------------------------------------------------------------def _setup_pool_with_user(cognito_idp, generate_secret=True):- """Create a user pool with a confirmed user and an OAuth-enabled client."""- pool = cognito_idp.create_user_pool(PoolName='OAuth2TestPool')- pool_id = pool['UserPool']['Id']-- client_kwargs = {- 'UserPoolId': pool_id,- 'ClientName': 'oauth2-test-client',- 'GenerateSecret': generate_secret,- 'AllowedOAuthFlows': ['code'],- 'AllowedOAuthScopes': ['openid', 'email', 'profile'],- 'AllowedOAuthFlowsUserPoolClient': True,- 'CallbackURLs': ['http://localhost:3000/callback'],- 'LogoutURLs': ['http://localhost:3000/logout'],- 'DefaultRedirectURI': 'http://localhost:3000/callback',- 'ExplicitAuthFlows': ['ALLOW_USER_PASSWORD_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'],- }- client_resp = cognito_idp.create_user_pool_client(**client_kwargs)- client = client_resp['UserPoolClient']-- cognito_idp.admin_create_user(- UserPoolId=pool_id,- Username='testuser',- TemporaryPassword='TempPass1!',- UserAttributes=[- {'Name': 'email', 'Value': '[email protected]'},- {'Name': 'email_verified', 'Value': 'true'},- {'Name': 'name', 'Value': 'Test User'},- ],- )- cognito_idp.admin_set_user_password(- UserPoolId=pool_id, Username='testuser', Password='TestPass1!', Permanent=True,- )-- return pool_id, client---def _lower_headers(h):- """Return a plain dict with all header names lowercased."""- return {k.lower(): v for k, v in h.items()}---def _get(url, follow_redirects=True):- """GET request, optionally not following redirects."""- req = urllib.request.Request(url, method='GET')- if not follow_redirects:- opener = urllib.request.build_opener(_NoRedirectHandler)- else:- opener = urllib.request.build_opener()- try:- resp = opener.open(req, timeout=10)- return resp.status, _lower_headers(resp.headers), resp.read()- except urllib.error.HTTPError as e:- return e.code, _lower_headers(e.headers), e.read()---def _post_form(url, data, headers=None, follow_redirects=True):- """POST form-encoded data."""- body = urllib.parse.urlencode(data).encode()- req = urllib.request.Request(url, data=body, method='POST')- req.add_header('Content-Type', 'application/x-www-form-urlencoded')- if headers:- for k, v in headers.items():- req.add_header(k, v)- if not follow_redirects:- opener = urllib.request.build_opener(_NoRedirectHandler)- else:- opener = urllib.request.build_opener()- try:- resp = opener.open(req, timeout=10)- return resp.status, _lower_headers(resp.headers), resp.read()- except urllib.error.HTTPError as e:- return e.code, _lower_headers(e.headers), e.read()---class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):- def redirect_request(self, req, fp, code, msg, headers, newurl):- raise urllib.error.HTTPError(newurl, code, msg, headers, fp)---# ----------------------------------------------------------------------------# Tests — /oauth2/authorize-# -----------------------------------------------------------------------------def test_oauth2_authorize_shows_login_form():- cognito_idp = make_client('cognito-idp')- pool_id, client = _setup_pool_with_user(cognito_idp)- client_id = client['ClientId']-- url = (f'{ENDPOINT}/oauth2/authorize?response_type=code'- f'&client_id={client_id}'- f'&redirect_uri=http://localhost:3000/callback'- f'&scope=openid+email'- f'&state=abc123')- status, headers, body = _get(url)- html = body.decode('utf-8')-- assert status == 200- assert 'text/html' in headers.get('content-type', '')- assert '<form' in html- assert 'username' in html- assert 'password' in html- assert client_id in html---def test_oauth2_authorize_invalid_client():- url = (f'{ENDPOINT}/oauth2/authorize?response_type=code'- f'&client_id=nonexistent'- f'&redirect_uri=http://localhost:3000/callback')- status, headers, body = _get(url)- resp = json.loads(body)-- assert status == 400- assert resp['error'] == 'invalid_client'---def test_oauth2_authorize_invalid_redirect_uri():- cognito_idp = make_client('cognito-idp')- pool_id, client = _setup_pool_with_user(cognito_idp)- client_id = client['ClientId']-- url = (f'{ENDPOINT}/oauth2/authorize?response_type=code'- f'&client_id={client_id}'- f'&redirect_uri=http://evil.com/callback')- status, headers, body = _get(url)- resp = json.loads(body)-- assert status == 400- assert resp['error'] == 'invalid_request'---def test_oauth2_authorize_unsupported_response_type():- cognito_idp = make_client('cognito-idp')- pool_id, client = _setup_pool_with_user(cognito_idp)- client_id = client['ClientId']-- url = (f'{ENDPOINT}/oauth2/authorize?response_type=token'- f'&client_id={client_id}'- f'&redirect_uri=http://localhost:3000/callback')- status, headers, body = _get(url)- resp = json.loads(body)-- assert status == 400- assert resp['error'] == 'unsupported_response_type'---# ----------------------------------------------------------------------------# Tests — /login-# -----------------------------------------------------------------------------def test_oauth2_login_success_redirects_with_code():- cognito_idp = make_client('cognito-idp')- pool_id, client = _setup_pool_with_user(cognito_idp)- client_id = client['ClientId']-- status, headers, body = _post_form(- f'{ENDPOINT}/login',- {- 'username': 'testuser',- 'password': 'TestPass1!',- 'client_id': client_id,- 'redirect_uri': 'http://localhost:3000/callback',- 'scope': 'openid email',- 'state': 'mystate',- 'response_type': 'code',- },- follow_redirects=False,- )-- assert status == 302- location = headers.get('location', '')- assert location.startswith('http://localhost:3000/callback')- parsed = urllib.parse.urlparse(location)- qs = urllib.parse.parse_qs(parsed.query)- assert 'code' in qs- assert qs['state'] == ['mystate']---def test_oauth2_login_failure_shows_error():- cognito_idp = make_client('cognito-idp')- pool_id, client = _setup_pool_with_user(cognito_idp)- client_id = client['ClientId']-- status, headers, body = _post_form(- f'{ENDPOINT}/login',- {- 'username': 'testuser',- 'password': 'WrongPass!',- 'client_id': client_id,- 'redirect_uri': 'http://localhost:3000/callback',- 'scope': 'openid',- 'state': 'xyz',- 'response_type': 'code',- },- )-- assert status == 200- html = body.decode('utf-8')- assert 'Incorrect username or password' in html---# ----------------------------------------------------------------------------# Tests — /oauth2/token-# -----------------------------------------------------------------------------def _do_login_and_get_code(cognito_idp, client_id, extra_form=None):- """Helper: submit login form, return the authorization code."""- form = {- 'username': 'testuser',- 'password': 'TestPass1!',- 'client_id': client_id,- 'redirect_uri': 'http://localhost:3000/callback',- 'scope': 'openid email',- 'state': 'test',- 'response_type': 'code',- }- if extra_form:- form.update(extra_form)- status, headers, body = _post_form(f'{ENDPOINT}/login', form, follow_redirects=False)- assert status == 302- location = headers.get('location', '')- qs = urllib.parse.parse_qs(urllib.parse.urlparse(location).query)- return qs['code'][0]---def test_oauth2_token_authorization_code():- cognito_idp = make_client('cognito-idp')- pool_id, client = _setup_pool_with_user(cognito_idp)- client_id = client['ClientId']- client_secret = client.get('ClientSecret', '')- code = _do_login_and_get_code(cognito_idp, client_id)-- status, headers, body = _post_form(f'{ENDPOINT}/oauth2/token', {- 'grant_type': 'authorization_code',- 'code': code,- 'redirect_uri': 'http://localhost:3000/callback',- 'client_id': client_id,- 'client_secret': client_secret,- })-- assert status == 200- resp = json.loads(body)- assert 'access_token' in resp- assert 'id_token' in resp- assert 'refresh_token' in resp- assert resp['token_type'] == 'Bearer'- assert resp['expires_in'] == 3600---def test_oauth2_token_authorization_code_with_pkce():- cognito_idp = make_client('cognito-idp')- pool_id, client = _setup_pool_with_user(cognito_idp, generate_secret=False)- client_id = client['ClientId']-- # Generate PKCE pair- code_verifier = secrets.token_urlsafe(64)- digest = hashlib.sha256(code_verifier.encode('ascii')).digest()- code_challenge = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii')-- code = _do_login_and_get_code(cognito_idp, client_id, {- 'code_challenge': code_challenge,- 'code_challenge_method': 'S256',- })-- status, headers, body = _post_form(f'{ENDPOINT}/oauth2/token', {- 'grant_type': 'authorization_code',- 'code': code,- 'redirect_uri': 'http://localhost:3000/callback',- 'client_id': client_id,- 'code_verifier': code_verifier,- })-- assert status == 200- resp = json.loads(body)- assert 'access_token' in resp- assert 'id_token' in resp---def test_oauth2_token_invalid_pkce_verifier():- cognito_idp = make_client('cognito-idp')- pool_id, client = _setup_pool_with_user(cognito_idp, generate_secret=False)- client_id = client['ClientId']-- code_verifier = secrets.token_urlsafe(64)- digest = hashlib.sha256(code_verifier.encode('ascii')).digest()- code_challenge = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii')-- code = _do_login_and_get_code(cognito_idp, client_id, {- 'code_challenge': code_challenge,- 'code_challenge_method': 'S256',- })-- status, headers, body = _post_form(f'{ENDPOINT}/oauth2/token', {- 'grant_type': 'authorization_code',- 'code': code,- 'redirect_uri': 'http://localhost:3000/callback',- 'client_id': client_id,- 'code_verifier': 'wrong-verifier',- })-- assert status == 400- resp = json.loads(body)- assert resp['error'] == 'invalid_grant'---def test_oauth2_token_code_reuse():- cognito_idp = make_client('cognito-idp')- pool_id, client = _setup_pool_with_user(cognito_idp)- client_id = client['ClientId']- client_secret = client.get('ClientSecret', '')- code = _do_login_and_get_code(cognito_idp, client_id)-- # First use — should succeed- status1, _, body1 = _post_form(f'{ENDPOINT}/oauth2/token', {- 'grant_type': 'authorization_code',- 'code': code,- 'redirect_uri': 'http://localhost:3000/callback',- 'client_id': client_id,- 'client_secret': client_secret,- })- assert status1 == 200-- # Second use — should fail- status2, _, body2 = _post_form(f'{ENDPOINT}/oauth2/token', {- 'grant_type': 'authorization_code',- 'code': code,- 'redirect_uri': 'http://localhost:3000/callback',- 'client_id': client_id,- 'client_secret': client_secret,- })- assert status2 == 400- resp2 = json.loads(body2)- assert resp2['error'] == 'invalid_grant'---def test_oauth2_token_refresh_token():- cognito_idp = make_client('cognito-idp')- pool_id, client = _setup_pool_with_user(cognito_idp)- client_id = client['ClientId']- client_secret = client.get('ClientSecret', '')- code = _do_login_and_get_code(cognito_idp, client_id)-- # Get initial tokens- status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {- 'grant_type': 'authorization_code',- 'code': code,- 'redirect_uri': 'http://localhost:3000/callback',- 'client_id': client_id,- 'client_secret': client_secret,- })- assert status == 200- tokens = json.loads(body)- refresh_token = tokens['refresh_token']-- # Refresh- status2, _, body2 = _post_form(f'{ENDPOINT}/oauth2/token', {- 'grant_type': 'refresh_token',- 'refresh_token': refresh_token,- 'client_id': client_id,- 'client_secret': client_secret,- })- assert status2 == 200- resp2 = json.loads(body2)- assert 'access_token' in resp2- assert 'id_token' in resp2---def test_oauth2_token_client_credentials():- cognito_idp = make_client('cognito-idp')- pool_id, client = _setup_pool_with_user(cognito_idp, generate_secret=True)- client_id = client['ClientId']- client_secret = client['ClientSecret']-- status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {- 'grant_type': 'client_credentials',- 'client_id': client_id,- 'client_secret': client_secret,- 'scope': 'openid',- })-- assert status == 200- resp = json.loads(body)- assert 'access_token' in resp- assert resp['token_type'] == 'Bearer'- # client_credentials should NOT return id_token or refresh_token- assert 'id_token' not in resp- assert 'refresh_token' not in resp---def test_oauth2_token_client_auth_basic():- cognito_idp = make_client('cognito-idp')- pool_id, client = _setup_pool_with_user(cognito_idp, generate_secret=True)- client_id = client['ClientId']- client_secret = client['ClientSecret']-- basic = base64.b64encode(f'{client_id}:{client_secret}'.encode()).decode()-- status, _, body = _post_form(- f'{ENDPOINT}/oauth2/token',- {- 'grant_type': 'client_credentials',- 'scope': 'openid',- },- headers={'Authorization': f'Basic {basic}'},- )-- assert status == 200- resp = json.loads(body)- assert 'access_token' in resp---# ----------------------------------------------------------------------------# Tests — /oauth2/userInfo-# -----------------------------------------------------------------------------def test_oauth2_userinfo():- cognito_idp = make_client('cognito-idp')- pool_id, client = _setup_pool_with_user(cognito_idp)- client_id = client['ClientId']- client_secret = client.get('ClientSecret', '')- code = _do_login_and_get_code(cognito_idp, client_id)-- # Get tokens- _, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {- 'grant_type': 'authorization_code',- 'code': code,- 'redirect_uri': 'http://localhost:3000/callback',- 'client_id': client_id,- 'client_secret': client_secret,- })- tokens = json.loads(body)- access_token = tokens['access_token']-- # Call userInfo- req = urllib.request.Request(- f'{ENDPOINT}/oauth2/userInfo',- headers={'Authorization': f'Bearer {access_token}'},- )- resp = urllib.request.urlopen(req, timeout=10)- assert resp.status == 200- claims = json.loads(resp.read())-- assert 'sub' in claims- assert claims.get('email') == '[email protected]'- assert claims.get('cognito:username') == 'testuser'- assert claims.get('name') == 'Test User'---def test_oauth2_userinfo_invalid_token():- req = urllib.request.Request(- f'{ENDPOINT}/oauth2/userInfo',- headers={'Authorization': 'Bearer invalid-token'},- )- try:- urllib.request.urlopen(req, timeout=10)- assert False, 'Expected 401'- except urllib.error.HTTPError as e:- assert e.code == 401- resp = json.loads(e.read())- assert resp['error'] == 'invalid_token'---def test_oauth2_userinfo_missing_token():- req = urllib.request.Request(f'{ENDPOINT}/oauth2/userInfo')- try:- urllib.request.urlopen(req, timeout=10)- assert False, 'Expected 401'- except urllib.error.HTTPError as e:- assert e.code == 401---# ----------------------------------------------------------------------------# Tests — /logout-# -----------------------------------------------------------------------------def test_oauth2_logout_redirects():- cognito_idp = make_client('cognito-idp')- pool_id, client = _setup_pool_with_user(cognito_idp)- client_id = client['ClientId']-- url = (f'{ENDPOINT}/logout'- f'?client_id={client_id}'- f'&logout_uri=http://localhost:3000/logout')- status, headers, body = _get(url, follow_redirects=False)-- assert status == 302- assert headers.get('location', '') == 'http://localhost:3000/logout'---def test_oauth2_logout_invalid_uri():- cognito_idp = make_client('cognito-idp')- pool_id, client = _setup_pool_with_user(cognito_idp)- client_id = client['ClientId']-- url = (f'{ENDPOINT}/logout'- f'?client_id={client_id}'- f'&logout_uri=http://evil.com/logout')- status, headers, body = _get(url, follow_redirects=False)-- assert status == 400- resp = json.loads(body)- assert resp['error'] == 'invalid_request'---# ----------------------------------------------------------------------------# Tests — E2E flow-# -----------------------------------------------------------------------------def test_oauth2_full_flow():- """End-to-end: authorize -> login -> token -> userInfo."""- cognito_idp = make_client('cognito-idp')- pool_id, client = _setup_pool_with_user(cognito_idp)- client_id = client['ClientId']- client_secret = client.get('ClientSecret', '')-- # 1. GET /oauth2/authorize — get login form- url = (f'{ENDPOINT}/oauth2/authorize?response_type=code'- f'&client_id={client_id}'- f'&redirect_uri=http://localhost:3000/callback'- f'&scope=openid+email'- f'&state=e2e-state')- status, headers, body = _get(url)- assert status == 200- assert '<form' in body.decode('utf-8')-- # 2. POST /login — submit credentials- status, headers, body = _post_form(- f'{ENDPOINT}/login',- {- 'username': 'testuser',- 'password': 'TestPass1!',- 'client_id': client_id,- 'redirect_uri': 'http://localhost:3000/callback',- 'scope': 'openid email',- 'state': 'e2e-state',- 'response_type': 'code',- },- follow_redirects=False,- )- assert status == 302- location = headers.get('location', '')- qs = urllib.parse.parse_qs(urllib.parse.urlparse(location).query)- code = qs['code'][0]- assert qs['state'] == ['e2e-state']-- # 3. POST /oauth2/token — exchange code for tokens- status, _, body = _post_form(f'{ENDPOINT}/oauth2/token', {- 'grant_type': 'authorization_code',- 'code': code,- 'redirect_uri': 'http://localhost:3000/callback',- 'client_id': client_id,- 'client_secret': client_secret,- })- assert status == 200- tokens = json.loads(body)- assert 'access_token' in tokens- assert 'id_token' in tokens- assert 'refresh_token' in tokens-- # 4. GET /oauth2/userInfo — verify user claims- req = urllib.request.Request(- f'{ENDPOINT}/oauth2/userInfo',- headers={'Authorization': f'Bearer {tokens["access_token"]}'},- )- resp = urllib.request.urlopen(req, timeout=10)- claims = json.loads(resp.read())- assert claims['email'] == '[email protected]'- assert claims['cognito:username'] == 'testuser'-- # 5. GET /logout — redirect to logout URI- logout_url = (f'{ENDPOINT}/logout'- f'?client_id={client_id}'- f'&logout_uri=http://localhost:3000/logout')- status, headers, _ = _get(logout_url, follow_redirects=False)- assert status == 302- assert headers.get('location', '') == 'http://localhost:3000/logout'diff --git a/tests/test_ministack.py b/tests/test_ministack.pyindex c8b9cd3f..b199fced 100644--- a/tests/test_ministack.py+++ b/tests/test_ministack.py@@ -1,12 +1,17 @@+"""Ministack admin/core tests — health, config, persistence, hypercorn compat."""+import ioimport jsonimport os+import pytestimport time+import uuid as _uuid_modimport zipfile-from urllib.parse import urlparse-import pytestfrom botocore.exceptions import ClientError-import uuid as _uuid_mod+from urllib.parse import urlparse+++# ========== from test_ministack.py ==========_ministack_installed = True@@ -137,3 +142,365 @@ def test_ministack_package_services_importable():sts,]:assert callable(getattr(mod, "handle_request", None)), f"{mod.__name__} missing handle_request"++# ========== from test_ministack_persist.py ==========++def test_ministack_persist_sqs_roundtrip():+ from ministack.services import sqs as _sqs+ _sqs._queues["http://localhost:4566/000000000000/persist-q"] = {"name": "persist-q", "messages": [], "attributes": {}}+ _sqs._queue_name_to_url["persist-q"] = "http://localhost:4566/000000000000/persist-q"+ state = _sqs.get_state()+ assert "queues" in state+ saved_queues = dict(_sqs._queues)+ _sqs._queues.clear()+ _sqs._queue_name_to_url.clear()+ _sqs.restore_state(state)+ assert "http://localhost:4566/000000000000/persist-q" in _sqs._queues+ _sqs._queues.update(saved_queues)++def test_ministack_persist_sns_roundtrip():+ from ministack.services import sns as _sns+ _sns._topics["arn:aws:sns:us-east-1:000000000000:persist-topic"] = {"TopicArn": "arn:aws:sns:us-east-1:000000000000:persist-topic", "subscriptions": []}+ state = _sns.get_state()+ assert "topics" in state+ _sns._topics.pop("arn:aws:sns:us-east-1:000000000000:persist-topic", None)+ _sns.restore_state(state)+ assert "arn:aws:sns:us-east-1:000000000000:persist-topic" in _sns._topics+ _sns._topics.pop("arn:aws:sns:us-east-1:000000000000:persist-topic", None)++def test_ministack_persist_ssm_roundtrip():+ from ministack.services import ssm as _ssm+ _ssm._parameters["/persist/key"] = {"Name": "/persist/key", "Value": "val", "Type": "String"}+ state = _ssm.get_state()+ assert "parameters" in state+ _ssm._parameters.pop("/persist/key")+ _ssm.restore_state(state)+ assert "/persist/key" in _ssm._parameters+ _ssm._parameters.pop("/persist/key")++def test_ministack_persist_secretsmanager_roundtrip():+ from ministack.services import secretsmanager as _sm+ _sm._secrets["persist-secret"] = {"Name": "persist-secret", "ARN": "arn:test", "Versions": {}}+ state = _sm.get_state()+ assert "secrets" in state+ _sm._secrets.pop("persist-secret")+ _sm.restore_state(state)+ assert "persist-secret" in _sm._secrets+ _sm._secrets.pop("persist-secret")++def test_ministack_persist_dynamodb_roundtrip():+ from ministack.services import dynamodb as _ddb+ _ddb._tables["persist-tbl"] = {"TableName": "persist-tbl", "pk_name": "pk", "sk_name": None, "items": {}}+ state = _ddb.get_state()+ assert "tables" in state+ _ddb._tables.pop("persist-tbl")+ _ddb.restore_state(state)+ assert "persist-tbl" in _ddb._tables+ _ddb._tables.pop("persist-tbl")++def test_ministack_persist_eventbridge_roundtrip():+ from ministack.services import eventbridge as _eb+ _eb._rules["default|persist-rule"] = {"Name": "persist-rule", "State": "ENABLED", "EventPattern": "{}"}+ state = _eb.get_state()+ assert "rules" in state+ _eb._rules.pop("default|persist-rule")+ _eb.restore_state(state)+ assert "default|persist-rule" in _eb._rules+ _eb._rules.pop("default|persist-rule")++def test_ministack_persist_kinesis_roundtrip():+ from ministack.services import kinesis as _kin+ _kin._streams["persist-stream"] = {"StreamName": "persist-stream", "StreamStatus": "ACTIVE", "shards": {}}+ state = _kin.get_state()+ assert "streams" in state+ _kin._streams.pop("persist-stream")+ _kin.restore_state(state)+ assert "persist-stream" in _kin._streams+ _kin._streams.pop("persist-stream")++def test_ministack_persist_kms_roundtrip():+ from ministack.services import kms as _kms+ key_id = "test-persist-key-id"+ _kms._keys[key_id] = {"KeyId": key_id, "Description": "persist-key", "KeySpec": "SYMMETRIC_DEFAULT", "_symmetric_key": b"\x00" * 32}+ state = _kms.get_state()+ assert "keys" in state+ _kms._keys.pop(key_id)+ _kms.restore_state(state)+ assert key_id in _kms._keys+ assert _kms._keys[key_id]["Description"] == "persist-key"+ _kms._keys.pop(key_id)++def test_ministack_persist_ec2_roundtrip():+ from ministack.services import ec2 as _ec2+ _ec2._instances["i-persist01"] = {"InstanceId": "i-persist01", "State": {"Name": "running"}}+ state = _ec2.get_state()+ assert "instances" in state+ _ec2._instances.pop("i-persist01")+ _ec2.restore_state(state)+ assert "i-persist01" in _ec2._instances+ _ec2._instances.pop("i-persist01")++def test_ministack_persist_route53_roundtrip():+ from ministack.services import route53 as _r53+ _r53._zones["Z00PERSIST"] = {"Id": "Z00PERSIST", "Name": "persist.test."}+ state = _r53.get_state()+ assert "zones" in state+ _r53._zones.pop("Z00PERSIST")+ _r53.restore_state(state)+ assert "Z00PERSIST" in _r53._zones+ _r53._zones.pop("Z00PERSIST")++def test_ministack_persist_cognito_roundtrip():+ from ministack.services import cognito as _cog+ _cog._user_pools["us-east-1_PERSIST"] = {"Id": "us-east-1_PERSIST", "Name": "persist-pool"}+ state = _cog.get_state()+ assert "user_pools" in state+ _cog._user_pools.pop("us-east-1_PERSIST")+ _cog.restore_state(state)+ assert "us-east-1_PERSIST" in _cog._user_pools+ _cog._user_pools.pop("us-east-1_PERSIST")++def test_ministack_persist_ecr_roundtrip():+ from ministack.services import ecr as _ecr+ _ecr._repositories["persist-repo"] = {"repositoryName": "persist-repo", "repositoryArn": "arn:test"}+ state = _ecr.get_state()+ assert "repositories" in state+ _ecr._repositories.pop("persist-repo")+ _ecr.restore_state(state)+ assert "persist-repo" in _ecr._repositories+ _ecr._repositories.pop("persist-repo")++def test_ministack_persist_cloudwatch_roundtrip():+ from ministack.services import cloudwatch as _cw+ _cw._alarms["persist-alarm"] = {"AlarmName": "persist-alarm", "StateValue": "OK"}+ state = _cw.get_state()+ assert "alarms" in state+ _cw._alarms.pop("persist-alarm")+ _cw.restore_state(state)+ assert "persist-alarm" in _cw._alarms+ _cw._alarms.pop("persist-alarm")++def test_ministack_persist_s3_metadata_roundtrip():+ from ministack.services import s3 as _s3+ _s3._buckets["persist-bkt"] = {"created": "2025-01-01T00:00:00Z", "objects": {"k": {"body": b"v"}}, "region": "us-east-1"}+ _s3._bucket_versioning["persist-bkt"] = "Enabled"+ state = _s3.get_state()+ assert "buckets_meta" in state+ # Object bodies must NOT be in the persisted metadata+ assert "objects" not in state["buckets_meta"].get("persist-bkt", {})+ assert "bucket_versioning" in state+ _s3._buckets.pop("persist-bkt")+ _s3._bucket_versioning.pop("persist-bkt")+ _s3.restore_state(state)+ assert "persist-bkt" in _s3._buckets+ assert _s3._buckets["persist-bkt"]["objects"] == {} # objects not restored+ assert _s3._bucket_versioning["persist-bkt"] == "Enabled"+ _s3._buckets.pop("persist-bkt")+ _s3._bucket_versioning.pop("persist-bkt")++def test_ministack_persist_lambda_roundtrip():+ from ministack.services import lambda_svc as _lam+ _lam._functions["persist-fn"] = {+ "config": {"FunctionName": "persist-fn", "Runtime": "python3.11"},+ "code_zip": b"fake-zip-bytes",+ "versions": {},+ "next_version": 1,+ }+ state = _lam.get_state()+ assert "functions" in state+ # code_zip should be base64-encoded in state+ assert isinstance(state["functions"]["persist-fn"]["code_zip"], str)+ _lam._functions.pop("persist-fn")+ _lam.restore_state(state)+ assert "persist-fn" in _lam._functions+ # code_zip should be decoded back to bytes+ assert _lam._functions["persist-fn"]["code_zip"] == b"fake-zip-bytes"+ _lam._functions.pop("persist-fn")++def test_ministack_persist_rds_roundtrip():+ from ministack.services import rds as _rds+ _rds._instances["persist-db"] = {+ "DBInstanceIdentifier": "persist-db",+ "Engine": "postgres",+ "DBInstanceStatus": "available",+ "_docker_container_id": "fake-container-id",+ }+ state = _rds.get_state()+ assert "instances" in state+ assert "_docker_container_id" not in state["instances"]["persist-db"]+ _rds._instances.pop("persist-db")+ _rds.restore_state(state)+ assert "persist-db" in _rds._instances+ assert _rds._instances["persist-db"]["Engine"] == "postgres"+ _rds._instances.pop("persist-db")++def test_ministack_persist_ecs_roundtrip():+ from ministack.services import ecs as _ecs+ _ecs._clusters["persist-cluster"] = {"clusterName": "persist-cluster", "status": "ACTIVE"}+ _ecs._tasks["arn:persist-task"] = {+ "taskArn": "arn:persist-task",+ "lastStatus": "RUNNING",+ "_docker_ids": ["fake-id"],+ }+ state = _ecs.get_state()+ assert "clusters" in state+ assert "tasks" in state+ assert "_docker_ids" not in state["tasks"]["arn:persist-task"]+ _ecs._clusters.pop("persist-cluster")+ _ecs._tasks.pop("arn:persist-task")+ _ecs.restore_state(state)+ assert "persist-cluster" in _ecs._clusters+ assert "arn:persist-task" in _ecs._tasks+ assert _ecs._tasks["arn:persist-task"]["lastStatus"] == "STOPPED"+ _ecs._clusters.pop("persist-cluster")+ _ecs._tasks.pop("arn:persist-task")++def test_ministack_persist_elasticache_roundtrip():+ from ministack.services import elasticache as _ec+ _ec._clusters["persist-cache"] = {+ "CacheClusterId": "persist-cache",+ "Engine": "redis",+ "CacheClusterStatus": "available",+ "_docker_container_id": "fake-id",+ }+ state = _ec.get_state()+ assert "clusters" in state+ assert "_docker_container_id" not in state["clusters"]["persist-cache"]+ _ec._clusters.pop("persist-cache")+ _ec.restore_state(state)+ assert "persist-cache" in _ec._clusters+ assert _ec._clusters["persist-cache"]["Engine"] == "redis"+ _ec._clusters.pop("persist-cache")++def test_ministack_persist_stepfunctions_roundtrip():+ from ministack.services import stepfunctions as _sfn+ sm_arn = "arn:aws:states:us-east-1:000000000000:stateMachine:persist-sm"+ _sfn._state_machines[sm_arn] = {+ "stateMachineArn": sm_arn,+ "name": "persist-sm",+ "definition": '{"StartAt":"Pass","States":{"Pass":{"Type":"Pass","End":true}}}',+ "roleArn": "arn:aws:iam::000000000000:role/sfn",+ "type": "STANDARD",+ "status": "ACTIVE",+ }+ state = _sfn.get_state()+ assert "state_machines" in state+ assert sm_arn in state["state_machines"]+ _sfn._state_machines.pop(sm_arn)+ _sfn.restore_state(state)+ assert sm_arn in _sfn._state_machines+ assert _sfn._state_machines[sm_arn]["name"] == "persist-sm"+ _sfn._state_machines.pop(sm_arn)++def test_ministack_persist_stepfunctions_running_marked_failed():+ from ministack.services import stepfunctions as _sfn+ run_arn = "arn:aws:states:us-east-1:000000000000:execution:persist-sm:run-1"+ done_arn = "arn:aws:states:us-east-1:000000000000:execution:persist-sm:done-1"+ _sfn._executions[run_arn] = {+ "executionArn": run_arn,+ "stateMachineArn": "arn:aws:states:us-east-1:000000000000:stateMachine:persist-sm",+ "status": "RUNNING",+ "startDate": "2026-01-01T00:00:00.000Z",+ }+ _sfn._executions[done_arn] = {+ "executionArn": done_arn,+ "stateMachineArn": "arn:aws:states:us-east-1:000000000000:stateMachine:persist-sm",+ "status": "SUCCEEDED",+ "startDate": "2026-01-01T00:00:00.000Z",+ "stopDate": "2026-01-01T00:01:00.000Z",+ "output": '{"result": "ok"}',+ }+ state = _sfn.get_state()+ _sfn._executions.pop(run_arn)+ _sfn._executions.pop(done_arn)+ _sfn.restore_state(state)+ # RUNNING execution should be marked FAILED+ restored_run = _sfn._executions[run_arn]+ assert restored_run["status"] == "FAILED"+ assert restored_run["error"] == "States.ServiceRestart"+ assert restored_run["cause"] == "Execution was running when service restarted"+ assert "stopDate" in restored_run+ assert restored_run["startDate"] == "2026-01-01T00:00:00.000Z"+ # SUCCEEDED execution should pass through unchanged+ restored_done = _sfn._executions[done_arn]+ assert restored_done["status"] == "SUCCEEDED"+ assert restored_done["output"] == '{"result": "ok"}'+ _sfn._executions.pop(run_arn)+ _sfn._executions.pop(done_arn)++# ========== from test_expect_100_continue.py ==========++"""Regression test for issue #389.++boto3 < 1.40's bundled urllib3 aborts with ``BadStatusLine`` when the server+replies to ``Expect: 100-continue`` with ``HTTP/1.1 100 \\r\\n`` (empty reason+phrase). h11's default behaviour is to emit an empty reason; the compat shim in+``ministack/core/hypercorn_compat.py`` injects the canonical reason phrase so+the wire output is ``HTTP/1.1 100 Continue\\r\\n``, matching real AWS and every+SDK we test.+"""++import os+import socket+from urllib.parse import urlparse+++def test_unit_h11_informational_has_reason_phrase():+ """h11.InformationalResponse(100, ...) serialises as 'HTTP/1.1 100 Continue' once the patch is installed."""+ # Import ministack.app triggers the patch; tests usually hit a live server+ # already, but import it here defensively for isolated runs.+ import ministack.app # noqa: F401++ import h11++ conn = h11.Connection(our_role=h11.SERVER)+ conn.receive_data(+ b"PUT /foo HTTP/1.1\r\n"+ b"Host: x\r\n"+ b"Expect: 100-continue\r\n"+ b"Content-Length: 4\r\n\r\n"+ )+ conn.next_event()+ out = conn.send(h11.InformationalResponse(status_code=100, headers=[]))+ assert out is not None+ assert out.startswith(b"HTTP/1.1 100 Continue\r\n"), \+ f"expected canonical reason phrase, got: {out!r}"+++def test_wire_expect_100_continue_returns_canonical_status_line():+ """End-to-end: a raw PUT with Expect: 100-continue against ministack must+ receive a 100 Continue with the reason phrase intact (issue #389)."""+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ parsed = urlparse(endpoint)+ host = parsed.hostname or "localhost"+ port = parsed.port or 4566++ # Use a bucket path that exists without having to PUT a real object: any+ # path that accepts a body will do, because the server must emit the 100+ # response before the body arrives. We target S3 because that's the SDK+ # path in the bug report, but any 100-capable endpoint would work.+ body = b"ministack-issue-389-probe"++ sock = socket.create_connection((host, port), timeout=5)+ try:+ request = (+ f"PUT /ministack-probe-389/key HTTP/1.1\r\n"+ f"Host: {host}:{port}\r\n"+ f"Expect: 100-continue\r\n"+ f"Content-Length: {len(body)}\r\n"+ f"Content-Type: application/octet-stream\r\n"+ f"\r\n"+ ).encode("ascii")+ sock.sendall(request)+ # Server must send 100 Continue before we write the body.+ sock.settimeout(3.0)+ first_line = b""+ while b"\r\n" not in first_line:+ chunk = sock.recv(1)+ if not chunk:+ break+ first_line += chunk+ assert first_line.startswith(b"HTTP/1.1 100 Continue\r\n"), \+ f"expected '100 Continue' status line, got: {first_line!r}"+ finally:+ sock.close()diff --git a/tests/test_ministack_persist.py b/tests/test_ministack_persist.pydeleted file mode 100644index 59b050b2..00000000--- a/tests/test_ministack_persist.py+++ /dev/null@@ -1,292 +0,0 @@-import io-import json-import os-import time-import zipfile-from urllib.parse import urlparse-import pytest-from botocore.exceptions import ClientError-import uuid as _uuid_mod--def test_ministack_persist_sqs_roundtrip():- from ministack.services import sqs as _sqs- _sqs._queues["http://localhost:4566/000000000000/persist-q"] = {"name": "persist-q", "messages": [], "attributes": {}}- _sqs._queue_name_to_url["persist-q"] = "http://localhost:4566/000000000000/persist-q"- state = _sqs.get_state()- assert "queues" in state- saved_queues = dict(_sqs._queues)- _sqs._queues.clear()- _sqs._queue_name_to_url.clear()- _sqs.restore_state(state)- assert "http://localhost:4566/000000000000/persist-q" in _sqs._queues- _sqs._queues.update(saved_queues)--def test_ministack_persist_sns_roundtrip():- from ministack.services import sns as _sns- _sns._topics["arn:aws:sns:us-east-1:000000000000:persist-topic"] = {"TopicArn": "arn:aws:sns:us-east-1:000000000000:persist-topic", "subscriptions": []}- state = _sns.get_state()- assert "topics" in state- _sns._topics.pop("arn:aws:sns:us-east-1:000000000000:persist-topic", None)- _sns.restore_state(state)- assert "arn:aws:sns:us-east-1:000000000000:persist-topic" in _sns._topics- _sns._topics.pop("arn:aws:sns:us-east-1:000000000000:persist-topic", None)--def test_ministack_persist_ssm_roundtrip():- from ministack.services import ssm as _ssm- _ssm._parameters["/persist/key"] = {"Name": "/persist/key", "Value": "val", "Type": "String"}- state = _ssm.get_state()- assert "parameters" in state- _ssm._parameters.pop("/persist/key")- _ssm.restore_state(state)- assert "/persist/key" in _ssm._parameters- _ssm._parameters.pop("/persist/key")--def test_ministack_persist_secretsmanager_roundtrip():- from ministack.services import secretsmanager as _sm- _sm._secrets["persist-secret"] = {"Name": "persist-secret", "ARN": "arn:test", "Versions": {}}- state = _sm.get_state()- assert "secrets" in state- _sm._secrets.pop("persist-secret")- _sm.restore_state(state)- assert "persist-secret" in _sm._secrets- _sm._secrets.pop("persist-secret")--def test_ministack_persist_dynamodb_roundtrip():- from ministack.services import dynamodb as _ddb- _ddb._tables["persist-tbl"] = {"TableName": "persist-tbl", "pk_name": "pk", "sk_name": None, "items": {}}- state = _ddb.get_state()- assert "tables" in state- _ddb._tables.pop("persist-tbl")- _ddb.restore_state(state)- assert "persist-tbl" in _ddb._tables- _ddb._tables.pop("persist-tbl")--def test_ministack_persist_eventbridge_roundtrip():- from ministack.services import eventbridge as _eb- _eb._rules["default|persist-rule"] = {"Name": "persist-rule", "State": "ENABLED", "EventPattern": "{}"}- state = _eb.get_state()- assert "rules" in state- _eb._rules.pop("default|persist-rule")- _eb.restore_state(state)- assert "default|persist-rule" in _eb._rules- _eb._rules.pop("default|persist-rule")--def test_ministack_persist_kinesis_roundtrip():- from ministack.services import kinesis as _kin- _kin._streams["persist-stream"] = {"StreamName": "persist-stream", "StreamStatus": "ACTIVE", "shards": {}}- state = _kin.get_state()- assert "streams" in state- _kin._streams.pop("persist-stream")- _kin.restore_state(state)- assert "persist-stream" in _kin._streams- _kin._streams.pop("persist-stream")--def test_ministack_persist_kms_roundtrip():- from ministack.services import kms as _kms- key_id = "test-persist-key-id"- _kms._keys[key_id] = {"KeyId": key_id, "Description": "persist-key", "KeySpec": "SYMMETRIC_DEFAULT", "_symmetric_key": b"\x00" * 32}- state = _kms.get_state()- assert "keys" in state- _kms._keys.pop(key_id)- _kms.restore_state(state)- assert key_id in _kms._keys- assert _kms._keys[key_id]["Description"] == "persist-key"- _kms._keys.pop(key_id)--def test_ministack_persist_ec2_roundtrip():- from ministack.services import ec2 as _ec2- _ec2._instances["i-persist01"] = {"InstanceId": "i-persist01", "State": {"Name": "running"}}- state = _ec2.get_state()- assert "instances" in state- _ec2._instances.pop("i-persist01")- _ec2.restore_state(state)- assert "i-persist01" in _ec2._instances- _ec2._instances.pop("i-persist01")--def test_ministack_persist_route53_roundtrip():- from ministack.services import route53 as _r53- _r53._zones["Z00PERSIST"] = {"Id": "Z00PERSIST", "Name": "persist.test."}- state = _r53.get_state()- assert "zones" in state- _r53._zones.pop("Z00PERSIST")- _r53.restore_state(state)- assert "Z00PERSIST" in _r53._zones- _r53._zones.pop("Z00PERSIST")--def test_ministack_persist_cognito_roundtrip():- from ministack.services import cognito as _cog- _cog._user_pools["us-east-1_PERSIST"] = {"Id": "us-east-1_PERSIST", "Name": "persist-pool"}- state = _cog.get_state()- assert "user_pools" in state- _cog._user_pools.pop("us-east-1_PERSIST")- _cog.restore_state(state)- assert "us-east-1_PERSIST" in _cog._user_pools- _cog._user_pools.pop("us-east-1_PERSIST")--def test_ministack_persist_ecr_roundtrip():- from ministack.services import ecr as _ecr- _ecr._repositories["persist-repo"] = {"repositoryName": "persist-repo", "repositoryArn": "arn:test"}- state = _ecr.get_state()- assert "repositories" in state- _ecr._repositories.pop("persist-repo")- _ecr.restore_state(state)- assert "persist-repo" in _ecr._repositories- _ecr._repositories.pop("persist-repo")--def test_ministack_persist_cloudwatch_roundtrip():- from ministack.services import cloudwatch as _cw- _cw._alarms["persist-alarm"] = {"AlarmName": "persist-alarm", "StateValue": "OK"}- state = _cw.get_state()- assert "alarms" in state- _cw._alarms.pop("persist-alarm")- _cw.restore_state(state)- assert "persist-alarm" in _cw._alarms- _cw._alarms.pop("persist-alarm")--def test_ministack_persist_s3_metadata_roundtrip():- from ministack.services import s3 as _s3- _s3._buckets["persist-bkt"] = {"created": "2025-01-01T00:00:00Z", "objects": {"k": {"body": b"v"}}, "region": "us-east-1"}- _s3._bucket_versioning["persist-bkt"] = "Enabled"- state = _s3.get_state()- assert "buckets_meta" in state- # Object bodies must NOT be in the persisted metadata- assert "objects" not in state["buckets_meta"].get("persist-bkt", {})- assert "bucket_versioning" in state- _s3._buckets.pop("persist-bkt")- _s3._bucket_versioning.pop("persist-bkt")- _s3.restore_state(state)- assert "persist-bkt" in _s3._buckets- assert _s3._buckets["persist-bkt"]["objects"] == {} # objects not restored- assert _s3._bucket_versioning["persist-bkt"] == "Enabled"- _s3._buckets.pop("persist-bkt")- _s3._bucket_versioning.pop("persist-bkt")--def test_ministack_persist_lambda_roundtrip():- from ministack.services import lambda_svc as _lam- _lam._functions["persist-fn"] = {- "config": {"FunctionName": "persist-fn", "Runtime": "python3.11"},- "code_zip": b"fake-zip-bytes",- "versions": {},- "next_version": 1,- }- state = _lam.get_state()- assert "functions" in state- # code_zip should be base64-encoded in state- assert isinstance(state["functions"]["persist-fn"]["code_zip"], str)- _lam._functions.pop("persist-fn")- _lam.restore_state(state)- assert "persist-fn" in _lam._functions- # code_zip should be decoded back to bytes- assert _lam._functions["persist-fn"]["code_zip"] == b"fake-zip-bytes"- _lam._functions.pop("persist-fn")--def test_ministack_persist_rds_roundtrip():- from ministack.services import rds as _rds- _rds._instances["persist-db"] = {- "DBInstanceIdentifier": "persist-db",- "Engine": "postgres",- "DBInstanceStatus": "available",- "_docker_container_id": "fake-container-id",- }- state = _rds.get_state()- assert "instances" in state- assert "_docker_container_id" not in state["instances"]["persist-db"]- _rds._instances.pop("persist-db")- _rds.restore_state(state)- assert "persist-db" in _rds._instances- assert _rds._instances["persist-db"]["Engine"] == "postgres"- _rds._instances.pop("persist-db")--def test_ministack_persist_ecs_roundtrip():- from ministack.services import ecs as _ecs- _ecs._clusters["persist-cluster"] = {"clusterName": "persist-cluster", "status": "ACTIVE"}- _ecs._tasks["arn:persist-task"] = {- "taskArn": "arn:persist-task",- "lastStatus": "RUNNING",- "_docker_ids": ["fake-id"],- }- state = _ecs.get_state()- assert "clusters" in state- assert "tasks" in state- assert "_docker_ids" not in state["tasks"]["arn:persist-task"]- _ecs._clusters.pop("persist-cluster")- _ecs._tasks.pop("arn:persist-task")- _ecs.restore_state(state)- assert "persist-cluster" in _ecs._clusters- assert "arn:persist-task" in _ecs._tasks- assert _ecs._tasks["arn:persist-task"]["lastStatus"] == "STOPPED"- _ecs._clusters.pop("persist-cluster")- _ecs._tasks.pop("arn:persist-task")--def test_ministack_persist_elasticache_roundtrip():- from ministack.services import elasticache as _ec- _ec._clusters["persist-cache"] = {- "CacheClusterId": "persist-cache",- "Engine": "redis",- "CacheClusterStatus": "available",- "_docker_container_id": "fake-id",- }- state = _ec.get_state()- assert "clusters" in state- assert "_docker_container_id" not in state["clusters"]["persist-cache"]- _ec._clusters.pop("persist-cache")- _ec.restore_state(state)- assert "persist-cache" in _ec._clusters- assert _ec._clusters["persist-cache"]["Engine"] == "redis"- _ec._clusters.pop("persist-cache")--def test_ministack_persist_stepfunctions_roundtrip():- from ministack.services import stepfunctions as _sfn- sm_arn = "arn:aws:states:us-east-1:000000000000:stateMachine:persist-sm"- _sfn._state_machines[sm_arn] = {- "stateMachineArn": sm_arn,- "name": "persist-sm",- "definition": '{"StartAt":"Pass","States":{"Pass":{"Type":"Pass","End":true}}}',- "roleArn": "arn:aws:iam::000000000000:role/sfn",- "type": "STANDARD",- "status": "ACTIVE",- }- state = _sfn.get_state()- assert "state_machines" in state- assert sm_arn in state["state_machines"]- _sfn._state_machines.pop(sm_arn)- _sfn.restore_state(state)- assert sm_arn in _sfn._state_machines- assert _sfn._state_machines[sm_arn]["name"] == "persist-sm"- _sfn._state_machines.pop(sm_arn)--def test_ministack_persist_stepfunctions_running_marked_failed():- from ministack.services import stepfunctions as _sfn- run_arn = "arn:aws:states:us-east-1:000000000000:execution:persist-sm:run-1"- done_arn = "arn:aws:states:us-east-1:000000000000:execution:persist-sm:done-1"- _sfn._executions[run_arn] = {- "executionArn": run_arn,- "stateMachineArn": "arn:aws:states:us-east-1:000000000000:stateMachine:persist-sm",- "status": "RUNNING",- "startDate": "2026-01-01T00:00:00.000Z",- }- _sfn._executions[done_arn] = {- "executionArn": done_arn,- "stateMachineArn": "arn:aws:states:us-east-1:000000000000:stateMachine:persist-sm",- "status": "SUCCEEDED",- "startDate": "2026-01-01T00:00:00.000Z",- "stopDate": "2026-01-01T00:01:00.000Z",- "output": '{"result": "ok"}',- }- state = _sfn.get_state()- _sfn._executions.pop(run_arn)- _sfn._executions.pop(done_arn)- _sfn.restore_state(state)- # RUNNING execution should be marked FAILED- restored_run = _sfn._executions[run_arn]- assert restored_run["status"] == "FAILED"- assert restored_run["error"] == "States.ServiceRestart"- assert restored_run["cause"] == "Execution was running when service restarted"- assert "stopDate" in restored_run- assert restored_run["startDate"] == "2026-01-01T00:00:00.000Z"- # SUCCEEDED execution should pass through unchanged- restored_done = _sfn._executions[done_arn]- assert restored_done["status"] == "SUCCEEDED"- assert restored_done["output"] == '{"result": "ok"}'- _sfn._executions.pop(run_arn)- _sfn._executions.pop(done_arn)diff --git a/tests/test_ses.py b/tests/test_ses.pyindex 236ae307..c516d04b 100644--- a/tests/test_ses.py+++ b/tests/test_ses.py@@ -1,12 +1,17 @@+"""SES tests — API operations + SMTP relay integration."""+import ioimport jsonimport os+import pytestimport time+import uuid as _uuid_modimport zipfile-from urllib.parse import urlparse-import pytestfrom botocore.exceptions import ClientError-import uuid as _uuid_mod+from urllib.parse import urlparse+++# ========== from test_ses.py ==========def test_ses_parse_smtp_host_not_set():from ministack.services.ses import _parse_smtp_host@@ -237,3 +242,209 @@ def test_ses_v2_get_account(sesv2):resp = sesv2.get_account()assert resp["SendingEnabled"] is Trueassert resp["ProductionAccessEnabled"] is True++# ========== from test_ses_smtp_relay.py ==========++"""Unit tests for SES SMTP relay functionality."""+import os+from unittest.mock import MagicMock, patch++import pytest++[email protected](autouse=True)+def _clear_smtp_host():+ """Ensure SMTP_HOST is clean before/after each test."""+ old = os.environ.pop('SMTP_HOST', None)+ yield+ if old is not None:+ os.environ['SMTP_HOST'] = old+ else:+ os.environ.pop('SMTP_HOST', None)++[email protected](autouse=True)+def _reset_ses():+ """Reset SES module state between tests."""+ from ministack.services import ses+ ses.reset()++# ---------------------------------------------------------------------------+# _build_mime_message+# ---------------------------------------------------------------------------++def _parse_mime(msg_str):+ """Parse a MIME message string back for assertion."""+ from email import message_from_string+ return message_from_string(msg_str)+++def test_build_mime_text_only():+ from ministack.services.ses import _build_mime_message+ result = _build_mime_message(+ '[email protected]', ['[email protected]'], [], [],+ 'Subject', 'body text', '', 'msg-001',+ )+ msg = _parse_mime(result)+ assert msg['Subject'] == 'Subject'+ assert msg['From'] == '[email protected]'+ assert msg['To'] == '[email protected]'+ assert msg.get_content_type() == 'text/plain'+++def test_build_mime_html_only():+ from ministack.services.ses import _build_mime_message+ result = _build_mime_message(+ '[email protected]', ['[email protected]'], [], [],+ 'Subject', '', '<b>html</b>', 'msg-002',+ )+ msg = _parse_mime(result)+ assert msg.get_content_type() == 'text/html'+++def test_build_mime_multipart():+ from ministack.services.ses import _build_mime_message+ result = _build_mime_message(+ 'Subject', 'text', '<b>html</b>', 'msg-003',+ )+ msg = _parse_mime(result)+ assert msg.get_content_type() == 'multipart/alternative'+ assert msg['Cc'] == '[email protected]'++# ---------------------------------------------------------------------------+# _smtp_relay+# ---------------------------------------------------------------------------++def test_ses_smtp_relay_skipped_when_no_host():+ from ministack.services.ses import _smtp_relay+ with patch('ministack.services.ses.smtplib.SMTP') as mock_cls:+ _smtp_relay('[email protected]', ['[email protected]'], 'message')+ mock_cls.assert_not_called()+++def test_ses_smtp_relay_sends_when_host_set():+ os.environ['SMTP_HOST'] = '127.0.0.1:1025'+ from ministack.services.ses import _smtp_relay+ mock_smtp = MagicMock()+ with patch('ministack.services.ses.smtplib.SMTP', return_value=mock_smtp) as mock_cls:+ mock_smtp.__enter__ = MagicMock(return_value=mock_smtp)+ mock_smtp.__exit__ = MagicMock(return_value=False)+ _smtp_relay('[email protected]', ['[email protected]'], 'message body')+ mock_cls.assert_called_once_with('127.0.0.1', 1025)+ mock_smtp.sendmail.assert_called_once_with(+ '[email protected]', ['[email protected]'], 'message body',+ )+++def test_ses_smtp_relay_error_is_logged_not_raised():+ os.environ['SMTP_HOST'] = '127.0.0.1:1025'+ from ministack.services.ses import _smtp_relay+ with patch('ministack.services.ses.smtplib.SMTP', side_effect=ConnectionRefusedError):+ # Should not raise+ _smtp_relay('[email protected]', ['[email protected]'], 'message')+++# ---------------------------------------------------------------------------+# SendEmail with SMTP relay+# ---------------------------------------------------------------------------++def test_ses_smtp_relay_send_email(monkeypatch):+ monkeypatch.setenv('SMTP_HOST', '127.0.0.1:1025')+ from ministack.services.ses import _send_email+ mock_smtp = MagicMock()+ with patch('ministack.services.ses.smtplib.SMTP', return_value=mock_smtp):+ mock_smtp.__enter__ = MagicMock(return_value=mock_smtp)+ mock_smtp.__exit__ = MagicMock(return_value=False)+ params = {+ 'Source': ['[email protected]'],+ 'Destination.ToAddresses.member.1': ['[email protected]'],+ 'Destination.CcAddresses.member.1': ['[email protected]'],+ 'Message.Subject.Data': ['Test Subject'],+ 'Message.Body.Text.Data': ['Hello'],+ 'Message.Body.Html.Data': ['<b>Hello</b>'],+ }+ status, headers, body = _send_email(params)+ assert status == 200+ mock_smtp.sendmail.assert_called_once()+ call_args = mock_smtp.sendmail.call_args+ assert call_args[0][0] == '[email protected]'+ assert set(call_args[0][1]) == {'[email protected]', '[email protected]'}+ msg = _parse_mime(call_args[0][2])+ assert msg['Subject'] == 'Test Subject'+ assert msg.get_content_type() == 'multipart/alternative'+++def test_ses_smtp_relay_send_email_no_relay_without_host():+ from ministack.services.ses import _send_email+ with patch('ministack.services.ses.smtplib.SMTP') as mock_cls:+ params = {+ 'Source': ['[email protected]'],+ 'Destination.ToAddresses.member.1': ['[email protected]'],+ 'Message.Subject.Data': ['Test'],+ 'Message.Body.Text.Data': ['body'],+ }+ status, _, _ = _send_email(params)+ assert status == 200+ mock_cls.assert_not_called()+++# ---------------------------------------------------------------------------+# SendRawEmail with SMTP relay+# ---------------------------------------------------------------------------++def test_ses_smtp_relay_send_raw_email(monkeypatch):+ monkeypatch.setenv('SMTP_HOST', 'localhost:2525')+ from ministack.services.ses import _send_raw_email+ mock_smtp = MagicMock()+ with patch('ministack.services.ses.smtplib.SMTP', return_value=mock_smtp):+ mock_smtp.__enter__ = MagicMock(return_value=mock_smtp)+ mock_smtp.__exit__ = MagicMock(return_value=False)+ raw_msg = (+ 'From: [email protected]\r\n'+ 'To: [email protected]\r\n'+ 'Subject: Raw Test\r\n'+ '\r\n'+ 'Raw body'+ )+ params = {+ 'Source': ['[email protected]'],+ 'Destinations.member.1': ['[email protected]'],+ 'RawMessage.Data': [raw_msg],+ }+ status, _, _ = _send_raw_email(params)+ assert status == 200+ mock_smtp.sendmail.assert_called_once()+ call_args = mock_smtp.sendmail.call_args+ assert call_args[0][0] == '[email protected]'+ assert '[email protected]' in call_args[0][1]+++# ---------------------------------------------------------------------------+# SendTemplatedEmail with SMTP relay+# ---------------------------------------------------------------------------++def test_ses_smtp_relay_send_templated_email(monkeypatch):+ monkeypatch.setenv('SMTP_HOST', 'localhost:1025')+ from ministack.services.ses import _send_templated_email, _templates+ _templates['MyTemplate'] = {+ 'TemplateName': 'MyTemplate',+ 'SubjectPart': 'Hello {{name}}',+ 'TextPart': 'Hi {{name}}',+ 'HtmlPart': '<b>Hi {{name}}</b>',+ }+ mock_smtp = MagicMock()+ with patch('ministack.services.ses.smtplib.SMTP', return_value=mock_smtp):+ mock_smtp.__enter__ = MagicMock(return_value=mock_smtp)+ mock_smtp.__exit__ = MagicMock(return_value=False)+ params = {+ 'Source': ['[email protected]'],+ 'Destination.ToAddresses.member.1': ['[email protected]'],+ 'Template': ['MyTemplate'],+ 'TemplateData': ['{"name": "World"}'],+ }+ status, _, _ = _send_templated_email(params)+ assert status == 200+ mock_smtp.sendmail.assert_called_once()+ msg = _parse_mime(mock_smtp.sendmail.call_args[0][2])+ assert 'Hello World' in msg['Subject']diff --git a/tests/test_ses_smtp_relay.py b/tests/test_ses_smtp_relay.pydeleted file mode 100644index edf766e7..00000000--- a/tests/test_ses_smtp_relay.py+++ /dev/null@@ -1,203 +0,0 @@-"""Unit tests for SES SMTP relay functionality."""-import os-from unittest.mock import MagicMock, patch--import pytest--[email protected](autouse=True)-def _clear_smtp_host():- """Ensure SMTP_HOST is clean before/after each test."""- old = os.environ.pop('SMTP_HOST', None)- yield- if old is not None:- os.environ['SMTP_HOST'] = old- else:- os.environ.pop('SMTP_HOST', None)--[email protected](autouse=True)-def _reset_ses():- """Reset SES module state between tests."""- from ministack.services import ses- ses.reset()--# ----------------------------------------------------------------------------# _build_mime_message-# -----------------------------------------------------------------------------def _parse_mime(msg_str):- """Parse a MIME message string back for assertion."""- from email import message_from_string- return message_from_string(msg_str)---def test_build_mime_text_only():- from ministack.services.ses import _build_mime_message- result = _build_mime_message(- '[email protected]', ['[email protected]'], [], [],- 'Subject', 'body text', '', 'msg-001',- )- msg = _parse_mime(result)- assert msg['Subject'] == 'Subject'- assert msg['From'] == '[email protected]'- assert msg['To'] == '[email protected]'- assert msg.get_content_type() == 'text/plain'---def test_build_mime_html_only():- from ministack.services.ses import _build_mime_message- result = _build_mime_message(- '[email protected]', ['[email protected]'], [], [],- 'Subject', '', '<b>html</b>', 'msg-002',- )- msg = _parse_mime(result)- assert msg.get_content_type() == 'text/html'---def test_build_mime_multipart():- from ministack.services.ses import _build_mime_message- result = _build_mime_message(- 'Subject', 'text', '<b>html</b>', 'msg-003',- )- msg = _parse_mime(result)- assert msg.get_content_type() == 'multipart/alternative'- assert msg['Cc'] == '[email protected]'--# ----------------------------------------------------------------------------# _smtp_relay-# -----------------------------------------------------------------------------def test_ses_smtp_relay_skipped_when_no_host():- from ministack.services.ses import _smtp_relay- with patch('ministack.services.ses.smtplib.SMTP') as mock_cls:- _smtp_relay('[email protected]', ['[email protected]'], 'message')- mock_cls.assert_not_called()---def test_ses_smtp_relay_sends_when_host_set():- os.environ['SMTP_HOST'] = '127.0.0.1:1025'- from ministack.services.ses import _smtp_relay- mock_smtp = MagicMock()- with patch('ministack.services.ses.smtplib.SMTP', return_value=mock_smtp) as mock_cls:- mock_smtp.__enter__ = MagicMock(return_value=mock_smtp)- mock_smtp.__exit__ = MagicMock(return_value=False)- _smtp_relay('[email protected]', ['[email protected]'], 'message body')- mock_cls.assert_called_once_with('127.0.0.1', 1025)- mock_smtp.sendmail.assert_called_once_with(- '[email protected]', ['[email protected]'], 'message body',- )---def test_ses_smtp_relay_error_is_logged_not_raised():- os.environ['SMTP_HOST'] = '127.0.0.1:1025'- from ministack.services.ses import _smtp_relay- with patch('ministack.services.ses.smtplib.SMTP', side_effect=ConnectionRefusedError):- # Should not raise- _smtp_relay('[email protected]', ['[email protected]'], 'message')---# ----------------------------------------------------------------------------# SendEmail with SMTP relay-# -----------------------------------------------------------------------------def test_ses_smtp_relay_send_email(monkeypatch):- monkeypatch.setenv('SMTP_HOST', '127.0.0.1:1025')- from ministack.services.ses import _send_email- mock_smtp = MagicMock()- with patch('ministack.services.ses.smtplib.SMTP', return_value=mock_smtp):- mock_smtp.__enter__ = MagicMock(return_value=mock_smtp)- mock_smtp.__exit__ = MagicMock(return_value=False)- params = {- 'Source': ['[email protected]'],- 'Destination.ToAddresses.member.1': ['[email protected]'],- 'Destination.CcAddresses.member.1': ['[email protected]'],- 'Message.Subject.Data': ['Test Subject'],- 'Message.Body.Text.Data': ['Hello'],- 'Message.Body.Html.Data': ['<b>Hello</b>'],- }- status, headers, body = _send_email(params)- assert status == 200- mock_smtp.sendmail.assert_called_once()- call_args = mock_smtp.sendmail.call_args- assert call_args[0][0] == '[email protected]'- assert set(call_args[0][1]) == {'[email protected]', '[email protected]'}- msg = _parse_mime(call_args[0][2])- assert msg['Subject'] == 'Test Subject'- assert msg.get_content_type() == 'multipart/alternative'---def test_ses_smtp_relay_send_email_no_relay_without_host():- from ministack.services.ses import _send_email- with patch('ministack.services.ses.smtplib.SMTP') as mock_cls:- params = {- 'Source': ['[email protected]'],- 'Destination.ToAddresses.member.1': ['[email protected]'],- 'Message.Subject.Data': ['Test'],- 'Message.Body.Text.Data': ['body'],- }- status, _, _ = _send_email(params)- assert status == 200- mock_cls.assert_not_called()---# ----------------------------------------------------------------------------# SendRawEmail with SMTP relay-# -----------------------------------------------------------------------------def test_ses_smtp_relay_send_raw_email(monkeypatch):- monkeypatch.setenv('SMTP_HOST', 'localhost:2525')- from ministack.services.ses import _send_raw_email- mock_smtp = MagicMock()- with patch('ministack.services.ses.smtplib.SMTP', return_value=mock_smtp):- mock_smtp.__enter__ = MagicMock(return_value=mock_smtp)- mock_smtp.__exit__ = MagicMock(return_value=False)- raw_msg = (- 'From: [email protected]\r\n'- 'To: [email protected]\r\n'- 'Subject: Raw Test\r\n'- '\r\n'- 'Raw body'- )- params = {- 'Source': ['[email protected]'],- 'Destinations.member.1': ['[email protected]'],- 'RawMessage.Data': [raw_msg],- }- status, _, _ = _send_raw_email(params)- assert status == 200- mock_smtp.sendmail.assert_called_once()- call_args = mock_smtp.sendmail.call_args- assert call_args[0][0] == '[email protected]'- assert '[email protected]' in call_args[0][1]---# ----------------------------------------------------------------------------# SendTemplatedEmail with SMTP relay-# -----------------------------------------------------------------------------def test_ses_smtp_relay_send_templated_email(monkeypatch):- monkeypatch.setenv('SMTP_HOST', 'localhost:1025')- from ministack.services.ses import _send_templated_email, _templates- _templates['MyTemplate'] = {- 'TemplateName': 'MyTemplate',- 'SubjectPart': 'Hello {{name}}',- 'TextPart': 'Hi {{name}}',- 'HtmlPart': '<b>Hi {{name}}</b>',- }- mock_smtp = MagicMock()- with patch('ministack.services.ses.smtplib.SMTP', return_value=mock_smtp):- mock_smtp.__enter__ = MagicMock(return_value=mock_smtp)- mock_smtp.__exit__ = MagicMock(return_value=False)- params = {- 'Source': ['[email protected]'],- 'Destination.ToAddresses.member.1': ['[email protected]'],- 'Template': ['MyTemplate'],- 'TemplateData': ['{"name": "World"}'],- }- status, _, _ = _send_templated_email(params)- assert status == 200- mock_smtp.sendmail.assert_called_once()- msg = _parse_mime(mock_smtp.sendmail.call_args[0][2])- assert 'Hello World' in msg['Subject']