Skip to content

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

fix(cloudformation): key API Gateway stage MethodSettings as a map (#1781)

maximoosemine3773584de3c8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 07e7c9de..91849689 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ All notable changes to MiniStack will be documented here.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
Versioning follows [Semantic Versioning](https://semver.org/).
+## [Unreleased]
+
+### Fixed
+
+- **CloudFormation — `AWS::ApiGateway::Stage` method settings reach the stage as a map** — the template's `MethodSettings` list was stored verbatim, so the throttling lookup added in 1.5.14 raised on it and every request to a CloudFormation- or SAM-deployed API answered 500. The list is now keyed `"<resourcePath>/<httpMethod>"`, `"*/*"` for the stage-wide entry, over the account-level defaults AWS reports from `GetStage`.
+
## [1.5.14] — 2026-09-20
### Added
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 4b70ff0a..3cd2ee3c 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -4506,6 +4506,46 @@ def _apigw_deployment_delete(physical_id, props):
# --- API Gateway Stage ---
+_APIGW_METHOD_SETTING_FIELDS = (
+ ("CacheDataEncrypted", "cacheDataEncrypted"),
+ ("CacheTtlInSeconds", "cacheTtlInSeconds"),
+ ("CachingEnabled", "cachingEnabled"),
+ ("DataTraceEnabled", "dataTraceEnabled"),
+ ("LoggingLevel", "loggingLevel"),
+ ("MetricsEnabled", "metricsEnabled"),
+ ("ThrottlingBurstLimit", "throttlingBurstLimit"),
+ ("ThrottlingRateLimit", "throttlingRateLimit"),
+)
+
+
+def _apigw_method_settings(raw):
+ """Map a CFN MethodSettings list to the map GetStage returns.
+
+ CloudFormation takes a list of method-setting objects; the service keys
+ them ``"<resourcePath>/<httpMethod>"``, with ``"*/*"`` for the stage-wide
+ entry, over the account-level defaults."""
+ if isinstance(raw, dict):
+ return raw
+ settings = {}
+ for item in raw or []:
+ if not isinstance(item, dict):
+ continue
+ resource_path = item.get("ResourcePath", "/*")
+ http_method = item.get("HttpMethod", "*")
+ if resource_path == "/*" and http_method == "*":
+ key = "*/*"
+ else:
+ key = f"{resource_path}/{http_method}"
+ entry = _apigw_v1._default_method_setting_entry()
+ for prop, field in _APIGW_METHOD_SETTING_FIELDS:
+ if item.get(prop) is not None:
+ entry[field] = _apigw_v1._parse_stage_method_setting_value(
+ field, item[prop]
+ )
+ settings[key] = entry
+ return settings
+
+
def _apigw_stage_create(logical_id, props, stack_name):
api_id = props.get("RestApiId", "")
stage_name = props.get("StageName", "")
@@ -4514,7 +4554,7 @@ def _apigw_stage_create(logical_id, props, stack_name):
"deploymentId": props.get("DeploymentId", ""),
"description": props.get("Description", ""),
"variables": props.get("Variables", {}),
- "methodSettings": props.get("MethodSettings", {}),
+ "methodSettings": _apigw_method_settings(props.get("MethodSettings")),
"tracingEnabled": props.get("TracingEnabled", False),
"tags": {t["Key"]: t["Value"] for t in props.get("Tags", [])},
}
@@ -4541,14 +4581,14 @@ def _apigw_stage_update(physical_id, old_props, new_props, stack_name):
("DeploymentId", "/deploymentId", ""),
("Description", "/description", ""),
("Variables", "/variables", {}),
- ("MethodSettings", "/methodSettings", {}),
+ ("MethodSettings", "/methodSettings", []),
("TracingEnabled", "/tracingEnabled", False),
):
if new_props.get(prop, default) != old_props.get(prop, default):
- patch_ops.append({
- "op": "replace", "path": path,
- "value": new_props.get(prop, default),
- })
+ value = new_props.get(prop, default)
+ if prop == "MethodSettings":
+ value = _apigw_method_settings(value)
+ patch_ops.append({"op": "replace", "path": path, "value": value})
if patch_ops:
resp = _apigw_v1._update_stage(api_id, stage_name, {"patchOperations": patch_ops})
if resp[0] >= 400:
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 57bfa25d..2e95ee2b 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -12599,6 +12599,180 @@ def test_cfn_apigateway_stage_ref_returns_stage_name(cfn, apigw_v1):
_wait_stack(cfn, stack_name)
+def test_cfn_apigateway_stage_method_settings_become_a_map(cfn, apigw_v1):
+ """MethodSettings is a list in CloudFormation and a map on the stage.
+
+ Regression for the 1.5.14 outage: the list was stored verbatim, so the
+ throttling lookup on the request path raised and every method answered 500.
+ """
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+ port = urlparse(endpoint).port or 4566
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"intg-cfn-apigw-method-settings-{suffix}"
+ template = {
+ "Resources": {
+ "Api": {
+ "Type": "AWS::ApiGateway::RestApi",
+ "Properties": {"Name": f"method-settings-{suffix}"},
+ },
+ "MockResource": {
+ "Type": "AWS::ApiGateway::Resource",
+ "Properties": {
+ "RestApiId": {"Ref": "Api"},
+ "ParentId": {"Fn::GetAtt": ["Api", "RootResourceId"]},
+ "PathPart": "mock",
+ },
+ },
+ "MockMethod": {
+ "Type": "AWS::ApiGateway::Method",
+ "Properties": {
+ "RestApiId": {"Ref": "Api"},
+ "ResourceId": {"Ref": "MockResource"},
+ "HttpMethod": "GET",
+ "AuthorizationType": "NONE",
+ "Integration": {"Type": "MOCK"},
+ },
+ },
+ "Deployment": {
+ "Type": "AWS::ApiGateway::Deployment",
+ "DependsOn": "MockMethod",
+ "Properties": {"RestApiId": {"Ref": "Api"}},
+ },
+ "Stage": {
+ "Type": "AWS::ApiGateway::Stage",
+ "Properties": {
+ "RestApiId": {"Ref": "Api"},
+ "DeploymentId": {"Ref": "Deployment"},
+ "StageName": "prod",
+ "MethodSettings": [
+ {
+ "ResourcePath": "/*",
+ "HttpMethod": "*",
+ "LoggingLevel": "INFO",
+ "MetricsEnabled": True,
+ },
+ {
+ "ResourcePath": "/mock",
+ "HttpMethod": "GET",
+ "ThrottlingBurstLimit": 11,
+ "ThrottlingRateLimit": 7,
+ "CachingEnabled": "false",
+ "CacheTtlInSeconds": "60",
+ },
+ ],
+ },
+ },
+ },
+ "Outputs": {"ApiId": {"Value": {"Ref": "Api"}}},
+ }
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ api_id = {item["OutputKey"]: item["OutputValue"] for item in stack["Outputs"]}[
+ "ApiId"
+ ]
+
+ settings = apigw_v1.get_stage(restApiId=api_id, stageName="prod")[
+ "methodSettings"
+ ]
+ assert set(settings) == {"*/*", "/mock/GET"}
+ assert settings["*/*"] == {
+ "metricsEnabled": True,
+ "loggingLevel": "INFO",
+ "dataTraceEnabled": False,
+ "throttlingBurstLimit": 5000,
+ "throttlingRateLimit": 10000.0,
+ "cachingEnabled": False,
+ "cacheTtlInSeconds": 300,
+ "cacheDataEncrypted": False,
+ "requireAuthorizationForCacheControl": True,
+ "unauthorizedCacheControlHeaderStrategy": "SUCCEED_WITH_RESPONSE_HEADER",
+ }
+ # Each property is typed by its shape, not by how the template spelled
+ # it: a stringly-typed template value lands as the bool or int AWS reports.
+ per_method = settings["/mock/GET"]
+ assert per_method["throttlingBurstLimit"] == 11
+ assert isinstance(per_method["throttlingRateLimit"], float)
+ assert per_method["throttlingRateLimit"] == 7.0
+ assert per_method["cachingEnabled"] is False
+ assert per_method["cacheTtlInSeconds"] == 60
+ assert per_method["loggingLevel"] == "OFF"
+
+ req = urllib.request.Request(
+ f"http://127.0.0.1:{port}/prod/mock",
+ method="GET",
+ headers={"Host": f"{api_id}.execute-api.localhost:{port}"},
+ )
+ with urllib.request.urlopen(req) as resp:
+ assert resp.status == 200
+ finally:
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+
+
+def test_cfn_apigateway_stage_method_settings_update_in_place(cfn, apigw_v1):
+ """A changed MethodSettings list reaches the stage through UpdateStage as a
+ map, not as the raw CloudFormation list."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"intg-cfn-apigw-method-settings-upd-{suffix}"
+
+ def _template(logging_level):
+ return json.dumps({
+ "Resources": {
+ "Api": {
+ "Type": "AWS::ApiGateway::RestApi",
+ "Properties": {"Name": f"method-settings-upd-{suffix}"},
+ },
+ "Deployment": {
+ "Type": "AWS::ApiGateway::Deployment",
+ "Properties": {"RestApiId": {"Ref": "Api"}},
+ },
+ "Stage": {
+ "Type": "AWS::ApiGateway::Stage",
+ "Properties": {
+ "RestApiId": {"Ref": "Api"},
+ "DeploymentId": {"Ref": "Deployment"},
+ "StageName": "prod",
+ "MethodSettings": [
+ {
+ "ResourcePath": "/*",
+ "HttpMethod": "*",
+ "LoggingLevel": logging_level,
+ },
+ ],
+ },
+ },
+ },
+ "Outputs": {"ApiId": {"Value": {"Ref": "Api"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=_template("ERROR"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ api_id = {item["OutputKey"]: item["OutputValue"] for item in stack["Outputs"]}[
+ "ApiId"
+ ]
+ settings = apigw_v1.get_stage(restApiId=api_id, stageName="prod")[
+ "methodSettings"
+ ]
+ assert settings["*/*"]["loggingLevel"] == "ERROR"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_template("INFO"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ settings = apigw_v1.get_stage(restApiId=api_id, stageName="prod")[
+ "methodSettings"
+ ]
+ assert set(settings) == {"*/*"}
+ assert settings["*/*"]["loggingLevel"] == "INFO"
+ finally:
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+
+
def test_cfn_apigateway_rest_api_tracks_stack_region(cfn, apigw_v1):
"""A v1 REST API created by a regional stack is scoped to that region, while
unsigned execute-api data-plane requests still resolve by API id."""