Skip to content

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

fix(cfn): support API Gateway gateway responses (#1124) (#1125)

robert-pitt-foodhub9cf3a979b353
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3642c9cb..681c6296 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
- **IoT — device shadow operations** — `GetThingShadow`, `UpdateThingShadow`, and `DeleteThingShadow` on the `iot-data` endpoint (classic and named shadows via `?name=`) previously returned `InvalidRequestException: Unsupported iot-data path: .../shadow`. Shadows now store `desired`/`reported` state: updates deep-merge into the stored document (a `null` value removes the field), bump the version, and stamp per-field `metadata` timestamps; the `/accepted` response echoes only the sections sent, while `GetThingShadow` returns the full document including the computed `state.delta` (desired fields that differ from reported). A stale `version` in an update is rejected with a `409`, and reading or deleting a nonexistent shadow returns `ResourceNotFoundException`. Shadows are account-scoped and persisted with the rest of the IoT state.
- **KMS — `GenerateDataKeyPair` and `GenerateDataKeyPairWithoutPlaintext`** — the emulator implemented `GenerateDataKey` and `GenerateDataKeyWithoutPlaintext` but no data key *pair* operation, so both returned `InvalidAction: Unknown action`. These provision an asymmetric data key pair wrapped under a symmetric CMK: `GenerateDataKeyPair` returns `PrivateKeyPlaintext`, `PrivateKeyCiphertextBlob` and `PublicKey`, while the `WithoutPlaintext` variant omits `PrivateKeyPlaintext` so the private key never reaches the caller in the clear — the caller persists the ciphertext plus public key and nothing else. Supported `KeyPairSpec` values follow the real AWS enum — `RSA_2048/3072/4096`, `ECC_NIST_P256/P384/P521`, `ECC_SECG_P256K1`, `ECC_NIST_EDWARDS25519` (`SM2` is excluded, as `CreateKey` does not implement it either). Note this is a superset of what `CreateKey` accepts today: `CreateKey` still lacks `RSA_3072`, a pre-existing gap these operations do not share. The wrapping CMK must be symmetric, `EncryptionContext` binds the wrapped private key as it does for `Encrypt`, and the blob decrypts back to a PKCS#8 DER private key that pairs with the returned public key. The wrapped private key uses the emulator's ciphertext layout, now extended with a per-blob random nonce (`key_id(36) + context_hash(32) + nonce(16) + data`) that is mixed into key derivation; `Decrypt` reads these blobs exactly as it reads `Encrypt`'s and `GenerateDataKey`'s. The nonce is required for correctness of the `WithoutPlaintext` guarantee: without it the XOR keystream repeats across every blob sharing a CMK and `EncryptionContext`, and because a key pair's plaintext embeds its (public) modulus, the wrapped private key could be recovered from the public outputs alone. `Encrypt` and `GenerateDataKey` adopt the same nonced layout so all three wrap through an identical format.
+- **API Gateway v1 — `AWS::ApiGateway::GatewayResponse` CloudFormation support** — CDK/CloudFormation stacks that customize REST API errors such as `BAD_REQUEST_BODY`, `DEFAULT_4XX`, or `UNAUTHORIZED` now provision instead of rolling back with `Unsupported resource type`. The v1 control plane adds `PutGatewayResponse`, `GetGatewayResponse`, `GetGatewayResponses`, and `DeleteGatewayResponse`; customizations are account-scoped and persisted, mutable CFN properties update in place, `RestApiId`/`ResponseType` changes replace the resource, and deletion restores API Gateway's generated default response. Reported by @robert-pitt-foodhub (#1124).
### Fixed
- **Lambda — Node warm-worker invoke no longer fails on fd 1 writes** — `fs.writeSync` / `fs.write` on stdout bypassed the existing `process.stdout.write` redirect to stderr (#373), so sync loggers (e.g. pino with `{ sync: true }`) could emit on the JSON-line protocol channel and surface false `Runtime.HandlerError` / `Unknown error` responses even when the handler succeeded. The Node worker bootstrap now redirects fd 1 through `fs.writeSync` / `fs.write`, and the warm-worker stdout reader accepts only protocol lines whose `status` is `ok` or `error`. Reported by @kofuk (#1093).
diff --git a/README.md b/README.md
index a9d04a79..2967e1c6 100644
--- a/README.md
+++ b/README.md
@@ -488,6 +488,7 @@ subnet = ec2.create_subnet(
| `AWS::ApiGateway::Method` | Method ID | — |
| `AWS::ApiGateway::Deployment` | Deployment ID | — |
| `AWS::ApiGateway::Stage` | Stage name | — |
+| `AWS::ApiGateway::GatewayResponse` | Response ID | Id |
| `AWS::AppConfig::Application` | Application ID | ApplicationId |
| `AWS::AppSync::GraphQLApi` | API ID | Arn, GraphQLUrl, ApiId |
| `AWS::AppSync::DataSource` | DataSource name | DataSourceArn |
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 51a52a37..8f79cdd5 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -43,6 +43,10 @@ Control plane endpoints implemented:
GET /restapis/{id}/models — GetModels
GET /restapis/{id}/models/{modelName} — GetModel
DELETE /restapis/{id}/models/{modelName} — DeleteModel
+ PUT /restapis/{id}/gatewayresponses/{responseType} — PutGatewayResponse
+ GET /restapis/{id}/gatewayresponses — GetGatewayResponses
+ GET /restapis/{id}/gatewayresponses/{responseType} — GetGatewayResponse
+ DELETE /restapis/{id}/gatewayresponses/{responseType} — DeleteGatewayResponse
GET /apikeys — GetApiKeys
POST /apikeys — CreateApiKey
GET /apikeys/{keyId} — GetApiKey
@@ -115,6 +119,56 @@ _domain_name_regions = AccountScopedDict() # domain_name -> owning region
_base_path_mappings = AccountScopedDict() # domain_name -> {base_path -> BasePathMapping}
_v1_tags = AccountScopedDict() # resource_arn -> {key -> value}
_account_settings = AccountScopedDict() # singleton per account: stores fields set via UpdateAccount
+_gateway_responses = AccountScopedDict() # rest_api_id -> {response_type -> customized GatewayResponse}
+
+
+_GATEWAY_RESPONSE_TYPES = (
+ "DEFAULT_4XX",
+ "DEFAULT_5XX",
+ "RESOURCE_NOT_FOUND",
+ "UNAUTHORIZED",
+ "INVALID_API_KEY",
+ "ACCESS_DENIED",
+ "AUTHORIZER_FAILURE",
+ "AUTHORIZER_CONFIGURATION_ERROR",
+ "INVALID_SIGNATURE",
+ "EXPIRED_TOKEN",
+ "MISSING_AUTHENTICATION_TOKEN",
+ "INTEGRATION_FAILURE",
+ "INTEGRATION_TIMEOUT",
+ "API_CONFIGURATION_ERROR",
+ "UNSUPPORTED_MEDIA_TYPE",
+ "BAD_REQUEST_PARAMETERS",
+ "BAD_REQUEST_BODY",
+ "REQUEST_TOO_LARGE",
+ "THROTTLED",
+ "QUOTA_EXCEEDED",
+ "WAF_FILTERED",
+)
+
+_DEFAULT_GATEWAY_RESPONSE_STATUS_CODES = {
+ "RESOURCE_NOT_FOUND": "404",
+ "UNAUTHORIZED": "401",
+ "INVALID_API_KEY": "403",
+ "ACCESS_DENIED": "403",
+ "AUTHORIZER_FAILURE": "500",
+ "AUTHORIZER_CONFIGURATION_ERROR": "500",
+ "INVALID_SIGNATURE": "403",
+ "EXPIRED_TOKEN": "403",
+ "MISSING_AUTHENTICATION_TOKEN": "403",
+ "INTEGRATION_FAILURE": "504",
+ "INTEGRATION_TIMEOUT": "504",
+ "API_CONFIGURATION_ERROR": "500",
+ "UNSUPPORTED_MEDIA_TYPE": "415",
+ "BAD_REQUEST_PARAMETERS": "400",
+ "BAD_REQUEST_BODY": "400",
+ "REQUEST_TOO_LARGE": "413",
+ "THROTTLED": "429",
+ "QUOTA_EXCEEDED": "429",
+ "WAF_FILTERED": "403",
+}
+
+_DEFAULT_GATEWAY_RESPONSE_TEMPLATE = '{"message":$context.error.messageString}'
# ---- Helpers ----
@@ -593,6 +647,7 @@ def get_state():
"base_path_mappings": copy.deepcopy(_base_path_mappings),
"v1_tags": copy.deepcopy(_v1_tags),
"account_settings": copy.deepcopy(_account_settings),
+ "gateway_responses": copy.deepcopy(_gateway_responses),
}
@@ -670,6 +725,7 @@ def load_persisted_state(data):
_base_path_mappings.update(data.get("base_path_mappings", {}))
_v1_tags.update(data.get("v1_tags", {}))
_account_settings.update(data.get("account_settings", {}))
+ _gateway_responses.update(data.get("gateway_responses", {}))
_backfill_tag_region_map(_rest_apis, _rest_api_regions, _region_from_rest_api_record)
_backfill_tag_region_map(_api_keys, _api_key_regions, _region_from_api_key_record)
_backfill_tag_region_map(_usage_plans, _usage_plan_regions, _region_from_usage_plan_record)
@@ -695,6 +751,7 @@ def reset():
_base_path_mappings.clear()
_v1_tags.clear()
_account_settings.clear()
+ _gateway_responses.clear()
# ---- Control plane router ----
@@ -965,6 +1022,20 @@ async def handle_request(method, path, headers, body, query_params):
if method == "DELETE":
return _delete_model(api_id, model_name)
+ # /restapis/{id}/gatewayresponses[/{responseType}]
+ elif sub == "gatewayresponses":
+ response_type = parts[3] if len(parts) > 3 else None
+ if response_type is None:
+ if method == "GET":
+ return _get_gateway_responses(api_id)
+ else:
+ if method == "PUT":
+ return _put_gateway_response(api_id, response_type, data)
+ if method == "GET":
+ return _get_gateway_response(api_id, response_type)
+ if method == "DELETE":
+ return _delete_gateway_response(api_id, response_type)
+
return _v1_error("NotFoundException", f"Unknown API Gateway v1 path: {path}", 404)
@@ -1321,6 +1392,7 @@ def _create_rest_api(data):
_deployments_v1[api_id] = {}
_authorizers_v1[api_id] = {}
_models[api_id] = {}
+ _gateway_responses[api_id] = {}
# Create root resource "/"
root_id = _new_id()[:8]
@@ -1367,6 +1439,7 @@ def _delete_rest_api(api_id):
_deployments_v1.pop(api_id, None)
_authorizers_v1.pop(api_id, None)
_models.pop(api_id, None)
+ _gateway_responses.pop(api_id, None)
_v1_tags.pop(_rest_api_arn(api_id), None)
return 202, {}, b""
@@ -1944,6 +2017,88 @@ def _delete_model(api_id, model_name):
return 202, {}, b""
+# ---- Control plane: Gateway Responses ----
+
+def _default_gateway_response(response_type):
+ """Return the API Gateway-generated response used when no customization exists."""
+ response = {
+ "defaultResponse": True,
+ "responseType": response_type,
+ "responseParameters": {},
+ "responseTemplates": {
+ "application/json": _DEFAULT_GATEWAY_RESPONSE_TEMPLATE,
+ },
+ }
+ status_code = _DEFAULT_GATEWAY_RESPONSE_STATUS_CODES.get(response_type)
+ if status_code is not None:
+ response["statusCode"] = status_code
+ 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)
+ if response_type not in _GATEWAY_RESPONSE_TYPES:
+ return _v1_error(
+ "BadRequestException",
+ f"Invalid gateway response type: {response_type}",
+ 400,
+ )
+ return None
+
+
+def _put_gateway_response(api_id, response_type, data):
+ error = _validate_gateway_response_target(api_id, response_type)
+ if error is not None:
+ return error
+
+ status_code = data.get("statusCode")
+ if status_code is not None and not re.fullmatch(r"[1-5]\d\d", str(status_code)):
+ return _v1_error(
+ "BadRequestException",
+ "Invalid status code specified",
+ 400,
+ )
+
+ response = _default_gateway_response(response_type)
+ response["defaultResponse"] = False
+ 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 {})
+ _gateway_responses.setdefault(api_id, {})[response_type] = response
+ return _v1_response(response, 201)
+
+
+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))
+
+
+def _get_gateway_responses(api_id):
+ if api_id not in _rest_apis:
+ 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)
+ for response_type in _GATEWAY_RESPONSE_TYPES
+ ]
+ # AWS returns the complete GatewayResponses collection and ignores the
+ # otherwise-standard API Gateway pagination parameters for this operation.
+ return _v1_response({"item": responses})
+
+
+def _delete_gateway_response(api_id, response_type):
+ error = _validate_gateway_response_target(api_id, response_type)
+ if error is not None:
+ return error
+ _gateway_responses.get(api_id, {}).pop(response_type, None)
+ return 202, {}, b""
+
+
# ---- Control plane: API Keys ----
def _create_api_key(data):
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 497a59a6..96e9b36b 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -1922,6 +1922,50 @@ def _apigw_account_delete(physical_id, props):
_apigw_v1._account_settings["settings"] = settings
+# --- API Gateway GatewayResponse ---
+
+def _apigw_gateway_response_create(logical_id, props, stack_name):
+ """Provision an ``AWS::ApiGateway::GatewayResponse`` customization."""
+ api_id = props.get("RestApiId", "")
+ response_type = props.get("ResponseType", "")
+ data = {
+ "responseParameters": props.get("ResponseParameters", {}),
+ "responseTemplates": props.get("ResponseTemplates", {}),
+ }
+ if "StatusCode" in props:
+ data["statusCode"] = props["StatusCode"]
+
+ status, _headers, body = _apigw_v1._put_gateway_response(api_id, response_type, data)
+ if status >= 400:
+ raise ValueError(f"AWS::ApiGateway::GatewayResponse create failed: {body!r}")
+
+ physical_id = f"{api_id}/{response_type}"
+ return physical_id, {"Id": physical_id}
+
+
+def _apigw_gateway_response_update(physical_id, old_props, new_props, stack_name):
+ # RestApiId and ResponseType require replacement in the AWS CFN resource
+ # specification. Create the replacement first, then reset the old
+ # customization so a failed create cannot destroy the working resource.
+ if any(new_props.get(key) != old_props.get(key) for key in ("RestApiId", "ResponseType")):
+ new_id, attrs = _apigw_gateway_response_create(physical_id, new_props, stack_name)
+ _apigw_gateway_response_delete(physical_id, old_props)
+ return new_id, attrs
+
+ _new_id, attrs = _apigw_gateway_response_create(physical_id, new_props, stack_name)
+ return physical_id, attrs
+
+
+def _apigw_gateway_response_delete(physical_id, props):
+ api_id = props.get("RestApiId", "")
+ response_type = props.get("ResponseType", "")
+ # Deletion resets the customization to API Gateway's generated default.
+ # Keep CloudFormation cleanup idempotent when the parent REST API has
+ # already gone away during rollback.
+ if api_id in _apigw_v1._rest_apis:
+ _apigw_v1._delete_gateway_response(api_id, response_type)
+
+
# --- Lambda EventSourceMapping ---
def _lambda_esm_create(logical_id, props, stack_name):
@@ -4373,6 +4417,11 @@ _RESOURCE_HANDLERS = {
"AWS::ApiGateway::Deployment": {"create": _apigw_deployment_create, "delete": _apigw_deployment_delete},
"AWS::ApiGateway::Stage": {"create": _apigw_stage_create, "delete": _apigw_stage_delete},
"AWS::ApiGateway::Account": {"create": _apigw_account_create, "delete": _apigw_account_delete},
+ "AWS::ApiGateway::GatewayResponse": {
+ "create": _apigw_gateway_response_create,
+ "update": _apigw_gateway_response_update,
+ "delete": _apigw_gateway_response_delete,
+ },
"AWS::Lambda::EventSourceMapping": {"create": _lambda_esm_create, "update": _lambda_esm_update, "delete": _lambda_esm_delete},
"AWS::Pipes::Pipe": {"create": _pipes_pipe_create, "delete": _pipes_pipe_delete},
"AWS::Lambda::Alias": {"create": _lambda_alias_create, "delete": _lambda_alias_delete},
diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.py
index 01f2a164..b1408c71 100644
--- a/tests/test_apigatewayv1.py
+++ b/tests/test_apigatewayv1.py
@@ -115,6 +115,92 @@ def test_apigwv1_delete_rest_api(apigw_v1):
apigw_v1.get_rest_api(restApiId=api_id)
assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+
+def test_apigwv1_gateway_response_crud_resets_to_default(apigw_v1):
+ """GatewayResponse customizations round-trip and deletion restores AWS defaults."""
+ api_id = apigw_v1.create_rest_api(name="v1-gateway-response-test")["id"]
+ response_type = "BAD_REQUEST_BODY"
+ response_parameters = {
+ "gatewayresponse.header.Access-Control-Allow-Origin": "'*'",
+ }
+ response_templates = {
+ "application/json": '{"error":"$context.error.messageString"}',
+ }
+
+ try:
+ default = apigw_v1.get_gateway_response(
+ restApiId=api_id,
+ responseType=response_type,
+ )
+ assert default["defaultResponse"] is True
+ assert default["statusCode"] == "400"
+
+ created = apigw_v1.put_gateway_response(
+ restApiId=api_id,
+ responseType=response_type,
+ statusCode="422",
+ responseParameters=response_parameters,
+ responseTemplates=response_templates,
+ )
+ assert created["defaultResponse"] is False
+ assert created["statusCode"] == "422"
+
+ fetched = apigw_v1.get_gateway_response(
+ restApiId=api_id,
+ responseType=response_type,
+ )
+ assert fetched["responseParameters"] == response_parameters
+ assert fetched["responseTemplates"] == response_templates
+
+ listed = apigw_v1.get_gateway_responses(restApiId=api_id)["items"]
+ listed_response = next(item for item in listed if item["responseType"] == response_type)
+ assert listed_response["defaultResponse"] is False
+ assert listed_response["statusCode"] == "422"
+
+ apigw_v1.delete_gateway_response(
+ restApiId=api_id,
+ responseType=response_type,
+ )
+ reset_response = apigw_v1.get_gateway_response(
+ restApiId=api_id,
+ responseType=response_type,
+ )
+ assert reset_response["defaultResponse"] is True
+ assert reset_response["statusCode"] == "400"
+ assert reset_response["responseParameters"] == {}
+ finally:
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
+def test_apigwv1_gateway_response_state_survives_persistence_roundtrip():
+ """Customized gateway responses participate in API Gateway v1 persistence."""
+ from ministack.services import apigateway_v1 as service
+
+ service.reset()
+ try:
+ _status, _headers, body = service._create_rest_api({"name": "persist-gateway-response"})
+ api_id = json.loads(body)["id"]
+ service._put_gateway_response(
+ api_id,
+ "BAD_REQUEST_BODY",
+ {
+ "statusCode": "422",
+ "responseParameters": {"gatewayresponse.header.X-Test": "'yes'"},
+ "responseTemplates": {"application/json": '{"persisted":true}'},
+ },
+ )
+
+ snapshot = service.get_state()
+ service.reset()
+ service.load_persisted_state(snapshot)
+
+ restored = service._gateway_responses[api_id]["BAD_REQUEST_BODY"]
+ assert restored["statusCode"] == "422"
+ assert restored["responseTemplates"] == {"application/json": '{"persisted":true}'}
+ finally:
+ service.reset()
+
+
def test_apigwv1_create_resource(apigw_v1):
"""CreateResource creates a child resource with computed path."""
api_id = apigw_v1.create_rest_api(name="v1-resource-create")["id"]
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 2cf0a6fe..655f6ada 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -3987,6 +3987,169 @@ def test_cfn_apigateway_account_provisions(cfn, apigw_v1):
_wait_stack(cfn, stack_name)
+def test_cfn_apigateway_gateway_response_resolves_rest_api_ref(cfn, apigw_v1):
+ """The issue #1124 CDK shape provisions a response against a stack REST API."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"intg-cfn-gateway-response-ref-{suffix}"
+ template = {
+ "Resources": {
+ "Api": {
+ "Type": "AWS::ApiGateway::RestApi",
+ "Properties": {"Name": f"gateway-response-ref-{suffix}"},
+ },
+ "BadRequestBody": {
+ "Type": "AWS::ApiGateway::GatewayResponse",
+ "Properties": {
+ "RestApiId": {"Ref": "Api"},
+ "ResponseType": "BAD_REQUEST_BODY",
+ "StatusCode": "400",
+ "ResponseParameters": {
+ "gatewayresponse.header.Access-Control-Allow-Origin": "'*'",
+ },
+ },
+ },
+ },
+ "Outputs": {"ApiId": {"Value": {"Ref": "Api"}}},
+ }
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ api_id = next(
+ item["OutputValue"]
+ for item in stack.get("Outputs", [])
+ if item["OutputKey"] == "ApiId"
+ )
+ response = apigw_v1.get_gateway_response(
+ restApiId=api_id,
+ responseType="BAD_REQUEST_BODY",
+ )
+ assert response["defaultResponse"] is False
+ assert response["responseParameters"] == {
+ "gatewayresponse.header.Access-Control-Allow-Origin": "'*'",
+ }
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+
+
+def test_cfn_apigateway_gateway_response_lifecycle(cfn, apigw_v1):
+ """GatewayResponse creates, updates, replaces, and resets through CFN.
+
+ Regression for #1124: the resource type previously failed immediately as
+ unsupported, rolling back every CDK stack that declared a gateway response.
+ """
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"intg-cfn-gateway-response-{suffix}"
+ api_id = apigw_v1.create_rest_api(name=f"gateway-response-{suffix}")["id"]
+ stack_deleted = False
+
+ def template(response_type, status_code, marker):
+ return {
+ "Resources": {
+ "GatewayResponse": {
+ "Type": "AWS::ApiGateway::GatewayResponse",
+ "Properties": {
+ "RestApiId": api_id,
+ "ResponseType": response_type,
+ "StatusCode": status_code,
+ "ResponseParameters": {
+ "gatewayresponse.header.X-Marker": f"'{marker}'",
+ },
+ "ResponseTemplates": {
+ "application/json": f'{{"marker":"{marker}"}}',
+ },
+ },
+ },
+ },
+ "Outputs": {
+ "GatewayResponseId": {
+ "Value": {"Fn::GetAtt": ["GatewayResponse", "Id"]},
+ },
+ },
+ }
+
+ def physical_id():
+ detail = cfn.describe_stack_resource(
+ StackName=stack_name,
+ LogicalResourceId="GatewayResponse",
+ )["StackResourceDetail"]
+ return detail["PhysicalResourceId"]
+
+ try:
+ cfn.create_stack(
+ StackName=stack_name,
+ TemplateBody=json.dumps(template("BAD_REQUEST_BODY", "400", "created")),
+ )
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ created_id = physical_id()
+ outputs = {item["OutputKey"]: item["OutputValue"] for item in stack.get("Outputs", [])}
+ assert outputs["GatewayResponseId"] == created_id
+
+ created = apigw_v1.get_gateway_response(
+ restApiId=api_id,
+ responseType="BAD_REQUEST_BODY",
+ )
+ assert created["defaultResponse"] is False
+ assert created["responseTemplates"] == {"application/json": '{"marker":"created"}'}
+
+ # Mutable properties update in place and keep the physical id.
+ cfn.update_stack(
+ StackName=stack_name,
+ TemplateBody=json.dumps(template("BAD_REQUEST_BODY", "422", "updated")),
+ )
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert physical_id() == created_id
+ updated = apigw_v1.get_gateway_response(
+ restApiId=api_id,
+ responseType="BAD_REQUEST_BODY",
+ )
+ assert updated["statusCode"] == "422"
+ assert updated["responseParameters"] == {
+ "gatewayresponse.header.X-Marker": "'updated'",
+ }
+
+ # ResponseType is immutable: replace the physical resource and reset
+ # the previous response type to its generated default.
+ cfn.update_stack(
+ StackName=stack_name,
+ TemplateBody=json.dumps(template("BAD_REQUEST_PARAMETERS", "409", "replacement")),
+ )
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ replacement_id = physical_id()
+ assert replacement_id != created_id
+ assert apigw_v1.get_gateway_response(
+ restApiId=api_id,
+ responseType="BAD_REQUEST_BODY",
+ )["defaultResponse"] is True
+ assert apigw_v1.get_gateway_response(
+ restApiId=api_id,
+ responseType="BAD_REQUEST_PARAMETERS",
+ )["statusCode"] == "409"
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+ stack_deleted = True
+ reset_response = apigw_v1.get_gateway_response(
+ restApiId=api_id,
+ responseType="BAD_REQUEST_PARAMETERS",
+ )
+ assert reset_response["defaultResponse"] is True
+ assert reset_response["statusCode"] == "400"
+ finally:
+ if not stack_deleted:
+ try:
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+ except ClientError:
+ pass
+ apigw_v1.delete_rest_api(restApiId=api_id)
+
+
# ---------------------------------------------------------------------------
# ApiGatewayV1 Integration with OpenAPI spec parsing
# ---------------------------------------------------------------------------