Skip to content

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

feat(appsync): AppSync Events API (#519)

marcin-nowak-sclc8de281d465f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 40af56e6..1e5d605e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ Versioning follows [Semantic Versioning](https://semver.org/).
---
+## [Unreleased]
+
+### Added
+- **AppSync Events API emulator** — Event APIs are now available under the AppSync service: `CreateApi`/`GetApi`/`ListApis`/`UpdateApi`/`DeleteApi`, channel namespace CRUD, API-key management through the AWS SDK's `/v1/apis/{apiId}/apikeys` path, HTTP `POST /event` publishing on `*.appsync-api.*`, and realtime `*.appsync-realtime-api.*` WebSocket subscribe/publish flows. Channel validation follows the AppSync Events grammar, publish fan-out returns AWS-shaped identifiers, and API-key / Lambda-authorizer checks are enforced consistently across HTTP and WebSocket publish paths.
## [1.3.24] — 2026-05-02
### Fixed
diff --git a/README.md b/README.md
index fc68becc..8eb782ef 100644
--- a/README.md
+++ b/README.md
@@ -491,7 +491,7 @@ Unsupported resource types fail with `CREATE_FAILED` (or `ROLLBACK_COMPLETE` if
| **EMR** | RunJobFlow, DescribeCluster, ListClusters, TerminateJobFlows, ModifyCluster, SetTerminationProtection, SetVisibleToAllUsers, AddJobFlowSteps, DescribeStep, ListSteps, CancelSteps, AddInstanceFleet, ListInstanceFleets, ModifyInstanceFleet, AddInstanceGroups, ListInstanceGroups, ModifyInstanceGroups, ListBootstrapActions, AddTags, RemoveTags, GetBlockPublicAccessConfiguration, PutBlockPublicAccessConfiguration | Control plane only — no real Spark/Hadoop; clusters start in WAITING (KeepAlive=true) or TERMINATED (KeepAlive=false); steps stored as COMPLETED immediately; all three instance modes (simple, InstanceGroups, InstanceFleets); TerminationProtected enforced; Pro-only on LocalStack — free here |
| **Cognito** | **User Pools**: CreateUserPool, DeleteUserPool, DescribeUserPool, ListUserPools, UpdateUserPool, CreateUserPoolClient, DeleteUserPoolClient, DescribeUserPoolClient, ListUserPoolClients, UpdateUserPoolClient, AdminCreateUser, AdminDeleteUser, AdminGetUser, ListUsers, AdminSetUserPassword, AdminUpdateUserAttributes, AdminConfirmSignUp, AdminDisableUser, AdminEnableUser, AdminResetUserPassword, AdminUserGlobalSignOut, AdminAddUserToGroup, AdminRemoveUserFromGroup, AdminListGroupsForUser, AdminListUserAuthEvents, AdminInitiateAuth, AdminRespondToAuthChallenge, InitiateAuth, RespondToAuthChallenge, GlobalSignOut, RevokeToken, SignUp, ConfirmSignUp, ForgotPassword, ConfirmForgotPassword, ChangePassword, GetUser, UpdateUserAttributes, DeleteUser, CreateGroup, DeleteGroup, GetGroup, ListGroups, ListUsersInGroup, CreateUserPoolDomain, DeleteUserPoolDomain, DescribeUserPoolDomain, GetUserPoolMfaConfig, SetUserPoolMfaConfig, AssociateSoftwareToken, VerifySoftwareToken, AdminSetUserMFAPreference, SetUserMFAPreference, TagResource, UntagResource, ListTagsForResource; **Identity Pools**: CreateIdentityPool, DeleteIdentityPool, DescribeIdentityPool, ListIdentityPools, UpdateIdentityPool, GetId, GetCredentialsForIdentity, GetOpenIdToken, SetIdentityPoolRoles, GetIdentityPoolRoles, ListIdentities, DescribeIdentity, MergeDeveloperIdentities, UnlinkDeveloperIdentity, UnlinkIdentity, TagResource, UntagResource, ListTagsForResource; **OAuth2**: /oauth2/token (client_credentials) | Stub JWT tokens (structurally valid base64url JWTs); SRP auth returns PASSWORD_VERIFIER challenge; confirmation codes hardcoded (signup: 123456, forgot-password: 654321); TOTP SOFTWARE_TOKEN_MFA challenge flow; MFA config and per-user enrollment stored in-memory |
| **ECR** | CreateRepository, DescribeRepositories, DeleteRepository, ListImages, DescribeImages, PutImage, BatchGetImage, BatchDeleteImage, GetAuthorizationToken, GetRepositoryPolicy, SetRepositoryPolicy, DeleteRepositoryPolicy, PutLifecyclePolicy, GetLifecyclePolicy, DeleteLifecyclePolicy, ListTagsForResource, TagResource, UntagResource, PutImageTagMutability, PutImageScanningConfiguration, DescribeRegistry, GetDownloadUrlForLayer, BatchCheckLayerAvailability, InitiateLayerUpload, UploadLayerPart, CompleteLayerUpload | In-memory image registry; Docker V2 manifest support; authorization token generation; lifecycle policies; tag mutability; Pro-only on LocalStack — free here |
-| **AppSync** | CreateGraphQLApi, GetGraphQLApi, ListGraphQLApis, UpdateGraphQLApi, DeleteGraphQLApi, CreateApiKey, DeleteApiKey, ListApiKeys, CreateDataSource, GetDataSource, ListDataSources, DeleteDataSource, CreateResolver, GetResolver, ListResolvers, DeleteResolver, CreateType, ListTypes, GetType, TagResource, UntagResource, ListTagsForResource | Control plane + data plane; GraphQL queries/mutations execute against DynamoDB resolvers (create/get/list/update/delete); Lambda resolvers supported; designed for Amplify/CDK CRUD patterns — not a full GraphQL spec engine |
+| **AppSync** | **GraphQL APIs**: CreateGraphQLApi, GetGraphQLApi, ListGraphQLApis, UpdateGraphQLApi, DeleteGraphQLApi, CreateApiKey, DeleteApiKey, ListApiKeys, CreateDataSource, GetDataSource, ListDataSources, DeleteDataSource, CreateResolver, GetResolver, ListResolvers, DeleteResolver, CreateType, ListTypes, GetType, TagResource, UntagResource, ListTagsForResource; **Event APIs**: CreateApi, GetApi, ListApis, UpdateApi, DeleteApi, CreateChannelNamespace, GetChannelNamespace, ListChannelNamespaces, UpdateChannelNamespace, DeleteChannelNamespace, CreateApiKey, ListApiKeys, DeleteApiKey, HTTP Publish, WebSocket subscribe/publish | GraphQL queries/mutations execute against DynamoDB resolvers; Lambda resolvers supported. Event APIs support AWS-shaped `/v2/apis` management, `/v1/apis/{apiId}/apikeys` API-key operations, `POST /event` on `*.appsync-api.*`, and realtime `*.appsync-realtime-api.*` WebSocket flows with API-key and Lambda-authorizer checks |
| **Cloud Map** | CreateHttpNamespace, CreatePrivateDnsNamespace, CreatePublicDnsNamespace, GetNamespace, ListNamespaces, DeleteNamespace, UpdateHttpNamespace, UpdatePrivateDnsNamespace, UpdatePublicDnsNamespace, CreateService, GetService, ListServices, DeleteService, UpdateService, RegisterInstance, DeregisterInstance, DiscoverInstances, DiscoverInstancesRevision, ListInstances, GetInstancesHealthStatus, UpdateInstanceCustomHealthStatus, GetServiceAttributes, UpdateServiceAttributes, DeleteServiceAttributes, GetOperation, ListOperations, TagResource, UntagResource, ListTagsForResource | DNS namespaces create Route53 hosted zones; operation tracking; Terraform `aws_service_discovery_*` compatible |
| **RDS Data API** | ExecuteStatement, BatchExecuteStatement, BeginTransaction, CommitTransaction, RollbackTransaction | Routes SQL to real Docker-backed RDS database containers; supports MySQL (pymysql) and PostgreSQL (psycopg2); REST paths (`/Execute`, `/BeginTransaction`, etc.) |
| **S3 Files** | CreateFileSystem, GetFileSystem, ListFileSystems, DeleteFileSystem, CreateMountTarget, GetMountTarget, ListMountTargets, UpdateMountTarget, DeleteMountTarget, CreateAccessPoint, GetAccessPoint, ListAccessPoints, DeleteAccessPoint, GetFileSystemPolicy, PutFileSystemPolicy, DeleteFileSystemPolicy, GetSynchronizationConfiguration, PutSynchronizationConfiguration, TagResource, UntagResource, ListTagsForResource | 21 operations; control plane for the new S3 Files service (launched April 2026); file systems, mount targets, access points, policies |
diff --git a/ministack/app.py b/ministack/app.py
index bc58bb3a..2874b573 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -37,6 +37,8 @@ if _VERSION == "dev":
_EXECUTE_API_RE = re.compile(
r"^([a-f0-9]{8})\.execute-api\." + re.escape(_MINISTACK_HOST) + r"(?::\d+)?$"
)
+# AppSync Events realtime WebSocket: {apiId}.appsync-realtime-api.<anything>[:port].
+_APPSYNC_REALTIME_RE = re.compile(r"^([a-z0-9]+)\.appsync-realtime-api\.")
# Virtual-hosted S3 bucket extraction. AWS-aligned per
# docs.aws.amazon.com/AmazonS3/latest/userguide/VirtualHosting.html and
# bucketnamingrules.html (HTTP vhost — ministack is HTTP). Works for any
@@ -81,7 +83,7 @@ def _extract_s3_vhost_bucket(host: str):
if first_tail_segment == "s3" or first_tail_segment.startswith(("s3-", "s3express-")):
return candidate
return None
-_S3_VHOST_EXCLUDE_RE = re.compile(r"\.(execute-api|alb|emr|efs|elasticache|s3-control)\.")
+_S3_VHOST_EXCLUDE_RE = re.compile(r"\.(execute-api|alb|emr|efs|elasticache|s3-control|appsync-api|appsync-realtime-api)\.")
_HEALTH_PATHS = ("/_ministack/health", "/_localstack/health", "/health")
_BODY_METHODS = ("POST", "PUT", "PATCH")
_COGNITO_USERINFO_PATHS = ("/oauth2/userInfo", "/oauth2/userinfo")
@@ -94,6 +96,7 @@ _NON_S3_VHOST_NAMES = frozenset({
"secretsmanager", "logs", "ssm", "events", "kinesis", "monitoring", "ses",
"states", "ecs", "rds", "rds-data", "elasticache", "glue", "athena",
"apigateway", "cloudformation", "autoscaling", "codebuild", "transfer",
+ "appsync-api", "appsync-realtime-api",
})
from ministack.core.hypercorn_compat import install as _install_hypercorn_compat
@@ -183,6 +186,7 @@ SERVICE_REGISTRY = {
"appconfig": {"module": "appconfig"},
"appconfigdata": {"module": "appconfig"},
"appsync": {"module": "appsync"},
+ "appsync-events": {"module": "appsync_events"},
"athena": {"module": "athena"},
"autoscaling": {"module": "autoscaling"},
"cloudformation": {"module": "cloudformation"},
@@ -254,6 +258,7 @@ _state_map = {
"ecr": "ecr", "cloudwatch": "cloudwatch", "s3": "s3",
"lambda": "lambda_svc", "rds": "rds", "ecs": "ecs",
"elasticache": "elasticache", "appsync": "appsync",
+ "appsync_events": "appsync_events",
"stepfunctions": "stepfunctions", "alb": "alb",
"glue": "glue", "efs": "efs", "waf": "waf",
"athena": "athena", "emr": "emr", "cloudfront": "cloudfront",
@@ -1083,16 +1088,22 @@ async def app(scope, receive, send):
ws_host = ws_headers.get("host", "")
ws_path = scope.get("path", "")
parsed = _parse_execute_api_url(ws_host, ws_path)
- if not parsed:
+ appsync_rt_m = _APPSYNC_REALTIME_RE.match(ws_host)
+ if not parsed and not appsync_rt_m:
msg = await receive()
if msg.get("type") == "websocket.connect":
await send({"type": "websocket.close", "code": 1008})
return
- ws_api_id, _stage, _execute_path = parsed
try:
- await _get_module("apigateway").handle_websocket(
- scope, receive, send, ws_api_id, path_override=_execute_path,
- )
+ if parsed:
+ ws_api_id, _stage, _execute_path = parsed
+ await _get_module("apigateway").handle_websocket(
+ scope, receive, send, ws_api_id, path_override=_execute_path,
+ )
+ else:
+ await _get_module("appsync_events").handle_websocket(
+ scope, receive, send, appsync_rt_m.group(1)
+ )
except Exception:
logger.exception("Error in WebSocket dispatch")
try:
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 22b40d8d..e4d4b6d4 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -236,6 +236,13 @@ SERVICE_PATTERNS = {
"path_prefixes": ["/v1/apis", "/v1/tags"],
"credential_scope": "appsync",
},
+ # AppSync Events data plane: HTTP publish lives on
+ # {apiId}.appsync-api.{region}.{host}; realtime WebSocket lives on
+ # {apiId}.appsync-realtime-api.{region}.{host}. Management shares the
+ # "appsync" credential scope and is delegated from services/appsync.py.
+ "appsync-events": {
+ "host_patterns": [r"appsync-api\.", r"appsync-realtime-api\."],
+ },
"servicediscovery": {
"target_prefixes": ["Route53AutoNaming_v20170314"],
"host_patterns": [r"servicediscovery\."],
@@ -300,6 +307,13 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
if target.startswith(prefix):
return svc
+ # AppSync Events HTTP publish: POST /event on
+ # {apiId}.appsync-api.{region}.{host}. AWS SDKs sign these requests with
+ # the legacy "appsync" credential scope, so the data-plane host/path must
+ # win before credential-scope routing.
+ if method == "POST" and path == "/event" and re.search(r"\.appsync-api\.", host):
+ return "appsync-events"
+
# 2. Check Authorization header for service name in credential scope
if auth:
match = re.search(r"Credential=[^/]+/[^/]+/[^/]+/([^/]+)/", auth)
@@ -576,6 +590,10 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
return "cloudfront"
if path_lower.startswith("/2013-04-01/"):
return "route53"
+ if (path_lower.startswith("/v2/apis") or path_lower.startswith("/v2/tags")) and (
+ re.search(r"appsync-api\.", host) or re.search(r"appsync-realtime-api\.", host)
+ ):
+ return "appsync-events"
if path_lower.startswith("/v2/apis"):
return "apigateway"
if (path_lower.startswith("/restapis") or path_lower.startswith("/apikeys")
diff --git a/ministack/services/appsync.py b/ministack/services/appsync.py
index 48d0c3df..29c63f63 100644
--- a/ministack/services/appsync.py
+++ b/ministack/services/appsync.py
@@ -481,6 +481,13 @@ _PATH_RE = re.compile(r"^/v1/apis(?:/([^/]+))?(?:/([^/]+))?(?:/([^/]+))?(?:/([^/
async def handle_request(method, path, headers, body, query_params):
"""Main entry point — route AppSync REST requests."""
+ # AppSync Events Event APIs live under /v2/apis and share the
+ # "appsync" credential scope with GraphQL, so delegate here instead of
+ # teaching the central router to differentiate by credential scope.
+ if path.startswith("/v2/apis") or path.startswith("/v2/tags"):
+ from ministack.services import appsync_events
+ return await appsync_events.handle_request(method, path, headers, body, query_params)
+
# Tags endpoint: /v1/tags/{resourceArn}
if path.startswith("/v1/tags/"):
from urllib.parse import unquote
@@ -541,6 +548,19 @@ async def handle_request(method, path, headers, body, query_params):
# /v1/apis/{apiId}/apikeys
if sub1 == "apikeys":
+ # Real SDKs route AppSync API key operations through the v1 path even
+ # for Event APIs. If the id is not a GraphQL API but is an Event API,
+ # hand the request to the Events service.
+ if api_id and api_id not in _apis:
+ from ministack.services import appsync_events
+ if api_id in appsync_events._apis:
+ if sub2 is None:
+ if method == "POST":
+ return appsync_events._create_api_key(api_id, body or b"{}")
+ elif method == "GET":
+ return appsync_events._list_api_keys(api_id)
+ elif method == "DELETE":
+ return appsync_events._delete_api_key(api_id, sub2)
if sub2 is None:
if method == "POST":
return _create_api_key(api_id, data)
diff --git a/ministack/services/appsync_events.py b/ministack/services/appsync_events.py
new file mode 100644
index 00000000..9321ddc8
--- /dev/null
+++ b/ministack/services/appsync_events.py
@@ -0,0 +1,1133 @@
+"""
+AppSync Events Service Emulator — AWS-compatible.
+Supports: CreateApi, GetApi, ListApis, UpdateApi, DeleteApi,
+ CreateChannelNamespace, GetChannelNamespace, ListChannelNamespaces,
+ UpdateChannelNamespace, DeleteChannelNamespace,
+ CreateApiKey, ListApiKeys, DeleteApiKey,
+ Publish (HTTP POST /event on {apiId}.appsync-api.{region}.{host}),
+ WebSocket subscribe (wss://{apiId}.appsync-realtime-api.{region}.{host}/event/realtime,
+ aws-appsync-event-ws subprotocol: connection_init, subscribe,
+ unsubscribe, publish, server-pushed data + ka keep-alives).
+Event API management is REST/JSON under /v2/apis (shares the ``appsync``
+credential scope); API key operations use the AWS SDK's /v1/apis/{apiId}/apikeys
+path and are delegated from ``services/appsync.py``. Channel paths validated
+against the 1..5-segment spec regex; subscribe patterns accept a trailing
+``*`` single-level wildcard. Connection-scoped
+authorization is sent via a second ``header-<base64url(json)>`` subprotocol
+entry and cached for later subscribe/publish frames. Set
+``APPSYNC_EVENTS_ENFORCE_AUTH=1`` for strict mode: without an ``AWS_LAMBDA``
+``authProvider``, only registered **x-api-key** values are accepted; when
+``authType: AWS_LAMBDA`` and ``lambdaAuthorizerConfig.authorizerUri`` are present
+in the API ``eventConfig``, the named Lambda is invoked (connect + subscribe +
+publish) with the same ``AuthorizationToken`` / ``Channel`` / ``Operation``
+shape as on AWS. By default ``CreateApi`` / ``GetApi`` return ``dns`` hostnames of
+the form ``{apiId}.appsync-api.{region}.{MINISTACK_HOST}:{port}`` and
+``{apiId}.appsync-realtime-api.{region}.{MINISTACK_HOST}:{port}`` (AWS-style
+service labels with a local base host and explicit ``GATEWAY_PORT``).
+Optional: ``APPSYNC_EVENTS_HTTP_HOST_TEMPLATE`` and
+``APPSYNC_EVENTS_REALTIME_HOST_TEMPLATE`` (``{api_id}``, ``{region}``, ``{port}``)
+override those defaults when **both** are set.
+"""
+
+import asyncio
+import base64
+import binascii
+import copy
+import json
+import logging
+import os
+import re
+import time
+
+from ministack.core.persistence import load_state
+from ministack.core.responses import (
+ AccountScopedDict,
+ error_response_json,
+ get_account_id,
+ get_region,
+ json_response,
+ new_uuid,
+)
+
+logger = logging.getLogger("appsync_events")
+
+# ---------------------------------------------------------------------------
+# In-memory state
+# ---------------------------------------------------------------------------
+
+# apiId -> api record
+_apis = AccountScopedDict()
+# apiId -> {name -> channel namespace record}
+_channel_namespaces = AccountScopedDict()
+# apiId -> {keyId -> api key record}
+_api_keys = AccountScopedDict()
+
+# Active realtime connections, keyed by opaque connection id assigned on accept.
+# {connection_id -> {"api_id": str, "account_id": str, "outbox": asyncio.Queue,
+# "subscriptions": {sub_id -> pattern}}}
+_connections: dict[str, dict] = {}
+_connections_lock: asyncio.Lock | None = None
+
+
+def _get_connections_lock() -> asyncio.Lock:
+ global _connections_lock
+ if _connections_lock is None:
+ _connections_lock = asyncio.Lock()
+ return _connections_lock
+
+
+# ---------------------------------------------------------------------------
+# Persistence / reset
+# ---------------------------------------------------------------------------
+
+def get_state():
+ # Only persist control-plane records; connections and live subscriptions
+ # are in-process only and cannot survive a restart.
+ return {
+ "apis": copy.deepcopy(_apis),
+ "channel_namespaces": copy.deepcopy(_channel_namespaces),
+ "api_keys": copy.deepcopy(_api_keys),
+ }
+
+
+def restore_state(data):
+ if not data:
+ return
+ _apis.update(data.get("apis", {}))
+ _channel_namespaces.update(data.get("channel_namespaces", {}))
+ _api_keys.update(data.get("api_keys", {}))
+
+
+# Same contract as apigateway.py (used by app.py persistence loader)
+load_persisted_state = restore_state
+
+
+try:
+ _restored = load_state("appsync_events")
+ if _restored:
+ restore_state(_restored)
+except Exception:
+ logger.exception("Failed to restore AppSync Events state")
+
+
+def reset():
+ _apis.clear()
+ _channel_namespaces.clear()
+ _api_keys.clear()
+ _connections.clear()
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+_APPSYNC_API_HOST_RE = re.compile(r"^([a-z0-9]+)\.appsync-api\.")
+
+
+def _now() -> int:
+ return int(time.time())
+
+
+def _api_arn(api_id: str) -> str:
+ return f"arn:aws:appsync:{get_region()}:{get_account_id()}:apis/{api_id}"
+
+
+def _new_api_id() -> str:
+ return new_uuid().replace("-", "")[:26]
+
+
+def _default_dns_for_api(api_id: str) -> dict[str, str]:
+ """Return Event API ``dns`` block (HTTP + REALTIME).
+
+ 1) If both ``APPSYNC_EVENTS_HTTP_HOST_TEMPLATE`` and
+ ``APPSYNC_EVENTS_REALTIME_HOST_TEMPLATE`` are set, they are
+ :meth:`str.format`\\ -ed with ``api_id``, ``region``, ``port``, ``GATEWAY_PORT``.
+ 2) Otherwise default to AWS-shaped localhost vhosts (see module docstring).
+ """
+ region = get_region()
+ port = os.environ.get("GATEWAY_PORT") or os.environ.get("EDGE_PORT") or "4566"
+ mini_host = os.environ.get("MINISTACK_HOST", "localhost")
+ host_t = os.environ.get("APPSYNC_EVENTS_HTTP_HOST_TEMPLATE", "").strip()
+ rt_t = os.environ.get("APPSYNC_EVENTS_REALTIME_HOST_TEMPLATE", "").strip()
+ if host_t and rt_t:
+ return {
+ "HTTP": host_t.format(
+ api_id=api_id, region=region, port=port, GATEWAY_PORT=port
+ ),
+ "REALTIME": rt_t.format(
+ api_id=api_id, region=region, port=port, GATEWAY_PORT=port
+ ),
+ }
+ return {
+ "HTTP": f"{api_id}.appsync-api.{region}.{mini_host}:{port}",
+ "REALTIME": (
+ f"{api_id}.appsync-realtime-api.{region}.{mini_host}:{port}"
+ ),
+ }
+
+
+def _default_event_config(requested: dict | None) -> dict:
+ """Normalise an incoming eventConfig into the shape real AWS returns.
+
+ Every field gets a default so boto3 ``get_api``/``list_apis`` responses
+ always contain the full set of keys — matches AWS behaviour and makes
+ downstream schema-validating SDKs happy.
+ """
+ requested = requested or {}
+ default_auth = [{"authType": "API_KEY"}]
+ return {
+ "authProviders": requested.get("authProviders") or default_auth,
+ "connectionAuthModes": requested.get("connectionAuthModes") or default_auth,
+ "defaultPublishAuthModes": requested.get("defaultPublishAuthModes") or default_auth,
+ "defaultSubscribeAuthModes": requested.get("defaultSubscribeAuthModes") or default_auth,
+ "logConfig": requested.get("logConfig"),
+ }
+
+
+def _api_response(api_id: str) -> dict:
+ api = _apis.get(api_id)
+ if not api:
+ return {}
+ return {
+ "apiId": api_id,
+ "name": api["name"],
+ "ownerContact": api.get("ownerContact"),
+ "tags": api.get("tags", {}),
+ "dns": api["dns"],
+ "apiArn": api["apiArn"],
+ "created": api["created"],
+ "xrayEnabled": api.get("xrayEnabled", False),
+ "wafWebAclArn": api.get("wafWebAclArn"),
+ "eventConfig": api["eventConfig"],
+ }
+
+
+def _channel_response(api_id: str, name: str) -> dict:
+ ns = _channel_namespaces.get(api_id, {}).get(name, {})
+ if not ns:
+ return {}
+ return {
+ "apiId": api_id,
+ "name": name,
+ "subscribeAuthModes": ns.get("subscribeAuthModes", []),
+ "publishAuthModes": ns.get("publishAuthModes", []),
+ "codeHandlers": ns.get("codeHandlers"),
+ "handlerConfigs": ns.get("handlerConfigs"),
+ "tags": ns.get("tags", {}),
+ "created": ns["created"],
+ "lastModified": ns["lastModified"],
+ }
+
+
+def _api_key_response(api_id: str, key_id: str) -> dict:
+ k = _api_keys.get(api_id, {}).get(key_id, {})
+ if not k:
+ return {}
+ return {
+ "id": key_id,
+ "description": k.get("description", ""),
+ "expires": k["expires"],
+ "deletes": k.get("deletes", k["expires"]),
+ }
+
+
+def _parse_json_body(body: bytes) -> tuple[dict, object]:
+ if not body:
+ return {}, None
+ try:
+ data = json.loads(body)
+ if not isinstance(data, dict):
+ return {}, error_response_json(
+ "BadRequestException", "Request body must be a JSON object", 400
+ )
+ return data, None
+ except json.JSONDecodeError:
+ return {}, error_response_json(
+ "BadRequestException", "Invalid JSON in request body", 400
+ )
+
+
+def _not_found(msg: str):
+ return error_response_json("NotFoundException", msg, 404)
+
+
+# ---------------------------------------------------------------------------
+# Channel validation + matching (subscribe pattern -> publish channel)
+# ---------------------------------------------------------------------------
+
+# Per the AWS AppSync Events spec, a channel segment is 1..50 chars made up of
+# alphanumerics and dashes, not starting or ending with a dash. A path is 1..5
+# segments separated by ``/`` with optional leading/trailing slash.
+_CHANNEL_SEGMENT_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,48}[A-Za-z0-9])?$")
+
+
+def _split_channel(channel: str) -> list[str] | None:
+ if not channel or not channel.startswith("/"):
+ return None
+ parts = [p for p in channel.split("/") if p != ""]
+ if not 1 <= len(parts) <= 5:
+ return None
+ return parts
+
+
+def _validate_channel(channel: str, *, allow_wildcard: bool) -> str | None:
+ """Return an error message when ``channel`` is invalid, else ``None``.
+
+ When ``allow_wildcard`` is true, the terminal segment may be ``*`` — used
+ for subscribe patterns. Publish channels must be fully-qualified paths.
+ """
+ parts = _split_channel(channel)
+ if parts is None:
+ return (
+ "channel must start with '/' and have 1..5 segments "
+ "(alphanumeric + dash, 1..50 chars each)"
+ )
+ last_idx = len(parts) - 1
+ for i, seg in enumerate(parts):
+ if seg == "*":
+ if not allow_wildcard:
+ return "wildcard '*' not allowed in publish channel"
+ if i != last_idx:
+ return "wildcard '*' is only allowed as the terminal segment"
+ continue
+ if not _CHANNEL_SEGMENT_RE.match(seg):
+ return f"invalid channel segment: '{seg}'"
+ return None
+
+
+def _channel_namespace_for(channel: str) -> str | None:
+ """Return the namespace name embedded in ``channel`` (``/ns/...``)."""
+ parts = _split_channel(channel)
+ return parts[0] if parts else None
+
+
+def _channel_matches(publish_channel: str, subscribe_pattern: str) -> bool:
+ """Match an AppSync Events subscribe pattern against a publish channel.
+
+ Supported (per spec):
+ - Exact: ``/ns/room1`` matches ``/ns/room1``.
+ - Single-level: ``/ns/*`` matches any single-segment suffix of ``/ns``
+ (``/ns/room1`` yes, ``/ns/room1/sub`` no).
+ """
+ pub = _split_channel(publish_channel)
+ sub = _split_channel(subscribe_pattern)
+ if pub is None or sub is None:
+ return False
+ if len(pub) != len(sub):
+ return False
+ for p, s in zip(pub, sub):
+ if s == "*":
+ continue
+ if p != s:
+ return False
+ return True
+
+
+# ---------------------------------------------------------------------------
+# Authorization — header-<base64url(json)> subprotocol + frame-level fallback
+# ---------------------------------------------------------------------------
+
+def _strict_auth_enabled() -> bool:
+ return os.environ.get("APPSYNC_EVENTS_ENFORCE_AUTH", "").lower() in ("1", "true", "yes")
+
+
+def _decode_header_subprotocol(requested: str) -> tuple[dict | None, str | None]:
+ """Parse the ``header-<base64url(json)>`` entry from Sec-WebSocket-Protocol.
+
+ Returns ``(auth_dict, None)`` on success, ``(None, None)`` when absent,
+ or ``(None, "<error>")`` when the entry exists but is malformed.
+ """
+ for proto in (p.strip() for p in requested.split(",")):
+ if not proto.startswith("header-"):
+ continue
+ b64 = proto[len("header-"):]
+ try:
+ padded = b64 + "=" * (-len(b64) % 4)
+ raw = base64.urlsafe_b64decode(padded.encode("ascii"))
+ obj = json.loads(raw.decode("utf-8"))
+ except (binascii.Error, UnicodeDecodeError, json.JSONDecodeError) as e:
+ return None, f"Invalid header subprotocol: {e}"
+ if not isinstance(obj, dict):
+ return None, "Header subprotocol must decode to a JSON object"
+ return obj, None
+ return None, None
+
+
+def _auth_has_known_api_key(api_id: str, auth: dict | None) -> bool:
+ """Return True when ``auth`` carries an ``x-api-key`` registered on the API.
+
+ MiniStack doesn't verify JWTs or SigV4 — in strict mode we only
+ enforce structural presence plus registered API keys.
+ """
+ if not isinstance(auth, dict):
+ return False
+ provided = auth.get("x-api-key") or auth.get("X-Api-Key")
+ if not provided:
+ return False
+ return provided in _api_keys.get(api_id, {})
+
+
+def _find_lambda_authorizer_arn(api_id: str) -> str | None:
+ ev = (_apis.get(api_id) or {}).get("eventConfig") or {}
+ for p in ev.get("authProviders") or ev.get("auth_providers") or []:
+ a_type = p.get("authType") or p.get("auth_type")
+ if a_type != "AWS_LAMBDA":
+ continue
+ cfg = p.get("lambdaAuthorizerConfig") or p.get("lambda_authorizer_config") or {}
+ if not isinstance(cfg, dict):
+ continue
+ uri = cfg.get("authorizerUri") or cfg.get("authorizer_uri")
+ if isinstance(uri, str) and uri.strip():
+ return uri.strip()
+ return None
+
+
+def _bearer_from_auth_dict(auth: dict | None) -> str:
+ """Value for the AppSync Events Lambda authorizer ``AuthorizationToken`` field."""
+ if not auth or not isinstance(auth, dict):
+ return ""
+ for key in (
+ "Authorization", "authorization",
+ "AuthorizationToken", "authorizationToken",
+ ):
+ v = auth.get(key)
+ if isinstance(v, str) and v.strip():
+ return v.strip()
+ return ""
+
+
+def _parse_lambda_authorizer_body(body: object) -> tuple[bool, dict | None]:
+ if isinstance(body, str):
+ try:
+ body = json.loads(body)
+ except Exception:
+ return False, None
+ if not isinstance(body, dict):
+ return False, None
+ ok = bool(
+ body.get("isAuthorized")
+ or body.get("IsAuthorized")
+ )
+ ctx = body.get("resolverContext")
+ if ctx is None:
+ ctx = body.get("ResolverContext")
+ if not ok:
+ return False, None
+ if isinstance(ctx, dict):
+ return True, ctx
+ return True, None
+
+
+def _events_authorizer_invoke(arn: str, operation: str, channel: str | None, authorization_token: str) -> tuple[bool, dict | None]:
+ """Invoke the configured authorizer Lambda with AppSync-style request/response payloads."""
+ if not authorization_token.strip() or not arn:
+ return False, None
+ payload: dict = {
+ "AuthorizationToken": authorization_token,
+ "Channel": channel,
+ "Operation": operation,
+ }
+ try:
+ from ministack.services import lambda_svc
+ name, q = lambda_svc._resolve_name_and_qualifier(arn) # noqa: SLF001
+ fn, _cfg = lambda_svc._get_func_record_for_qualifier(name, q) # noqa: SLF001
+ except Exception as e:
+ logger.error("AppSync Events authorizer resolve %s: %s", arn, e)
+ return False, None
+ if not fn:
+ logger.error("AppSync Events authorizer Lambda not registered: %s", arn)
+ return False, None
+ try:
+ res = lambda_svc._execute_function(fn, payload) # noqa: SLF001
+ except Exception as e:
+ logger.error("AppSync Events authorizer invoke: %s", e)
+ return False, None
+ if not isinstance(res, dict) or res.get("error"):
+ return False, None
+ return _parse_lambda_authorizer_body(res.get("body"))
+
+
+async def _authorize_event_op(
+ api_id: str,
+ channel: str | None,
+ operation: str,
+ auth: dict | None,
+) -> tuple[bool, str | None]:
+ """Authorize an AppSync Events subscribe/publish operation."""
+ lambda_arn = _find_lambda_authorizer_arn(api_id)
+ if lambda_arn:
+ token = _bearer_from_auth_dict(auth)
+ if not token:
+ return False, f"{operation} rejected: no Authorization token"
+ ok, _resolver_context = await asyncio.to_thread(
+ _events_authorizer_invoke,
+ lambda_arn,
+ operation,
+ channel,
+ token,
+ )
+ if not ok:
+ return False, f"{operation} rejected: AppSync authorizer denied"
+ return True, None
+
+ if _strict_auth_enabled() and not _auth_has_known_api_key(api_id, auth):
+ return False, f"{operation} rejected: no valid x-api-key"
+
+ return True, None
+
+
+def _auth_from_headers(headers: dict) -> dict:
+ auth: dict = {}
+ if key := headers.get("x-api-key"):
+ auth["x-api-key"] = key
+ if value := headers.get("authorization"):
+ auth["Authorization"] = value
+ return auth
+
+
+# ---------------------------------------------------------------------------
+# Entry point — dispatches management + data plane HTTP requests
+# ---------------------------------------------------------------------------
+
+async def handle_request(method, path, headers, body, query_params):
+ # HTTP publish lives on a separate host:
+ # {apiId}.appsync-api.{region}.{host}, with a fixed "/event" path.
+ # Dispatch it before the management router.
+ host = headers.get("host", "")
+ host_match = _APPSYNC_API_HOST_RE.match(host)
+ if host_match and path == "/event" and method == "POST":
+ return await _publish(host_match.group(1), headers, body)
+
+ if path.startswith("/v2/apis"):
+ return await _handle_mgmt(method, path, headers, body, query_params)
+
+ return error_response_json("BadRequestException", f"Unsupported AppSync Events path: {path}", 400)
+
+
+# ---------------------------------------------------------------------------
+# Management plane (/v2/apis...)
+# ---------------------------------------------------------------------------
+
+_PATH_API_ROOT = re.compile(r"^/v2/apis/?$")
+_PATH_API_ID = re.compile(r"^/v2/apis/([^/]+)/?$")
+_PATH_NS_ROOT = re.compile(r"^/v2/apis/([^/]+)/channelNamespaces/?$")
+_PATH_NS_ITEM = re.compile(r"^/v2/apis/([^/]+)/channelNamespaces/([^/]+)/?$")
+
+
+async def _handle_mgmt(method, path, headers, body, query_params):
+ if _PATH_API_ROOT.match(path):
+ if method == "POST":
+ return _create_api(body)
+ if method == "GET":
+ return _list_apis(query_params)
+ return error_response_json("BadRequestException", f"Method {method} not allowed on {path}", 405)
+
+ if (m := _PATH_API_ID.match(path)):
+ api_id = m.group(1)
+ if method == "GET":
+ return _get_api(api_id)
+ # boto3's UpdateApi uses POST; accept PATCH/PUT for raw-HTTP callers too.
+ if method in ("POST", "PATCH", "PUT"):
+ return _update_api(api_id, body)
+ if method == "DELETE":
+ return _delete_api(api_id)
+ return error_response_json("BadRequestException", f"Method {method} not allowed on {path}", 405)
+
+ if (m := _PATH_NS_ROOT.match(path)):
+ api_id = m.group(1)
+ if method == "POST":
+ return _create_channel_namespace(api_id, body)
+ if method == "GET":
+ return _list_channel_namespaces(api_id, query_params)
+ return error_response_json("BadRequestException", f"Method {method} not allowed on {path}", 405)
+
+ if (m := _PATH_NS_ITEM.match(path)):
+ api_id, name = m.group(1), m.group(2)
+ if method == "GET":
+ return _get_channel_namespace(api_id, name)
+ if method in ("POST", "PATCH", "PUT"):
+ return _update_channel_namespace(api_id, name, body)
+ if method == "DELETE":
+ return _delete_channel_namespace(api_id, name)
+ return error_response_json("BadRequestException", f"Method {method} not allowed on {path}", 405)
+
+ return error_response_json("NotFoundException", f"Path not found: {path}", 404)
+
+
+# --- API CRUD --------------------------------------------------------------
+
+def _create_api(body):
+ data, err = _parse_json_body(body)
+ if err:
+ return err
+ name = data.get("name")
+ if not name:
+ return error_response_json("BadRequestException", "'name' is required", 400)
+
+ api_id = _new_api_id()
+ record = {
+ "name": name,
+ "ownerContact": data.get("ownerContact"),
+ "tags": data.get("tags", {}),
+ "dns": _default_dns_for_api(api_id),
+ "apiArn": _api_arn(api_id),
+ "created": _now(),
+ "xrayEnabled": bool(data.get("xrayEnabled", False)),
+ "wafWebAclArn": None,
+ "eventConfig": _default_event_config(data.get("eventConfig")),
+ }
+ _apis[api_id] = record
+ _channel_namespaces.setdefault(api_id, {})
+ _api_keys.setdefault(api_id, {})
+ return json_response({"api": _api_response(api_id)})
+
+
+def _get_api(api_id):
+ if api_id not in _apis:
+ return _not_found(f"Api {api_id} not found")
+ return json_response({"api": _api_response(api_id)})
+
+
+def _list_apis(query_params):
+ max_results = int((query_params.get("maxResults", [100])[0]) if isinstance(query_params.get("maxResults"), list) else query_params.get("maxResults", 100) or 100)
+ page = [_api_response(aid) for aid in sorted(_apis.keys())]
+ return json_response({"apis": page[:max_results]})
+
+
+def _update_api(api_id, body):
+ if api_id not in _apis:
+ return _not_found(f"Api {api_id} not found")
+ data, err = _parse_json_body(body)
+ if err:
+ return err
+ api = _apis[api_id]
+ if "name" in data:
+ api["name"] = data["name"]
+ if "ownerContact" in data:
+ api["ownerContact"] = data["ownerContact"]
+ if "xrayEnabled" in data:
+ api["xrayEnabled"] = bool(data["xrayEnabled"])
+ if "eventConfig" in data:
+ api["eventConfig"] = _default_event_config(data["eventConfig"])
+ return json_response({"api": _api_response(api_id)})
+
+
+def _delete_api(api_id):
+ if api_id not in _apis:
+ return _not_found(f"Api {api_id} not found")
+ _apis.pop(api_id, None)
+ _channel_namespaces.pop(api_id, None)
+ _api_keys.pop(api_id, None)
+ return json_response({}, status=200)
+
+
+# --- Channel namespaces ----------------------------------------------------
+
+def _create_channel_namespace(api_id, body):
+ if api_id not in _apis:
+ return _not_found(f"Api {api_id} not found")
+ data, err = _parse_json_body(body)
+ if err:
+ return err
+ name = data.get("name")
+ if not name:
+ return error_response_json("BadRequestException", "'name' is required", 400)
+
+ namespaces = _channel_namespaces.setdefault(api_id, {})
+ if name in namespaces:
+ return error_response_json(
+ "ConflictException",
+ f"Channel namespace '{name}' already exists",
+ 409,
+ )
+
+ now = _now()
+ default_modes = _apis[api_id]["eventConfig"]["defaultPublishAuthModes"]
+ namespaces[name] = {
+ "publishAuthModes": data.get("publishAuthModes") or default_modes,
+ "subscribeAuthModes": data.get("subscribeAuthModes") or default_modes,
+ "codeHandlers": data.get("codeHandlers"),
+ "handlerConfigs": data.get("handlerConfigs"),
+ "tags": data.get("tags", {}),
+ "created": now,
+ "lastModified": now,
+ }
+ return json_response({"channelNamespace": _channel_response(api_id, name)})
+
+
+def _get_channel_namespace(api_id, name):
+ if name not in _channel_namespaces.get(api_id, {}):
+ return _not_found(f"Channel namespace '{name}' not found")
+ return json_response({"channelNamespace": _channel_response(api_id, name)})
+
+
+def _list_channel_namespaces(api_id, query_params):
+ if api_id not in _apis:
+ return _not_found(f"Api {api_id} not found")
+ namespaces = _channel_namespaces.get(api_id, {})
+ items = [_channel_response(api_id, n) for n in sorted(namespaces.keys())]
+ return json_response({"channelNamespaces": items})
+
+
+def _update_channel_namespace(api_id, name, body):
+ if name not in _channel_namespaces.get(api_id, {}):
+ return _not_found(f"Channel namespace '{name}' not found")
+ data, err = _parse_json_body(body)
+ if err:
+ return err
+ ns = _channel_namespaces[api_id][name]
+ for field in ("publishAuthModes", "subscribeAuthModes", "codeHandlers", "handlerConfigs"):
+ if field in data:
+ ns[field] = data[field]
+ ns["lastModified"] = _now()
+ return json_response({"channelNamespace": _channel_response(api_id, name)})
+
+
+def _delete_channel_namespace(api_id, name):
+ if name not in _channel_namespaces.get(api_id, {}):
+ return _not_found(f"Channel namespace '{name}' not found")
+ del _channel_namespaces[api_id][name]
+ return json_response({}, status=200)
+
+
+# --- API keys --------------------------------------------------------------
+
+def _create_api_key(api_id, body):
+ if api_id not in _apis:
+ return _not_found(f"Api {api_id} not found")
+ data, err = _parse_json_body(body)
+ if err:
+ return err
+
+ key_id = "da2-" + new_uuid().replace("-", "")[:26]
+ # Real AppSync defaults to 7d and caps at 365d; we don't enforce the cap.
+ expires = int(data.get("expires") or (_now() + 7 * 24 * 3600))
+ _api_keys.setdefault(api_id, {})[key_id] = {
+ "description": data.get("description", ""),
+ "expires": expires,
+ "deletes": expires,
+ }
+ return json_response({"apiKey": _api_key_response(api_id, key_id)})
+
+
+def _list_api_keys(api_id):
+ if api_id not in _apis:
+ return _not_found(f"Api {api_id} not found")
+ keys = _api_keys.get(api_id, {})
+ return json_response({
+ "apiKeys": [_api_key_response(api_id, kid) for kid in sorted(keys.keys())],
+ })
+
+
+def _delete_api_key(api_id, key_id):
+ if key_id not in _api_keys.get(api_id, {}):
+ return _not_found(f"ApiKey {key_id} not found")
+ del _api_keys[api_id][key_id]
+ return json_response({}, status=200)
+
+
+# ---------------------------------------------------------------------------
+# Data plane — HTTP publish
+# ---------------------------------------------------------------------------
+
+async def _publish(api_id: str, headers: dict, body: bytes):
+ if api_id not in _apis:
+ return _not_found(f"Api {api_id} not found")
+
+ data, err = _parse_json_body(body)
+ if err:
+ return err
+
+ channel = data.get("channel")
+ events = data.get("events")
+ if not channel or not isinstance(events, list):
+ return error_response_json(
+ "BadRequestException",
+ "Request body must include 'channel' and 'events' (array)",
+ 400,
+ )
+
+ channel_err = _validate_channel(channel, allow_wildcard=False)
+ if channel_err:
+ return error_response_json("BadRequestException", channel_err, 400)
+
+ ns_name = _channel_namespace_for(channel)
+ if ns_name is None or ns_name not in _channel_namespaces.get(api_id, {}):
+ return error_response_json(
+ "UnauthorizedException",
+ f"No channel namespace matches '{channel}'",
+ 401,
+ )
+
+ ok, message = await _authorize_event_op(api_id, str(channel), "publish", _auth_from_headers(headers))
+ if not ok:
+ return error_response_json("UnauthorizedException", message or "Unauthorized", 401)
+
+ successful, failed = await _fanout_publish(api_id, channel, events)
+ return json_response({"successful": successful, "failed": failed})
+
+
+async def _fanout_publish(api_id: str, channel: str, events: list) -> tuple[list, list]:
+ """Deliver each event to every matching subscriber on ``api_id``.
+
+ Shared between the HTTP ``POST /event`` handler and the WebSocket ``publish``
+ frame handler so both paths return the same ``(successful, failed)`` shape.
+ Each outbound frame uses ``"event": [<json-string>]`` per the spec.
+ """
+ successful: list = []
+ failed: list = []
+ async with _get_connections_lock():
+ matching_conns = [
+ conn for conn in _connections.values()
+ if conn["api_id"] == api_id
+ ]
+
+ for idx, ev in enumerate(events):
+ identifier = new_uuid()
+ try:
+ if not isinstance(ev, str):
+ raise ValueError("event must be a JSON-encoded string")
+ for conn in matching_conns:
+ for sub_id, pattern in list(conn["subscriptions"].items()):
+ if _channel_matches(channel, pattern):
+ await conn["outbox"].put({
+ "type": "data",
+ "id": sub_id,
+ "event": [ev],
+ })
+ successful.append({"identifier": identifier, "index": idx})
+ except Exception as e:
+ failed.append({
+ "identifier": identifier,
+ "index": idx,
+ "code": 400,
+ "errorMessage": str(e),
+ })
+ return successful, failed
+
+
+# ---------------------------------------------------------------------------
+# Data plane — WebSocket subscribe
+# ---------------------------------------------------------------------------
+
+_KA_INTERVAL_DEFAULT = 60.0 # AppSync Events spec: one "ka" every 60s.
+_CONN_TIMEOUT_MS = 300000 # connection_ack connectionTimeoutMs per spec.
+
+
+def _ka_interval_secs() -> float:
+ """Keep-alive cadence; overridable for tests via ``APPSYNC_EVENTS_KA_INTERVAL_SECS``."""
+ try:
+ return float(os.environ.get("APPSYNC_EVENTS_KA_INTERVAL_SECS", _KA_INTERVAL_DEFAULT))
+ except ValueError:
+ return _KA_INTERVAL_DEFAULT
+
+
+async def handle_websocket(scope, receive, send, api_id: str):
+ """Drive an AppSync Events realtime WebSocket session.
+
+ Wire protocol (``aws-appsync-event-ws``):
+ - Handshake: ``Sec-WebSocket-Protocol: header-<b64>, aws-appsync-event-ws``
+ The ``header-<b64>`` entry is base64url(JSON) describing connection-scoped
+ auth (``x-api-key``, Cognito/OIDC ``Authorization``, Lambda token, or
+ SigV4 headers). MiniStack stores the decoded object on the connection and
+ uses it as the fallback when ``subscribe``/``publish`` frames omit their
+ own ``authorization`` block.
+ - ``{"type":"connection_init"}`` -> ``{"type":"connection_ack","connectionTimeoutMs":300000}``.
+ - ``{"type":"subscribe","id":..,"channel":..,"authorization":{...}}`` ->
+ ``subscribe_success`` / ``subscribe_error``.
+ - ``{"type":"publish","id":..,"channel":..,"events":[..],"authorization":{...}}``
+ -> ``publish_success`` (fans events out to matching subscribers) / ``publish_error``.
+ - ``{"type":"unsubscribe","id":..}`` -> ``unsubscribe_success``.
+ - Server pushes ``{"type":"data","id":<sub-id>,"event":[<json-string>]}`` on
+ each matching publish and emits ``{"type":"ka"}`` every ~60s.
+ """
+ msg = await receive()
+ if msg.get("type") != "websocket.connect":
+ return
+
+ if api_id not in _apis:
+ await send({"type": "websocket.close", "code": 1008})
+ return
+
+ sub_headers = {}
+ for name, value in scope.get("headers", []):
+ try:
+ sub_headers[name.decode("latin-1").lower()] = value.decode("utf-8")
+ except UnicodeDecodeError:
+ sub_headers[name.decode("latin-1").lower()] = value.decode("latin-1")
+ requested = sub_headers.get("sec-websocket-protocol", "")
+ chosen = None
+ for proto in [p.strip() for p in requested.split(",") if p.strip()]:
+ if proto.startswith("aws-appsync-event-ws"):
+ chosen = proto
+ break
+
+ conn_auth, auth_error = _decode_header_subprotocol(requested)
+ strict = _strict_auth_enabled()
+ lambda_auth_arn = _find_lambda_authorizer_arn(api_id)
+
+ accept_msg: dict = {"type": "websocket.accept"}
+ if chosen:
+ accept_msg["subprotocol"] = chosen
+ await send(accept_msg)
+
+ async def _deny_websocket(msg: str, *, code: int = 4401) -> bool:
+ try:
+ await send({
+ "type": "websocket.send",
+ "text": json.dumps({
+ "type": "connection_error",
+ "errors": [{
+ "errorType": "UnauthorizedException",
+ "message": msg,
+ }],
+ }),
+ })
+ except Exception:
+ pass
+ try:
+ await send({"type": "websocket.close", "code": code})
+ except Exception:
+ pass
+ return True
+
+ # Malformed header payload, strict API-key, or AppSync-Events authorizer.
+ connect_rctx: dict | None = None
+ if auth_error is not None:
+ if await _deny_websocket(
+ auth_error or "Invalid header-<b64> subprotocol", code=4400
+ ):
+ return
+ elif lambda_auth_arn:
+ if not (tok := _bearer_from_auth_dict(conn_auth)):
+ if await _deny_websocket(
+ "Unauthorized: Authorization token required in header- subprotocol",
+ ):
+ return
+ else:
+ ok, connect_rctx = await asyncio.to_thread(
+ _events_authorizer_invoke,
+ lambda_auth_arn,
+ "connect",
+ None,
+ tok,
+ )
+ if not ok and await _deny_websocket(
+ "connect rejected: AppSync authorizer returned deny or error",
+ ):
+ return
+ elif strict and (conn_auth is None or not _auth_has_known_api_key(api_id, conn_auth)):
+ if await _deny_websocket(
+ "Unauthorized: missing or invalid API key in header-<b64> subprotocol",
+ ):
+ return
+
+ from ministack.core.responses import _request_account_id
+ account_id = get_account_id()
+ token = _request_account_id.set(account_id)
+
+ connection_id = new_uuid()
+ outbox: asyncio.Queue = asyncio.Queue()
+ async with _get_connections_lock():
+ _connections[connection_id] = {
+ "api_id": api_id,
+ "account_id": account_id,
+ "outbox": outbox,
+ "subscriptions": {},
+ "auth": conn_auth,
+ "resolverContext": connect_rctx,
+ }
+
+ close_event = asyncio.Event()
+
+ async def _drain_outbox():
+ """Forward server-originated frames (acks, data pushes, ka) to the socket."""
+ while not close_event.is_set():
+ try:
+ item = await asyncio.wait_for(outbox.get(), timeout=0.5)
+ except asyncio.TimeoutError:
+ continue
+ if item is None:
+ return
+ try:
+ await send({"type": "websocket.send", "text": json.dumps(item)})
+ except Exception:
+ return
+
+ async def _heartbeat():
+ """Push ``{"type":"ka"}`` every interval until the connection closes."""
+ interval = _ka_interval_secs()
+ while not close_event.is_set():
+ try:
+ await asyncio.wait_for(close_event.wait(), timeout=interval)
+ except asyncio.TimeoutError:
+ pass
+ else:
+ return
+ await outbox.put({"type": "ka"})
+
+ drain_task = asyncio.create_task(_drain_outbox())
+ ka_task = asyncio.create_task(_heartbeat())
+
+ try:
+ while True:
+ incoming = await receive()
+ mtype = incoming.get("type")
+ if mtype == "websocket.disconnect":
+ break
+ if mtype != "websocket.receive":
+ continue
+ payload = incoming.get("text")
+ if payload is None and incoming.get("bytes") is not None:
+ payload = incoming["bytes"].decode("utf-8", errors="replace")
+ if not payload:
+ continue
+ try:
+ frame = json.loads(payload)
+ except json.JSONDecodeError:
+ await outbox.put({"type": "error", "errors": [{"errorType": "BadRequestException", "message": "invalid json"}]})
+ continue
+ await _handle_client_frame(api_id, connection_id, frame, outbox)
+ except Exception:
+ logger.exception("AppSync Events WebSocket error")
+ finally:
+ close_event.set()
+ drain_task.cancel()
+ ka_task.cancel()
+ async with _get_connections_lock():
+ _connections.pop(connection_id, None)
+ _request_account_id.reset(token)
+ try:
+ await send({"type": "websocket.close", "code": 1000})
+ except Exception:
+ pass
+
+
+def _effective_auth(frame: dict, connection_id: str) -> dict | None:
+ """Resolve the auth used for a given frame: per-frame if provided, else connection-scoped."""
+ per_frame = frame.get("authorization")
+ if isinstance(per_frame, dict):
+ return per_frame
+ conn = _connections.get(connection_id) or {}
+ return conn.get("auth")
+
+
+async def _handle_client_frame(api_id: str, connection_id: str, frame: dict, outbox: asyncio.Queue):
+ ftype = frame.get("type")
+ if ftype == "connection_init":
+ await outbox.put({"type": "connection_ack", "connectionTimeoutMs": _CONN_TIMEOUT_MS})
+ return
+
+ if ftype == "ka":
+ # Client-side keep-alive; spec says server acks are not required.
+ return
+
+ if ftype == "subscribe":
+ sub_id = frame.get("id")
+ channel = frame.get("channel")
+ if not sub_id or not channel:
+ await outbox.put({
+ "type": "subscribe_error",
+ "id": sub_id,
+ "errors": [{"errorType": "BadRequestException",
+ "message": "'id' and 'channel' are required"}],
+ })
+ return
+ channel_err = _validate_channel(channel, allow_wildcard=True)
+ if channel_err:
+ await outbox.put({
+ "type": "subscribe_error",
+ "id": sub_id,
+ "errors": [{"errorType": "BadRequestException", "message": channel_err}],
+ })
+ return
+ ns_name = _channel_namespace_for(channel)
+ if ns_name is None or ns_name not in _channel_namespaces.get(api_id, {}):
+ await outbox.put({
+ "type": "subscribe_error",
+ "id": sub_id,
+ "errors": [{"errorType": "UnauthorizedException",
+ "message": f"No channel namespace matches '{channel}'"}],
+ })
+ return
+ ok, message = await _authorize_event_op(
+ api_id, str(channel), "subscribe", _effective_auth(frame, connection_id),
+ )
+ if not ok:
+ await outbox.put({
+ "type": "subscribe_error",
+ "id": sub_id,
+ "errors": [{"errorType": "UnauthorizedException",
+ "message": message or "subscribe rejected"}],
+ })
+ return
+ async with _get_connections_lock():
+ conn = _connections.get(connection_id)
+ if conn is not None:
+ conn["subscriptions"][sub_id] = channel
+ await outbox.put({"type": "subscribe_success", "id": sub_id})
+ return
+
+ if ftype == "publish":
+ pub_id = frame.get("id")
+ channel = frame.get("channel")
+ events = frame.get("events")
+ if not pub_id or not channel or not isinstance(events, list):
+ await outbox.put({
+ "type": "publish_error",
+ "id": pub_id,
+ "errors": [{"errorType": "BadRequestException",
+ "message": "'id', 'channel' and 'events' (array) are required"}],
+ })
+ return
+ channel_err = _validate_channel(channel, allow_wildcard=False)
+ if channel_err:
+ await outbox.put({
+ "type": "publish_error",
+ "id": pub_id,
+ "errors": [{"errorType": "BadRequestException", "message": channel_err}],
+ })
+ return
+ ns_name = _channel_namespace_for(channel)
+ if ns_name is None or ns_name not in _channel_namespaces.get(api_id, {}):
+ await outbox.put({
+ "type": "publish_error",
+ "id": pub_id,
+ "errors": [{"errorType": "UnauthorizedException",
+ "message": f"No channel namespace matches '{channel}'"}],
+ })
+ return
+ ok, message = await _authorize_event_op(
+ api_id, str(channel), "publish", _effective_auth(frame, connection_id),
+ )
+ if not ok:
+ await outbox.put({
+ "type": "publish_error",
+ "id": pub_id,
+ "errors": [{"errorType": "UnauthorizedException",
+ "message": message or "publish rejected"}],
+ })
+ return
+ successful, failed = await _fanout_publish(api_id, channel, events)
+ await outbox.put({
+ "type": "publish_success",
+ "id": pub_id,
+ "successful": successful,
+ "failed": failed,
+ })
+ return
+
+ if ftype == "unsubscribe":
+ sub_id = frame.get("id")
+ async with _get_connections_lock():
+ conn = _connections.get(connection_id)
+ if conn is not None:
+ conn["subscriptions"].pop(sub_id, None)
+ await outbox.put({"type": "unsubscribe_success", "id": sub_id})
+ return
+
+ await outbox.put({
+ "type": "error",
+ "errors": [{"errorType": "BadRequestException",
+ "message": f"unknown frame type: {ftype}"}],
+ })
diff --git a/tests/test_appsync_dns_defaults.py b/tests/test_appsync_dns_defaults.py
new file mode 100644
index 00000000..bd3ab58f
--- /dev/null
+++ b/tests/test_appsync_dns_defaults.py
@@ -0,0 +1,60 @@
+"""Unit tests for AppSync Events ``dns`` defaults (no live MiniStack)."""
+
+from __future__ import annotations
+
+import asyncio
+
+from ministack.core.responses import set_request_region
+
+
+def test_default_dns_localhost_with_region(monkeypatch):
+ monkeypatch.delenv("APPSYNC_EVENTS_HTTP_HOST_TEMPLATE", raising=False)
+ monkeypatch.delenv("APPSYNC_EVENTS_REALTIME_HOST_TEMPLATE", raising=False)
+ monkeypatch.setenv("MINISTACK_HOST", "localhost")
+ monkeypatch.setenv("GATEWAY_PORT", "4566")
+ set_request_region("us-east-1")
+
+ from ministack.services.appsync_events import _default_dns_for_api
+
+ d = _default_dns_for_api("abc123")
+ assert d["HTTP"] == "abc123.appsync-api.us-east-1.localhost:4566"
+ assert d["REALTIME"] == "abc123.appsync-realtime-api.us-east-1.localhost:4566"
+
+
+def test_dns_templates_override_when_both_set(monkeypatch):
+ monkeypatch.setenv(
+ "APPSYNC_EVENTS_HTTP_HOST_TEMPLATE",
+ "{api_id}.appsync-api.custom:{port}",
+ )
+ monkeypatch.setenv(
+ "APPSYNC_EVENTS_REALTIME_HOST_TEMPLATE",
+ "{api_id}.appsync-realtime-api.custom:{port}",
+ )
+ monkeypatch.setenv("GATEWAY_PORT", "8080")
+ set_request_region("eu-west-2")
+
+ from ministack.services.appsync_events import _default_dns_for_api
+
+ d = _default_dns_for_api("x")
+ assert d["HTTP"] == "x.appsync-api.custom:8080"
+ assert d["REALTIME"] == "x.appsync-realtime-api.custom:8080"
+
+
+def test_appsync_events_service_hosts_are_not_s3_virtual_hosts():
+ from ministack.app import _handle_s3_vhost_request
+
+ for host in (
+ "appsync-api.eu-west-2.localhost:4566",
+ "appsync-realtime-api.eu-west-2.localhost:4566",
+ ):
+ result = asyncio.run(
+ _handle_s3_vhost_request(
+ host,
+ "/v2/apis",
+ "GET",
+ {"host": host},
+ b"",
+ {},
+ )
+ )
+ assert result is None
diff --git a/tests/test_appsync_events.py b/tests/test_appsync_events.py
new file mode 100644
index 00000000..a4d334fc
--- /dev/null
+++ b/tests/test_appsync_events.py
@@ -0,0 +1,903 @@
+"""
+Integration tests for AWS AppSync Events.
+
+Covers:
+ - Management plane (/v2/apis): CreateApi/GetApi/ListApis/UpdateApi/DeleteApi,
+ ChannelNamespace CRUD, ApiKey CRUD (via boto3.client("appsync")).
+ - HTTP publish (POST /event on {apiId}.appsync-api.*).
+ - WebSocket handshake with the ``header-<b64>`` auth subprotocol.
+ - WebSocket subscribe + fan-out (exact paths and terminal ``*`` wildcard).
+ - WebSocket publish frame (``publish_success`` + fan-out to peers).
+ - Server-pushed ``ka`` keep-alive frames.
+ - Channel path regex validation (1..5 segments, alphanumeric + dash).
+
+Uses a stdlib WebSocket client (no new runtime deps).
+"""
+
+import asyncio
+import base64
+import hashlib
+import http.client
+import json
+import os
+import socket
+import struct
+import time
+from urllib.parse import urlparse
+
+import pytest
+from botocore.exceptions import ClientError
+
+_ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+_PORT = urlparse(_ENDPOINT).port or 4566
+_WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
+
+
+def _encode_auth_header(payload: dict) -> str:
+ """Return the ``header-<base64url(json)>`` subprotocol string."""
+ raw = json.dumps(payload).encode("utf-8")
+ b64 = base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
+ return f"header-{b64}"
+
+
+# ---------------------------------------------------------------------------
+# Stdlib WebSocket client (mirrors the helper in test_apigwv2_websocket.py)
+# ---------------------------------------------------------------------------
+
+class _WSClient:
+ def __init__(self, host_header: str, path: str, subprotocol: str | None = None):
+ self._sock = socket.create_connection(("127.0.0.1", _PORT), timeout=5)
+ key = base64.b64encode(os.urandom(16)).decode()
+ request_headers = {
+ "Host": host_header,
+ "Upgrade": "websocket",
+ "Connection": "Upgrade",
+ "Sec-WebSocket-Key": key,
+ "Sec-WebSocket-Version": "13",
+ }
+ if subprotocol:
+ request_headers["Sec-WebSocket-Protocol"] = subprotocol
+ 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):
+ 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)
+ self.handshake_headers = header_blob # exposed for tests that inspect status
+ 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_json(self, obj):
+ payload = json.dumps(obj).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_json(self, timeout=3.0):
+ 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):
+ return json.loads(payload.decode("utf-8", errors="replace"))
+ if opcode == 0x8:
+ return None
+ except socket.timeout:
+ return None
+
+ def _recv_all(self, n):
+ 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):
+ try:
+ self._sock.sendall(b"\x88\x82" + os.urandom(4) + b"\x03\xe8")
+ except Exception:
+ pass
+ try:
+ self._sock.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+_DEFAULT_EVENT_CONFIG = {
+ "authProviders": [{"authType": "API_KEY"}],
+ "connectionAuthModes": [{"authType": "API_KEY"}],
+ "defaultPublishAuthModes": [{"authType": "API_KEY"}],
+ "defaultSubscribeAuthModes": [{"authType": "API_KEY"}],
+}
+
+
+def _create_api(appsync, name):
+ return appsync.create_api(name=name, eventConfig=_DEFAULT_EVENT_CONFIG)["api"]
+
+
+async def _invoke_asgi_http(
+ method: str,
+ path: str,
+ host: str,
+ body: bytes = b"",
+ *,
+ extra_headers: dict[str, str] | None = None,
+):
+ """Drive MiniStack's ASGI ``app`` in-process (no TCP server)."""
+ from ministack.app import app as asgi_app
+
+ messages: list[dict] = []
+
+ async def send(message: dict):
+ messages.append(message)
+
+ headers = [(b"host", host.encode("ascii"))]
+ if body:
+ headers.append((b"content-type", b"application/json"))
+ headers.append((b"content-length", str(len(body)).encode("ascii")))
+ if extra_headers:
+ for hk, hv in extra_headers.items():
+ headers.append((hk.lower().encode("ascii"), hv.encode("utf-8")))
+
+ scope = {
+ "type": "http",
+ "asgi": {"version": "3.0", "spec_version": "2.3"},
+ "http_version": "1.1",
+ "method": method,
+ "scheme": "http",
+ "path": path,
+ "raw_path": path.encode("utf-8"),
+ "root_path": "",
+ "query_string": b"",
+ "headers": headers,
+ "client": ("127.0.0.1", 55555),
+ "server": ("127.0.0.1", 4566),
+ }
+ body_sent = False
+
+ async def receive():
+ nonlocal body_sent
+ if not body_sent:
+ body_sent = True
+ return {"type": "http.request", "body": body, "more_body": False}
+ return {"type": "http.request", "body": b"", "more_body": False}
+
+ await asgi_app(scope, receive, send)
+ return messages
+
+
+def _asgi_response(messages: list[dict]) -> tuple[int, dict[str, str], bytes]:
+ start = next(m for m in messages if m["type"] == "http.response.start")
+ body_msg = next(m for m in messages if m["type"] == "http.response.body")
+ hdrs: dict[str, str] = {}
+ for k, v in start.get("headers", []):
+ hdrs[k.decode("latin-1").lower()] = v.decode("latin-1", errors="replace")
+ return start["status"], hdrs, body_msg.get("body", b"")
+
+
+def _create_namespace(appsync, api_id, name):
+ return appsync.create_channel_namespace(apiId=api_id, name=name)["channelNamespace"]
+
+
+def _minimal_sigv4_appsync_authorization() -> str:
+ """SigV4-shaped header with credential scope ``.../appsync/aws4_request`` (unsigned).
+
+ MiniStack's router only inspects the ``Credential=`` segment — real Lambdas
+ sign with the same ``appsync`` service name as AppSync GraphQL.
+ """
+ return (
+ "AWS4-HMAC-SHA256 "
+ "Credential=testkey/20260127/us-east-1/appsync/aws4_request, "
+ "SignedHeaders=host;x-amz-date, "
+ "Signature=" + "0" * 64
+ )
+
+
+def _publish_http(
+ api_id,
+ channel,
+ events,
+ api_key="da2-local-test-key",
+ *,
+ authorization=None,
+ host_header=None,
+):
+ """POST /event on the {apiId}.appsync-api.* virtual host (or ``host_header`` override)."""
+ conn = http.client.HTTPConnection("127.0.0.1", _PORT, timeout=5)
+ body = json.dumps({"channel": channel, "events": events})
+ hh = host_header or f"{api_id}.appsync-api.us-east-1.amazonaws.com"
+ hdrs = {
+ "Host": hh,
+ "Content-Type": "application/json",
+ "x-api-key": api_key,
+ }
+ if authorization:
+ hdrs["Authorization"] = authorization
+ conn.request(
+ "POST", "/event",
+ body=body.encode("utf-8"),
+ headers=hdrs,
+ )
+ resp = conn.getresponse()
+ data = resp.read()
+ conn.close()
+ return resp.status, json.loads(data) if data else None
+
+
+def _open_subscriber(api_id, *, auth_header: dict | None = None):
+ """Open a realtime WebSocket with the spec-shaped subprotocol list.
+
+ Sends ``Sec-WebSocket-Protocol: header-<b64>, aws-appsync-event-ws`` and
+ waits for the ``connection_ack``. When ``auth_header`` is None, a default
+ ``{"host":..., "x-api-key":"da2-local-test-key"}`` payload is supplied —
+ matching how a real client would wrap API_KEY credentials.
+ """
+ host_header = f"{api_id}.appsync-realtime-api.us-east-1.amazonaws.com"
+ http_host = f"{api_id}.appsync-api.us-east-1.amazonaws.com"
+ if auth_header is None:
+ auth_header = {"host": http_host, "x-api-key": "da2-local-test-key"}
+ protocols = f"{_encode_auth_header(auth_header)}, aws-appsync-event-ws"
+ ws = _WSClient(host_header=host_header, path="/event/realtime", subprotocol=protocols)
+ ws.send_json({"type": "connection_init"})
+ ack = ws.recv_json()
+ assert ack["type"] == "connection_ack"
+ assert ack.get("connectionTimeoutMs") == 300000
+ return ws
+
+
+def _subscribe(ws, sub_id, channel):
+ ws.send_json({"type": "subscribe", "id": sub_id, "channel": channel})
+ resp = ws.recv_json()
+ return resp
+
+
+def _drain_until(ws, predicate, *, timeout=3.0):
+ """Read frames until ``predicate(frame)`` returns True, ignoring 'ka' noise."""
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ remaining = max(0.1, deadline - time.time())
+ frame = ws.recv_json(timeout=remaining)
+ if frame is None:
+ return None
+ if predicate(frame):
+ return frame
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+def api(appsync):
+ """A clean API + default channel namespace for each test."""
+ suffix = str(int(time.time() * 1000))[-10:]
+ created = _create_api(appsync, f"events-{suffix}")
+ api_id = created["apiId"]
+ _create_namespace(appsync, api_id, "default")
+ yield api_id
+ try:
+ appsync.delete_api(apiId=api_id)
+ except ClientError:
+ pass
+
+
+# ---------------------------------------------------------------------------
+# Management plane
+# ---------------------------------------------------------------------------
+
+def test_asgi_get_v2_apis_appsync_api_vhost_discovers_api():
+ """Unsigned GET /v2/apis with an AppSync Events API vhost reaches Events.
+
+ Regression: path-only ``/v2/apis`` routing must not send this to ``apigateway``
+ (404). It must reach ``appsync_events`` and return CORS headers from dispatch.
+ """
+ from ministack.services import appsync_events as ae
+
+ ae.reset()
+ host = "example.appsync-api.us-east-1.localhost:4566"
+
+ async def _run():
+ create_body = json.dumps({"name": "asgi-discovery-e2e"}).encode()
+ post_msgs = await _invoke_asgi_http("POST", "/v2/apis", host, create_body)
+ post_status, _post_hdrs, post_body = _asgi_response(post_msgs)
+ assert post_status == 200
+ created = json.loads(post_body.decode())["api"]
+ api_id = created["apiId"]
+ assert api_id
+
+ get_msgs = await _invoke_asgi_http("GET", "/v2/apis", host)
+ get_status, get_hdrs, get_body = _asgi_response(get_msgs)
+ assert get_status == 200
+ assert get_hdrs.get("access-control-allow-origin") == "*"
+ listed = json.loads(get_body.decode())["apis"]
+ assert any(a["apiId"] == api_id for a in listed)
+
+ asyncio.run(_run())
+
+
+def test_create_api_defaults(appsync):
+ api = _create_api(appsync, "events-defaults")
+ try:
+ assert api["name"] == "events-defaults"
+ assert api["apiId"]
+ assert api["dns"]["HTTP"].endswith(f".appsync-api.us-east-1.localhost:{_PORT}")
+ assert api["dns"]["REALTIME"].endswith(
+ f".appsync-realtime-api.us-east-1.localhost:{_PORT}"
+ )
+ assert api["eventConfig"]["authProviders"] == [{"authType": "API_KEY"}]
+ assert api["apiArn"].startswith("arn:aws:appsync:")
+ finally:
+ appsync.delete_api(apiId=api["apiId"])
+
+
+def test_get_list_update_delete_api(appsync):
+ created = _create_api(appsync, "events-crud")
+ api_id = created["apiId"]
+
+ fetched = appsync.get_api(apiId=api_id)["api"]
+ assert fetched["apiId"] == api_id
+ assert fetched["name"] == "events-crud"
+
+ ids = {a["apiId"] for a in appsync.list_apis()["apis"]}
+ assert api_id in ids
+
+ updated = appsync.update_api(
+ apiId=api_id,
+ name="events-crud-renamed",
+ eventConfig=_DEFAULT_EVENT_CONFIG,
+ )["api"]
+ assert updated["name"] == "events-crud-renamed"
+
+ appsync.delete_api(apiId=api_id)
+ with pytest.raises(ClientError) as exc:
+ appsync.get_api(apiId=api_id)
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+
+
+def test_api_key_crud_via_v1_path(appsync, api):
+ """boto3's ``create_api_key`` / ``list_api_keys`` / ``delete_api_key`` all
+ target the v1 GraphQL endpoint. The Terraform AWS provider's
+ ``aws_appsync_api_key`` resource does the same. We transparently delegate
+ to the v2 Event API registry when the apiId belongs to an Event API, so
+ these SDK calls work for both resource types.
+ """
+ created = appsync.create_api_key(apiId=api, description="terraform-style")["apiKey"]
+ assert created["id"].startswith("da2-")
+ assert created["description"] == "terraform-style"
+
+ listed = appsync.list_api_keys(apiId=api)["apiKeys"]
+ assert any(k["id"] == created["id"] for k in listed)
+
+ appsync.delete_api_key(apiId=api, id=created["id"])
+ listed_after = appsync.list_api_keys(apiId=api)["apiKeys"]
+ assert not any(k["id"] == created["id"] for k in listed_after)
+
+
+def test_channel_namespace_crud(appsync, api):
+ ns = appsync.create_channel_namespace(apiId=api, name="chat")["channelNamespace"]
+ assert ns["name"] == "chat"
+ assert ns["publishAuthModes"]
+ assert ns["subscribeAuthModes"]
+
+ fetched = appsync.get_channel_namespace(apiId=api, name="chat")["channelNamespace"]
+ assert fetched["name"] == "chat"
+
+ listed = appsync.list_channel_namespaces(apiId=api)["channelNamespaces"]
+ names = {n["name"] for n in listed}
+ assert {"default", "chat"}.issubset(names)
+
+ updated = appsync.update_channel_namespace(
+ apiId=api,
+ name="chat",
+ publishAuthModes=[{"authType": "API_KEY"}],
+ )["channelNamespace"]
+ assert updated["publishAuthModes"] == [{"authType": "API_KEY"}]
+
+ appsync.delete_channel_namespace(apiId=api, name="chat")
+ with pytest.raises(ClientError) as exc:
+ appsync.get_channel_namespace(apiId=api, name="chat")
+ assert exc.value.response["Error"]["Code"] == "NotFoundException"
+
+
+# ---------------------------------------------------------------------------
+# HTTP publish
+# ---------------------------------------------------------------------------
+
+def test_publish_returns_identifiers(api):
+ events = [json.dumps("hello"), json.dumps({"msg": "world"})]
+ status, body = _publish_http(api, "/default/room1", events)
+ assert status == 200
+ assert len(body["successful"]) == 2
+ assert body["failed"] == []
+ assert {item["index"] for item in body["successful"]} == {0, 1}
+
+
+def test_publish_unknown_namespace_rejected(api):
+ status, body = _publish_http(api, "/does-not-exist/room", [json.dumps("x")])
+ assert status == 401
+ assert body["__type"].endswith("UnauthorizedException") or body["__type"] == "UnauthorizedException"
+
+
+def test_publish_unknown_api_404():
+ status, body = _publish_http("deadbeefdeadbeefdeadbeefde", "/default/x", [json.dumps("x")])
+ assert status == 404
+
+
+def test_detect_service_post_event_appsync_api_vhost_returns_appsync_events():
+ from ministack.core.router import detect_service
+
+ auth = _minimal_sigv4_appsync_authorization()
+ host = "abc123dead.appsync-api.us-east-1.amazonaws.com"
+ assert detect_service("POST", "/event", {"host": host, "authorization": auth}, {}) == "appsync-events"
+
+
+def test_detect_service_post_graphql_appsync_api_vhost_stays_appsync():
+ """GraphQL data plane shares the ``appsync`` SigV4 scope and the same vhost."""
+ from ministack.core.router import detect_service
+
+ auth = _minimal_sigv4_appsync_authorization()
+ host = "abc123dead.appsync-api.us-east-1.amazonaws.com"
+ assert detect_service("POST", "/graphql", {"host": host, "authorization": auth}, {}) == "appsync"
+
+
+def test_detect_service_post_event_localhost_stays_appsync():
+ """Without ``.appsync-api.`` in Host, step 2 credential scope still routes to GraphQL service."""
+ from ministack.core.router import detect_service
+
+ auth = _minimal_sigv4_appsync_authorization()
+ host = f"localhost:{_PORT}"
+ assert detect_service("POST", "/event", {"host": host, "authorization": auth}, {}) == "appsync"
+
+
+def test_publish_with_appsync_sigv4_scope_on_events_vhost():
+ """Regression: signed ``POST /event`` must reach ``appsync_events`` (not GraphQL 404).
+
+ Uses in-process ASGI (no TCP MiniStack) so CI and local runs stay green.
+ """
+ from ministack.services import appsync_events as ae
+
+ ae.reset()
+ mgmt_host = "example.appsync-api.us-east-1.localhost:4566"
+ auth = _minimal_sigv4_appsync_authorization()
+
+ async def _run():
+ create_body = json.dumps(
+ {"name": "sigv4-pub-asgi", "eventConfig": _DEFAULT_EVENT_CONFIG}
+ ).encode()
+ post_msgs = await _invoke_asgi_http("POST", "/v2/apis", mgmt_host, create_body)
+ post_status, _, post_body = _asgi_response(post_msgs)
+ assert post_status == 200
+ api_id = json.loads(post_body.decode())["api"]["apiId"]
+
+ ns_body = json.dumps({"name": "default"}).encode()
+ ns_path = f"/v2/apis/{api_id}/channelNamespaces"
+ ns_msgs = await _invoke_asgi_http("POST", ns_path, mgmt_host, ns_body)
+ ns_status, _, ns_raw = _asgi_response(ns_msgs)
+ assert ns_status == 200, ns_raw
+
+ pub_host = f"{api_id}.appsync-api.us-east-1.amazonaws.com"
+ pub_body = json.dumps(
+ {"channel": "/default/room1", "events": [json.dumps({"sigv4": True})]}
+ ).encode()
+ pub_msgs = await _invoke_asgi_http(
+ "POST",
+ "/event",
+ pub_host,
+ pub_body,
+ extra_headers={
+ "authorization": auth,
+ "x-api-key": "da2-local-test-key",
+ },
+ )
+ p_status, _, p_raw = _asgi_response(pub_msgs)
+ assert p_status == 200
+ parsed = json.loads(p_raw.decode())
+ assert len(parsed["successful"]) == 1
+ assert parsed["failed"] == []
+
+ asyncio.run(_run())
+
+
+def test_publish_with_appsync_sigv4_on_management_host_still_404():
+ """``POST /event`` on the AppSync *management* vhost is not an Events publish URL."""
+ auth = _minimal_sigv4_appsync_authorization()
+
+ async def _run():
+ pub_body = json.dumps(
+ {"channel": "/default/room1", "events": [json.dumps("x")]}
+ ).encode()
+ pub_msgs = await _invoke_asgi_http(
+ "POST",
+ "/event",
+ "appsync.us-east-1.amazonaws.com",
+ pub_body,
+ extra_headers={
+ "authorization": auth,
+ "x-api-key": "da2-local-test-key",
+ },
+ )
+ status, _, raw = _asgi_response(pub_msgs)
+ assert status == 404
+ body = json.loads(raw.decode())
+ assert "Unknown path" in (body.get("message") or "")
+
+ asyncio.run(_run())
+
+
+# ---------------------------------------------------------------------------
+# WebSocket subscribe + fan-out
+# ---------------------------------------------------------------------------
+
+def test_websocket_subscribe_receives_published_event(api):
+ ws = _open_subscriber(api)
+ try:
+ sub_resp = _subscribe(ws, "sub-1", "/default/room1")
+ assert sub_resp == {"type": "subscribe_success", "id": "sub-1"}
+
+ # tiny settle so the connection is registered before publish
+ time.sleep(0.05)
+
+ status, _ = _publish_http(api, "/default/room1", [json.dumps({"text": "hi"})])
+ assert status == 200
+
+ data = _drain_until(ws, lambda f: f.get("type") == "data", timeout=3.0)
+ assert data is not None
+ assert data["id"] == "sub-1"
+ # Per spec, the `event` field is an ARRAY of JSON-encoded strings.
+ assert isinstance(data["event"], list)
+ assert json.loads(data["event"][0]) == {"text": "hi"}
+ finally:
+ ws.close()
+
+
+def test_websocket_single_level_wildcard(api):
+ ws = _open_subscriber(api)
+ try:
+ _subscribe(ws, "sub-1", "/default/*")
+ time.sleep(0.05)
+
+ _publish_http(api, "/default/room1", [json.dumps("a")])
+ first = _drain_until(ws, lambda f: f.get("type") == "data", timeout=3.0)
+ assert first is not None
+ assert first["id"] == "sub-1"
+ assert json.loads(first["event"][0]) == "a"
+
+ # "/default/room1/child" is a two-segment suffix — should NOT match /default/*
+ _publish_http(api, "/default/room1/child", [json.dumps("nope")])
+ extra = _drain_until(ws, lambda f: f.get("type") == "data", timeout=1.0)
+ assert extra is None
+ finally:
+ ws.close()
+
+
+def test_websocket_unsubscribe_stops_delivery(api):
+ ws = _open_subscriber(api)
+ try:
+ _subscribe(ws, "sub-x", "/default/room1")
+ time.sleep(0.05)
+
+ _publish_http(api, "/default/room1", [json.dumps("first")])
+ first = _drain_until(ws, lambda f: f.get("type") == "data", timeout=3.0)
+ assert first is not None
+ assert json.loads(first["event"][0]) == "first"
+
+ ws.send_json({"type": "unsubscribe", "id": "sub-x"})
+ unsub_ack = _drain_until(ws, lambda f: f.get("type") == "unsubscribe_success", timeout=2.0)
+ assert unsub_ack == {"type": "unsubscribe_success", "id": "sub-x"}
+
+ _publish_http(api, "/default/room1", [json.dumps("after")])
+ after = _drain_until(ws, lambda f: f.get("type") == "data", timeout=1.0)
+ assert after is None
+ finally:
+ ws.close()
+
+
+# ---------------------------------------------------------------------------
+# WebSocket publish frame
+# ---------------------------------------------------------------------------
+
+def test_websocket_publish_frame_acks_and_fans_out(api):
+ publisher = _open_subscriber(api)
+ listener = _open_subscriber(api)
+ try:
+ assert _subscribe(listener, "sub-listener", "/default/room1") == {
+ "type": "subscribe_success", "id": "sub-listener",
+ }
+ time.sleep(0.05)
+
+ publisher.send_json({
+ "type": "publish",
+ "id": "pub-1",
+ "channel": "/default/room1",
+ "events": [json.dumps("over-ws")],
+ })
+ ack = _drain_until(publisher, lambda f: f.get("type") == "publish_success", timeout=3.0)
+ assert ack is not None
+ assert ack["id"] == "pub-1"
+ assert len(ack["successful"]) == 1
+ assert ack["failed"] == []
+
+ data = _drain_until(listener, lambda f: f.get("type") == "data", timeout=3.0)
+ assert data is not None
+ assert data["id"] == "sub-listener"
+ assert json.loads(data["event"][0]) == "over-ws"
+ finally:
+ publisher.close()
+ listener.close()
+
+
+# ---------------------------------------------------------------------------
+# Server-initiated keep-alive
+# ---------------------------------------------------------------------------
+
+def test_websocket_server_sends_keepalive():
+ """With APPSYNC_EVENTS_KA_INTERVAL_SECS lowered via compose, we should see a ka.
+
+ If the environment hasn't been configured for a short interval, skip —
+ the real 60s default is too slow for unit tests. Set the env var on the
+ MiniStack container (e.g. APPSYNC_EVENTS_KA_INTERVAL_SECS=1) to enable.
+ """
+ ka_interval = os.environ.get("APPSYNC_EVENTS_KA_INTERVAL_SECS")
+ if not ka_interval:
+ pytest.skip("Set APPSYNC_EVENTS_KA_INTERVAL_SECS on the server to exercise ka frames")
+ # Create a throwaway API so we can open a connection.
+ import boto3
+ client = boto3.client(
+ "appsync",
+ endpoint_url=_ENDPOINT,
+ region_name="us-east-1",
+ aws_access_key_id="test",
+ aws_secret_access_key="test",
+ )
+ created = client.create_api(name="events-ka-test", eventConfig=_DEFAULT_EVENT_CONFIG)["api"]
+ api_id = created["apiId"]
+ try:
+ client.create_channel_namespace(apiId=api_id, name="default")
+ ws = _open_subscriber(api_id)
+ try:
+ ka = _drain_until(ws, lambda f: f.get("type") == "ka", timeout=float(ka_interval) + 2.0)
+ assert ka == {"type": "ka"}
+ finally:
+ ws.close()
+ finally:
+ client.delete_api(apiId=api_id)
+
+
+# ---------------------------------------------------------------------------
+# Handshake auth (header-<b64> subprotocol)
+# ---------------------------------------------------------------------------
+
+def test_websocket_accepts_without_header_subprotocol_in_lax_mode(api):
+ """Default MiniStack config is lax — missing header-<b64> still accepts."""
+ host_header = f"{api}.appsync-realtime-api.us-east-1.amazonaws.com"
+ ws = _WSClient(host_header=host_header, path="/event/realtime",
+ subprotocol="aws-appsync-event-ws")
+ try:
+ ws.send_json({"type": "connection_init"})
+ ack = ws.recv_json()
+ assert ack["type"] == "connection_ack"
+ finally:
+ ws.close()
+
+
+def test_websocket_malformed_header_subprotocol_rejected(api):
+ """A ``header-<b64>`` entry that doesn't decode to JSON must close the socket."""
+ host_header = f"{api}.appsync-realtime-api.us-east-1.amazonaws.com"
+ # "not-base64!!" is invalid base64url — decode fails.
+ ws = _WSClient(
+ host_header=host_header,
+ path="/event/realtime",
+ subprotocol="header-not@@@base64, aws-appsync-event-ws",
+ )
+ try:
+ # Server should push a connection_error then close with 4401.
+ frame = ws.recv_json(timeout=2.0)
+ if frame is not None:
+ assert frame["type"] == "connection_error"
+ assert frame["errors"][0]["errorType"] == "UnauthorizedException"
+ finally:
+ ws.close()
+
+
+def test_websocket_frame_authorization_falls_back_to_connection_auth(api):
+ """Frames without their own ``authorization`` should reuse the handshake header.
+
+ In lax mode this path is effectively a no-op for acceptance, but it still
+ exercises the connection-scoped auth plumbing: a subscribe without an
+ ``authorization`` block must still succeed.
+ """
+ ws = _open_subscriber(
+ api,
+ auth_header={"host": f"{api}.appsync-api.us-east-1.amazonaws.com",
+ "x-api-key": "da2-local-test-key"},
+ )
+ try:
+ resp = _subscribe(ws, "sub-fallback", "/default/room-x")
+ assert resp == {"type": "subscribe_success", "id": "sub-fallback"}
+ finally:
+ ws.close()
+
+
+# ---------------------------------------------------------------------------
+# Channel path validation
+# ---------------------------------------------------------------------------
+
+def test_publish_rejects_invalid_channel_path(api):
+ # Too many segments (>5).
+ status, body = _publish_http(api, "/default/a/b/c/d/e/f", [json.dumps("x")])
+ assert status == 400
+ assert "BadRequestException" in body["__type"]
+
+
+def test_publish_rejects_segment_with_bad_chars(api):
+ # Underscores are not allowed by the spec segment regex.
+ status, body = _publish_http(api, "/default/bad_seg", [json.dumps("x")])
+ assert status == 400
+ assert "BadRequestException" in body["__type"]
+
+
+def test_subscribe_rejects_invalid_channel_path(api):
+ ws = _open_subscriber(api)
+ try:
+ ws.send_json({"type": "subscribe", "id": "sub-bad", "channel": "default/no-leading-slash"})
+ err = _drain_until(ws, lambda f: f.get("type") == "subscribe_error", timeout=2.0)
+ assert err is not None
+ assert err["id"] == "sub-bad"
+ finally:
+ ws.close()
+
+
+# ---------------------------------------------------------------------------
+# Terraform compatibility tests
+#
+# The Terraform AWS provider ships ``aws_appsync_api`` and
+# ``aws_appsync_channel_namespace`` resources that drive the v2 Event API
+# through the SDK's CreateApi / GetApi / UpdateApi / DeleteApi operations.
+# These tests replicate the exact wire shape Terraform reads back.
+# ---------------------------------------------------------------------------
+
+
+def test_terraform_aws_appsync_api_read_after_create(appsync):
+ """aws_appsync_api reads: api_id, name, api_arn, dns, event_config, tags.
+
+ Regression against Terraform AWS provider `internal/service/appsync/api.go`
+ which keys on these exact camelCase fields from the boto/Go SDK response.
+ """
+ created = appsync.create_api(
+ name="tf-events",
+ eventConfig=_DEFAULT_EVENT_CONFIG,
+ tags={"env": "local", "managed-by": "terraform"},
+ )["api"]
+ try:
+ fetched = appsync.get_api(apiId=created["apiId"])["api"]
+ for key in ("apiId", "name", "apiArn", "dns", "eventConfig", "tags", "created"):
+ assert key in fetched, f"Terraform AWS provider requires '{key}'"
+ assert fetched["name"] == "tf-events"
+ assert fetched["apiArn"].startswith("arn:aws:appsync:")
+ assert fetched["dns"]["HTTP"].endswith(f".appsync-api.us-east-1.localhost:{_PORT}")
+ assert fetched["dns"]["REALTIME"].endswith(
+ f".appsync-realtime-api.us-east-1.localhost:{_PORT}"
+ )
+ assert fetched["tags"] == {"env": "local", "managed-by": "terraform"}
+ assert fetched["eventConfig"]["authProviders"] == [{"authType": "API_KEY"}]
+ finally:
+ appsync.delete_api(apiId=created["apiId"])
+
+
+def test_terraform_aws_appsync_channel_namespace_read_after_create(appsync, api):
+ """aws_appsync_channel_namespace reads publish_auth_modes/subscribe_auth_modes."""
+ ns = appsync.create_channel_namespace(
+ apiId=api,
+ name="tf-ns",
+ publishAuthModes=[{"authType": "API_KEY"}],
+ subscribeAuthModes=[{"authType": "API_KEY"}],
+ )["channelNamespace"]
+ try:
+ assert ns["publishAuthModes"] == [{"authType": "API_KEY"}]
+ assert ns["subscribeAuthModes"] == [{"authType": "API_KEY"}]
+ for key in ("apiId", "name", "publishAuthModes", "subscribeAuthModes", "created"):
+ assert key in ns
+ finally:
+ appsync.delete_channel_namespace(apiId=api, name="tf-ns")
+
+
+def test_terraform_aws_appsync_api_key_on_event_api_uses_v1_path(appsync, api):
+ """aws_appsync_api_key targets POST /v1/apis/{apiId}/apikeys even when the
+ apiId is an Event API. Without the v1->v2 delegation in services/appsync.py
+ this test raises NotFoundException and `terraform apply` fails.
+ """
+ key = appsync.create_api_key(apiId=api, description="tf-managed")["apiKey"]
+ assert key["id"].startswith("da2-")
+ appsync.delete_api_key(apiId=api, id=key["id"])
+
+
+def test_http_publish_invokes_lambda_authorizer(monkeypatch):
+ """HTTP publish must enforce the same Lambda authorizer as WebSocket publish."""
+ from ministack.services import appsync_events as ae
+
+ ae.reset()
+ create_body = json.dumps({
+ "name": "auth-events",
+ "eventConfig": {
+ "authProviders": [{
+ "authType": "AWS_LAMBDA",
+ "lambdaAuthorizerConfig": {
+ "authorizerUri": "arn:aws:lambda:us-east-1:000000000000:function:authz"
+ },
+ }],
+ },
+ }).encode()
+ status, _headers, raw = ae._create_api(create_body)
+ assert status == 200
+ api_id = json.loads(raw)["api"]["apiId"]
+ ae._create_channel_namespace(api_id, b'{"name":"default"}')
+
+ calls = []
+
+ def _fake_invoke(arn, operation, channel, authorization_token):
+ calls.append((arn, operation, channel, authorization_token))
+ return authorization_token == "allow", {"tenant": "local"}
+
+ monkeypatch.setattr(ae, "_events_authorizer_invoke", _fake_invoke)
+ publish_body = json.dumps({"channel": "/default/room", "events": ['{"ok":true}']}).encode()
+
+ denied = asyncio.run(ae._publish(api_id, {}, publish_body))
+ assert denied[0] == 401
+
+ allowed = asyncio.run(ae._publish(api_id, {"authorization": "allow"}, publish_body))
+ assert allowed[0] == 200
+ assert calls[-1] == (
+ "arn:aws:lambda:us-east-1:000000000000:function:authz",
+ "publish",
+ "/default/room",
+ "allow",
+ )
diff --git a/tests/test_ministack.py b/tests/test_ministack.py
index b6e304b1..e950158d 100644
--- a/tests/test_ministack.py
+++ b/tests/test_ministack.py
@@ -121,10 +121,11 @@ def test_ministack_package_core_importable():
@_requires_package
def test_ministack_package_services_importable():
- """All 25 ministack.services modules must be importable and expose handle_request."""
+ """All core ministack.services modules must be importable and expose handle_request."""
from ministack.services import (
apigateway,
apigateway_v1,
+ appsync_events,
athena,
cloudwatch,
cloudwatch_logs,
@@ -170,6 +171,7 @@ def test_ministack_package_services_importable():
glue,
athena,
apigateway,
+ appsync_events,
firehose,
route53,
cognito,