Skip to content

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

feat(cfn): implement CloudFormation Custom Resource protocol (Custom:: + AWS::CloudFormation::CustomResource) (#603)

Michael Smithcebfc0aef173
diff --git a/ministack/app.py b/ministack/app.py
index f0a57255..735b1dbd 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -771,6 +771,20 @@ async def _handle_admin_config_request(path: str, method: str, body: bytes):
async def _handle_post_body_shortcuts(method: str, path: str, headers: dict, body: bytes, query_params: dict, request_id: str):
"""Handle body-dependent routes before the generic service router."""
+ # CloudFormation custom resource ResponseURL intercept
+ if method == "PUT" and path.startswith("/_ministack/cfn-response/"):
+ token = path[len("/_ministack/cfn-response/"):]
+ try:
+ payload = json.loads(body) if body else {}
+ except (json.JSONDecodeError, ValueError):
+ payload = {}
+ from ministack.services.cloudformation import custom_resource as _cfn_cr
+ if not _cfn_cr.deliver_response(token, payload):
+ logging.getLogger("cloudformation").warning(
+ "CFN ResponseURL PUT for unknown token %r — ignoring", token
+ )
+ return 200, {}, b""
+
response = await _handle_cognito_body_request(method, path, headers, body, query_params)
if response is not None:
# See _handle_pre_body_request: browser-based OIDC clients need CORS.
diff --git a/ministack/services/cloudformation/__init__.py b/ministack/services/cloudformation/__init__.py
index 30a31c12..f62930a2 100644
--- a/ministack/services/cloudformation/__init__.py
+++ b/ministack/services/cloudformation/__init__.py
@@ -74,6 +74,8 @@ def reset():
_stack_events.clear()
_exports.clear()
_change_sets.clear()
+ from ministack.services.cloudformation import custom_resource as _cr
+ _cr.reset()
# Must be last — handlers imports from this module
diff --git a/ministack/services/cloudformation/custom_resource.py b/ministack/services/cloudformation/custom_resource.py
new file mode 100644
index 00000000..fa6d63ba
--- /dev/null
+++ b/ministack/services/cloudformation/custom_resource.py
@@ -0,0 +1,133 @@
+"""
+CloudFormation Custom Resource — ResponseURL intercept and Lambda invocation.
+"""
+import logging
+import os
+import threading
+
+logger = logging.getLogger("cloudformation")
+
+_HOST = os.environ.get("MINISTACK_HOST", "localhost")
+_PORT = os.environ.get("GATEWAY_PORT", "4566")
+
+_lock = threading.Lock()
+# token → {"event": threading.Event, "result": dict | None}
+_pending: dict = {}
+
+
+def register_token(token: str) -> threading.Event:
+ evt = threading.Event()
+ with _lock:
+ _pending[token] = {"event": evt, "result": None}
+ return evt
+
+
+def deliver_response(token: str, response: dict) -> bool:
+ """Called by the HTTP handler when ResponseURL is PUT to. Returns False if token unknown."""
+ with _lock:
+ entry = _pending.get(token)
+ if entry is None:
+ return False
+ entry["result"] = response
+ entry["event"].set()
+ return True
+
+
+def reset():
+ with _lock:
+ _pending.clear()
+
+
+def _response_url(token: str) -> str:
+ return f"http://{_HOST}:{_PORT}/_ministack/cfn-response/{token}"
+
+
+def _func_name_from_arn(service_token: str) -> str:
+ """Extract function name from a Lambda ARN, or return as-is."""
+ if service_token.startswith("arn:"):
+ parts = service_token.split(":")
+ # arn:aws:lambda:region:account:function:<name>[:<qualifier>]
+ return parts[6] if len(parts) >= 7 else parts[-1]
+ return service_token
+
+
+def invoke_custom_resource(
+ request_type: str,
+ logical_id: str,
+ props: dict,
+ stack_name: str,
+ stack_id: str,
+ resource_type: str,
+ physical_id: str | None = None,
+ old_props: dict | None = None,
+) -> tuple:
+ """Invoke the ServiceToken Lambda and block until it PUTs to the ResponseURL.
+
+ CALLER CONTRACT: Must be run in a worker thread (via asyncio.to_thread), never
+ directly from a coroutine — it blocks on threading.Event.wait() so the event
+ loop must remain free to receive the ResponseURL PUT callback.
+
+ Returns (physical_resource_id, data_attributes).
+ Raises ValueError if the Lambda is not found.
+ Raises TimeoutError if no response arrives within ServiceTimeout seconds.
+ Raises RuntimeError if the Lambda responds with Status=FAILED.
+ """
+ import ministack.services.lambda_svc as _lambda_svc
+ from ministack.core.responses import new_uuid
+
+ service_token = props.get("ServiceToken", "")
+ func_name = _func_name_from_arn(service_token)
+
+ if func_name not in _lambda_svc._functions:
+ raise ValueError(
+ f"Custom resource ServiceToken {service_token!r} not found. "
+ "Ensure the Lambda function is provisioned before the custom resource."
+ )
+
+ func_record = _lambda_svc._functions[func_name]
+ try:
+ service_timeout = int(props.get("ServiceTimeout", 3600))
+ except (ValueError, TypeError):
+ service_timeout = 3600
+
+ token = new_uuid()
+ request_id = new_uuid()
+
+ cfn_event = {
+ "RequestType": request_type,
+ "RequestId": request_id,
+ "StackId": stack_id,
+ "ResponseURL": _response_url(token),
+ "ResourceType": resource_type,
+ "LogicalResourceId": logical_id,
+ "ResourceProperties": dict(props),
+ }
+ if physical_id is not None:
+ cfn_event["PhysicalResourceId"] = physical_id
+ if old_props is not None:
+ cfn_event["OldResourceProperties"] = dict(old_props)
+
+ event_obj = register_token(token)
+
+ try:
+ _lambda_svc._execute_function(func_record, cfn_event)
+ except Exception as exc:
+ logger.warning("Custom resource Lambda raised synchronously: %s", exc)
+
+ signalled = event_obj.wait(timeout=service_timeout)
+
+ with _lock:
+ entry = _pending.pop(token, None)
+
+ if not signalled or entry is None or entry["result"] is None:
+ raise TimeoutError(
+ f"Custom resource {logical_id!r} timed out after {service_timeout}s "
+ "waiting for ResponseURL callback"
+ )
+
+ result = entry["result"]
+ if result.get("Status") == "FAILED":
+ raise RuntimeError(result.get("Reason", "Custom resource reported FAILED"))
+
+ pid = result.get("PhysicalResourceId") or (physical_id if physical_id else request_id)
+ return pid, result.get("Data") or {}
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index bde95fd0..ad620ba3 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -79,6 +79,9 @@ def _provision_resource(resource_type: str, logical_id: str, props: dict,
handler = _RESOURCE_HANDLERS.get(resource_type)
if handler and "create" in handler:
return handler["create"](logical_id, props, stack_name)
+ # Custom resource types (Custom::* handled here; AWS::CloudFormation::CustomResource goes through handler)
+ if resource_type.startswith("Custom::"):
+ return _custom_resource_create(logical_id, props, stack_name, resource_type)
# CloudFormation internal types are no-ops
if resource_type.startswith("AWS::CloudFormation::"):
logger.info("CloudFormation internal type %s for %s -- noop", resource_type, logical_id)
@@ -87,18 +90,28 @@ def _provision_resource(resource_type: str, logical_id: str, props: dict,
raise ValueError(f"Unsupported resource type: {resource_type}")
-def _delete_resource(resource_type: str, physical_id: str, props: dict):
+def _delete_resource(resource_type: str, physical_id: str, props: dict,
+ stack_name: str | None = None, logical_id: str | None = None):
"""Delete a provisioned resource."""
handler = _RESOURCE_HANDLERS.get(resource_type)
if handler and "delete" in handler:
handler["delete"](physical_id, props)
return
+ # Custom resource types
+ if resource_type.startswith("Custom::") or resource_type == "AWS::CloudFormation::CustomResource":
+ _custom_resource_delete(
+ physical_id, props,
+ stack_name=stack_name, logical_id=logical_id,
+ resource_type=resource_type,
+ )
+ return
logger.warning("No delete handler for resource type %s (id=%s)",
resource_type, physical_id)
def _update_resource(resource_type: str, physical_id: str, old_props: dict,
- new_props: dict, stack_name: str) -> tuple:
+ new_props: dict, stack_name: str,
+ logical_id: str | None = None) -> tuple:
"""Update a provisioned resource in place when the type provides an ``update``
handler. Falls back to ``create`` (which provisioners are expected to
implement idempotently) when no explicit update handler is registered.
@@ -107,6 +120,13 @@ def _update_resource(resource_type: str, physical_id: str, old_props: dict,
handler = _RESOURCE_HANDLERS.get(resource_type)
if handler and "update" in handler:
return handler["update"](physical_id, old_props, new_props, stack_name)
+ # Custom resource types
+ if resource_type.startswith("Custom::") or resource_type == "AWS::CloudFormation::CustomResource":
+ return _custom_resource_update(
+ physical_id, old_props, new_props, stack_name,
+ logical_id=logical_id,
+ resource_type=resource_type,
+ )
# No update handler — fall through to create. Most resource types make
# their create idempotent; CFN never sees a fresh physical id this way.
return _provision_resource(resource_type, physical_id, new_props, stack_name)
@@ -1028,6 +1048,49 @@ def _cfn_wait_condition_handle_create(logical_id, props, stack_name):
return pid, {"Ref": url}
+# --- CloudFormation Custom Resource ---
+
+def _cr_stack_id(stack_name: str) -> str:
+ """Return the StackId for stack_name, falling back to a synthesised ARN."""
+ from ministack.services.cloudformation import _stacks
+ stack = _stacks.get(stack_name) or {}
+ return stack.get(
+ "StackId",
+ f"arn:aws:cloudformation:{get_region()}:{get_account_id()}:stack/{stack_name}/unknown",
+ )
+
+
+def _custom_resource_create(logical_id, props, stack_name, resource_type="AWS::CloudFormation::CustomResource"):
+ from ministack.services.cloudformation import custom_resource as _cr
+ return _cr.invoke_custom_resource(
+ "Create", logical_id, props, stack_name, _cr_stack_id(stack_name), resource_type,
+ )
+
+
+def _custom_resource_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None, resource_type="AWS::CloudFormation::CustomResource"):
+ from ministack.services.cloudformation import custom_resource as _cr
+ return _cr.invoke_custom_resource(
+ "Update", logical_id or physical_id, new_props, stack_name,
+ _cr_stack_id(stack_name), resource_type,
+ physical_id=physical_id, old_props=old_props,
+ )
+
+
+def _custom_resource_delete(physical_id, props, stack_name=None, logical_id=None,
+ resource_type="AWS::CloudFormation::CustomResource"):
+ # CDK uses a marker physical ID when Create failed — treat as no-op
+ if not physical_id or physical_id == "FAILED_CREATE_MARKER":
+ return
+ sname = stack_name or ""
+ from ministack.services.cloudformation import custom_resource as _cr
+ _cr.invoke_custom_resource(
+ "Delete", logical_id or physical_id, props, sname,
+ _cr_stack_id(sname), resource_type,
+ physical_id=physical_id,
+ )
+
+
# --- API Gateway REST API ---
def _apigw_rest_api_create(logical_id, props, stack_name):
@@ -3091,6 +3154,11 @@ _RESOURCE_HANDLERS = {
"AWS::Lambda::Version": {"create": _lambda_version_create},
"AWS::CloudFormation::WaitCondition": {"create": _cfn_wait_condition_create},
"AWS::CloudFormation::WaitConditionHandle": {"create": _cfn_wait_condition_handle_create},
+ # The "create" entry is load-bearing: without it, _provision_resource would
+ # hit the generic "AWS::CloudFormation::*" no-op branch. Update and delete
+ # are intentionally absent — they route through the explicit if-branches in
+ # _update_resource/_delete_resource so stack_name and logical_id reach the handler.
+ "AWS::CloudFormation::CustomResource": {"create": _custom_resource_create},
"AWS::ApiGateway::RestApi": {"create": _apigw_rest_api_create, "delete": _apigw_rest_api_delete},
"AWS::ApiGateway::Resource": {"create": _apigw_resource_create, "delete": _apigw_resource_delete},
"AWS::ApiGateway::Method": {"create": _apigw_method_create, "delete": _apigw_method_delete},
diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.py
index 8d0420cc..3e529756 100644
--- a/ministack/services/cloudformation/stacks.py
+++ b/ministack/services/cloudformation/stacks.py
@@ -23,6 +23,10 @@ from .provisioners import REGION, _delete_resource, _provision_resource, _update
logger = logging.getLogger("cloudformation")
+def _is_custom_resource(resource_type: str) -> bool:
+ return resource_type.startswith("Custom::") or resource_type == "AWS::CloudFormation::CustomResource"
+
+
# ===========================================================================
# Stack Events helper
# ===========================================================================
@@ -124,13 +128,24 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
if prev_resource:
old_pid = prev_resource.get("PhysicalResourceId", logical_id)
old_props = prev_resource.get("Properties", {})
- physical_id, attrs = _update_resource(
- resource_type, old_pid, old_props, resolved_props, stack_name
- )
+ if _is_custom_resource(resource_type):
+ physical_id, attrs = await asyncio.to_thread(
+ _update_resource, resource_type, old_pid, old_props,
+ resolved_props, stack_name, logical_id
+ )
+ else:
+ physical_id, attrs = _update_resource(
+ resource_type, old_pid, old_props, resolved_props, stack_name
+ )
else:
- physical_id, attrs = _provision_resource(
- resource_type, logical_id, resolved_props, stack_name
- )
+ if _is_custom_resource(resource_type):
+ physical_id, attrs = await asyncio.to_thread(
+ _provision_resource, resource_type, logical_id, resolved_props, stack_name
+ )
+ else:
+ physical_id, attrs = _provision_resource(
+ resource_type, logical_id, resolved_props, stack_name
+ )
except Exception as exc:
logger.error("Failed to provision %s (%s): %s",
logical_id, resource_type, exc)
@@ -163,7 +178,13 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
pid = old_res.get("PhysicalResourceId", "")
old_props = old_res.get("Properties", {})
try:
- _delete_resource(rtype, pid, old_props)
+ if _is_custom_resource(rtype):
+ await asyncio.to_thread(
+ _delete_resource, rtype, pid, old_props,
+ stack_name, logical_id
+ )
+ else:
+ _delete_resource(rtype, pid, old_props, stack_name, logical_id)
except Exception as exc:
logger.warning("Failed to delete old resource %s: %s",
logical_id, exc)
@@ -191,7 +212,13 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,
pid = res.get("PhysicalResourceId", "")
res_props = res.get("Properties", {})
try:
- _delete_resource(rtype, pid, res_props)
+ if _is_custom_resource(rtype):
+ await asyncio.to_thread(
+ _delete_resource, rtype, pid, res_props,
+ stack_name, logical_id
+ )
+ else:
+ _delete_resource(rtype, pid, res_props, stack_name, logical_id)
_add_event(stack_id, stack_name, logical_id, rtype,
"DELETE_COMPLETE", physical_id=pid)
except Exception as del_exc:
@@ -293,7 +320,13 @@ async def _delete_stack_async(stack_name: str, stack_id: str):
_add_event(stack_id, stack_name, logical_id, rtype,
"DELETE_IN_PROGRESS", physical_id=pid)
try:
- _delete_resource(rtype, pid, res_props)
+ if _is_custom_resource(rtype):
+ await asyncio.to_thread(
+ _delete_resource, rtype, pid, res_props,
+ stack_name, logical_id
+ )
+ else:
+ _delete_resource(rtype, pid, res_props, stack_name, logical_id)
_add_event(stack_id, stack_name, logical_id, rtype,
"DELETE_COMPLETE", physical_id=pid)
except Exception as exc:
diff --git a/tests/test_cfn_custom_resource.py b/tests/test_cfn_custom_resource.py
new file mode 100644
index 00000000..41ad6567
--- /dev/null
+++ b/tests/test_cfn_custom_resource.py
@@ -0,0 +1,523 @@
+"""
+CloudFormation Custom Resource integration tests.
+Requires a running Ministack server at MINISTACK_ENDPOINT (default http://localhost:4566).
+"""
+import io
+import json
+import time
+import threading
+import uuid
+import urllib.request
+import zipfile
+
+import pytest
+from botocore.exceptions import ClientError
+
+ENDPOINT = "http://localhost:4566"
+_LAMBDA_ROLE = "arn:aws:iam::000000000000:role/lambda-role"
+
+
+def _make_zip(code: str) -> bytes:
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", code)
+ return buf.getvalue()
+
+
+def _wait_stack(cfn, name, timeout=30):
+ deadline = time.time() + timeout
+ status = "UNKNOWN"
+ while time.time() < deadline:
+ try:
+ stacks = cfn.describe_stacks(StackName=name)["Stacks"]
+ except ClientError as exc:
+ if "does not exist" in str(exc):
+ return {"StackStatus": "DELETE_COMPLETE", "StackName": name}
+ raise
+ status = stacks[0]["StackStatus"]
+ if not status.endswith("_IN_PROGRESS"):
+ return stacks[0]
+ time.sleep(0.3)
+ raise TimeoutError(f"Stack {name} stuck at {status}")
+
+
+def _cfn_template(func_name, resource_type="Custom::Tester", extra_props=None, outputs=None):
+ """Build a CF template with a single custom resource."""
+ props = {"ServiceToken": f"arn:aws:lambda:us-east-1:000000000000:function:{func_name}"}
+ if extra_props:
+ props.update(extra_props)
+ tpl = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "CR": {
+ "Type": resource_type,
+ "Properties": props,
+ }
+ },
+ }
+ if outputs:
+ tpl["Outputs"] = outputs
+ return json.dumps(tpl)
+
+
+# ── token registry smoke test ──────────────────────────────────────────────
+
+def test_cfn_response_endpoint_accepts_put(cfn):
+ """PUT to /_ministack/cfn-response/{token} returns 200 even for unknown tokens."""
+ token = str(uuid.uuid4())
+ payload = json.dumps({"Status": "SUCCESS", "PhysicalResourceId": "x",
+ "RequestId": "r", "StackId": "s", "LogicalResourceId": "l"}).encode()
+ req = urllib.request.Request(
+ f"{ENDPOINT}/_ministack/cfn-response/{token}",
+ data=payload,
+ method="PUT",
+ headers={"content-type": "", "content-length": str(len(payload))},
+ )
+ with urllib.request.urlopen(req, timeout=5) as resp:
+ assert resp.status == 200
+
+
+# ── Create lifecycle ───────────────────────────────────────────────────────
+
+_CR_HANDLER_SUCCESS = """\
+import json, urllib.request
+
+def handler(event, context):
+ payload = json.dumps({
+ "Status": "SUCCESS",
+ "RequestId": event["RequestId"],
+ "StackId": event["StackId"],
+ "LogicalResourceId": event["LogicalResourceId"],
+ "PhysicalResourceId": "my-custom-resource-123",
+ "Data": {"Endpoint": "https://example.com", "Region": "us-east-1"},
+ }).encode()
+ req = urllib.request.Request(
+ event["ResponseURL"],
+ data=payload,
+ method="PUT",
+ headers={"content-type": "", "content-length": str(len(payload))},
+ )
+ urllib.request.urlopen(req, timeout=10)
+"""
+
+
+def test_custom_resource_create_success(cfn, lam):
+ lam.create_function(
+ FunctionName="cr-test-success",
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(_CR_HANDLER_SUCCESS)},
+ )
+ try:
+ cfn.create_stack(
+ StackName="cr-t01",
+ TemplateBody=_cfn_template("cr-test-success"),
+ )
+ stack = _wait_stack(cfn, "cr-t01")
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ res = cfn.describe_stack_resource(StackName="cr-t01", LogicalResourceId="CR")
+ assert res["StackResourceDetail"]["PhysicalResourceId"] == "my-custom-resource-123"
+ finally:
+ cfn.delete_stack(StackName="cr-t01")
+ _wait_stack(cfn, "cr-t01")
+ lam.delete_function(FunctionName="cr-test-success")
+
+
+def test_custom_resource_type_prefix(cfn, lam):
+ """Custom::Tester and AWS::CloudFormation::CustomResource both work."""
+ lam.create_function(
+ FunctionName="cr-test-prefix",
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(_CR_HANDLER_SUCCESS)},
+ )
+ try:
+ cfn.create_stack(
+ StackName="cr-t02a",
+ TemplateBody=_cfn_template("cr-test-prefix", resource_type="Custom::MyTester"),
+ )
+ stack = _wait_stack(cfn, "cr-t02a")
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+
+ cfn.create_stack(
+ StackName="cr-t02b",
+ TemplateBody=_cfn_template("cr-test-prefix", resource_type="AWS::CloudFormation::CustomResource"),
+ )
+ stack = _wait_stack(cfn, "cr-t02b")
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ finally:
+ for name in ("cr-t02a", "cr-t02b"):
+ try:
+ cfn.delete_stack(StackName=name)
+ _wait_stack(cfn, name)
+ except Exception:
+ pass
+ lam.delete_function(FunctionName="cr-test-prefix")
+
+
+# ── FAILED status → rollback ───────────────────────────────────────────────
+
+_CR_HANDLER_FAILED = """\
+import json, urllib.request
+
+def handler(event, context):
+ payload = json.dumps({
+ "Status": "FAILED",
+ "Reason": "Intentional test failure",
+ "RequestId": event["RequestId"],
+ "StackId": event["StackId"],
+ "LogicalResourceId": event["LogicalResourceId"],
+ "PhysicalResourceId": "failed-resource",
+ }).encode()
+ req = urllib.request.Request(
+ event["ResponseURL"],
+ data=payload,
+ method="PUT",
+ headers={"content-type": "", "content-length": str(len(payload))},
+ )
+ urllib.request.urlopen(req, timeout=10)
+"""
+
+
+def test_custom_resource_create_failed_triggers_rollback(cfn, lam):
+ lam.create_function(
+ FunctionName="cr-test-fail",
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(_CR_HANDLER_FAILED)},
+ )
+ try:
+ cfn.create_stack(StackName="cr-t03", TemplateBody=_cfn_template("cr-test-fail"))
+ stack = _wait_stack(cfn, "cr-t03")
+ assert stack["StackStatus"] in ("ROLLBACK_COMPLETE", "CREATE_FAILED"), stack
+ finally:
+ try:
+ cfn.delete_stack(StackName="cr-t03")
+ _wait_stack(cfn, "cr-t03")
+ except Exception:
+ pass
+ lam.delete_function(FunctionName="cr-test-fail")
+
+
+# ── Update lifecycle ───────────────────────────────────────────────────────
+
+_CR_HANDLER_RECORD = """\
+import json, urllib.request
+
+def handler(event, context):
+ # Echo what was received so tests can inspect it
+ data = {
+ "RequestType": event["RequestType"],
+ "PhysicalResourceId": event.get("PhysicalResourceId", ""),
+ "HasOldProps": str("OldResourceProperties" in event),
+ "OldFoo": str(event.get("OldResourceProperties", {}).get("Foo", "")),
+ "NewFoo": str(event.get("ResourceProperties", {}).get("Foo", "")),
+ }
+ pid = event.get("PhysicalResourceId") or "recorded-resource-id"
+ payload = json.dumps({
+ "Status": "SUCCESS",
+ "RequestId": event["RequestId"],
+ "StackId": event["StackId"],
+ "LogicalResourceId": event["LogicalResourceId"],
+ "PhysicalResourceId": pid,
+ "Data": data,
+ }).encode()
+ req = urllib.request.Request(
+ event["ResponseURL"],
+ data=payload,
+ method="PUT",
+ headers={"content-type": "", "content-length": str(len(payload))},
+ )
+ urllib.request.urlopen(req, timeout=10)
+"""
+
+
+def test_custom_resource_update_sends_old_properties(cfn, lam):
+ lam.create_function(
+ FunctionName="cr-test-record",
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(_CR_HANDLER_RECORD)},
+ )
+ try:
+ tpl_v1 = _cfn_template("cr-test-record", extra_props={"Foo": "bar-v1"})
+ cfn.create_stack(StackName="cr-t04", TemplateBody=tpl_v1)
+ _wait_stack(cfn, "cr-t04")
+
+ tpl_v2 = _cfn_template(
+ "cr-test-record",
+ extra_props={"Foo": "bar-v2"},
+ outputs={
+ "HasOldPropsOut": {"Value": {"Fn::GetAtt": ["CR", "HasOldProps"]}},
+ "OldFooOut": {"Value": {"Fn::GetAtt": ["CR", "OldFoo"]}},
+ "NewFooOut": {"Value": {"Fn::GetAtt": ["CR", "NewFoo"]}},
+ },
+ )
+ cfn.update_stack(StackName="cr-t04", TemplateBody=tpl_v2)
+ stack = _wait_stack(cfn, "cr-t04")
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+
+ res = cfn.describe_stack_resource(StackName="cr-t04", LogicalResourceId="CR")
+ assert res["StackResourceDetail"]["ResourceStatus"] == "UPDATE_COMPLETE"
+
+ # Verify OldResourceProperties were forwarded to the Lambda on Update
+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}
+ assert outputs.get("HasOldPropsOut") == "True", f"OldResourceProperties missing: {outputs}"
+ assert outputs.get("OldFooOut") == "bar-v1", f"OldFoo wrong: {outputs}"
+ assert outputs.get("NewFooOut") == "bar-v2", f"NewFoo wrong: {outputs}"
+ finally:
+ cfn.delete_stack(StackName="cr-t04")
+ _wait_stack(cfn, "cr-t04")
+ lam.delete_function(FunctionName="cr-test-record")
+
+
+def test_custom_resource_delete_sends_physical_id(cfn, lam):
+ """Stack delete must send the PhysicalResourceId from Create to the Lambda."""
+ _CR_DELETE_CHECK = """\
+import json, urllib.request
+
+def handler(event, context):
+ data = {
+ "RequestType": event["RequestType"],
+ "ReceivedPhysicalId": event.get("PhysicalResourceId", "MISSING"),
+ }
+ pid = event.get("PhysicalResourceId") or "delete-test-id"
+ payload = json.dumps({
+ "Status": "SUCCESS",
+ "RequestId": event["RequestId"],
+ "StackId": event["StackId"],
+ "LogicalResourceId": event["LogicalResourceId"],
+ "PhysicalResourceId": pid,
+ "Data": data,
+ }).encode()
+ req = urllib.request.Request(
+ event["ResponseURL"],
+ data=payload,
+ method="PUT",
+ headers={"content-type": "", "content-length": str(len(payload))},
+ )
+ urllib.request.urlopen(req, timeout=10)
+"""
+
+ lam.create_function(
+ FunctionName="cr-test-delete",
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(_CR_DELETE_CHECK)},
+ )
+ try:
+ cfn.create_stack(StackName="cr-t05", TemplateBody=_cfn_template("cr-test-delete"))
+ _wait_stack(cfn, "cr-t05")
+
+ res = cfn.describe_stack_resource(StackName="cr-t05", LogicalResourceId="CR")
+ create_pid = res["StackResourceDetail"]["PhysicalResourceId"]
+ assert create_pid # must be non-empty
+
+ cfn.delete_stack(StackName="cr-t05")
+ stack = _wait_stack(cfn, "cr-t05")
+ assert stack["StackStatus"] == "DELETE_COMPLETE", stack
+ finally:
+ try:
+ cfn.delete_stack(StackName="cr-t05")
+ _wait_stack(cfn, "cr-t05")
+ except Exception:
+ pass
+ lam.delete_function(FunctionName="cr-test-delete")
+
+
+# ── Data accessible via Fn::GetAtt ────────────────────────────────────────
+
+def test_custom_resource_data_via_getatt(cfn, lam, ssm):
+ """Data keys returned by the Lambda are accessible via Fn::GetAtt in outputs."""
+ lam.create_function(
+ FunctionName="cr-test-getatt",
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(_CR_HANDLER_SUCCESS)},
+ )
+ tpl = {
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "CR": {
+ "Type": "Custom::GetAttTest",
+ "Properties": {
+ "ServiceToken": "arn:aws:lambda:us-east-1:000000000000:function:cr-test-getatt",
+ },
+ },
+ "Param": {
+ "Type": "AWS::SSM::Parameter",
+ "Properties": {
+ "Name": "cr-t06-endpoint",
+ "Type": "String",
+ "Value": {"Fn::GetAtt": ["CR", "Endpoint"]},
+ },
+ },
+ },
+ }
+ try:
+ cfn.create_stack(StackName="cr-t06", TemplateBody=json.dumps(tpl))
+ stack = _wait_stack(cfn, "cr-t06")
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ val = ssm.get_parameter(Name="cr-t06-endpoint")["Parameter"]["Value"]
+ assert val == "https://example.com"
+ finally:
+ cfn.delete_stack(StackName="cr-t06")
+ _wait_stack(cfn, "cr-t06")
+ lam.delete_function(FunctionName="cr-test-getatt")
+
+
+# ── PhysicalResourceId fallback ───────────────────────────────────────────
+
+_CR_HANDLER_NO_PID = """\
+import json, urllib.request
+
+def handler(event, context):
+ # Deliberately omit PhysicalResourceId — Ministack should use RequestId
+ payload = json.dumps({
+ "Status": "SUCCESS",
+ "RequestId": event["RequestId"],
+ "StackId": event["StackId"],
+ "LogicalResourceId": event["LogicalResourceId"],
+ }).encode()
+ req = urllib.request.Request(
+ event["ResponseURL"],
+ data=payload,
+ method="PUT",
+ headers={"content-type": "", "content-length": str(len(payload))},
+ )
+ urllib.request.urlopen(req, timeout=10)
+"""
+
+
+def test_custom_resource_physical_id_fallback(cfn, lam):
+ """When Lambda omits PhysicalResourceId on Create, Ministack falls back to RequestId."""
+ lam.create_function(
+ FunctionName="cr-test-nopid",
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(_CR_HANDLER_NO_PID)},
+ )
+ try:
+ cfn.create_stack(StackName="cr-t07", TemplateBody=_cfn_template("cr-test-nopid"))
+ stack = _wait_stack(cfn, "cr-t07")
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+
+ res = cfn.describe_stack_resource(StackName="cr-t07", LogicalResourceId="CR")
+ pid = res["StackResourceDetail"]["PhysicalResourceId"]
+ # Must be a non-empty UUID (the RequestId fallback)
+ assert pid and len(pid) > 8
+ finally:
+ cfn.delete_stack(StackName="cr-t07")
+ _wait_stack(cfn, "cr-t07")
+ lam.delete_function(FunctionName="cr-test-nopid")
+
+
+# ── Async response (Lambda returns before PUTting ResponseURL) ─────────────
+
+_CR_HANDLER_ASYNC = """\
+import json, threading, time, urllib.request
+
+def handler(event, context):
+ # Return immediately; a background thread delivers the response after a delay.
+ captured = dict(event)
+
+ def respond():
+ time.sleep(0.5)
+ payload = json.dumps({
+ "Status": "SUCCESS",
+ "RequestId": captured["RequestId"],
+ "StackId": captured["StackId"],
+ "LogicalResourceId": captured["LogicalResourceId"],
+ "PhysicalResourceId": "async-resource-id",
+ "Data": {"AsyncResult": "done"},
+ }).encode()
+ req = urllib.request.Request(
+ captured["ResponseURL"],
+ data=payload,
+ method="PUT",
+ headers={"content-type": "", "content-length": str(len(payload))},
+ )
+ urllib.request.urlopen(req, timeout=10)
+
+ threading.Thread(target=respond, daemon=True).start()
+"""
+
+
+def test_custom_resource_async_response(cfn, lam):
+ """Lambda returns without responding; background thread PUTs to ResponseURL later."""
+ lam.create_function(
+ FunctionName="cr-test-async",
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(_CR_HANDLER_ASYNC)},
+ )
+ try:
+ cfn.create_stack(StackName="cr-t08", TemplateBody=_cfn_template("cr-test-async"))
+ stack = _wait_stack(cfn, "cr-t08", timeout=30)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ res = cfn.describe_stack_resource(StackName="cr-t08", LogicalResourceId="CR")
+ assert res["StackResourceDetail"]["PhysicalResourceId"] == "async-resource-id"
+ finally:
+ cfn.delete_stack(StackName="cr-t08")
+ _wait_stack(cfn, "cr-t08")
+ lam.delete_function(FunctionName="cr-test-async")
+
+
+# ── Timeout ───────────────────────────────────────────────────────────────
+
+_CR_HANDLER_SILENT = """\
+def handler(event, context):
+ # Never PUTs to ResponseURL — triggers timeout
+ pass
+"""
+
+
+def test_custom_resource_timeout_fails_stack(cfn, lam):
+ """ServiceTimeout=2 with a silent Lambda causes the stack to fail."""
+ lam.create_function(
+ FunctionName="cr-test-timeout",
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(_CR_HANDLER_SILENT)},
+ )
+ tpl = _cfn_template("cr-test-timeout", extra_props={"ServiceTimeout": "2"})
+ try:
+ cfn.create_stack(StackName="cr-t09", TemplateBody=tpl)
+ stack = _wait_stack(cfn, "cr-t09", timeout=30)
+ assert stack["StackStatus"] in ("ROLLBACK_COMPLETE", "CREATE_FAILED"), stack
+ finally:
+ try:
+ cfn.delete_stack(StackName="cr-t09")
+ _wait_stack(cfn, "cr-t09")
+ except Exception:
+ pass
+ lam.delete_function(FunctionName="cr-test-timeout")
+
+
+# ── Lambda not found ──────────────────────────────────────────────────────
+
+def test_custom_resource_lambda_not_found(cfn):
+ """ServiceToken pointing to a nonexistent Lambda fails the stack immediately."""
+ tpl = _cfn_template("cr-does-not-exist-function")
+ try:
+ cfn.create_stack(StackName="cr-t10", TemplateBody=tpl)
+ stack = _wait_stack(cfn, "cr-t10")
+ assert stack["StackStatus"] in ("ROLLBACK_COMPLETE", "CREATE_FAILED"), stack
+ finally:
+ try:
+ cfn.delete_stack(StackName="cr-t10")
+ _wait_stack(cfn, "cr-t10")
+ except Exception:
+ pass