Skip to content

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

fix(auth): authorize API Gateway and AppSync calls by the API's own authorization under AUTH=true (#2280)

iot-rocket2578c60faf4a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ab099a8f..1078bb01 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,11 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Fixed
+- **AppSync — GraphQL requests under `AUTH=true` follow the API's authentication type** — a GraphQL call to `/v1/apis/{apiId}/graphql` signed with an IAM key was authorized as `appsync:UpdateGraphqlApi` whatever the API's authentication type, and the API's own host served an `AWS_IAM` API to any signed call; an API key request now ignores its signature, and a SigV4 request to an `AWS_IAM` API is authorized on both endpoints as `appsync:GraphQL` on each top-level field, answering 401 `Permission denied` when no field is allowed, a field error for each denied one, and 400 `BadRequestException` for a wrong signature. Contributed by @iot-rocket.
+- **Auth — a signed call to a REST API method without authorization is anonymous to the API policy** — under `AUTH=true` a SigV4-signed call to a method whose `authorizationType` is `NONE` was judged as its signer, so a user the API policy names, or one whose identity policy allows the invoke, got through; API Gateway evaluates every call to such a method as anonymous, signed or not, and now so does MiniStack, answering `ACCESS_DENIED` unless the policy allows everyone. Contributed by @iot-rocket.
+- **API Gateway — methods without `AWS_IAM` authorization read no credentials under `AUTH=true`** — a REST method with `NONE` or `COGNITO_USER_POOLS` authorization, or an HTTP API route without authorization, refused a SigV4-signed caller whose policies did not allow `execute-api:Invoke` or whose signature failed; such a call now reaches the method, and its own authorizer if it has one, whatever it is signed with. Contributed by @iot-rocket.
+- **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.
### Added
- **Auth — bucket policies see S3's request condition keys under `AUTH=true`** — `s3:x-amz-server-side-encryption`, `s3:x-amz-acl` and `s3:ExistingObjectTag/<key>` were absent from every request but a signed browser POST, so the common "require encryption" Deny refused even an `AES256` upload; a write now carries its encryption and canned ACL headers (an upload part and the completion the encryption header of their `CreateMultipartUpload`), and `GetObject` / `HeadObject` the object's tags, for bucket and identity policies alike. Contributed by @iot-rocket.
### Fixed
diff --git a/ministack/app.py b/ministack/app.py
index 5dd7962c..753199da 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -60,6 +60,8 @@ _LAMBDA_URL_RE = re.compile(r"^([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})\.la
_AOSS_COLLECTION_HOST_RE = re.compile(r"^[a-z0-9]{3,40}\.[a-z0-9-]+\.aoss\.", re.IGNORECASE)
# AppSync Events realtime WebSocket: {apiId}.appsync-realtime-api.<anything>[:port].
_APPSYNC_REALTIME_RE = re.compile(r"^([a-z0-9]+)\.appsync-realtime-api\.")
+# AppSync GraphQL data plane: POST /v1/apis/{apiId}/graphql.
+_APPSYNC_GRAPHQL_RE = re.compile(r"^/v1/apis/[^/]+/graphql$")
# IoT data plane WebSocket: anything containing ".iot." in the host header.
# Match AWS-shaped IoT hosts only — `iot.<region>.<host>`,
# `data-ats.iot.<region>.<host>`, `data.iot.<region>.<host>`, and the
@@ -1856,6 +1858,12 @@ def _parse_execute_api_url(host: str, path: str) -> tuple[str, str, str] | None:
return None
+def _execute_api_authorization_type(api_id: str, stage: str, method: str, execute_path: str) -> str | None:
+ """The authorization type of the REST method or HTTP API route an execute-api call reaches, or None."""
+ return (_get_module("apigateway_v1").method_authorization_type(api_id, stage, method, execute_path)
+ or _get_module("apigateway").route_authorization_type(api_id, stage, method, execute_path))
+
+
def _enforce_execute_api(api_id: str, stage: str, method: str, execute_path: str,
headers: dict, query_params: dict,
iam_action: str = "execute-api:Invoke"):
@@ -1877,6 +1885,10 @@ def _enforce_execute_api(api_id: str, stage: str, method: str, execute_path: str
from ministack.core.arn import execute_api_arn
from ministack.core.responses import get_account_id
+ # Only an AWS_IAM method reads the caller's signature and policies.
+ if AUTH and iam_action == "execute-api:Invoke" and _execute_api_authorization_type(
+ api_id, stage, method, execute_path) not in (None, "AWS_IAM"):
+ return None
return _enforce_data_plane(
"apigateway", iam_action, headers, query_params, "",
resource_arn=execute_api_arn(
@@ -2783,7 +2795,8 @@ async def _dispatch_service_request(
if service == "unknown_query":
return _unknown_query_error(body, request_id)
- if AUTH:
+ # AppSync authorizes a GraphQL request by the API's own authorization types.
+ if AUTH and not (service == "appsync" and method == "POST" and _APPSYNC_GRAPHQL_RE.match(path)):
from ministack.core.iam_actions import (
access_denied_response,
agentcore_endpoint_arn,
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index de83b056..9b5be9e7 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -61,6 +61,7 @@ from ministack.core.responses import (
get_account_id,
get_region,
new_uuid,
+ request_scope,
)
_HOST = os.environ.get("MINISTACK_HOST", "localhost")
@@ -1538,6 +1539,18 @@ def _match_route(api_id, method, path):
return None
+def route_authorization_type(api_id, stage, method, path):
+ """The authorizationType of the route an HTTP API request reaches, or None."""
+ scope = find_api_scope(api_id)
+ if scope is None:
+ return None
+ with request_scope(*scope):
+ if stage not in _stages.get(api_id, {}) and stage != "$default":
+ return None
+ route = _match_route(api_id, method, "/" + path.lstrip("/"))
+ return (route.get("authorizationType") or "NONE").upper() if route else None
+
+
def _extract_path_params(route_path: str, request_path: str) -> dict | None:
"""
Extract path parameter values from a request path using the route template.
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index c1511382..ff4cb1ac 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -932,12 +932,13 @@ def rest_api_policy_for_arn(resource_arn):
return policy, account_id
-def _anonymous_policy_error(api_id, stage_name, method, path, headers, account_id, region):
- """ACCESS_DENIED for a call without SigV4 that the REST API's resource policy does not allow."""
+def _anonymous_policy_error(api_id, stage_name, method, path, account_id, region):
+ """ACCESS_DENIED for a call to a method without authorization that the REST API's resource policy does not allow."""
from ministack.app import AUTH
from ministack.core.iam_evaluator import EvalContext, evaluate_resource_policy
- if not AUTH or _header_ci(headers, "authorization").startswith("AWS4-"):
+ # Such a call is anonymous even when it is signed.
+ if not AUTH:
return None
arn = execute_api_arn(region, account_id, api_id, stage_name, method, path)
policy = (rest_api_policy_for_arn(arn) or ("",))[0]
@@ -1594,6 +1595,25 @@ def authentication_error_response(api_id, stage_name, error, headers, query_para
return _gateway_error_response(_GatewayError(response_type, error.message, error_type), request)
+def method_authorization_type(api_id, stage_name, method, path):
+ """The authorizationType of the method a REST API stage serves for this request, or None."""
+ scope = find_api_scope(api_id)
+ if scope is None:
+ return None
+ segments = [s for s in path.strip("/").split("/") if s]
+ with request_scope(*scope):
+ if stage_name not in _stages_v1.get(api_id, {}):
+ return None
+ resource, _ = _match_resource_tree(api_id, segments)
+ methods = (resource or {}).get("resourceMethods", {})
+ method_obj = methods.get(method) or methods.get("ANY")
+ if not method_obj:
+ resource, _ = _match_greedy_fallback(api_id, segments, method)
+ methods = (resource or {}).get("resourceMethods", {})
+ method_obj = methods.get(method) or methods.get("ANY")
+ return (method_obj.get("authorizationType") or "NONE").upper() if method_obj else None
+
+
def _arn_matches(pattern, arn):
"""Match an IAM policy Resource against a method ARN, honoring `*`/`?` globs."""
regex = "^" + re.escape(pattern).replace(r"\*", ".*").replace(r"\?", ".") + "$"
@@ -1923,7 +1943,7 @@ async def _authorize_request_v1(
auth_type = (method_obj.get("authorizationType") or "NONE").upper()
if auth_type in ("", "NONE"):
return _anonymous_policy_error(
- api_id, stage_name, method, request_path, headers, owner_account_id, owner_region), None
+ api_id, stage_name, method, request_path, owner_account_id, owner_region), None
if auth_type == "AWS_IAM":
# Signatures are verified only under AUTH; here match AWS only to the extent
# that a request with no Authorization header is rejected as unauthenticated.
diff --git a/ministack/services/appsync.py b/ministack/services/appsync.py
index 1f906d3a..62ea4bd1 100644
--- a/ministack/services/appsync.py
+++ b/ministack/services/appsync.py
@@ -1072,13 +1072,16 @@ async def handle_request(method, path, headers, body, query_params):
)
if not api_id:
return error_response_json("UnauthorizedException", "Valid API key required", 401)
+ authorize = _iam_field_authorizer(api_id, headers, query_params)
+ if isinstance(authorize, tuple):
+ return authorize
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.
- return await asyncio.to_thread(_execute_graphql, api_id, data, headers)
+ return await asyncio.to_thread(_execute_graphql, api_id, data, headers, authorize)
if path.startswith("/v1/apis/") and path.endswith("/graphql") and method == "POST":
parts = path.split("/")
@@ -1086,13 +1089,16 @@ 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)
+ authorize = _iam_field_authorizer(api_id, headers, query_params)
+ if isinstance(authorize, tuple):
+ return authorize
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.
- return await asyncio.to_thread(_execute_graphql, api_id, data, headers)
+ return await asyncio.to_thread(_execute_graphql, api_id, data, headers, authorize)
m = _PATH_RE.match(path)
if not m:
@@ -1499,10 +1505,10 @@ def _malformed_graphql_request(message):
return _graphql_error(400, "MalformedHttpRequestException", message)
-def _unauthorized_response():
+def _unauthorized_response(message="You are not authorized to make this call."):
"""AppSync's wire-shape for an authorizer rejection: HTTP 401 with a
GraphQL `errors` envelope carrying `UnauthorizedException`."""
- return _graphql_error(401, "UnauthorizedException", "You are not authorized to make this call.")
+ return _graphql_error(401, "UnauthorizedException", message)
def _auth_modes(api):
@@ -1544,7 +1550,39 @@ def _request_is_authenticated(api_id, api, request_headers):
return False
-def _execute_with_schema(api_id, sdl, query, variables, operation_name, request_headers):
+def _iam_field_authorizer(api_id, headers, query_params):
+ """Under AUTH, authenticate a SigV4 request to an API that accepts AWS_IAM: its per-field check or a refusal."""
+ from ministack.app import AUTH
+
+ api = _apis.get(api_id)
+ if not AUTH or not api or "AWS_IAM" not in _auth_modes(api) or not _has_sigv4_credentials(headers, query_params):
+ return None
+ from ministack.core.iam_evaluator import AuthError, authenticate, enforce, resolve_principal
+ from ministack.core.router import extract_access_key_id
+
+ access_key, account_id, region = extract_access_key_id(headers, query_params), get_account_id(), get_region()
+ caller = authenticate(access_key, account_id)
+ if not isinstance(caller, AuthError):
+ caller = resolve_principal(access_key, account_id, caller)
+ if isinstance(caller, AuthError):
+ status, error_type = (400, "BadRequestException") if caller.code == "SignatureDoesNotMatch" else (
+ 403, caller.code)
+ return _graphql_error(status, error_type, caller.message)
+ arn = _api_arn(api_id)
+
+ def authorize(type_name, field_name):
+ return enforce(access_key, "appsync:GraphQL", "appsync", region,
+ resource_arn=f"{arn}/types/{type_name}/fields/{field_name}") is None
+
+ return authorize
+
+
+def _unauthorized_field(type_name, field_name):
+ """The error of a top-level field the IAM caller may not access."""
+ return _AppSyncResolverError(f"Not Authorized to access {field_name} on type {type_name}", "Unauthorized")
+
+
+def _execute_with_schema(api_id, sdl, query, variables, operation_name, request_headers, authorize=None):
"""Execute against the API's schema with the real GraphQL algorithm."""
from ministack.core import appsync_graphql
@@ -1561,11 +1599,16 @@ def _execute_with_schema(api_id, sdl, query, variables, operation_name, request_
return _unauthorized_response()
appended = []
+ checked = [] # whether the IAM caller may access each top-level field it asked for
def field_resolver(source, info, **args):
"""Called for every field graphql-core resolves."""
type_name = info.parent_type.name
field_name = info.field_name
+ if authorize is not None and info.path.prev is None:
+ checked.append(authorize(type_name, field_name))
+ if not checked[-1]:
+ raise _unauthorized_field(type_name, field_name)
resolver = (_resolvers.get(api_id) or {}).get(type_name, {}).get(field_name)
if resolver is None:
@@ -1592,6 +1635,12 @@ def _execute_with_schema(api_id, sdl, query, variables, operation_name, request_
return _json(200, {"data": None, "errors": [{"message": str(exc)}]})
except appsync_graphql.QuerySyntaxError:
return _malformed_graphql_request("Unable to parse GraphQL query.")
+ # An IAM caller allowed none of the top-level fields it asked for is refused as a whole;
+ # a request for nothing but __typename needs that field of the root type.
+ if authorize is not None and data is not None and not checked:
+ checked.append(authorize("Mutation" if query.lstrip().startswith("mutation") else "Query", "__typename"))
+ if authorize is not None and checked and not any(checked):
+ return _unauthorized_response("Permission denied")
# util.appendError is non-fatal and rides alongside the data.
for a in appended:
@@ -1603,7 +1652,7 @@ def _execute_with_schema(api_id, sdl, query, variables, operation_name, request_
return _json(200, body)
-def _execute_graphql(api_id, data, request_headers=None):
+def _execute_graphql(api_id, data, request_headers=None, authorize=None):
"""Execute a GraphQL query/mutation against the configured resolvers."""
query = data.get("query", "")
variables = data.get("variables", {})
@@ -1631,7 +1680,7 @@ def _execute_graphql(api_id, data, request_headers=None):
sdl = (_schemas.get(api_id) or {}).get("definition")
if sdl:
return _execute_with_schema(
- api_id, sdl, query, variables, operation_name, request_headers or {})
+ api_id, sdl, query, variables, operation_name, request_headers or {}, authorize)
# Parse the top-level operation
# Strip __typename fields — Amplify adds these everywhere
@@ -1672,7 +1721,16 @@ def _execute_graphql(api_id, data, request_headers=None):
results = {}
errors = []
+ allowed = []
for field_name, args, sub_fields in fields:
+ if authorize is not None:
+ root_type = "Mutation" if is_mutation else "Query"
+ if not authorize(root_type, field_name):
+ e = _unauthorized_field(root_type, field_name)
+ errors.append({"message": str(e), "errorType": e.error_type, "path": [field_name]})
+ results[field_name] = None
+ continue
+ allowed.append(field_name)
resolver = _find_resolver(api_id, "Mutation" if is_mutation else "Query", field_name)
if resolver:
# A mutation is never served from cache, and never populates it.
@@ -1727,6 +1785,10 @@ def _execute_graphql(api_id, data, request_headers=None):
# No resolver — return mock empty result
results[field_name] = None
+ # A request for nothing but __typename needs that field of the root type.
+ if authorize is not None and not allowed and (
+ fields or not authorize("Mutation" if is_mutation else "Query", "__typename")):
+ return _unauthorized_response("Permission denied")
response = {"data": results}
if errors:
response["errors"] = errors
diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.py
index 4b66068c..0010c8fd 100644
--- a/tests/test_apigatewayv1.py
+++ b/tests/test_apigatewayv1.py
@@ -1518,6 +1518,71 @@ def test_api_policy_treats_a_bearer_token_on_a_method_without_authorization_as_a
assert _invoke(api_id, "open", headers={"authorization": "Bearer abc.def.ghi"})[0] == 403
+def _contract_signing_credentials(user):
+ """A second access key of an ``iam_user`` for raw SigV4 calls, deleted before the fixture's cleanup."""
+ from botocore.credentials import Credentials
+
+ admin = make_client("iam")
+ key = admin.create_access_key(UserName=user.name)["AccessKey"]
+ try:
+ yield Credentials(key["AccessKeyId"], key["SecretAccessKey"])
+ finally:
+ admin.delete_access_key(UserName=user.name, AccessKeyId=key["AccessKeyId"])
+
+
+def _contract_invoke(api_id, path, credentials=None):
+ """GET /s/<path> of a deployed API over HTTP, SigV4-signed with *credentials* unless None."""
+ import urllib.error
+ import urllib.request
+
+ from botocore.auth import SigV4Auth
+ from botocore.awsrequest import AWSRequest
+
+ host = f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"
+ request = AWSRequest("GET", f"http://{host}/s/{path}", headers={"host": host})
+ if credentials:
+ SigV4Auth(credentials, "execute-api", "us-east-1").add_auth(request)
+ try:
+ with urllib.request.urlopen(urllib.request.Request(
+ request.url, headers=dict(request.headers.items()), method="GET"), timeout=10) as response:
+ return response.status, response.headers, response.read()
+ except urllib.error.HTTPError as exc:
+ return exc.code, exc.headers, exc.read()
+
+
+def test_api_policy_signed_call_on_a_method_without_authorization_contract(auth_enabled, iam_user, apigw_v1):
+ """A signed call to a NONE method meets the REST API policy as anonymous, even by the user it allows."""
+ user = iam_user(policy=_ALLOW_INVOKE)
+ api_id = apigw_v1.create_rest_api(
+ name=f"auth-none-{_uuid_mod.uuid4().hex[:8]}", policy=json.dumps(_api_policy(("Allow", {"AWS": user.arn}))),
+ )["id"]
+ try:
+ root_id = next(r["id"] for r in apigw_v1.get_resources(restApiId=api_id)["items"] if r["path"] == "/")
+ for part, authorization in (("iam", "AWS_IAM"), ("open", "NONE")):
+ resource_id = apigw_v1.create_resource(restApiId=api_id, parentId=root_id, pathPart=part)["id"]
+ method = {"restApiId": api_id, "resourceId": resource_id, "httpMethod": "GET"}
+ apigw_v1.put_method(**method, authorizationType=authorization)
+ apigw_v1.put_integration(
+ **method, type="MOCK", requestTemplates={"application/json": '{"statusCode": 200}'})
+ apigw_v1.put_method_response(**method, statusCode="200")
+ apigw_v1.put_integration_response(**method, statusCode="200")
+ apigw_v1.create_deployment(restApiId=api_id, stageName="s")
+ with _contract_signing_credentials(user) as credentials:
+ assert _contract_invoke(api_id, "iam", credentials)[0] == 200
+ for signer in (credentials, None):
+ status, headers, body = _contract_invoke(api_id, "open", signer)
+ if auth_enabled:
+ assert (status, headers.get("x-amzn-ErrorType")) == (403, "AccessDeniedException")
+ assert json.loads(body)["Message"].startswith(
+ "User: anonymous is not authorized to perform: execute-api:Invoke")
+ else:
+ assert status == 200
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
def test_apigwv1_execute_lambda_proxy_multi_value_headers(apigw_v1, lam):
"""Payload format 1.0 `multiValueHeaders` yields one header line per value.
@@ -4654,6 +4719,67 @@ def test_apigwv1_aws_iam_method_fills_caller_identity(apigw_v1, lam, cognito_idp
lam.delete_function(FunctionName=fname)
+def test_apigwv1_methods_without_aws_iam_read_no_credentials(auth_enabled, iam_user, apigw_v1, apigw, cognito_idp):
+ """NONE and COGNITO_USER_POOLS methods and an HTTP API route without authorization ignore the SigV4 signer."""
+ import http.client as _http
+
+ from botocore.auth import SigV4Auth
+ from botocore.awsrequest import AWSRequest
+ from botocore.credentials import Credentials
+
+ pool = cognito_idp.create_user_pool(PoolName="none-methods")["UserPool"]
+ api = apigw_v1.create_rest_api(name="none-methods")["id"]
+ http_api = apigw.create_api(Name="none-route", ProtocolType="HTTP")["ApiId"]
+ try:
+ root = apigw_v1.get_resources(restApiId=api)["items"][0]["id"]
+ authorizer = apigw_v1.create_authorizer(
+ restApiId=api, name="pool", type="COGNITO_USER_POOLS", providerARNs=[pool["Arn"]],
+ identitySource="method.request.header.Authorization")["id"]
+ for part, kind in ((None, "NONE"), ("cognito", "COGNITO_USER_POOLS"), ("iam", "AWS_IAM")):
+ resource = apigw_v1.create_resource(restApiId=api, parentId=root, pathPart=part)["id"] if part else root
+ method = {"restApiId": api, "resourceId": resource, "httpMethod": "GET"}
+ extra = {"authorizerId": authorizer} if kind == "COGNITO_USER_POOLS" else {}
+ apigw_v1.put_method(**method, authorizationType=kind, **extra)
+ apigw_v1.put_integration(
+ **method, type="MOCK", requestTemplates={"application/json": '{"statusCode": 200}'})
+ apigw_v1.put_method_response(**method, statusCode="200")
+ apigw_v1.put_integration_response(**method, statusCode="200", responseTemplates={"application/json": "{}"})
+ apigw_v1.create_deployment(restApiId=api, stageName="p")
+ integration = apigw.create_integration( # nothing listens there: reaching it answers 502
+ ApiId=http_api, IntegrationType="HTTP_PROXY", IntegrationMethod="GET", IntegrationUri="http://127.0.0.1:9",
+ PayloadFormatVersion="1.0")["IntegrationId"]
+ apigw.create_route(ApiId=http_api, RouteKey="GET /open", Target=f"integrations/{integration}")
+ apigw.create_stage(ApiId=http_api, StageName="$default", AutoDeploy=True)
+
+ def status(api_id, path, credentials):
+ host = f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}"
+ request = AWSRequest(method="GET", url=f"http://{host}{path}", headers={"Host": host})
+ SigV4Auth(credentials, "execute-api", "us-east-1").add_auth(request)
+ conn = _http.HTTPConnection("127.0.0.1", _EXECUTE_PORT, timeout=10)
+ try:
+ conn.request("GET", path, headers=dict(request.headers))
+ return conn.getresponse().status
+ finally:
+ conn.close()
+
+ allowed = iam_user(policy={"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "execute-api:Invoke", "Resource": "*"}]})
+ with _contract_signing_credentials(allowed) as allowed_key, \
+ _contract_signing_credentials(iam_user()) as bare_key:
+ assert status(api, "/p/iam", allowed_key) == 200
+ assert status(api, "/p/iam", bare_key) == (403 if auth_enabled else 200)
+ unknown = Credentials("AKIAUNKNOWNKEY000001", "secret")
+ for signer in (bare_key, Credentials(bare_key.access_key, "wrong-secret"), unknown):
+ assert status(api, "/p/", signer) == 200
+ assert status(api, "/p/cognito", signer) == 401
+ assert status(http_api, "/open", signer) == 502
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api)
+ apigw.delete_api(ApiId=http_api)
+ cognito_idp.delete_user_pool(UserPoolId=pool["Id"])
+
+
def _v1_signed_token(claims: dict) -> str:
"""Mint an RS256 token signed with the local Cognito pool key."""
import base64 as _b64
diff --git a/tests/test_appsync.py b/tests/test_appsync.py
index 8cd767a6..24868346 100644
--- a/tests/test_appsync.py
+++ b/tests/test_appsync.py
@@ -1,3 +1,4 @@
+import contextlib
import io
import json
import os
@@ -193,6 +194,150 @@ def test_appsync_graphql_host_reaches_the_api_it_names(host_shape):
west.delete_graphql_api(apiId=iam_api["apiId"])
+def graphql_auth_apis(appsync):
+ """An API_KEY and an AWS_IAM API serving Query.hello and Query.other, and the API_KEY API's key."""
+ apis = {}
+ try:
+ for mode in ("API_KEY", "AWS_IAM"):
+ apis[mode] = api = appsync.create_graphql_api(
+ name=f"gql-auth-{mode}", authenticationType=mode)["graphqlApi"]
+ appsync.start_schema_creation(
+ apiId=api["apiId"], definition=b"type Msg { v: String }\n"
+ b"type Query { hello(v: String): Msg other(v: String): Msg }")
+ appsync.create_data_source(apiId=api["apiId"], name="none", type="NONE")
+ for field in ("hello", "other"):
+ appsync.create_resolver(apiId=api["apiId"], typeName="Query", fieldName=field, dataSourceName="none")
+ yield apis, appsync.create_api_key(apiId=apis["API_KEY"]["apiId"])["apiKey"]["id"]
+ finally:
+ for api in apis.values():
+ appsync.delete_graphql_api(apiId=api["apiId"])
+
+
+def _graphql_signed(api_id, route, query='{ hello(v: "hi") { v } }', credentials=None, x_api_key=None):
+ """POST a query to /v1/apis/{apiId}/graphql or the API's own host, SigV4-signed with *credentials* unless None."""
+ from botocore.auth import SigV4Auth
+ from botocore.awsrequest import AWSRequest
+
+ headers = {"Content-Type": "application/json", **({"x-api-key": x_api_key} if x_api_key else {})}
+ if route == "host":
+ url, headers["Host"] = f"{_ENDPOINT}/graphql", f"{api_id}.appsync-api.us-east-1.{_ENDPOINT_NETLOC}"
+ else:
+ url = f"{_ENDPOINT}/v1/apis/{api_id}/graphql"
+ request = AWSRequest(method="POST", url=url, data=json.dumps({"query": query}).encode(), headers=headers)
+ if credentials:
+ SigV4Auth(credentials, "appsync", "us-east-1").add_auth(request)
+ req = urllib.request.Request(url, data=request.body, headers=dict(request.headers), method="POST")
+ try:
+ with urllib.request.urlopen(req, timeout=10) as r:
+ return r.status, json.loads(r.read())
+ except urllib.error.HTTPError as exc:
+ return exc.code, json.loads(exc.read())
+
+
+def _contract_signing_credentials(user):
+ """A second access key of an ``iam_user`` for raw SigV4 calls, deleted before the fixture's cleanup."""
+ from botocore.credentials import Credentials
+ from conftest import make_client
+
+ admin = make_client("iam")
+ key = admin.create_access_key(UserName=user.name)["AccessKey"]
+ try:
+ yield Credentials(key["AccessKeyId"], key["SecretAccessKey"])
+ finally:
+ admin.delete_access_key(UserName=user.name, AccessKeyId=key["AccessKeyId"])
+
+
+def _other_secret(credentials):
+ """The same access key id with a wrong secret."""
+ from botocore.credentials import Credentials
+
+ return Credentials(credentials.access_key, "wrong-secret")
+
+
+_HELLO = (200, {"data": {"hello": {"v": "hi"}}})
+
+
[email protected]("route", ["v1", "host"])
+def test_appsync_graphql_api_key_api_ignores_the_signature(auth_enabled, iam_user, graphql_auth_apis, route):
+ apis, api_key = graphql_auth_apis
+ api_id = apis["API_KEY"]["apiId"]
+ with _contract_signing_credentials(iam_user()) as credentials:
+ assert _graphql_signed(api_id, route, x_api_key=api_key) == _HELLO
+ for signer in (credentials, _other_secret(credentials)):
+ assert _graphql_signed(api_id, route, credentials=signer, x_api_key=api_key) == _HELLO
+ assert _graphql_signed(api_id, route, credentials=credentials) == (401, _UNAUTHORIZED)
+
+
[email protected]("route", ["v1", "host"])
+def test_appsync_graphql_aws_iam_api_authorizes_each_top_level_field(
+ auth_enabled, iam_user, graphql_auth_apis, route):
+ from botocore.credentials import Credentials
+
+ api = graphql_auth_apis[0]["AWS_IAM"]
+ hello = iam_user(policy={"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Action": "appsync:GraphQL", "Resource": f"{api['arn']}/types/Query/fields/hello"}]})
+ every = iam_user(policy={"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Action": "appsync:GraphQL", "Resource": f"{api['arn']}/*"}]})
+ with _contract_signing_credentials(hello) as hello_key, _contract_signing_credentials(every) as every_key, \
+ _contract_signing_credentials(iam_user()) as bare_key:
+ assert _graphql_signed(api["apiId"], route, credentials=hello_key) == _HELLO
+ root = Credentials("test", "test")
+ assert _graphql_signed(api["apiId"], route, '{ other(v: "hi") { v } }', credentials=root)[0] == 200
+ assert _graphql_signed(api["apiId"], route, "{ __typename }", credentials=every_key) == (
+ 200, {"data": {"__typename": "Query"}})
+ both = _graphql_signed(
+ api["apiId"], route, '{ hello(v: "hi") { v } other(v: "hi") { v } }', credentials=hello_key)
+ refused = [_graphql_signed(api["apiId"], route, credentials=bare_key),
+ _graphql_signed(api["apiId"], route, '{ other(v: "hi") { v } }', credentials=hello_key),
+ _graphql_signed(api["apiId"], route, "{ __typename }", credentials=hello_key)]
+ if auth_enabled:
+ denied = (401, {"errors": [{"errorType": "UnauthorizedException", "message": "Permission denied"}]})
+ assert refused == [denied] * 3
+ assert (both[0], both[1]["data"]) == (200, {"hello": {"v": "hi"}, "other": None})
+ assert [(e["errorType"], e["message"], e["path"]) for e in both[1]["errors"]] == [
+ ("Unauthorized", "Not Authorized to access other on type Query", ["other"])]
+ else:
+ assert [status for status, _body in refused] == [200] * 3
+ assert both == (200, {"data": {"hello": {"v": "hi"}, "other": {"v": "hi"}}})
+
+
[email protected]("route", ["v1", "host"])
+def test_appsync_graphql_aws_iam_api_authentication_failures(auth_enabled, iam_user, graphql_auth_apis, route):
+ from botocore.credentials import Credentials
+
+ api_id = graphql_auth_apis[0]["AWS_IAM"]["apiId"]
+ with _contract_signing_credentials(iam_user()) as credentials:
+ wrong = _graphql_signed(api_id, route, credentials=_other_secret(credentials))
+ unknown = _graphql_signed(api_id, route, credentials=Credentials("AKIAUNKNOWNKEY000001", "secret"))
+ if auth_enabled:
+ assert (wrong[0], wrong[1]["errors"][0]["errorType"]) == (400, "BadRequestException")
+ assert wrong[1]["errors"][0]["message"].startswith("The request signature we calculated does not match")
+ assert unknown == (403, {"errors": [{"errorType": "UnrecognizedClientException",
+ "message": "The security token included in the request is invalid."}]})
+ else:
+ assert wrong == unknown == _HELLO
+
+
[email protected]("route", ["v1", "host"])
+def test_appsync_graphql_aws_iam_api_without_schema_authorizes_the_caller(auth_enabled, iam_user, appsync, route):
+ from botocore.credentials import Credentials
+
+ api_id = appsync.create_graphql_api(name="gql-no-schema", authenticationType="AWS_IAM")["graphqlApi"]["apiId"]
+ try:
+ assert _graphql_signed(api_id, route, "{ hello }", credentials=Credentials("test", "test"))[0] == 200
+ with _contract_signing_credentials(iam_user()) as credentials:
+ assert _graphql_signed(api_id, route, "{ hello }", credentials=credentials)[0] == (
+ 401 if auth_enabled else 200)
+ finally:
+ appsync.delete_graphql_api(apiId=api_id)
+
+
def test_appsync_graphql_on_an_event_api_host_is_not_found():
west = _client("us-west-2")
mode = [{"authType": "API_KEY"}]
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 583215e7..0ec3bafa 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -1828,6 +1828,12 @@ class _NoApiModule:
def find_api_scope(api_id):
return None
+ @staticmethod
+ def method_authorization_type(api_id, stage, method, path):
+ return None
+
+ route_authorization_type = method_authorization_type
+
@staticmethod
async def handle_connections_api(method, api_id, stage, connection_id, body, headers):
return 200, {}, b""