Skip to content

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

fix(appsync): route GraphQL requests on the API's own host (#2200)

iot-rocket83437b175ce6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c71908f6..36a72057 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **AppSync — GraphQL requests on the API's own host** — a `POST /graphql` to `{apiId}.appsync-api.{region}.{host}`, the endpoint `uris.GRAPHQL` reports, was routed to AppSync Events when unsigned and found its API only by `x-api-key` when signed, so an `AWS_IAM` API could not be called there once a second API existed; the host label now selects the API (in the host's region for an unsigned request) and `/graphql` on an Event API host answers `404 ResourceNotFoundException`, as on AWS. Contributed by @iot-rocket.
- **Cognito — no ID token without `openid`** — the `/oauth2/token` authorization code and refresh token grants returned an `id_token` whatever was granted; they now return one only when the grant carries `openid`, as AWS does, and a refresh token from `InitiateAuth` or `AdminInitiateAuth` still gets one. Contributed by @iot-rocket.
- **Cognito — token endpoint access tokens carry the granted scopes** — `/oauth2/token` wrote `aws.cognito.signin.user.admin` into every access token whatever was granted; the authorization code, client credentials and refresh token grants now write the requested scopes the app client allows (all of them when none are requested, only resource server scopes for client credentials) in the order AWS lists them, refreshed tokens keep the original scopes, and the pre token generation event's `request.scopes` lists them, so API Gateway scope checks decide as on AWS. Contributed by @iot-rocket.
- **S3 — object ACL grants answer another account's read** — a bucket owned by another account refused every read that only the object ACL granted: the ACL was looked up under the wrong version, and a grant to the caller's canonical ID was never read. With ACLs enabled, a `READ` grant to the account or a group now opens `GetObject` and `HeadObject` of the version it was set on, `?versionId=` included, and `READ_ACP` opens `GetObjectAcl`; a grant to one account is not public, so Block Public Access leaves it in force. Contributed by @iot-rocket.
diff --git a/ministack/core/router.py b/ministack/core/router.py
index ec6929d8..4d39db11 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -711,6 +711,9 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
# win before credential-scope routing.
if method == "POST" and path == "/event" and re.search(r"\.appsync-api\.", host):
return "appsync-events"
+ # GraphQL requests use the same host family with the fixed "/graphql" path.
+ if method == "POST" and path == "/graphql" and re.search(r"\.appsync-api\.", host):
+ return "appsync"
# 2. Check Authorization header for service name in credential scope
if auth:
diff --git a/ministack/services/appsync.py b/ministack/services/appsync.py
index 5c651901..4fd940fa 100644
--- a/ministack/services/appsync.py
+++ b/ministack/services/appsync.py
@@ -118,6 +118,37 @@ def _select_api_region(api_id):
return True
+# {apiId}.appsync-api[.{region}].{host}, the endpoint uris.GRAPHQL reports.
+_GRAPHQL_HOST_RE = re.compile(r"^([a-z0-9]+)\.appsync-api(?:\.([a-z0-9]+(?:-[a-z0-9]+)+-\d+))?(?:[.:]|$)")
+
+
+def _api_from_graphql_host(headers, query_params):
+ """Return the API named by the request host's first label and select its region, or None."""
+ m = _GRAPHQL_HOST_RE.match(str(headers.get("host") or "").lower())
+ if not m:
+ return None
+ api_id, host_region = m.groups()
+ if _has_sigv4_credentials(headers, query_params):
+ return api_id if api_id in _apis else None
+ if host_region is None:
+ return api_id if _select_api_region(api_id) else None
+ account_id = get_account_id()
+ for (stored_account, region, stored_api_id), _api in _apis.all_items():
+ if stored_account == account_id and region == host_region and stored_api_id == api_id:
+ set_request_region(region)
+ return api_id
+ return None
+
+
+def _graphql_host_names_event_api(headers):
+ """Whether the request host's first label is an AppSync Events API of this account."""
+ m = _GRAPHQL_HOST_RE.match(str(headers.get("host") or "").lower())
+ if not m:
+ return False
+ from ministack.services import appsync_events
+ return appsync_events._discover_api_scope(m.group(1), get_account_id()) is not None
+
+
def _has_sigv4_credentials(headers, query_params):
"""Return whether the data request carries an explicit SigV4 region."""
query_params = query_params or {}
@@ -1031,11 +1062,15 @@ async def handle_request(method, path, headers, body, query_params):
# GraphQL data plane: POST /graphql or POST /v1/apis/{apiId}/graphql
if path == "/graphql" and method == "POST":
- api_key = headers.get("x-api-key", "")
- api_id = _resolve_api_by_key(
- api_key,
- allow_cross_region=not _has_sigv4_credentials(headers, query_params),
- )
+ 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."}]})
+ if not api_id:
+ api_id = _resolve_api_by_key(
+ headers.get("x-api-key", ""),
+ allow_cross_region=not _has_sigv4_credentials(headers, query_params),
+ )
if not api_id:
return error_response_json("UnauthorizedException", "Valid API key required", 401)
data = json.loads(body) if body else {}
diff --git a/tests/test_appsync.py b/tests/test_appsync.py
index b0716bd0..4599d1d6 100644
--- a/tests/test_appsync.py
+++ b/tests/test_appsync.py
@@ -150,6 +150,64 @@ def test_appsync_signed_root_graphql_request_uses_current_region_fallback():
west.delete_graphql_api(apiId=api["apiId"])
+def _graphql_host_post(host, headers=None, sign=False):
+ """POST { __typename } (no schema, so data is {}) with this Host header; return (status, body)."""
+ headers = {"Host": host, **(headers or {})}
+ if sign:
+ headers["Authorization"] = (
+ "AWS4-HMAC-SHA256 Credential=test/20261012/us-west-2/appsync/aws4_request, "
+ "SignedHeaders=host;x-amz-date, Signature=fake"
+ )
+ try:
+ return 200, _appsync_graphql_post(f"{_ENDPOINT}/graphql", "{ __typename }", headers=headers)
+ except urllib.error.HTTPError as exc:
+ return exc.code, json.loads(exc.read())
+
+
+_UNAUTHORIZED = {"errors": [{
+ "errorType": "UnauthorizedException", "message": "You are not authorized to make this call."}]}
+
+
[email protected]("host_shape", ["region", "uris", "no_region"])
+def test_appsync_graphql_host_reaches_the_api_it_names(host_shape):
+ west = _client("us-west-2")
+ key_api = west.create_graphql_api(name="host-key", authenticationType="API_KEY")["graphqlApi"]
+ iam_api = west.create_graphql_api(name="host-iam", authenticationType="AWS_IAM")["graphqlApi"]
+ key = west.create_api_key(apiId=key_api["apiId"])["apiKey"]["id"]
+
+ def host(api):
+ if host_shape == "uris":
+ return urlparse(api["uris"]["GRAPHQL"]).netloc
+ region = ".us-west-2" if host_shape == "region" else ""
+ return f"{api['apiId']}.appsync-api{region}.{_ENDPOINT_NETLOC}"
+
+ try:
+ assert _graphql_host_post(host(key_api), {"x-api-key": key}) == (200, {"data": {}})
+ assert _graphql_host_post(host(key_api)) == (401, _UNAUTHORIZED)
+ assert _graphql_host_post(host(iam_api), sign=True) == (200, {"data": {}})
+ assert _graphql_host_post(host(iam_api)) == (401, _UNAUTHORIZED)
+ assert _graphql_host_post(host(iam_api), {"x-api-key": key}) == (401, _UNAUTHORIZED)
+ assert _graphql_host_post(host(iam_api), {"x-api-key": key}, sign=True) == (200, {"data": {}})
+ finally:
+ west.delete_graphql_api(apiId=key_api["apiId"])
+ west.delete_graphql_api(apiId=iam_api["apiId"])
+
+
+def test_appsync_graphql_on_an_event_api_host_is_not_found():
+ west = _client("us-west-2")
+ mode = [{"authType": "API_KEY"}]
+ api = west.create_api(name="host-events", eventConfig={
+ "authProviders": mode, "connectionAuthModes": mode,
+ "defaultPublishAuthModes": mode, "defaultSubscribeAuthModes": mode,
+ })["api"]
+ key = west.create_api_key(apiId=api["apiId"])["apiKey"]["id"]
+ try:
+ assert _graphql_host_post(f"{api['apiId']}.appsync-api.us-west-2.{_ENDPOINT_NETLOC}", {"x-api-key": key}) == (
+ 404, {"errors": [{"errorType": "ResourceNotFoundException", "message": "Unable to find the Api."}]})
+ finally:
+ west.delete_api(apiId=api["apiId"])
+
+
def test_appsync_graphql_honors_dynamodb_data_source_region():
east_ddb = boto3.client(
"dynamodb",
diff --git a/tests/test_router.py b/tests/test_router.py
index ddb7b80b..721c3645 100644
--- a/tests/test_router.py
+++ b/tests/test_router.py
@@ -308,6 +308,23 @@ def test_aws_shaped_hosts_route_as_before(host, expected):
assert detect_service("GET", "/status", {"host": host}, {}) == expected
+ "abcd1234.appsync-api.eu-central-1.amazonaws.com",
+ "abcd1234.appsync-api.us-east-1.localhost:4566",
+ "abcd1234.appsync-api.localhost:4566",
+])
[email protected]("signed", [False, True])
+def test_appsync_api_hosts_route_graphql_to_appsync_and_event_to_events(host, signed):
+ headers = {"host": host}
+ if signed:
+ headers["authorization"] = (
+ "AWS4-HMAC-SHA256 Credential=test/20261012/us-east-1/appsync/aws4_request, "
+ "SignedHeaders=host, Signature=x"
+ )
+ assert detect_service("POST", "/graphql", headers, {}) == "appsync"
+ assert detect_service("POST", "/event", headers, {}) == "appsync-events"
+
+
@pytest.mark.parametrize("host", [
"probe.iot.example.com",
"logs.example.com",