Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(apigateway): gateway responses, AWS error answers and MOCK status selection (#1756)
iot-rocket761c42e3fa57
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1852e761..5cd80841 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,11 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Fixed+- **IAM — three calls are authorized against the action and resource AWS uses** — a Lambda Function URL invoke is checked against its function ARN, alias qualifier included, and supplies `lambda:FunctionUrlAuthType`, so the policy `grantInvokeUrl` writes matches. The WebSocket `@connections` API asks for `execute-api:ManageConnections` instead of `execute-api:Invoke`. `iot-jobs-data` operations are authorized under `iotjobsdata:`, except `StartCommandExecution`, which stays on `iot:`. A policy written for the old action names stops matching, as on AWS. Contributed by @iot-rocket.+- **API Gateway — REST API gateway responses reach the data plane** — a customized gateway response was stored but never applied, so a 401 or 403 from the gateway carried none of the CORS headers a CDK stack declares for it. Gateway errors now resolve the response for their type, then `DEFAULT_4XX` or `DEFAULT_5XX`, then the built-in default, from the stage's last deployment, with header mappings, the `application/json` template and `x-amzn-ErrorType`. `GetGatewayResponse` reports an inherited `DEFAULT_4XX` or `DEFAULT_5XX`, and a response put without templates stores the default one. Contributed by @iot-rocket.+- **API Gateway — REST API gateway errors answer with the AWS status and message** — an authorizer that raised, a missing Lambda and an unreachable HTTP backend answered with invented statuses and exception text, and an unknown stage with `404`. They now answer `500` `AUTHORIZER_FAILURE` with a null message, `500` `API_CONFIGURATION_ERROR` with `Internal server error`, and `403` `Forbidden`; an explicit Deny carries the full AWS sentence, and a TOKEN authorizer policy without `principalId` is evaluated instead of refused. Contributed by @iot-rocket.+- **API Gateway — a MOCK integration honours its `statusCode`** — the `200` integration response was used whatever the request template set, so a MOCK method modelling an error returned `200`. The template's `statusCode` now selects the integration response by `selectionPattern`. Contributed by @iot-rocket.## [1.5.13] — 2026-09-17### Addeddiff --git a/ministack/app.py b/ministack/app.pyindex 18ce9611..18207549 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -1881,7 +1881,8 @@ def _with_data_plane_headers(response, request_id: str, include_s3_id: bool = Fastatus, headers, body = responseif wildcard_cors and "Access-Control-Allow-Origin" not in headers:headers["Access-Control-Allow-Origin"] = "*"- headers["x-amzn-requestid"] = request_id+ # An API Gateway gateway response already carries the id it rendered.+ request_id = headers.setdefault("x-amzn-requestid", request_id)headers["x-amz-request-id"] = request_idif include_s3_id:headers["x-amz-id-2"] = base64.b64encode(os.urandom(48)).decode()diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.pyindex f38eb2ca..f594ad93 100644--- a/ministack/services/apigateway_v1.py+++ b/ministack/services/apigateway_v1.py@@ -91,6 +91,7 @@ Custom domains:"""import base64+import copyimport datetimeimport jsonimport logging@@ -159,6 +160,8 @@ _base_path_mappings = AccountRegionScopedDict() # domain_name -> {base_path ->_v1_tags = AccountScopedDict() # resource_arn -> {key -> value}_account_settings = AccountRegionScopedDict() # singleton per account+region: stores fields set via UpdateAccount_gateway_responses = AccountRegionScopedDict() # rest_api_id -> {response_type -> customized GatewayResponse}+# rest_api_id -> {deployment_id -> customized gateway responses at CreateDeployment}+_deployed_gateway_responses = AccountRegionScopedDict()_documentation_parts = AccountRegionScopedDict() # rest_api_id -> {part_id -> DocumentationPart}@@ -210,6 +213,20 @@ _DEFAULT_GATEWAY_RESPONSE_STATUS_CODES = {_DEFAULT_GATEWAY_RESPONSE_TEMPLATE = '{"message":$context.error.messageString}'+# x-amzn-ErrorType API Gateway stamps on the gateway errors it emits.+_GATEWAY_RESPONSE_ERROR_TYPES = {+ "MISSING_AUTHENTICATION_TOKEN": "MissingAuthenticationTokenException",+ "UNAUTHORIZED": "UnauthorizedException",+ "ACCESS_DENIED": "AccessDeniedException",+ "AUTHORIZER_FAILURE": "AuthorizerConfigurationException",+ "AUTHORIZER_CONFIGURATION_ERROR": "AuthorizerConfigurationException",+ "API_CONFIGURATION_ERROR": "InternalServerErrorException",+}++_GATEWAY_TEMPLATE_VARIABLE = re.compile(+ r"\$(?:\{(context(?:\.\w+)+)\}|(context(?:\.[A-Za-z]\w*)+))"+)+_DOCUMENTATION_LOCATION_TYPES = frozenset({"API",@@ -716,8 +733,8 @@ async def _call_lambda_raw(function_ref, event, *, account_id=None, region=None)Routed through the central ``_execute_function`` dispatcher so CloudWatchLogs emission and Docker log output work for API Gateway invocations.- Non-proxy (custom) integrations need the raw payload; :func:`_call_lambda`- is this plus the AWS_PROXY response shaper, which would rewrite a handler's+ Non-proxy (custom) integrations need the raw payload; AWS_PROXY passes it+ through :func:`_lambda_proxy_response`, which would rewrite a handler's``statusCode`` key into the HTTP status."""from ministack.services import lambda_svc@@ -737,24 +754,17 @@ async def _call_lambda_raw(function_ref, event, *, account_id=None, region=None)return result, None-async def _call_lambda(function_ref, event, *, account_id=None, region=None):- """Invoke a Lambda function and return the parsed AWS_PROXY response dict.+def _lambda_proxy_response(result):+ """Shape a :func:`_call_lambda_raw` result into the AWS_PROXY response dict.- :func:`_call_lambda_raw` plus the shared response shaper (throttle→429,- error→502, body→envelope), which is what keeps v1 and v2 consistent.+ The shared response shaper (throttle→429, error→502, body→envelope) is what+ keeps v1 and v2 consistent."""from ministack.services import lambda_svc- result, err = await _call_lambda_raw(- function_ref, event, account_id=account_id, region=region- )- if err:- return None, err-lambda_response, _ = lambda_svc.lambda_execute_result_to_api_proxy_response(result)- # On error the helper returns {statusCode: 502, body: <msg>}; preserve- # the _call_lambda contract of (None, error_msg) so callers that check- # for error strings keep working.+ # On error the helper returns {statusCode: 502, body: <msg>}; return it as+ # (None, error_msg) so the caller answers with the error string.if result.get("error") and lambda_response and lambda_response.get("statusCode") == 502:return None, str(lambda_response.get("body") or "Lambda invocation error")return lambda_response, None@@ -786,6 +796,7 @@ def get_state():"v1_tags": copy.deepcopy(_v1_tags),"account_settings": copy.deepcopy(_account_settings),"gateway_responses": copy.deepcopy(_gateway_responses),+ "deployed_gateway_responses": copy.deepcopy(_deployed_gateway_responses),"documentation_parts": copy.deepcopy(_documentation_parts),}@@ -1001,6 +1012,9 @@ def load_persisted_state(data):_restore_child_store(_authorizers_v1, data.get("authorizers_v1", {}), api_regions)_restore_child_store(_models, data.get("models", {}), api_regions)_restore_child_store(_gateway_responses, data.get("gateway_responses", {}), api_regions)+ _restore_child_store(+ _deployed_gateway_responses, data.get("deployed_gateway_responses", {}), api_regions+ )_restore_child_store(_documentation_parts, data.get("documentation_parts", {}), api_regions)_restore_child_store(_usage_plan_keys, data.get("usage_plan_keys", {}), plan_regions)_restore_child_store(_base_path_mappings, data.get("base_path_mappings", {}), domain_regions)@@ -1024,6 +1038,7 @@ def reset():_v1_tags.clear()_account_settings.clear()_gateway_responses.clear()+ _deployed_gateway_responses.clear()_documentation_parts.clear()@@ -1368,32 +1383,117 @@ def _header_ci(headers, name):return ""-def _gw_error(status, message):- """A REST API gateway error response. Uses the lowercase `message` key that- API Gateway's default UNAUTHORIZED / MISSING_AUTHENTICATION_TOKEN / 5XX- gateway responses carry."""- return (- status,- {"Content-Type": "application/json"},- json.dumps({"message": message}).encode(),- )+class _GatewayError:+ """An error API Gateway itself emits, answered through the gateway response+ of ``response_type`` in the stage's deployment (see+ :func:`_gateway_error_response`)."""++ def __init__(self, response_type, message):+ self.response_type = response_type+ self.message = message+++def _gw_error(response_type, message):+ return _GatewayError(response_type, message)def _deny_error(explicit):- """The 403 an authorizer denial produces. The execute-api authorization- layer answers with a capitalised `Message` key (distinct from the lowercase- gateway-response bodies) — explicit Deny vs. no-matching-Allow differ only in- the trailing clause."""+ """The 403 an authorizer denial produces. Explicit Deny vs. no-matching-Allow+ differ only in the trailing clause."""msg = (- "User is not authorized to access this resource with an explicit deny"+ "User is not authorized to access this resource with an explicit deny in an identity-based policy"if explicitelse "User is not authorized to access this resource")- return (- 403,- {"Content-Type": "application/json"},- json.dumps({"Message": msg}).encode(),+ return _gw_error("ACCESS_DENIED", msg)+++def _gateway_request_value(source, request):+ """Resolve a ``gatewayresponse.header.*`` mapping expression against the+ request. None means the source is absent, which omits the header."""+ if len(source) >= 2 and source[0] == source[-1] == "'":+ return source[1:-1]+ if source.startswith("method.request.header."):+ target = source[len("method.request.header."):].lower()+ for key, value in request["headers"].items():+ if key.lower() == target:+ return value if isinstance(value, str) else (value[-1] if value else "")+ return None+ if source.startswith("method.request.querystring."):+ value = request["query_params"].get(source[len("method.request.querystring."):])+ return value[0] if isinstance(value, list) and value else value+ if source.startswith("method.request.path."):+ return request["path_params"].get(source[len("method.request.path."):])+ if source.startswith("stageVariables."):+ return (request["stage"].get("variables") or {}).get(source[len("stageVariables."):])+ if source == "context.requestId":+ return request["request_id"]+ return None+++def _gateway_error_response(error, request):+ """Render a gateway error the way API Gateway does.++ Precedence: the customized response for the type, else a customized+ DEFAULT_4XX / DEFAULT_5XX (by the type's default status), else the built-in+ default. The responses in effect are the ones captured by the stage's+ deployment. The application/json template is used whatever the request+ accepts.+ """+ api_id = request["api_id"]+ customized = _deployed_gateway_responses.get(api_id, {}).get(request["stage"].get("deploymentId"))+ if customized is None:+ # A deployment restored from state written before snapshots existed.+ customized = _gateway_responses.get(api_id, {})+ if isinstance(error, _PlainGatewayError) and not customized.keys() & {+ error.response_type, _gateway_response_family(error.response_type)+ }:+ return error.response+ response_type = error.response_type+ response = _gateway_response_for_type(customized, response_type)+ template = (response.get("responseTemplates") or {}).get("application/json")+ if response_type == "ACCESS_DENIED" and not customized.keys() & {response_type, "DEFAULT_4XX"}:+ # The built-in ACCESS_DENIED body carries a capitalised `Message` key.+ template = '{"Message":$context.error.messageString}'+ if template is None:+ template = _DEFAULT_GATEWAY_RESPONSE_TEMPLATE++ headers = {"Content-Type": "application/json"}+ for dest, source in (response.get("responseParameters") or {}).items():+ if not dest.startswith("gatewayresponse.header.") or not isinstance(source, str):+ continue+ value = _gateway_request_value(source, request)+ if value is not None:+ headers[dest[len("gatewayresponse.header."):]] = value+ error_type = _GATEWAY_RESPONSE_ERROR_TYPES.get(response_type)+ if error_type:+ headers["x-amzn-ErrorType"] = error_type+ headers["x-amzn-requestid"] = request["request_id"]++ message = error.message+ message_string = "null" if message is None else json.dumps(message)+ rendered_type = response_type+ if response_type in ("API_CONFIGURATION_ERROR", "AUTHORIZER_CONFIGURATION_ERROR"):+ # AWS renders the messageString of both types with a leading space, and+ # $context.error.responseType of an authorizer configuration error as+ # API_CONFIGURATION_ERROR, while the response entry, its status and+ # x-amzn-ErrorType stay those of AUTHORIZER_CONFIGURATION_ERROR (measured).+ message_string = " " + message_string+ rendered_type = "API_CONFIGURATION_ERROR"+ variables = {+ "context.error.message": "" if message is None else message,+ "context.error.messageString": message_string,+ "context.error.responseType": rendered_type,+ "context.requestId": request["request_id"],+ "context.resourcePath": request["resource_path"],+ "context.stage": request["stage_name"],+ # No integration answered, so the status variable renders empty (measured).+ "context.status": "",+ }+ body = _GATEWAY_TEMPLATE_VARIABLE.sub(+ lambda m: variables.get(m.group(1) or m.group(2), m.group(0)), template)+ return int(response["statusCode"]), headers, body.encode("utf-8")def _arn_matches(pattern, arn):@@ -1642,6 +1742,16 @@ def _token_scopes(claims):return sorted(set(scopes))+class _PlainGatewayError(_GatewayError):+ """A gateway error whose built-in default was not measured against AWS: it+ keeps the response it had before gateway responses were applied, while a+ customized response for its type still takes over."""++ def __init__(self, response_type, message, response):+ super().__init__(response_type, message)+ self.response = response++async def _validate_cognito_authorizer(authorizer, method_obj, headers, query_params, stage):"""Verify a user-pool token for a COGNITO_USER_POOLS method.@@ -1655,49 +1765,49 @@ async def _validate_cognito_authorizer(authorizer, method_obj, headers, query_paif not issuers:# An authorizer with no usable pool cannot authorize anything; AWS# reports this as a configuration error rather than letting it through.- return None, _gw_error(500, "Internal server error")+ return None, _gw_error("AUTHORIZER_CONFIGURATION_ERROR", "Internal server error")token = _cognito_token_from_request(authorizer, headers, query_params, stage)if not token:- return None, _gw_error(401, "Unauthorized")+ return None, _gw_error("UNAUTHORIZED", "Unauthorized")parts = token.split(".")if len(parts) != 3:- return None, _gw_error(401, "Unauthorized")+ return None, _gw_error("UNAUTHORIZED", "Unauthorized")try:header = json.loads(_b64url_decode(parts[0]))claims = json.loads(_b64url_decode(parts[1]))except (ValueError, json.JSONDecodeError):- return None, _gw_error(401, "Unauthorized")+ return None, _gw_error("UNAUTHORIZED", "Unauthorized")if not isinstance(claims, dict) or not isinstance(header, dict):- return None, _gw_error(401, "Unauthorized")+ return None, _gw_error("UNAUTHORIZED", "Unauthorized")issuer = claims.get("iss")if issuer not in issuers:- return None, _gw_error(401, "Unauthorized")+ return None, _gw_error("UNAUTHORIZED", "Unauthorized")kid = header.get("kid")jwks_url = await _resolve_jwks_url({"jwtConfiguration": {"issuer": issuer}})if not kid or not jwks_url:- return None, _gw_error(401, "Unauthorized")+ return None, _gw_error("UNAUTHORIZED", "Unauthorized")try:keys = ((await _fetch_jwks(jwks_url)).get("keys") or [])except (OSError, ValueError, json.JSONDecodeError):- return None, _gw_error(401, "Unauthorized")+ return None, _gw_error("UNAUTHORIZED", "Unauthorized")jwk = next((k for k in keys if k.get("kid") == kid), None)if not jwk or not _verify_rs256_signature(token, jwk):- return None, _gw_error(401, "Unauthorized")+ return None, _gw_error("UNAUTHORIZED", "Unauthorized")now = int(time.time())try:if "exp" in claims and int(claims["exp"]) <= now:- return None, _gw_error(401, "Unauthorized")+ return None, _gw_error("UNAUTHORIZED", "Unauthorized")if "nbf" in claims and int(claims["nbf"]) > now:- return None, _gw_error(401, "Unauthorized")+ return None, _gw_error("UNAUTHORIZED", "Unauthorized")if "iat" in claims and int(claims["iat"]) > now:- return None, _gw_error(401, "Unauthorized")+ return None, _gw_error("UNAUTHORIZED", "Unauthorized")except (TypeError, ValueError):- return None, _gw_error(401, "Unauthorized")+ return None, _gw_error("UNAUTHORIZED", "Unauthorized")# authorizationScopes on the method turns the check into an OAuth one: the# token must carry at least one of the listed scopes, and a token without@@ -1706,7 +1816,8 @@ async def _validate_cognito_authorizer(authorizer, method_obj, headers, query_paif required_scopes:granted = _token_scopes(claims)if not any(scope in granted for scope in required_scopes):- return None, _gw_error(403, "Forbidden")+ forbidden = (403, {"Content-Type": "application/json"}, json.dumps({"message": "Forbidden"}).encode())+ return None, _PlainGatewayError("ACCESS_DENIED", "Forbidden", forbidden)return claims, None@@ -1729,13 +1840,13 @@ async def _authorize_request_v1(# We do not verify SigV4 signatures; match AWS only to the extent that a# request with no Authorization header is rejected as unauthenticated.if not _header_ci(headers, "authorization"):- return _gw_error(403, "Missing Authentication Token"), None+ return _gw_error("MISSING_AUTHENTICATION_TOKEN", "Missing Authentication Token"), Nonereturn None, Noneif auth_type == "COGNITO_USER_POOLS":authorizer_id = method_obj.get("authorizerId")authorizer = _authorizers_v1.get(api_id, {}).get(authorizer_id) if authorizer_id else Noneif not authorizer:- return _gw_error(500, "Internal server error"), None+ return _gw_error("AUTHORIZER_CONFIGURATION_ERROR", "Internal server error"), Noneclaims, auth_error = await _validate_cognito_authorizer(authorizer, method_obj, headers, query_params, stage)@@ -1749,7 +1860,7 @@ async def _authorize_request_v1(authorizer_id = method_obj.get("authorizerId")authorizer = _authorizers_v1.get(api_id, {}).get(authorizer_id) if authorizer_id else Noneif not authorizer:- return _gw_error(500, "Internal server error"), None+ return _gw_error("AUTHORIZER_CONFIGURATION_ERROR", "Internal server error"), Nonemethod_arn = execute_api_arn(owner_region, owner_account_id, api_id, stage_name, method, request_path@@ -1766,7 +1877,7 @@ async def _authorize_request_v1()token = _header_ci(headers, header_name)if not token:- return _gw_error(401, "Unauthorized"), None+ return _gw_error("UNAUTHORIZED", "Unauthorized"), Noneval_expr = authorizer.get("identityValidationExpression")if val_expr:try:@@ -1776,9 +1887,9 @@ async def _authorize_request_v1(# uncompilable one only surfaces here. That is a# misconfiguration (AUTHORIZER_CONFIGURATION_ERROR), not an# exception that should escape the request handler.- return _gw_error(500, "Internal server error"), None+ return _gw_error("AUTHORIZER_CONFIGURATION_ERROR", "Internal server error"), Noneif not token_matches:- return _gw_error(401, "Unauthorized"), None+ return _gw_error("UNAUTHORIZED", "Unauthorized"), Noneidentity_values = (token,)event = {"type": "TOKEN", "authorizationToken": token, "methodArn": method_arn}else: # REQUEST@@ -1789,7 +1900,7 @@ async def _authorize_request_v1(# With caching on and identity sources declared, a missing source is a# 401 without invoking the authorizer (matches AWS).if ttl > 0 and identity_source and not all_present:- return _gw_error(401, "Unauthorized"), None+ return _gw_error("UNAUTHORIZED", "Unauthorized"), Noneidentity_values = tuple(id_values)single_headers = {k: (v if isinstance(v, str) else v[-1]) for k, v in headers.items()}multi_headers = {k: ([v] if isinstance(v, str) else list(v)) for k, v in headers.items()}@@ -1835,15 +1946,15 @@ async def _authorize_request_v1()if result is None:# Authorizer Lambda unresolved / not found → connection failure.- return _gw_error(500, "Internal server error"), None+ return _gw_error("AUTHORIZER_CONFIGURATION_ERROR", "Internal server error"), Noneif result.get("error"):err_body = result.get("body") or {}msg = err_body.get("errorMessage", "") if isinstance(err_body, dict) else str(err_body)# A function that raises exactly "Unauthorized" maps to 401; any other- # uncaught error is an authorizer failure → 500.+ # uncaught error is an authorizer failure → 500 with a null message.if isinstance(msg, str) and msg.strip().lower() == "unauthorized":- return _gw_error(401, "Unauthorized"), None- return _gw_error(500, "Internal server error"), None+ return _gw_error("UNAUTHORIZED", "Unauthorized"), None+ return _gw_error("AUTHORIZER_FAILURE", None), Nonepolicy = result.get("body")if isinstance(policy, (str, bytes)):@@ -1854,24 +1965,23 @@ async def _authorize_request_v1(except json.JSONDecodeError:policy = Noneif not isinstance(policy, dict):- return _gw_error(500, "Internal server error"), None+ return _gw_error("AUTHORIZER_CONFIGURATION_ERROR", "Internal server error"), Noneprincipal_id = policy.get("principalId")- if principal_id is None or str(principal_id) == "":- # AWS demands a principal. Without one the response is an- # AUTHORIZER_CONFIGURATION_ERROR, not an Allow that reaches the- # backend carrying an empty principalId.- return _gw_error(500, "Internal server error"), None+ has_principal = principal_id is not None and str(principal_id) != ""+ # AWS evaluates the policy of a TOKEN and of a REQUEST authorizer that+ # returns no principalId (measured for both); it is not a configuration error.policy_doc = policy.get("policyDocument")if not isinstance(policy_doc, dict):# Same AUTHORIZER_CONFIGURATION_ERROR shape: a response without a# policyDocument is a misconfigured authorizer, not an implicit# deny — and it must not be cached.- return _gw_error(500, "Internal server error"), None+ return _gw_error("AUTHORIZER_CONFIGURATION_ERROR", "Internal server error"), Noneauth_ctx = _stringify_context(policy.get("context"))- auth_ctx["principalId"] = str(principal_id)+ if has_principal:+ auth_ctx["principalId"] = str(principal_id)# Only a well-formed response is cached; failures re-invoke next time.cached = (policy_doc, auth_ctx)if ttl > 0:@@ -1887,6 +1997,30 @@ async def _authorize_request_v1(async def _handle_execute_in_scope(api_id, stage_name, method, path, headers, body, query_params,owner_account_id, owner_region,+):+ # What a gateway response can map from; filled in as routing resolves it.+ request = {+ "api_id": api_id,+ "stage_name": stage_name,+ "stage": None,+ "headers": headers or {},+ "query_params": query_params or {},+ "path_params": {},+ "resource_path": "",+ "request_id": new_uuid(),+ }+ response = await _execute_in_scope(+ request, api_id, stage_name, method, path, headers, body, query_params,+ owner_account_id, owner_region,+ )+ if isinstance(response, _GatewayError):+ return _gateway_error_response(response, request)+ return response+++async def _execute_in_scope(+ request, api_id, stage_name, method, path, headers, body, query_params,+ owner_account_id, owner_region,):api = _rest_apis.get(api_id)if not api:@@ -1894,7 +2028,13 @@ async def _handle_execute_in_scope(stage = _stages_v1.get(api_id, {}).get(stage_name)if not stage:- return 404, {"Content-Type": "application/json"}, json.dumps({"message": f"Stage '{stage_name}' not found"}).encode()+ # No gateway response applies: the request never reaches a deployment.+ return (+ 403,+ {"Content-Type": "application/json", "x-amzn-ErrorType": "ForbiddenException"},+ b'{"message":"Forbidden"}',+ )+ request["stage"] = stage# Match path against resource treesegments = [s for s in path.strip("/").split("/") if s]@@ -1903,7 +2043,7 @@ async def _handle_execute_in_scope(if not resource:# AWS returns 403 MISSING_AUTHENTICATION_TOKEN for an unsupported# resource (an unmatched path), not 404.- return _gw_error(403, "Missing Authentication Token")+ return _gw_error("MISSING_AUTHENTICATION_TOKEN", "Missing Authentication Token")# Look up methodresource_methods = resource.get("resourceMethods", {})@@ -1923,7 +2063,9 @@ async def _handle_execute_in_scope(method_obj = resource_methods.get(method) or resource_methods.get("ANY")if not method_obj:# Nothing in the tree serves this verb for this path.- return _gw_error(403, "Missing Authentication Token")+ return _gw_error("MISSING_AUTHENTICATION_TOKEN", "Missing Authentication Token")+ request["resource_path"] = resource["path"]+ request["path_params"] = path_params or {}integration = method_obj.get("methodIntegration")if not integration:@@ -2113,12 +2255,16 @@ async def _invoke_lambda_proxy_v1(caller_identity=caller_identity,)- lambda_response, err = await _call_lambda(+ result, err = await _call_lambda_raw(lambda_ref,event,account_id=owner_account_id,region=owner_region,)+ if err:+ # The integration names a function that does not exist.+ return _gw_error("API_CONFIGURATION_ERROR", "Internal server error")+ lambda_response, err = _lambda_proxy_response(result)if err:return 502, {"Content-Type": "application/json"}, json.dumps({"message": err}).encode()@@ -2302,29 +2448,47 @@ async def _invoke_http_proxy_v1(integration, path, method, headers, body, query_return status, resp_headers, resp_bodyexcept urllib.error.HTTPError as e:return e.code, {"Content-Type": "application/json"}, e.read()- except Exception as ex:- return 502, {"Content-Type": "application/json"}, json.dumps({"message": str(ex)}).encode()+ except Exception:+ # An unresolvable or unreachable backend.+ return _gw_error("API_CONFIGURATION_ERROR", "Internal server error")def _invoke_mock_v1(integration):"""Return a MOCK integration response.- Selection: iterate integrationResponses in status-code order; the first- entry whose selectionPattern is empty (default) or matches "200" is used,- matching AWS behaviour for MOCK where the input is always treated as- successful (statusCode 200).+ The request template's ``statusCode`` (200 when absent) is the integration+ status: the response whose selectionPattern matches it is used, else an+ explicit "200" entry, else the entry with an empty (default) pattern."""int_responses = integration.get("integrationResponses", {})if not int_responses:return 200, {"Content-Type": "application/json"}, b"{}"- # AWS selects the response whose selectionPattern matches the integration- # status code. For MOCK the "status" is always 200 (success path).+ template = (integration.get("requestTemplates") or {}).get("application/json") or ""+ match = re.search(r'"statusCode"\s*:\s*(\d{3})', template)+ status_code = match.group(1) if match else "200"selected = None- # Prefer an explicit "200" entry first- if "200" in int_responses:+ matches = []+ for resp in int_responses.values():+ pattern = resp.get("selectionPattern")+ try:+ if pattern and re.fullmatch(pattern, status_code):+ matches.append(resp)+ except re.error:+ continue+ # Several patterns can match; the entry whose own status code is the+ # integration status wins, so a catch-all on another entry does not+ # shadow the exact one.+ for resp in matches:+ if str(resp.get("statusCode")) == status_code:+ selected = resp+ break+ if selected is None and matches:+ selected = matches[0]+ if selected is None and "200" in int_responses:+ # Prefer an explicit "200" entryselected = int_responses["200"]- else:+ elif selected is None:# Fall back to the entry with an empty / catch-all selectionPatternfor resp in int_responses.values():pattern = resp.get("selectionPattern", "")@@ -2457,6 +2621,7 @@ def _delete_rest_api(api_id):_authorizers_v1.pop(api_id, None)_models.pop(api_id, None)_gateway_responses.pop(api_id, None)+ _deployed_gateway_responses.pop(api_id, None)_documentation_parts.pop(api_id, None)_v1_tags.pop(_rest_api_arn(api_id), None)return 202, {}, b""@@ -3102,6 +3267,11 @@ def _create_deployment(api_id, data):"apiSummary": _build_api_summary(api_id),}_deployments_v1.setdefault(api_id, {})[deployment_id] = deployment+ # The data plane answers with the gateway responses of the stage's+ # deployment: a Put or Delete takes effect with the next deployment only.+ _deployed_gateway_responses.setdefault(api_id, {})[deployment_id] = copy.deepcopy(+ _gateway_responses.get(api_id, {})+ )# If stageName is provided, create/update the stage automaticallystage_name = data.get("stageName")@@ -3166,6 +3336,7 @@ def _delete_deployment(api_id, deployment_id):if deployment_id not in _deployments_v1.get(api_id, {}):return _v1_error("NotFoundException", "Invalid Deployment identifier specified", 404)_deployments_v1[api_id].pop(deployment_id, None)+ _deployed_gateway_responses.get(api_id, {}).pop(deployment_id, None)return 202, {}, b""@@ -3454,6 +3625,31 @@ def _default_gateway_response(response_type):return response+def _gateway_response_family(response_type):+ """DEFAULT_4XX or DEFAULT_5XX by the type's default status (None for those two)."""+ status_code = _DEFAULT_GATEWAY_RESPONSE_STATUS_CODES.get(response_type)+ if status_code is None:+ return None+ return "DEFAULT_5XX" if status_code.startswith("5") else "DEFAULT_4XX"+++def _gateway_response_for_type(customized, response_type):+ """The gateway response in effect for ``response_type``.++ A customized entry wins. An uncustomized type inherits the parameters and+ templates of a customized DEFAULT_4XX / DEFAULT_5XX, keeps its own status+ code and still reports ``defaultResponse: true``.+ """+ if response_type in customized:+ return customized[response_type]+ response = _default_gateway_response(response_type)+ inherited = customized.get(_gateway_response_family(response_type))+ if inherited:+ response["responseParameters"] = dict(inherited.get("responseParameters") or {})+ response["responseTemplates"] = dict(inherited.get("responseTemplates") or {})+ return response++def _validate_gateway_response_target(api_id, response_type):if api_id not in _rest_apis:return _v1_error("NotFoundException", "Invalid API identifier specified", 404)@@ -3484,7 +3680,9 @@ def _put_gateway_response(api_id, response_type, data):if status_code is not None:response["statusCode"] = str(status_code)response["responseParameters"] = dict(data.get("responseParameters") or {})- response["responseTemplates"] = dict(data.get("responseTemplates") or {})+ # Without responseTemplates AWS stores the default application/json template.+ if data.get("responseTemplates"):+ response["responseTemplates"] = dict(data["responseTemplates"])_gateway_responses.setdefault(api_id, {})[response_type] = responsereturn _v1_response(response, 201)@@ -3493,8 +3691,9 @@ def _get_gateway_response(api_id, response_type):error = _validate_gateway_response_target(api_id, response_type)if error is not None:return error- response = _gateway_responses.get(api_id, {}).get(response_type)- return _v1_response(response or _default_gateway_response(response_type))+ return _v1_response(+ _gateway_response_for_type(_gateway_responses.get(api_id, {}), response_type)+ )def _get_gateway_responses(api_id):@@ -3502,7 +3701,7 @@ def _get_gateway_responses(api_id):return _v1_error("NotFoundException", "Invalid API identifier specified", 404)customized = _gateway_responses.get(api_id, {})responses = [- customized.get(response_type) or _default_gateway_response(response_type)+ _gateway_response_for_type(customized, response_type)for response_type in _GATEWAY_RESPONSE_TYPES]# AWS returns the complete GatewayResponses collection and ignores thediff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.pyindex f12b76eb..105160f1 100644--- a/tests/test_apigatewayv1.py+++ b/tests/test_apigatewayv1.py@@ -220,6 +220,8 @@ def test_apigwv1_gateway_response_state_survives_persistence_roundtrip():"responseTemplates": {"application/json": '{"persisted":true}'},},)+ _status, _headers, body = service._create_deployment(api_id, {})+ deployment_id = json.loads(body)["id"]snapshot = service.get_state()service.reset()@@ -228,6 +230,7 @@ def test_apigwv1_gateway_response_state_survives_persistence_roundtrip():restored = service._gateway_responses[api_id]["BAD_REQUEST_BODY"]assert restored["statusCode"] == "422"assert restored["responseTemplates"] == {"application/json": '{"persisted":true}'}+ assert service._deployed_gateway_responses[api_id][deployment_id] == {"BAD_REQUEST_BODY": restored}finally:service.reset()@@ -2494,8 +2497,9 @@ def test_apigwv1_custom_domain_empty_base_path_is_root_mapping(apigw_v1):apigw_v1.delete_rest_api(restApiId=api_id)-def test_apigwv1_execute_missing_stage_404(apigw_v1):- """execute-api returns 404 when stage does not exist."""+def test_apigwv1_execute_missing_stage_403(apigw_v1):+ """execute-api answers an unknown stage with 403 Forbidden, outside the+ gateway responses."""import urllib.error as _urlerrimport urllib.request as _urlreq@@ -2504,14 +2508,16 @@ def test_apigwv1_execute_missing_stage_404(apigw_v1):apigw_v1.put_method(restApiId=api_id, resourceId=root_id, httpMethod="GET", authorizationType="NONE")apigw_v1.put_integration(restApiId=api_id, resourceId=root_id, httpMethod="GET", type="MOCK")apigw_v1.create_deployment(restApiId=api_id)- # Do NOT create a stage — request to a nonexistent stage should 404+ # Do NOT create a stage — request to a nonexistent stage should 403url = f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/nonexistent/"req = _urlreq.Request(url, method="GET")req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")with pytest.raises(_urlerr.HTTPError) as exc:_urlreq.urlopen(req)- assert exc.value.code == 404+ assert exc.value.code == 403+ assert exc.value.headers["x-amzn-ErrorType"] == "ForbiddenException"+ assert exc.value.read() == b'{"message":"Forbidden"}'apigw_v1.delete_rest_api(restApiId=api_id)def test_apigwv1_execute_missing_method_403(apigw_v1):@@ -3824,40 +3830,6 @@ def test_apigwv1_authorizer_invalid_validation_expression_is_500(apigw_v1, lam):_auth_drop_lambda(lam, authz)-def test_apigwv1_authorizer_without_principal_id_is_500_and_not_cached(apigw_v1, lam, sqs):- """AWS requires a principal. An Allow policy with no principalId is an- AUTHORIZER_CONFIGURATION_ERROR, not an allow that reaches the backend with- an empty principalId — and a configuration error is never cached."""- qname = _auth_counter_queue(sqs)- backend = _auth_make_lambda(lam, "be", _AUTH_ECHO_BACKEND)- authz = _auth_make_lambda(- lam, "noprincipal",- _AUTH_MARK_PRELUDE- + "def handler(event, context):\n"- f" _mark({qname!r})\n"- " return {'policyDocument': {'Version': '2012-10-17', 'Statement': [\n"- " {'Action': 'execute-api:Invoke', 'Effect': 'Allow',\n"- " 'Resource': event['methodArn']}]}}\n",- )- api_id, _ = _auth_build_api(- apigw_v1, backend,- dict(name="noprincipal", type="TOKEN", authorizerUri=_auth_lambda_uri(authz),- authorizerResultTtlInSeconds=300),- )- try:- url = _auth_execute_url(api_id, "test", "secure")- for _ in range(2):- status, body = _auth_http(url, headers={"Authorization": "allow-abc"})- assert status == 500- assert json.loads(body) == {"message": "Internal server error"}- assert _auth_count(sqs, qname) == 2, "a configuration error must not be cached"- finally:- _auth_drop_api(apigw_v1, api_id)- _auth_drop_lambda(lam, backend)- _auth_drop_lambda(lam, authz)- _auth_delete_queue(sqs, qname)--def test_apigwv1_authorizer_without_policy_document_is_500_and_not_cached(apigw_v1, lam, sqs):"""A response with no policyDocument is a misconfigured authorizer: AWSanswers 500 AuthorizerConfigurationException, not an implicit deny — and@@ -4491,9 +4463,314 @@ def test_apigwv1_cognito_authorization_scopes(apigw_v1, lam, cognito_idp):assert _call(_v1_signed_token({**base, "scope": "files/read files/write"})) == 200# A token whose scopes do not overlap is authenticated but not authorized.assert _call(_v1_signed_token({**base, "scope": "other/scope"})) == 403+ assert _auth_http(url, headers={"Host": host, "Authorization": _v1_signed_token({**base, "scope": "other/scope"})})[1] == b'{"message": "Forbidden"}'# An ID token carries no scopes at all, so it can never satisfy one.assert _call(_v1_signed_token({**base, "token_use": "id", "aud": "c1"})) == 403finally:apigw_v1.delete_rest_api(restApiId=api_id)lam.delete_function(FunctionName=fname)cognito_idp.delete_user_pool(UserPoolId=pool_id)+++# ---- Data plane: gateway responses ----++_GWRESP_AUTHORIZER = (+ "def handler(event, context):\n"+ " headers = {k.lower(): v for k, v in (event.get('headers') or {}).items()}\n"+ " token = event.get('authorizationToken') or headers.get('authorization', '')\n"+ " if token == 'unauth':\n"+ " raise Exception('Unauthorized')\n"+ " if token == 'crash':\n"+ " raise ValueError('boom')\n"+ " effect = 'Deny' if token == 'deny' else 'Allow'\n"+ " policy = {'policyDocument': {'Version': '2012-10-17', 'Statement': [\n"+ " {'Action': 'execute-api:Invoke', 'Effect': effect,\n"+ " 'Resource': event['methodArn'].split('/')[0] + '/*'}]}}\n"+ " if token != 'noprincipal':\n"+ " policy['principalId'] = 'u1'\n"+ " return policy\n"+)+_GWRESP_MISSING_FN = "v1-gwresp-does-not-exist"++[email protected](scope="module")+def gwresp_api(apigw_v1, lam):+ """A deployed API (stage s1, variable sv) serving MOCK /mock and /mock500,+ TOKEN-guarded /auth/{x}, AWS_IAM /iam and an AWS_PROXY /nolambda naming a+ missing function."""+ authz = _auth_make_lambda(lam, "gwresp", _GWRESP_AUTHORIZER)+ api_id = apigw_v1.create_rest_api(name=f"v1-gwresp-{_uuid_mod.uuid4().hex[:6]}")["id"]+ root_id = _auth_root_id(apigw_v1, api_id)+ authorizer_id = apigw_v1.create_authorizer(+ restApiId=api_id, name="tok", type="TOKEN", authorizerUri=_auth_lambda_uri(authz),+ identitySource="method.request.header.Authorization", authorizerResultTtlInSeconds=0,+ )["id"]++ def mock(path_part, parent=root_id, status="200", **method_kwargs):+ rid = apigw_v1.create_resource(restApiId=api_id, parentId=parent, pathPart=path_part)["id"]+ method_kwargs.setdefault("authorizationType", "NONE")+ apigw_v1.put_method(restApiId=api_id, resourceId=rid, httpMethod="GET", **method_kwargs)+ apigw_v1.put_integration(+ restApiId=api_id, resourceId=rid, httpMethod="GET", type="MOCK",+ requestTemplates={"application/json": f'{{"statusCode": {status}}}'},+ )+ apigw_v1.put_integration_response(+ restApiId=api_id, resourceId=rid, httpMethod="GET", statusCode="200",+ responseTemplates={"application/json": '{"ok":true}'},+ )+ apigw_v1.put_integration_response(+ restApiId=api_id, resourceId=rid, httpMethod="GET", statusCode="500", selectionPattern="500",+ responseTemplates={"application/json": '{"mock":"500"}'},+ )+ return rid++ request_authorizer_id = apigw_v1.create_authorizer(+ restApiId=api_id, name="req", type="REQUEST", authorizerUri=_auth_lambda_uri(authz),+ identitySource="method.request.header.Authorization", authorizerResultTtlInSeconds=0,+ )["id"]+ missing_authorizer_id = apigw_v1.create_authorizer(+ restApiId=api_id, name="missing", type="TOKEN", authorizerUri=_auth_lambda_uri(_GWRESP_MISSING_FN),+ identitySource="method.request.header.Authorization", authorizerResultTtlInSeconds=0,+ )["id"]++ mock("mock")+ mock("mock500", status="500")+ auth_id = apigw_v1.create_resource(restApiId=api_id, parentId=root_id, pathPart="auth")["id"]+ mock("{x}", parent=auth_id, authorizationType="CUSTOM", authorizerId=authorizer_id)+ req_id = apigw_v1.create_resource(restApiId=api_id, parentId=root_id, pathPart="req")["id"]+ mock("{x}", parent=req_id, authorizationType="CUSTOM", authorizerId=request_authorizer_id)+ missing_id = apigw_v1.create_resource(restApiId=api_id, parentId=root_id, pathPart="authmissing")["id"]+ mock("{x}", parent=missing_id, authorizationType="CUSTOM", authorizerId=missing_authorizer_id)+ mock("iam", authorizationType="AWS_IAM")+ rid = apigw_v1.create_resource(restApiId=api_id, parentId=root_id, pathPart="nolambda")["id"]+ apigw_v1.put_method(restApiId=api_id, resourceId=rid, httpMethod="GET", authorizationType="NONE")+ apigw_v1.put_integration(+ restApiId=api_id, resourceId=rid, httpMethod="GET", type="AWS_PROXY",+ integrationHttpMethod="POST", uri=_auth_lambda_uri(_GWRESP_MISSING_FN),+ )+ apigw_v1.create_deployment(restApiId=api_id, stageName="s1", variables={"sv": "stagevar-v"})+ try:+ yield api_id+ finally:+ _auth_drop_api(apigw_v1, api_id)+ _auth_drop_lambda(lam, authz)+++def _gwresp_deploy(apigw_v1, api_id, responses):+ """Replace the API's customized gateway responses and redeploy stage s1."""+ for item in apigw_v1.get_gateway_responses(restApiId=api_id)["items"]:+ if not item["defaultResponse"]:+ apigw_v1.delete_gateway_response(restApiId=api_id, responseType=item["responseType"])+ for response_type, kwargs in responses.items():+ apigw_v1.put_gateway_response(restApiId=api_id, responseType=response_type, **kwargs)+ apigw_v1.create_deployment(restApiId=api_id, stageName="s1")+++def _gwresp_call(api_id, path, headers=None, stage="s1"):+ """(status, lower-cased headers, raw body) without raising on errors."""+ import urllib.error as _urlerr+ import urllib.request as _urlreq++ req = _urlreq.Request(_auth_execute_url(api_id, stage, path), headers=headers or {})+ try:+ resp = _urlreq.urlopen(req, timeout=30)+ except _urlerr.HTTPError as e:+ resp = e+ return resp.status, {k.lower(): v for k, v in resp.headers.items()}, resp.read()+++_GWRESP_DENY = "User is not authorized to access this resource with an explicit deny in an identity-based policy"+++ "path,headers,status,response_type,error_type,builtin_body",+ [+ ("mock", {}, 200, None, None, b'{"ok":true}'),+ # The MOCK request template's statusCode selects the integration response.+ ("mock500", {}, 500, None, None, b'{"mock":"500"}'),+ ("nope", {}, 403, "MISSING_AUTHENTICATION_TOKEN", "MissingAuthenticationTokenException",+ b'{"message":"Missing Authentication Token"}'),+ ("iam", {}, 403, "MISSING_AUTHENTICATION_TOKEN", "MissingAuthenticationTokenException",+ b'{"message":"Missing Authentication Token"}'),+ ("auth/abc", {}, 401, "UNAUTHORIZED", "UnauthorizedException", b'{"message":"Unauthorized"}'),+ ("auth/abc", {"Authorization": "unauth"}, 401, "UNAUTHORIZED", "UnauthorizedException",+ b'{"message":"Unauthorized"}'),+ ("auth/abc", {"Authorization": "deny"}, 403, "ACCESS_DENIED", "AccessDeniedException",+ b'{"Message":"%s"}' % _GWRESP_DENY.encode()),+ ("auth/abc", {"Authorization": "crash"}, 500, "AUTHORIZER_FAILURE", "AuthorizerConfigurationException",+ b'{"message":null}'),+ ("auth/abc", {"Authorization": "allow"}, 200, None, None, b'{"ok":true}'),+ # An authorizer returning no principalId still has its policy evaluated, TOKEN and REQUEST alike.+ ("auth/abc", {"Authorization": "noprincipal"}, 200, None, None, b'{"ok":true}'),+ ("req/abc", {"Authorization": "noprincipal"}, 200, None, None, b'{"ok":true}'),+ ("req/abc", {"Authorization": "allow"}, 200, None, None, b'{"ok":true}'),+ # An authorizer naming a missing function; AWS renders its messageString with a leading space too.+ ("authmissing/abc", {"Authorization": "x"}, 500, "AUTHORIZER_CONFIGURATION_ERROR",+ "AuthorizerConfigurationException", b'{"message": "Internal server error"}'),+ # AWS renders this type's messageString with a leading space.+ ("nolambda", {}, 500, "API_CONFIGURATION_ERROR", "InternalServerErrorException",+ b'{"message": "Internal server error"}'),+ ],+)+def test_apigwv1_gateway_response_types(+ apigw_v1, gwresp_api, path, headers, status, response_type, error_type, builtin_body+):+ """Each gateway error resolves to its response type: built-in body without+ customization, the type's own customized response once every type is+ tagged. Integration responses never carry x-amzn-ErrorType."""+ _gwresp_deploy(apigw_v1, gwresp_api, {})+ got_status, got_headers, body = _gwresp_call(gwresp_api, path, headers)+ assert (got_status, got_headers.get("x-amzn-errortype"), body) == (status, error_type, builtin_body)++ tagged = {t: {"responseParameters": {"gatewayresponse.header.X-Gw-Type": f"'{t}'"}}+ for t in apigateway_v1._DEFAULT_GATEWAY_RESPONSE_STATUS_CODES}+ tagged["DEFAULT_4XX"] = {"responseParameters": {"gatewayresponse.header.X-Default": "'4'"}}+ tagged["DEFAULT_5XX"] = {"responseParameters": {"gatewayresponse.header.X-Default": "'5'"}}+ _gwresp_deploy(apigw_v1, gwresp_api, tagged)+ got_status, got_headers, body = _gwresp_call(gwresp_api, path, headers)+ assert got_headers.get("x-gw-type") == response_type+ assert "x-default" not in got_headers+ assert got_headers.get("x-amzn-errortype") == error_type+ if response_type:+ # A customized response keeps the type's default status and template.+ assert got_status == int(apigateway_v1._DEFAULT_GATEWAY_RESPONSE_STATUS_CODES[response_type])+ assert json.loads(body) == {"message": next(iter(json.loads(builtin_body).values()))}+++_GWRESP_D4 = {+ "responseParameters": {"gatewayresponse.header.X-Default": "'d4'"},+ "responseTemplates": {"application/json": '{"d4":$context.error.messageString,"type":"$context.error.responseType"}'},+}+_GWRESP_D5 = {+ "responseParameters": {"gatewayresponse.header.X-Default": "'d5'"},+ "responseTemplates": {"application/json": '{"d5":$context.error.messageString,"type":"$context.error.responseType"}'},+}+++ "path,headers,responses,status,x_default,body",+ [+ # A specific response replaces DEFAULT_4XX (no header merge) and may override the status.+ ("nope", {}, {"DEFAULT_4XX": _GWRESP_D4, "MISSING_AUTHENTICATION_TOKEN": {+ "statusCode": "404", "responseParameters": {"gatewayresponse.header.X-Mat": "'mat'"},+ "responseTemplates": {"application/json": '{"notfound":$context.error.messageString}'}}},+ 404, None, {"notfound": "Missing Authentication Token"}),+ ("nope", {}, {"DEFAULT_4XX": _GWRESP_D4}, 403, "d4",+ {"d4": "Missing Authentication Token", "type": "MISSING_AUTHENTICATION_TOKEN"}),+ ("nope", {}, {"DEFAULT_5XX": _GWRESP_D5}, 403, None, {"message": "Missing Authentication Token"}),+ ("auth/abc", {"Authorization": "deny"}, {"DEFAULT_4XX": _GWRESP_D4}, 403, "d4",+ {"d4": _GWRESP_DENY, "type": "ACCESS_DENIED"}),+ ("auth/abc", {"Authorization": "crash"}, {"DEFAULT_4XX": _GWRESP_D4, "DEFAULT_5XX": _GWRESP_D5}, 500, "d5",+ {"d5": None, "type": "AUTHORIZER_FAILURE"}),+ ],+)+def test_apigwv1_gateway_response_precedence(+ apigw_v1, gwresp_api, path, headers, responses, status, x_default, body+):+ _gwresp_deploy(apigw_v1, gwresp_api, responses)+ got_status, got_headers, got_body = _gwresp_call(gwresp_api, path, headers)+ assert (got_status, got_headers.get("x-default"), json.loads(got_body)) == (status, x_default, body)+ assert ("x-mat" in got_headers) == ("MISSING_AUTHENTICATION_TOKEN" in responses)+++ "path,headers,expected",+ [+ ("auth/abc?q=qv", {"Origin": "https://probe.example", "Accept": "application/xml"},+ {"x-origin": "https://probe.example", "x-query": "qv"}),+ # A missing source omits the header; an empty one keeps it empty.+ ("auth/abc", {"Origin": ""}, {"x-origin": "", "x-query": None}),+ ("auth/abc", {}, {"x-origin": None, "x-query": None}),+ ],+)+def test_apigwv1_gateway_response_mappings(apigw_v1, gwresp_api, path, headers, expected):+ _gwresp_deploy(apigw_v1, gwresp_api, {"UNAUTHORIZED": {+ "statusCode": "418",+ "responseParameters": {+ "gatewayresponse.header.Access-Control-Allow-Origin": "'*'",+ "gatewayresponse.header.X-Origin": "method.request.header.origin",+ "gatewayresponse.header.X-Path": "method.request.path.x",+ "gatewayresponse.header.X-Query": "method.request.querystring.q",+ "gatewayresponse.header.X-Stagevar": "stageVariables.sv",+ "gatewayresponse.header.X-Req": "context.requestId",+ },+ "responseTemplates": {"application/json": (+ '{"msg":$context.error.messageString,"type":"$context.error.responseType",'+ '"raw":"$context.error.message","rid":"$context.requestId",'+ '"rpath":"$context.resourcePath","stage":"$context.stage"}'+ )},+ }})+ status, got_headers, body = _gwresp_call(gwresp_api, path, headers)+ assert status == 418+ assert got_headers["content-type"] == "application/json"+ assert got_headers["access-control-allow-origin"] == "*"+ assert (got_headers["x-path"], got_headers["x-stagevar"]) == ("abc", "stagevar-v")+ assert {k: got_headers.get(k) for k in expected} == expected+ request_id = got_headers["x-amzn-requestid"]+ assert got_headers["x-req"] == request_id+ assert json.loads(body) == {"msg": "Unauthorized", "type": "UNAUTHORIZED", "raw": "Unauthorized",+ "rid": request_id, "rpath": "/auth/{x}", "stage": "s1"}+++def test_apigwv1_gateway_response_configuration_error_variables(apigw_v1, gwresp_api):+ """$context.error.responseType of an authorizer configuration error renders as+ API_CONFIGURATION_ERROR while the entry, status and x-amzn-ErrorType stay the+ authorizer's; $context.status renders empty (both measured)."""+ template = '{"t":"$context.error.responseType","m":$context.error.messageString,"s":"$context.status"}'+ _gwresp_deploy(apigw_v1, gwresp_api, {+ "AUTHORIZER_CONFIGURATION_ERROR": {"statusCode": "503", "responseTemplates": {"application/json": template}},+ "DEFAULT_5XX": {"responseTemplates": {"application/json": template}},+ })+ status, headers, body = _gwresp_call(gwresp_api, "authmissing/abc", {"Authorization": "x"})+ assert (status, headers.get("x-amzn-errortype")) == (503, "AuthorizerConfigurationException")+ assert body == b'{"t":"API_CONFIGURATION_ERROR","m": "Internal server error","s":""}'+ status, headers, body = _gwresp_call(gwresp_api, "nolambda")+ assert (status, headers.get("x-amzn-errortype")) == (500, "InternalServerErrorException")+ assert body == b'{"t":"API_CONFIGURATION_ERROR","m": "Internal server error","s":""}'+++def test_apigwv1_gateway_responses_take_effect_on_deployment(apigw_v1, gwresp_api):+ """The data plane answers with the responses of the stage's last deployment."""+ _gwresp_deploy(apigw_v1, gwresp_api, {})++ def marker():+ return _gwresp_call(gwresp_api, "nope")[1].get("x-mark")++ apigw_v1.put_gateway_response(+ restApiId=gwresp_api, responseType="MISSING_AUTHENTICATION_TOKEN",+ responseParameters={"gatewayresponse.header.X-Mark": "'v1'"},+ )+ assert marker() is None+ apigw_v1.create_deployment(restApiId=gwresp_api, stageName="s1")+ assert marker() == "v1"+ apigw_v1.delete_gateway_response(restApiId=gwresp_api, responseType="MISSING_AUTHENTICATION_TOKEN")+ assert marker() == "v1"+ apigw_v1.create_deployment(restApiId=gwresp_api, stageName="s1")+ assert marker() is None+++def test_apigwv1_gateway_response_defaults_on_the_control_plane(apigw_v1, gwresp_api):+ """PutGatewayResponse without templates stores the default template; an+ uncustomized type reports the DEFAULT_4XX / DEFAULT_5XX it inherits."""+ _gwresp_deploy(apigw_v1, gwresp_api, {"DEFAULT_4XX": _GWRESP_D4})+ put = apigw_v1.put_gateway_response(+ restApiId=gwresp_api, responseType="ACCESS_DENIED",+ responseParameters={"gatewayresponse.header.X-A": "'a'"},+ )+ assert put["responseTemplates"] == {"application/json": '{"message":$context.error.messageString}'}++ expected_unauthorized = {+ "responseType": "UNAUTHORIZED", "statusCode": "401", "defaultResponse": True,+ "responseParameters": _GWRESP_D4["responseParameters"],+ "responseTemplates": _GWRESP_D4["responseTemplates"],+ }+ got = apigw_v1.get_gateway_response(restApiId=gwresp_api, responseType="UNAUTHORIZED")+ got.pop("ResponseMetadata")+ assert got == expected_unauthorized+ items = {i["responseType"]: i for i in apigw_v1.get_gateway_responses(restApiId=gwresp_api)["items"]}+ assert items["UNAUTHORIZED"] == expected_unauthorized+ assert items["API_CONFIGURATION_ERROR"]["responseParameters"] == {}++ apigw_v1.delete_gateway_response(restApiId=gwresp_api, responseType="DEFAULT_4XX")+ got = apigw_v1.get_gateway_response(restApiId=gwresp_api, responseType="UNAUTHORIZED")+ assert (got["defaultResponse"], got["responseParameters"]) == (True, {})diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex e31a42d8..393574cf 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -11880,6 +11880,69 @@ def test_cfn_apigateway_gateway_response_lifecycle(cfn, apigw_v1):apigw_v1.delete_rest_api(restApiId=api_id)+def test_cfn_apigateway_gateway_response_applies_with_its_deployment(cfn, apigw_v1):+ """A GatewayResponse reaches the data plane through the Deployment that+ depends on it; updating only the response leaves the deployed one in effect."""+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ port = urlparse(endpoint).port or 4566+ stack_name = f"intg-cfn-gateway-response-deploy-{_uuid_mod.uuid4().hex[:8]}"++ def template(marker):+ return json.dumps({+ "Resources": {+ "Api": {"Type": "AWS::ApiGateway::RestApi", "Properties": {"Name": stack_name}},+ "Method": {+ "Type": "AWS::ApiGateway::Method",+ "Properties": {+ "RestApiId": {"Ref": "Api"},+ "ResourceId": {"Fn::GetAtt": ["Api", "RootResourceId"]},+ "HttpMethod": "GET",+ "AuthorizationType": "NONE",+ "Integration": {"Type": "MOCK"},+ },+ },+ "Response": {+ "Type": "AWS::ApiGateway::GatewayResponse",+ "Properties": {+ "RestApiId": {"Ref": "Api"},+ "ResponseType": "MISSING_AUTHENTICATION_TOKEN",+ "ResponseParameters": {"gatewayresponse.header.X-Cfn": f"'{marker}'"},+ },+ },+ "Deploy": {+ "Type": "AWS::ApiGateway::Deployment",+ "DependsOn": ["Method", "Response"],+ "Properties": {"RestApiId": {"Ref": "Api"}, "StageName": "s1"},+ },+ },+ "Outputs": {"ApiId": {"Value": {"Ref": "Api"}}},+ })++ def marker(api_id):+ req = urllib.request.Request(f"http://localhost:{port}/_aws/execute-api/{api_id}/s1/nope")+ with pytest.raises(urllib.error.HTTPError) as exc:+ urllib.request.urlopen(req, timeout=30)+ assert exc.value.code == 403+ return exc.value.headers.get("X-Cfn")++ try:+ cfn.create_stack(StackName=stack_name, TemplateBody=template("v1"))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ api_id = stack["Outputs"][0]["OutputValue"]+ assert marker(api_id) == "v1"++ cfn.update_stack(StackName=stack_name, TemplateBody=template("v2"))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ response = apigw_v1.get_gateway_response(restApiId=api_id, responseType="MISSING_AUTHENTICATION_TOKEN")+ assert response["responseParameters"] == {"gatewayresponse.header.X-Cfn": "'v2'"}+ assert marker(api_id) == "v1"+ finally:+ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)++def test_cfn_apigateway_documentation_part_lifecycle(cfn, apigw_v1):"""DocumentationPart supports create, update, replacement, Ref, and delete.