Skip to content

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

fix(appsync): check Event API authorization under AUTH=true (#2400)

iot-rocketce28f63acd0c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f212a89e..6fc43741 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **Auth — SigV4a signatures are verified under `AUTH=true`** — requests signed with `AWS4-ECDSA-P256-SHA256`, which SDKs use for Multi-Region Access Points, were refused for every IAM user. Header and presigned S3 signatures are now checked with the P-256 key SigV4a derives from the secret, with their date or expiry, and an `X-Amz-Region-Set` that leaves out the serving region is refused (`RegionSetMismatch` on S3, the unknown-key error elsewhere). Contributed by @iot-rocket.
### Fixed
+- **AppSync Events — `AUTH=true` checks the Event API's authorization** — under `AUTH=true` an HTTP publish, a WebSocket connection or a subscription was accepted with any API key or none unless `APPSYNC_EVENTS_ENFORCE_AUTH` was set. It now needs what the API or the channel namespace accepts, as on AWS: a key registered on the API for `API_KEY`, a SigV4 signature for `AWS_IAM`, a bearer token for Cognito and OIDC. A refused publish answers 401 `UnauthorizedException`, with AWS's "You are not authorized to make this call." for a key the API does not know. `APPSYNC_EVENTS_ENFORCE_AUTH` works as before with `AUTH` unset. Contributed by @iot-rocket.
- **Cognito — pre token generation for `client_credentials`** — a `client_credentials` grant invoked a `V2_0` pre token generation trigger; it now invokes the trigger only when `LambdaVersion` is `V3_0`, as AWS documents and does. Contributed by @iot-rocket.
- **Cognito — `client_credentials` needs the flow** — the `/oauth2/token` endpoint gave a `client_credentials` token to an app client without `client_credentials` in `AllowedOAuthFlows`; such a client now gets `invalid_grant`, or `invalid_scope` first when a requested scope is unknown or none is left, as on AWS. Contributed by @iot-rocket.
- **S3 — ACLs on buckets with `BucketOwnerEnforced`** — on a bucket with ACLs disabled, the default for new buckets, ACL writes answered 200 and a stored bucket grant still opened the bucket to other accounts and anonymous callers; `PutBucketAcl` and `PutObjectAcl` now answer 400 `AccessControlListNotSupported`, `PutObject`, `CopyObject`, `CreateMultipartUpload` and POST uploads refuse any ACL but an owner-only one with the same error, `CreateBucket` and a switch to `BucketOwnerEnforced` refuse an ACL that grants others with 400 `InvalidBucketAclWithObjectOwnership`, and ACLs stored earlier grant nothing and read as the owner's until ACLs are enabled again. Contributed by @iot-rocket.
diff --git a/ministack/services/appsync_events.py b/ministack/services/appsync_events.py
index 7af12614..bc940f54 100644
--- a/ministack/services/appsync_events.py
+++ b/ministack/services/appsync_events.py
@@ -15,7 +15,8 @@ trailing ``*`` single-level wildcard. Connection-scoped authorization is
declared via a second ``header-<base64url(json)>`` Sec-WebSocket-Protocol
entry. Set ``APPSYNC_EVENTS_ENFORCE_AUTH=1`` for strict mode (registered
x-api-key required, or AWS_LAMBDA authorizer Lambda invoked when configured
-in the API ``eventConfig``).
+in the API ``eventConfig``). Under ``AUTH=true`` the check is on and follows the
+authorization modes of the API and the channel namespace.
"""
import asyncio
@@ -434,6 +435,34 @@ def _auth_has_known_api_key(api_id: str, auth: dict | None) -> bool:
return provided in _api_keys.get(api_id, {})
+def _operation_auth_modes(api_id: str, channel: str | None, operation: str) -> set:
+ """The authorization types the API, or the channel's namespace, accepts for ``operation``."""
+ if operation == EVENT_CONNECT:
+ modes = ((_apis.get(api_id) or {}).get("eventConfig") or {}).get("connectionAuthModes")
+ else:
+ namespace = _channel_namespaces.get(api_id, {}).get(_channel_namespace_for(channel or "")) or {}
+ modes = namespace.get("publishAuthModes" if operation == EVENT_PUBLISH else "subscribeAuthModes")
+ return {mode.get("authType") for mode in modes or [] if isinstance(mode, dict)}
+
+
+def _modes_accept(api_id: str, modes: set, auth: dict | None) -> tuple[bool, str | None]:
+ """Whether ``auth`` satisfies one of ``modes``, and AppSync's message when an API key is refused."""
+ auth = auth if isinstance(auth, dict) else {}
+ authorization = str(auth.get("Authorization") or auth.get("authorization") or "")
+ refused = None
+ if "API_KEY" in modes and (auth.get("x-api-key") or auth.get("X-Api-Key")):
+ if _auth_has_known_api_key(api_id, auth):
+ return True, None
+ refused = "You are not authorized to make this call."
+ # The gateway has checked an HTTP request's signature by now; a WebSocket's is taken as sent.
+ if "AWS_IAM" in modes and authorization.startswith("AWS4-HMAC-SHA256"):
+ return True, None
+ if {"AMAZON_COGNITO_USER_POOLS", "OPENID_CONNECT"} & modes and authorization and not authorization.startswith(
+ "AWS4-"):
+ return True, None
+ return False, refused
+
+
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 []:
@@ -571,6 +600,9 @@ async def _authorize_event_op(
return False, f"{operation} rejected: AppSync authorizer denied"
return True, None
+ from ministack.app import AUTH
+ if AUTH:
+ return _modes_accept(api_id, _operation_auth_modes(api_id, channel, operation), auth)
if _strict_auth_enabled() and not _auth_has_known_api_key(api_id, auth):
return False, f"{operation} rejected: no valid x-api-key"
@@ -969,7 +1001,7 @@ async def _publish(api_id: str, headers: dict, body: bytes):
api_id, str(channel), EVENT_PUBLISH, _auth_from_headers(headers), headers
)
if not ok:
- return _publish_error(401, "UnauthorizedException", message or "Unauthorized")
+ return _publish_error(401, "UnauthorizedException", message)
successful, failed = await _fanout_publish(api_id, channel, events)
return json_response({"successful": successful, "failed": failed}, content_type=REST_JSON_CONTENT_TYPE)
@@ -1112,6 +1144,8 @@ async def _handle_websocket_in_api_scope(
chosen = proto
break
+ from ministack.app import AUTH
+
conn_auth, auth_error = _decode_header_subprotocol(requested)
strict = _strict_auth_enabled()
lambda_auth_arn = _find_lambda_authorizer_arn(api_id)
@@ -1169,6 +1203,9 @@ async def _handle_websocket_in_api_scope(
"connect rejected: AppSync authorizer returned deny or error",
):
return
+ elif AUTH and not _modes_accept(api_id, _operation_auth_modes(api_id, None, EVENT_CONNECT), conn_auth)[0]:
+ if await _deny_websocket("Unauthorized: no authorization the API accepts for connections"):
+ 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",
diff --git a/tests/test_appsync_events.py b/tests/test_appsync_events.py
index 224c449a..a33b341e 100644
--- a/tests/test_appsync_events.py
+++ b/tests/test_appsync_events.py
@@ -236,6 +236,10 @@ def _asgi_response(messages: list[dict]) -> tuple[int, dict[str, str], bytes]:
return start["status"], hdrs, body_msg.get("body", b"")
+# The API key the ``api`` fixture registered on each API it created.
+_API_KEYS: dict[str, str] = {}
+
+
def _create_namespace(appsync, api_id, name):
return appsync.create_channel_namespace(apiId=api_id, name=name)["channelNamespace"]
@@ -258,19 +262,23 @@ def _publish_http(
api_id,
channel,
events,
- api_key="da2-local-test-key",
+ api_key=None,
*,
authorization=None,
host_header=None,
+ extra_headers=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"
+ if api_key is None:
+ api_key = _API_KEYS.get(api_id, "da2-local-test-key")
hdrs = {
"Host": hh,
"Content-Type": "application/json",
- "x-api-key": api_key,
+ **({"x-api-key": api_key} if api_key else {}),
+ **(extra_headers or {}),
}
if authorization:
hdrs["Authorization"] = authorization
@@ -291,7 +299,7 @@ def _event_host_request(api_id, method, path, body: bytes):
conn.request(method, path, body=body, headers={
"Host": f"{api_id}.appsync-api.us-east-1.amazonaws.com",
"Content-Type": "application/json",
- "x-api-key": "da2-local-test-key",
+ "x-api-key": _API_KEYS.get(api_id, "da2-local-test-key"),
})
resp = conn.getresponse()
data = resp.read()
@@ -304,13 +312,13 @@ def _open_subscriber(api_id, *, auth_header: dict | None = None):
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 —
+ ``{"host":..., "x-api-key": <the API's 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"}
+ auth_header = {"host": http_host, "x-api-key": _API_KEYS.get(api_id, "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"})
@@ -367,6 +375,7 @@ def api(appsync):
created = _create_api(appsync, f"events-{suffix}")
api_id = created["apiId"]
_create_namespace(appsync, api_id, "default")
+ _API_KEYS[api_id] = appsync.create_api_key(apiId=api_id)["apiKey"]["id"]
yield api_id
try:
appsync.delete_api(apiId=api_id)
@@ -578,6 +587,51 @@ def test_publish_unknown_namespace_rejected(api):
assert body == {"errors": [{"errorType": "UnauthorizedException"}]}
+def test_publish_follows_the_authorization_modes_contract(auth_enabled, iam_user, appsync):
+ """Under AUTH=true an API_KEY namespace needs a valid key and an AWS_IAM namespace a signature."""
+ from botocore.auth import SigV4Auth
+ from botocore.awsrequest import AWSRequest
+ from botocore.credentials import Credentials
+ from conftest import REGION, second_access_key
+
+ modes = lambda *types: [{"authType": t} for t in types] # noqa: E731
+ api_id = appsync.create_api(name=f"events-auth-{int(time.time() * 1000)}", eventConfig={
+ "authProviders": modes("API_KEY", "AWS_IAM"), "connectionAuthModes": modes("API_KEY", "AWS_IAM"),
+ "defaultPublishAuthModes": modes("API_KEY"), "defaultSubscribeAuthModes": modes("API_KEY"),
+ })["api"]["apiId"]
+ try:
+ _create_namespace(appsync, api_id, "keyed")
+ appsync.create_channel_namespace(apiId=api_id, name="iam", publishAuthModes=modes("AWS_IAM"),
+ subscribeAuthModes=modes("AWS_IAM"))
+ key = appsync.create_api_key(apiId=api_id)["apiKey"]["id"]
+ user = iam_user(policy={"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "appsync:EventPublish", "Resource": "*"}]})
+ host = f"{api_id}.appsync-api.us-east-1.amazonaws.com"
+ with second_access_key(user) as (key_id, secret):
+ body = json.dumps({"channel": "/iam/c", "events": [json.dumps("x")]})
+ request = AWSRequest(method="POST", url=f"http://{host}/event", data=body,
+ headers={"Content-Type": "application/json"})
+ SigV4Auth(Credentials(key_id, secret), "appsync", REGION).add_auth(request)
+ signed = _publish_http(api_id, "/iam/c", [json.dumps("x")], api_key="",
+ authorization=request.headers["Authorization"],
+ extra_headers={"X-Amz-Date": request.headers["X-Amz-Date"]})
+ answers = [
+ _publish_http(api_id, "/keyed/c", [json.dumps("x")], api_key=""),
+ _publish_http(api_id, "/keyed/c", [json.dumps("x")], api_key="da2-notakeyofthisapi"),
+ _publish_http(api_id, "/keyed/c", [json.dumps("x")], api_key=key),
+ _publish_http(api_id, "/iam/c", [json.dumps("x")], api_key=key),
+ signed,
+ ]
+ finally:
+ appsync.delete_api(apiId=api_id)
+ refused = {"errors": [{"errorType": "UnauthorizedException"}]}
+ wrong_key = {"errors": [{"errorType": "UnauthorizedException",
+ "message": "You are not authorized to make this call."}]}
+ expected = [(401, refused), (401, wrong_key), 200, (401, refused), 200] if auth_enabled else [200] * 5
+ assert [answer[0] if answer[0] == 200 else answer for answer in answers] == expected
+
+
@pytest.mark.parametrize("payload, status, error_type, message", [
(b"{not json", 400, "SerializationException", "Unable to parse request body"),
(b'{"channel": "default/a", "events": "x"}', 400, "SerializationException", "Expected list or null"),
@@ -1345,6 +1399,8 @@ def test_websocket_server_sends_keepalive():
# Handshake auth (header-<b64> subprotocol)
# ---------------------------------------------------------------------------
[email protected](os.environ.get("AUTH", "").lower() == "true",
+ reason="AUTH=true checks the connection's authorization")
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"
@@ -1387,7 +1443,7 @@ def test_websocket_frame_authorization_falls_back_to_connection_auth(api):
ws = _open_subscriber(
api,
auth_header={"host": f"{api}.appsync-api.us-east-1.amazonaws.com",
- "x-api-key": "da2-local-test-key"},
+ "x-api-key": _API_KEYS[api]},
)
try:
resp = _subscribe(ws, "sub-fallback", "/default/room-x")