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 base path mappings (#1154)

robert-pitt-foodhub756a49ee7a25
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index ee2d932a..19108af3 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -2089,6 +2089,46 @@ def _apigw_stage_delete(physical_id, props):
_apigw_v1._delete_stage(api_id, stage_name)
+# --- API Gateway BasePathMapping ---
+
+def _apigw_base_path_mapping_identity(props):
+ domain_name = props.get("DomainName", "")
+ base_path = props.get("BasePath") or "(none)"
+ return domain_name, base_path, f"{domain_name}/{base_path}"
+
+
+def _apigw_base_path_mapping_create(logical_id, props, stack_name):
+ domain_name, base_path, physical_id = _apigw_base_path_mapping_identity(props)
+ data = {
+ "basePath": base_path,
+ "restApiId": props.get("RestApiId", ""),
+ "stage": props.get("Stage", ""),
+ }
+ status, _headers, body = _apigw_v1._create_base_path_mapping(domain_name, data)
+ if status >= 400:
+ raise ValueError(f"AWS::ApiGateway::BasePathMapping create failed: {body!r}")
+ return physical_id, {}
+
+
+def _apigw_base_path_mapping_update(physical_id, old_props, new_props, stack_name):
+ old_domain, old_base_path, _old_id = _apigw_base_path_mapping_identity(old_props)
+ new_domain, new_base_path, _new_id = _apigw_base_path_mapping_identity(new_props)
+
+ # BasePath and DomainName require replacement; RestApiId and Stage update
+ # without interruption. The in-memory API Gateway implementation treats a
+ # create against an existing key as an upsert, which gives both paths the
+ # same atomic create-before-delete behavior here.
+ new_id, attrs = _apigw_base_path_mapping_create(physical_id, new_props, stack_name)
+ if (new_domain, new_base_path) != (old_domain, old_base_path):
+ _apigw_v1._delete_base_path_mapping(old_domain, old_base_path)
+ return new_id, attrs
+
+
+def _apigw_base_path_mapping_delete(physical_id, props):
+ domain_name, base_path, _mapping_id = _apigw_base_path_mapping_identity(props)
+ _apigw_v1._delete_base_path_mapping(domain_name, base_path)
+
+
def _apigw_account_create(logical_id, props, stack_name):
"""``AWS::ApiGateway::Account`` is a singleton per AWS account storing the
IAM role API Gateway uses to push logs to CloudWatch. CDK's
@@ -4895,6 +4935,11 @@ _RESOURCE_HANDLERS = {
"AWS::ApiGateway::Authorizer": {"create": _apigw_authorizer_create, "delete": _apigw_authorizer_delete},
"AWS::ApiGateway::Deployment": {"create": _apigw_deployment_create, "delete": _apigw_deployment_delete},
"AWS::ApiGateway::Stage": {"create": _apigw_stage_create, "delete": _apigw_stage_delete},
+ "AWS::ApiGateway::BasePathMapping": {
+ "create": _apigw_base_path_mapping_create,
+ "update": _apigw_base_path_mapping_update,
+ "delete": _apigw_base_path_mapping_delete,
+ },
"AWS::ApiGateway::Account": {"create": _apigw_account_create, "delete": _apigw_account_delete},
"AWS::ApiGateway::DomainName": {
"create": _apigw_domain_name_create,
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 61910527..550b772b 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -4202,6 +4202,101 @@ def test_cfn_apigateway_authorizer_provisions(cfn):
_wait_stack(cfn, stack_name)
+def test_cfn_apigateway_base_path_mapping_lifecycle(cfn, apigw_v1):
+ """AWS::ApiGateway::BasePathMapping creates, updates, replaces, and deletes."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"intg-cfn-base-path-mapping-{suffix}"
+ domain_name = f"cfn-base-path-{suffix}.example.com"
+ first_api_id = apigw_v1.create_rest_api(name=f"base-path-first-{suffix}")["id"]
+ second_api_id = apigw_v1.create_rest_api(name=f"base-path-second-{suffix}")["id"]
+ stack_deleted = False
+
+ apigw_v1.create_domain_name(domainName=domain_name)
+
+ def template(base_path, rest_api_id, stage):
+ properties = {
+ "DomainName": domain_name,
+ "RestApiId": rest_api_id,
+ "Stage": stage,
+ }
+ if base_path is not None:
+ properties["BasePath"] = base_path
+ return {
+ "Resources": {
+ "Mapping": {
+ "Type": "AWS::ApiGateway::BasePathMapping",
+ "Properties": properties,
+ },
+ },
+ "Outputs": {"MappingRef": {"Value": {"Ref": "Mapping"}}},
+ }
+
+ def physical_id():
+ detail = cfn.describe_stack_resource(
+ StackName=stack_name,
+ LogicalResourceId="Mapping",
+ )["StackResourceDetail"]
+ return detail["PhysicalResourceId"]
+
+ try:
+ cfn.create_stack(
+ StackName=stack_name,
+ TemplateBody=json.dumps(template(None, first_api_id, "prod")),
+ )
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert physical_id() == f"{domain_name}/(none)"
+ outputs = {item["OutputKey"]: item["OutputValue"] for item in stack.get("Outputs", [])}
+ assert outputs["MappingRef"] == f"{domain_name}/(none)"
+
+ mapping = apigw_v1.get_base_path_mapping(domainName=domain_name, basePath="(none)")
+ assert mapping["restApiId"] == first_api_id
+ assert mapping["stage"] == "prod"
+
+ # RestApiId and Stage update without replacing the physical resource.
+ cfn.update_stack(
+ StackName=stack_name,
+ TemplateBody=json.dumps(template(None, second_api_id, "beta")),
+ )
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert physical_id() == f"{domain_name}/(none)"
+ mapping = apigw_v1.get_base_path_mapping(domainName=domain_name, basePath="(none)")
+ assert mapping["restApiId"] == second_api_id
+ assert mapping["stage"] == "beta"
+
+ # BasePath requires replacement and removes the previous mapping.
+ cfn.update_stack(
+ StackName=stack_name,
+ TemplateBody=json.dumps(template("v2", second_api_id, "beta")),
+ )
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert physical_id() == f"{domain_name}/v2"
+ with pytest.raises(ClientError) as exc:
+ apigw_v1.get_base_path_mapping(domainName=domain_name, basePath="(none)")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ mapping = apigw_v1.get_base_path_mapping(domainName=domain_name, basePath="v2")
+ assert mapping["restApiId"] == second_api_id
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+ stack_deleted = True
+ with pytest.raises(ClientError) as exc:
+ apigw_v1.get_base_path_mapping(domainName=domain_name, basePath="v2")
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
+ 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=first_api_id)
+ apigw_v1.delete_rest_api(restApiId=second_api_id)
+ apigw_v1.delete_domain_name(domainName=domain_name)
+
+
def test_cfn_apigateway_account_provisions(cfn, apigw_v1):
"""AWS::ApiGateway::Account is the CDK ``cloudWatchRole: true`` resource.
Without a registered handler, stacks fail with ``Unsupported resource