Skip to content

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

fix(appsync): answer data-plane errors in the AppSync errors envelope (#2264)

iot-rocketd111ec32fd9c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e1cafb1a..301ec32f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **AppSync — data-plane error responses** — Event API `POST /event` refusals answered `{"__type", "message"}` with MiniStack's own messages, and the GraphQL endpoint answered 500 for a body that is not a JSON object, a message-only 400 for a missing query and 200 for an unparseable one; both now answer AWS's `{"errors": [{"errorType", "message"}]}` envelope with AWS's error types, messages and `x-amzn-ErrorType` header (`SerializationException`, `MalformedHttpRequestException`, `ResourceNotFoundException` for an unknown API, `UnknownOperationException` for another path on an Event API host), and the publish endpoint answers `application/json`. Contributed by @iot-rocket.
- **Cognito — OAuth scope checks for federation and `client_credentials`** — `/oauth2/authorize` with an `identity_provider` went on to the identity provider whatever the `scope`; it now redirects to the callback with `error_description=invalid_scope` (and the `state`) when a requested scope is not in the client's `AllowedOAuthScopes`, as the managed login does. The `client_credentials` grant answered `invalid_scope` to any request naming an undefined resource server scope; it now ignores those once a defined scope is requested, so `api/read bogus/x` is granted `api/read` and `api/admin bogus/x` answers `invalid_grant`, as AWS does. Contributed by @iot-rocket.
- **S3 — Block Public Access settings and public bucket ACL grants** — any one of the four Block Public Access settings shut off every public grant on a bucket, none refused setting a public ACL, and a public bucket ACL opened every read and write in the bucket. `BlockPublicAcls` now refuses a call that sets a public ACL on a bucket with ACLs enabled (403 `AccessDenied`) and leaves the grants in place, `IgnorePublicAcls` drops public ACL grants and `RestrictPublicBuckets` the bucket policy. A bucket ACL grants what its permission covers: `READ` the listings, `WRITE` adding and removing objects, `READ_ACP` and `WRITE_ACP` the bucket ACL. Contributed by @iot-rocket.
- **CloudTrail — `RecursiveLogging` on trails** — `CreateTrail` and `UpdateTrail` ignored `RecursiveLogging` and no trail response carried it; trails now store it (default `true`, kept by an `UpdateTrail` that leaves it out) and return it from `CreateTrail`, `UpdateTrail`, `GetTrail` and `DescribeTrails`. Contributed by @iot-rocket.
diff --git a/ministack/core/appsync_graphql.py b/ministack/core/appsync_graphql.py
index a3c97901..2e0bb090 100644
--- a/ministack/core/appsync_graphql.py
+++ b/ministack/core/appsync_graphql.py
@@ -63,6 +63,10 @@ class SchemaUnavailable(Exception):
"""The API has no usable schema, so nothing can be validated or executed."""
+class QuerySyntaxError(Exception):
+ """The request's query is not a parseable GraphQL document."""
+
+
def build_api_schema(api_id: str, sdl: str) -> GraphQLSchema:
"""Build (and cache) the executable schema for an API."""
key = (len(sdl), hash(sdl))
@@ -121,7 +125,7 @@ def execute(api_id, sdl, query, variables, operation_name, field_resolver, conte
try:
document = parse(query)
except GraphQLError as exc:
- return None, _as_appsync_errors([exc])
+ raise QuerySyntaxError(exc.message) from exc
# Validation is the step the regex could never do: an unknown field or a
# mistyped variable is refused here instead of resolving to null.
diff --git a/ministack/services/appsync.py b/ministack/services/appsync.py
index 4fd940fa..1f906d3a 100644
--- a/ministack/services/appsync.py
+++ b/ministack/services/appsync.py
@@ -1064,8 +1064,7 @@ async def handle_request(method, path, headers, body, query_params):
if path == "/graphql" and method == "POST":
api_id = _api_from_graphql_host(headers, query_params)
if not api_id and _graphql_host_names_event_api(headers):
- return _json(404, {"errors": [{
- "errorType": "ResourceNotFoundException", "message": "Unable to find the Api."}]})
+ return _graphql_error(404, "ResourceNotFoundException", "Unable to find the Api.")
if not api_id:
api_id = _resolve_api_by_key(
headers.get("x-api-key", ""),
@@ -1073,7 +1072,9 @@ async def handle_request(method, path, headers, body, query_params):
)
if not api_id:
return error_response_json("UnauthorizedException", "Valid API key required", 401)
- data = json.loads(body) if body else {}
+ data = _graphql_request(body)
+ if data is None:
+ return _malformed_graphql_request("Invalid JSON payload in GraphQLAuth POST request.")
# Resolver execution blocks — an HTTP or Lambda data source may call
# back into ministack, and a nested request cannot be served while
# the event loop waits on it. Run it on a worker thread.
@@ -1085,7 +1086,9 @@ async def handle_request(method, path, headers, body, query_params):
api_id = parts[3]
if not _has_sigv4_credentials(headers, query_params):
_select_api_region(api_id)
- data = json.loads(body) if body else {}
+ data = _graphql_request(body)
+ if data is None:
+ return _malformed_graphql_request("Invalid JSON payload in GraphQLAuth POST request.")
# Resolver execution blocks — an HTTP or Lambda data source may call
# back into ministack, and a nested request cannot be served while
# the event loop waits on it. Run it on a worker thread.
@@ -1475,15 +1478,31 @@ def _invoke_lambda_authorizer(
return {}
+def _graphql_error(status, error_type, message):
+ """A GraphQL endpoint refusal: an `errors` envelope plus the `x-amzn-ErrorType` header."""
+ status, headers, body = _json(status, {"errors": [{"errorType": error_type, "message": message}]})
+ return status, {**headers, "x-amzn-errortype": error_type}, body
+
+
+def _graphql_request(body):
+ """The decoded GraphQL request body, or None when it is not a JSON object."""
+ if not body:
+ return {}
+ try:
+ data = json.loads(body)
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ return None
+ return data if isinstance(data, dict) else None
+
+
+def _malformed_graphql_request(message):
+ return _graphql_error(400, "MalformedHttpRequestException", message)
+
+
def _unauthorized_response():
"""AppSync's wire-shape for an authorizer rejection: HTTP 401 with a
GraphQL `errors` envelope carrying `UnauthorizedException`."""
- return _json(401, {
- "errors": [{
- "errorType": "UnauthorizedException",
- "message": "You are not authorized to make this call.",
- }],
- })
+ return _graphql_error(401, "UnauthorizedException", "You are not authorized to make this call.")
def _auth_modes(api):
@@ -1571,6 +1590,8 @@ def _execute_with_schema(api_id, sdl, query, variables, operation_name, request_
api_id, sdl, query, variables, operation_name, field_resolver, None)
except appsync_graphql.SchemaUnavailable as exc:
return _json(200, {"data": None, "errors": [{"message": str(exc)}]})
+ except appsync_graphql.QuerySyntaxError:
+ return _malformed_graphql_request("Unable to parse GraphQL query.")
# util.appendError is non-fatal and rides alongside the data.
for a in appended:
@@ -1588,8 +1609,10 @@ def _execute_graphql(api_id, data, request_headers=None):
variables = data.get("variables", {})
operation_name = data.get("operationName")
+ if data.get("query") is None:
+ return _malformed_graphql_request("Invalid request, `query` can't be null.")
if not query.strip():
- return _json(400, {"errors": [{"message": "Query is required"}]})
+ return _malformed_graphql_request("Invalid request, `query` can't be empty.")
if api_id not in _apis:
return _json(404, {"errors": [{"message": f"API {api_id} not found"}]})
diff --git a/ministack/services/appsync_events.py b/ministack/services/appsync_events.py
index 96b72e84..b6ad76b5 100644
--- a/ministack/services/appsync_events.py
+++ b/ministack/services/appsync_events.py
@@ -30,6 +30,7 @@ import time
from ministack.core.concurrency import run_reentrant
from ministack.core.responses import (
+ REST_JSON_CONTENT_TYPE,
AccountRegionScopedDict,
AccountScopedDict,
error_response_json,
@@ -301,6 +302,17 @@ def _not_found(msg: str):
return error_response_json("NotFoundException", msg, 404)
+def _publish_error(status: int, error_type: str, message: str | None = None):
+ """An HTTP publish refusal in the data plane's ``errors`` envelope."""
+ error = {"errorType": error_type, **({"message": message} if message else {})}
+ headers = {"Content-Type": REST_JSON_CONTENT_TYPE, "x-amzn-errortype": error_type}
+ return status, headers, json.dumps({"errors": [error]}).encode("utf-8")
+
+
+def _publish_api_not_found():
+ return _publish_error(404, "ResourceNotFoundException", "Unable to find the Api.")
+
+
# ---------------------------------------------------------------------------
# Channel validation + matching (subscribe pattern -> publish channel)
# ---------------------------------------------------------------------------
@@ -597,6 +609,9 @@ async def handle_request(method, path, headers, body, query_params):
if path.startswith("/v2/apis"):
return await _handle_mgmt(method, path, headers, body, query_params)
+ if host_match:
+ return _publish_error(404, "UnknownOperationException", "Unknown Operation Request.")
+
return error_response_json("BadRequestException", f"Unsupported AppSync Events path: {path}", 400)
@@ -902,7 +917,7 @@ async def _publish_from_host(
api_scope = _discover_api_scope(api_id, get_account_id())
if api_scope is None:
- return _not_found(f"Api {api_id} not found")
+ return _publish_api_not_found()
from ministack.core.responses import _request_region
@@ -913,7 +928,7 @@ async def _publish_from_host(
and host_region is not None
and api_scope[1] != host_region
):
- return _not_found(f"Api {api_id} not found")
+ return _publish_api_not_found()
return await _publish(api_id, headers, body)
finally:
_request_region.reset(region_token)
@@ -921,48 +936,43 @@ async def _publish_from_host(
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")
+ return _publish_api_not_found()
- data, err = _parse_json_body(body)
- if err:
- return err
+ try:
+ data = json.loads(body) if body else {}
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ return _publish_error(400, "SerializationException", "Unable to parse request body")
+ if not isinstance(data, dict):
+ return _publish_error(400, "BadRequestException", "Request body must be a JSON object")
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,
- )
+ if events is not None and not isinstance(events, list):
+ return _publish_error(400, "SerializationException", "Expected list or null")
+ if not channel:
+ return _publish_error(400, "BadRequestException", "Missing channel")
+ if events is None:
+ return _publish_error(400, "BadRequestException", "Missing events")
# AWS spec: max 5 events per publish.
if len(events) > _MAX_EVENTS_PER_BATCH:
- return error_response_json(
- "BadRequestException",
- f"events array may contain at most {_MAX_EVENTS_PER_BATCH} entries",
- 400,
- )
+ return _publish_error(
+ 400, "BadRequestException", f"Input exceeded {_MAX_EVENTS_PER_BATCH} event limit")
- channel_err = _validate_channel(channel, allow_wildcard=False)
- if channel_err:
- return error_response_json("BadRequestException", channel_err, 400)
+ if _validate_channel(channel, allow_wildcard=False):
+ return _publish_error(400, "BadRequestException", "Invalid Channel Format")
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,
- )
+ return _publish_error(401, "UnauthorizedException")
ok, message = await _authorize_event_op(
api_id, str(channel), EVENT_PUBLISH, _auth_from_headers(headers), headers
)
if not ok:
- return error_response_json("UnauthorizedException", message or "Unauthorized", 401)
+ return _publish_error(401, "UnauthorizedException", message or "Unauthorized")
successful, failed = await _fanout_publish(api_id, channel, events)
- return json_response({"successful": successful, "failed": failed})
+ return json_response({"successful": successful, "failed": failed}, content_type=REST_JSON_CONTENT_TYPE)
async def _fanout_publish(api_id: str, channel: str, events: list) -> tuple[list, list]:
diff --git a/tests/test_appsync.py b/tests/test_appsync.py
index 4599d1d6..8cd767a6 100644
--- a/tests/test_appsync.py
+++ b/tests/test_appsync.py
@@ -208,6 +208,27 @@ def test_appsync_graphql_on_an_event_api_host_is_not_found():
west.delete_api(apiId=api["apiId"])
+def test_appsync_graphql_on_an_event_api_host_names_its_error_type():
+ west = _client("us-west-2")
+ mode = [{"authType": "API_KEY"}]
+ api = west.create_api(name="host-events-type", eventConfig={
+ "authProviders": mode, "connectionAuthModes": mode,
+ "defaultPublishAuthModes": mode, "defaultSubscribeAuthModes": mode,
+ })["api"]
+ key = west.create_api_key(apiId=api["apiId"])["apiKey"]["id"]
+ req = urllib.request.Request(f"{_ENDPOINT}/graphql", data=b'{"query": "{ __typename }"}', method="POST", headers={
+ "Host": f"{api['apiId']}.appsync-api.us-west-2.{_ENDPOINT_NETLOC}",
+ "Content-Type": "application/json", "x-api-key": key})
+ try:
+ with pytest.raises(urllib.error.HTTPError) as exc:
+ urllib.request.urlopen(req, timeout=10)
+ assert exc.value.code == 404
+ assert exc.value.headers["x-amzn-ErrorType"] == "ResourceNotFoundException"
+ assert exc.value.headers["Content-Type"] == "application/json"
+ finally:
+ west.delete_api(apiId=api["apiId"])
+
+
def test_appsync_graphql_honors_dynamodb_data_source_region():
east_ddb = boto3.client(
"dynamodb",
@@ -652,6 +673,50 @@ def test_appsync_graphql_empty_query():
assert e.code == 400
+def _graphql_raw(api_id, body, headers=None):
+ """POST raw bytes to an API's GraphQL endpoint; return status, headers and decoded body."""
+ req = urllib.request.Request(
+ f"{_ENDPOINT}/v1/apis/{api_id}/graphql", data=body, method="POST",
+ headers={"Content-Type": "application/json", **(headers or {})})
+ try:
+ with urllib.request.urlopen(req, timeout=10) as r:
+ return r.status, r.headers, json.loads(r.read())
+ except urllib.error.HTTPError as e:
+ return e.code, e.headers, json.loads(e.read())
+
+
[email protected]("body, message", [
+ (b"{not json", "Invalid JSON payload in GraphQLAuth POST request."),
+ (b'[{"query": "{ hello }"}]', "Invalid JSON payload in GraphQLAuth POST request."),
+ (b'{"variables": {}}', "Invalid request, `query` can't be null."),
+ (b'{"query": ""}', "Invalid request, `query` can't be empty."),
+ (b'{"query": "{ hello "}', "Unable to parse GraphQL query."),
+])
+def test_appsync_graphql_malformed_request_refused(appsync, body, message):
+ api_id = appsync.create_graphql_api(name="gql-malformed", authenticationType="API_KEY")["graphqlApi"]["apiId"]
+ appsync.start_schema_creation(apiId=api_id, definition=b"type Query { hello: String }")
+ key = appsync.create_api_key(apiId=api_id)["apiKey"]["id"]
+ try:
+ status, headers, doc = _graphql_raw(api_id, body, {"x-api-key": key})
+ assert status == 400
+ assert headers["x-amzn-ErrorType"] == "MalformedHttpRequestException"
+ assert headers["Content-Type"] == "application/json"
+ assert doc == {"errors": [{"errorType": "MalformedHttpRequestException", "message": message}]}
+ finally:
+ appsync.delete_graphql_api(apiId=api_id)
+
+
+def test_appsync_graphql_refusal_names_its_error_type(appsync):
+ api_id = appsync.create_graphql_api(name="gql-unauth", authenticationType="API_KEY")["graphqlApi"]["apiId"]
+ try:
+ status, headers, doc = _graphql_raw(api_id, b'{"query": "{ hello }"}')
+ assert status == 401
+ assert headers["x-amzn-ErrorType"] == "UnauthorizedException"
+ assert doc["errors"][0]["errorType"] == "UnauthorizedException"
+ finally:
+ appsync.delete_graphql_api(apiId=api_id)
+
+
# ---------------------------------------------------------------------------
# AppSync Lambda resolver event shape — verifies full AppSyncResolverEvent is built.
# ---------------------------------------------------------------------------
diff --git a/tests/test_appsync_events.py b/tests/test_appsync_events.py
index 9d1fde60..224c449a 100644
--- a/tests/test_appsync_events.py
+++ b/tests/test_appsync_events.py
@@ -285,6 +285,20 @@ def _publish_http(
return resp.status, json.loads(data) if data else None
+def _event_host_request(api_id, method, path, body: bytes):
+ """Send ``body`` to ``path`` on the API's appsync-api host; return status, headers and decoded body."""
+ conn = http.client.HTTPConnection("127.0.0.1", _PORT, timeout=5)
+ 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",
+ })
+ resp = conn.getresponse()
+ data = resp.read()
+ conn.close()
+ return resp.status, resp.headers, 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.
@@ -550,15 +564,50 @@ def test_publish_returns_identifiers(api):
assert {item["index"] for item in body["successful"]} == {0, 1}
+def test_publish_answers_application_json(api):
+ payload = json.dumps({"channel": "/default/room1", "events": [json.dumps("x")]}).encode()
+ status, headers, body = _event_host_request(api, "POST", "/event", payload)
+ assert status == 200
+ assert headers["Content-Type"] == "application/json"
+ assert len(body["successful"]) == 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"
+ assert body == {"errors": [{"errorType": "UnauthorizedException"}]}
+
+
[email protected]("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"),
+ (b'{"events": ["1"]}', 400, "BadRequestException", "Missing channel"),
+ (b'{"channel": "default/a"}', 400, "BadRequestException", "Missing events"),
+ (json.dumps({"channel": "default/a", "events": ["1"] * 6}).encode(), 400, "BadRequestException",
+ "Input exceeded 5 event limit"),
+ (b'{"channel": "default/a b", "events": ["1"]}', 400, "BadRequestException", "Invalid Channel Format"),
+ (b'{"channel": "default/*", "events": ["1"]}', 400, "BadRequestException", "Invalid Channel Format"),
+])
+def test_publish_refusal_uses_the_errors_envelope(api, payload, status, error_type, message):
+ got_status, headers, body = _event_host_request(api, "POST", "/event", payload)
+ assert got_status == status
+ assert headers["x-amzn-ErrorType"] == error_type
+ assert headers["Content-Type"] == "application/json"
+ assert body == {"errors": [{"errorType": error_type, "message": message}]}
def test_publish_unknown_api_404():
status, body = _publish_http("deadbeefdeadbeefdeadbeefde", "/default/x", [json.dumps("x")])
assert status == 404
+ assert body == {"errors": [{"errorType": "ResourceNotFoundException", "message": "Unable to find the Api."}]}
+
+
[email protected]("method, path", [("GET", "/event"), ("POST", "/other")])
+def test_event_api_host_unknown_operation(api, method, path):
+ status, headers, body = _event_host_request(api, method, path, b"{}")
+ assert status == 404
+ assert headers["x-amzn-ErrorType"] == "UnknownOperationException"
+ assert body == {"errors": [{"errorType": "UnknownOperationException", "message": "Unknown Operation Request."}]}
def test_detect_service_post_event_appsync_api_vhost_returns_appsync_events():
@@ -1355,14 +1404,14 @@ 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"]
+ assert body["errors"][0]["errorType"] == "BadRequestException"
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"]
+ assert body["errors"][0]["errorType"] == "BadRequestException"
def test_subscribe_rejects_invalid_channel_path(api):