Skip to content

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

release v1.4.16 (#1353)

Nahuel Nucerade640a16626f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6295e0f8..11a30572 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,14 +7,21 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+## [1.4.16] — 2026-08-12
+
+### Added
+- **Aurora DSQL emulator** — control plane over the REST-JSON API (cluster lifecycle, tags, and cluster policies; `clientToken` idempotency, `deletionProtectionEnabled`, `expectedPolicyVersion` concurrency). With `DSQL_STRICT=1` and Docker, each cluster gets a real Postgres container fronted by an in-process wire-protocol proxy enforcing DSQL's SQL subset; otherwise it goes `ACTIVE` metadata-only. Tunable via `DSQL_BASE_PORT` / `DSQL_STRICT` / `DSQL_PERSIST` / `DSQL_PG_IMAGE`. Contributed by @ry-allan.
+
### Fixed
-- **CloudFormation — resources unchanged by a stack update are left alone** — every previously-provisioned resource was reprocessed on every stack update regardless of whether its properties changed, and any resource type with no dedicated update handler fell back to calling create again — a fallback whose own name-generation regenerated a fresh random suffix on every call, and whose caller passed the wrong id into it, on top of that. An auto-named resource's "idempotent" create (the type framework's own documented expectation) silently produced a brand new, empty resource under a new identity on every single update, orphaning the real one — and anything referencing it via `Ref`/`Fn::GetAtt` picked up that new, wrong identity the moment it was reprocessed later in the same update, since real CloudFormation does propagate a changed reference. Found via a DynamoDB table silently duplicating on an unrelated update to a real multi-stack deploy. A genuinely unchanged resource is no longer touched at all, matching real CloudFormation; auto-generated names are now a deterministic hash of (stack name, logical id) rather than random, so the remaining case — a resource's properties *did* change but its type still has no update handler — reproduces the same name it started with. Also fixes the same symptom for `AWS::Events::EventBus` (previously failed a stack update outright with "already exists" once created) and any other resource type with no update handler and no name-collision guard of its own. Contributed by @ryan-bennett.
-- **CloudFormation — `AWS::ApiGatewayV2::Authorizer` survives a property update** — the type had no update handler, so changing e.g. `JwtConfiguration.Audience` (trusting an additional app client) fell back to create — whose `authorizerId` is a random id on every call, with no stable name to derive from — minting a second, orphaned authorizer while every `Route`'s own (unchanged) `AuthorizerId` kept pointing at the original, now-stale one. A real update handler now mutates the existing authorizer record in place, matching API Gateway's own `UpdateAuthorizer`. Contributed by @ryan-bennett.
-- **CloudFormation — `AWS::SSM::Parameter::Value<...>` template parameters now resolve against SSM Parameter Store** — a template parameter typed `AWS::SSM::Parameter::Value<String>` (or `<List<String>>` / `<AWS::EC2::Image::Id>`) takes an SSM parameter *name* as its Default/provided value; real CloudFormation resolves that name against Parameter Store before `Ref` ever sees it — the mechanism behind, e.g., CDK's `StringParameter.valueForStringParameter`. MiniStack treated these like any other AWS-specific parameter type and passed the literal name straight through, so `Ref` returned the parameter's name instead of its stored value, and any resource property built from it (or a nested stack composing two independently-deployed stacks through a shared parameter) silently received the wrong string. Resolution now looks the name up in the SSM store at parameter-resolution time; a name that doesn't exist fails `CreateStack`/`UpdateStack` synchronously with a `ValidationError`, matching AWS. Contributed by @ryan-bennett.
-- **S3 — `GetBucketLocation` returns the bucket's stored region** — two defects hid the region: a bucket created without a `CreateBucketConfiguration` stored no region at all (even when the request was signed for one), and the response suppressed the region whenever it equalled `MINISTACK_REGION`, so with the emulator homed in, say, `eu-central-1` a bucket in that region answered an empty `LocationConstraint` — which S3 clients read as us-east-1 and then mis-sign follow-up requests with. A bucket created with no explicit constraint now lands in the request's SigV4 signing region, as on AWS, and `GetBucketLocation` returns the empty `LocationConstraint` only for buckets literally in `us-east-1`, echoing every other region verbatim.
-- **S3 — versioned objects retain their custom metadata** — in a versioning-enabled bucket the per-version record stored only the wire basics (etag/size/storage class), dropping the object's `x-amz-meta-*` user metadata, preserved headers, and content-encoding; on top of that a `GetObject?versionId=` hand-built a five-header response that bypassed the only `x-amz-meta-*` emitter. A `PutObject` with `Metadata` followed by a `GetObject`/`HeadObject` of that version therefore came back with the metadata missing. Every version now stores its own metadata (across put, POST-form, copy, and multipart-complete), and versioned reads route through the shared header builder, so each version returns the metadata it was written with — matching S3, where metadata is per-version. Reported by @Kaphaalor.
-- **API Gateway (REST) — custom Lambda authorizers are invoked and enforced on the request path** — a method with `authorizationType: CUSTOM` stored its authorizer but never called it: requests reached the integration unauthenticated and `requestContext.authorizer` was never populated. `TOKEN` and `REQUEST` authorizers are now invoked on the data path with the AWS event shape (`type`/`authorizationToken`/`methodArn`, or the REQUEST parameter shape); a missing identity source returns `401` without invoking, the returned IAM policy is evaluated against the method ARN (explicit `Deny` and no-matching-`Allow` both `403`, an authorizer raising `Unauthorized` `401`), `authorizerResultTtlInSeconds` caches the decision, and on allow the returned `context` (values stringified) plus `principalId` are injected into `requestContext.authorizer`. `AWS_IAM` methods reject a request with no `Authorization` header (`403`); the SigV4 signature itself is not verified. Reported by @iot-rocket.
-- **Route 53 — a change is born `PENDING` and flips to `INSYNC`** — every `ChangeResourceRecordSets` / `CreateHostedZone` change was created `INSYNC`, so `GetChange` never returned `PENDING` and any waiter or poll loop (e.g. the `ResourceRecordSetsChanged` waiter) completed on its first read without exercising its retry path. Changes are now submitted `PENDING` and flip to `INSYNC` on the first `GetChange` read thereafter, reproducing the observable `PENDING`→`INSYNC` transition without a background timer. Reported by @jayjanssen.
+- **CloudFormation — resources unchanged by a stack update are left alone** — an unchanged resource was reprocessed on every update, and a type with no update handler fell back to create with a fresh random name, orphaning the real resource (and any `Ref`/`Fn::GetAtt` to it). Unchanged resources are now skipped, and auto-generated names are a deterministic hash of (stack name, logical id). Also fixes the `AWS::Events::EventBus` "already exists" update failure. Contributed by @ryan-bennett.
+- **CloudFormation — `AWS::ApiGatewayV2::Authorizer` survives a property update** — with no update handler, changing a property fell back to create and minted a second, orphaned authorizer; an update handler now mutates the existing record in place. Contributed by @ryan-bennett.
+- **CloudFormation — `AWS::SSM::Parameter::Value<...>` parameters resolve against SSM** — the SSM parameter *name* was passed straight through, so `Ref` returned the name instead of the stored value; it's now resolved against Parameter Store (a missing name fails the stack with `ValidationError`). Contributed by @ryan-bennett.
+- **CloudFormation — a `DELETE_COMPLETE` stack's name can be re-created** — a deleted stack stayed addressable by name, so `deploy` took the update path ("cannot be updated") instead of re-creating. A deleted stack is now addressable only by its stack ID; describe/update/change-set by name report "does not exist", so the name re-deploys as a fresh stack. Reported by @iot-rocket.
+- **S3 — versioned objects retain their custom metadata** — the per-version record dropped `x-amz-meta-*`, preserved headers, and content-encoding, and versioned `GetObject`/`HeadObject` bypassed the metadata emitter; each version now stores and returns its own metadata. Reported by @Kaphaalor.
+- **S3 — `GetBucketLocation` returns the bucket's stored region** — the location was compared against the configurable default region (so a non-`us-east-1` default blanked it) and buckets created without a `LocationConstraint` stored no region; a bucket now records its signing region and `GetBucketLocation` echoes it, returning empty only for `us-east-1`. Contributed by @iot-rocket.
+- **API Gateway (REST) — custom Lambda authorizers are invoked on the request path** — a `CUSTOM` method never called its authorizer. `TOKEN`/`REQUEST` authorizers now run on the data path: `401` on a missing identity source, `403` on `Deny`/no-match, `authorizerResultTtlInSeconds` caching, and `context` (stringified) plus `principalId` injected into `requestContext.authorizer`. `AWS_IAM` methods require an `Authorization` header (`403`); SigV4 is not verified. Reported by @iot-rocket.
+- **API Gateway (REST) — an unsupported resource or method returns `403`** — an unmatched path returned `404` and a matched resource with no method returned `405`; both now return `403 Missing Authentication Token` (a methodless resource does not fall through to a `{proxy+}` sibling). Reported by @iot-rocket.
+- **Route 53 — a change is born `PENDING` then flips to `INSYNC`** — every change was created `INSYNC`, so `GetChange` never returned `PENDING`; changes are now `PENDING` and flip to `INSYNC` on the first `GetChange` read. Reported by @jayjanssen.
## [1.4.15] — 2026-08-10
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 2d72b631..9506710d 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -1491,13 +1491,20 @@ async def _handle_execute_in_scope(
resource, path_params = _match_resource_tree(api_id, segments)
if not resource:
- return 404, {"Content-Type": "application/json"}, json.dumps({"message": "Missing Authentication Token"}).encode()
+ # AWS returns 403 MISSING_AUTHENTICATION_TOKEN for an unsupported
+ # resource (an unmatched path), not 404.
+ return _gw_error(403, "Missing Authentication Token")
# Look up method
resource_methods = resource.get("resourceMethods", {})
method_obj = resource_methods.get(method) or resource_methods.get("ANY")
if not method_obj:
- return 405, {"Content-Type": "application/json"}, json.dumps({"message": "Method Not Allowed"}).encode()
+ # A matched resource with no method for this verb — including a
+ # methodless intermediate node (e.g. `/jobs` created only as the parent
+ # of `/jobs/{op}`) — is an "unsupported method" in API Gateway, which
+ # answers 403 MISSING_AUTHENTICATION_TOKEN (not 405, and it does not
+ # fall through to a {proxy+} sibling: the specific resource wins).
+ return _gw_error(403, "Missing Authentication Token")
integration = method_obj.get("methodIntegration")
if not integration:
diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.py
index 1ea83e55..611baf1d 100644
--- a/ministack/services/cloudformation/changesets.py
+++ b/ministack/services/cloudformation/changesets.py
@@ -133,7 +133,11 @@ def _create_change_set(params):
"AWS::CloudFormation::Stack", "REVIEW_IN_PROGRESS",
physical_id=stack_id)
else:
- if not stack:
+ # An UPDATE change set against a deleted stack: the name no longer
+ # resolves (deleted stacks are addressable only by stack ID), so this is
+ # "does not exist" — which steers `aws cloudformation deploy` back to a
+ # CREATE change set for the re-deployed name.
+ if not stack or stack.get("StackStatus") == "DELETE_COMPLETE":
return _error("ValidationError",
f"Stack [{stack_name}] does not exist")
stack_id = stack["StackId"]
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index 22ea1d15..bbca0a8a 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -131,6 +131,12 @@ def _describe_stacks(params):
if stack_name:
stack = _stacks.get(stack_name)
+ # A DELETE_COMPLETE stack is addressable only by its unique stack ID, not
+ # by name — real CloudFormation returns "does not exist" for a deleted
+ # stack's name. Drop the name match and fall through to the stack-ID
+ # lookup (which a plain name never satisfies).
+ if stack is not None and stack.get("StackStatus") == "DELETE_COMPLETE":
+ stack = None
# Also try matching by stack ID
if not stack:
for s in _stacks.values():
@@ -466,7 +472,9 @@ def _update_stack(params):
return _error("ValidationError", "StackName is required")
stack = _stacks.get(stack_name)
- if not stack:
+ # A deleted stack is not addressable by name — updating it is "does not
+ # exist", not "cannot be updated" (a deployed stack name is free to re-create).
+ if not stack or stack.get("StackStatus") == "DELETE_COMPLETE":
return _error("ValidationError",
f"Stack [{stack_name}] does not exist")
diff --git a/pyproject.toml b/pyproject.toml
index 33af6405..da58b240 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ministack"
-version = "1.4.15"
+version = "1.4.16"
description = "Free, open-source local AWS emulator — drop-in LocalStack replacement"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.py
index e5100242..a0f0409d 100644
--- a/tests/test_apigatewayv1.py
+++ b/tests/test_apigatewayv1.py
@@ -1759,8 +1759,10 @@ def test_apigwv1_execute_mock_integration(apigw_v1):
apigw_v1.delete_rest_api(restApiId=api_id)
-def test_apigwv1_execute_missing_resource_404(apigw_v1):
- """Request to non-existent path returns 404 with AWS-style message."""
+def test_apigwv1_execute_missing_resource_403(apigw_v1):
+ """Request to a non-existent path returns 403 Missing Authentication Token —
+ real API Gateway (REST) treats an unsupported resource as
+ MISSING_AUTHENTICATION_TOKEN (403), not 404."""
import urllib.error as _urlerr
import urllib.request as _urlreq
@@ -1773,9 +1775,9 @@ def test_apigwv1_execute_missing_resource_404(apigw_v1):
req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
try:
_urlreq.urlopen(req)
- assert False, "Expected 404"
+ assert False, "Expected 403"
except _urlerr.HTTPError as e:
- assert e.code == 404
+ assert e.code == 403
apigw_v1.delete_rest_api(restApiId=api_id)
@@ -2203,8 +2205,10 @@ def test_apigwv1_execute_missing_stage_404(apigw_v1):
assert exc.value.code == 404
apigw_v1.delete_rest_api(restApiId=api_id)
-def test_apigwv1_execute_missing_method_405(apigw_v1):
- """execute-api returns 405 when resource exists but method is not configured."""
+def test_apigwv1_execute_missing_method_403(apigw_v1):
+ """execute-api returns 403 Missing Authentication Token when the resource
+ exists but the method is not configured — real API Gateway treats an
+ unsupported method as MISSING_AUTHENTICATION_TOKEN (403), not 405."""
import urllib.error as _urlerr
import urllib.request as _urlreq
@@ -2227,7 +2231,7 @@ def test_apigwv1_execute_missing_method_405(apigw_v1):
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 == 405
+ assert exc.value.code == 403
apigw_v1.delete_rest_api(restApiId=api_id)
def test_apigwv1_execute_lambda_arn_uri(apigw_v1, lam):
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index ac93b9fd..4bcfb019 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -37,10 +37,21 @@ def _cfn_iceberg_json(path):
def _wait_stack(cfn, name, timeout=30):
- """Poll until stack reaches terminal status."""
+ """Poll until stack reaches terminal status.
+
+ A deleted stack is addressable only by its stack ID, so once it reaches
+ DELETE_COMPLETE describe-by-name returns "does not exist" (real AWS); treat
+ that as the terminal deleted state.
+ """
deadline = time.time() + timeout
+ status = "UNKNOWN"
while time.time() < deadline:
- stacks = cfn.describe_stacks(StackName=name)["Stacks"]
+ 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]
@@ -438,6 +449,46 @@ def test_cfn_create_describe_delete_stack(cfn, s3):
with pytest.raises(ClientError):
s3.head_bucket(Bucket="cfn-t01-bucket")
+
+def test_cfn_deleted_stack_name_is_reusable(cfn):
+ """A DELETE_COMPLETE stack is addressable only by stack ID; its name is free
+ to re-create, and an UpdateStack against the deleted name is "does not
+ exist" (which is what lets `aws cloudformation deploy` re-create it). (#1345)
+ """
+ tpl = json.dumps({
+ "Resources": {
+ "P": {"Type": "AWS::SSM::Parameter",
+ "Properties": {"Type": "String", "Value": "v1"}},
+ },
+ })
+ name = "cfn-recreate-1345"
+ first_id = cfn.create_stack(StackName=name, TemplateBody=tpl)["StackId"]
+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+
+ cfn.delete_stack(StackName=name)
+ assert _wait_stack(cfn, name)["StackStatus"] == "DELETE_COMPLETE"
+
+ # By name: gone. By unique stack ID: still visible as DELETE_COMPLETE.
+ with pytest.raises(ClientError) as exc:
+ cfn.describe_stacks(StackName=name)
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+ assert "does not exist" in exc.value.response["Error"]["Message"]
+ by_id = cfn.describe_stacks(StackName=first_id)["Stacks"][0]
+ assert by_id["StackStatus"] == "DELETE_COMPLETE"
+
+ # UpdateStack against the deleted name is "does not exist", not "cannot be updated".
+ with pytest.raises(ClientError) as uexc:
+ cfn.update_stack(StackName=name, TemplateBody=tpl)
+ assert "does not exist" in uexc.value.response["Error"]["Message"]
+
+ # The name re-creates cleanly as a brand-new stack (new stack ID).
+ second_id = cfn.create_stack(StackName=name, TemplateBody=tpl)["StackId"]
+ assert second_id != first_id
+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ cfn.delete_stack(StackName=name)
+ _wait_stack(cfn, name)
+
+
def test_cfn_stack_with_parameters(cfn, sqs):
template = {
"AWSTemplateFormatVersion": "2010-09-09",
@@ -7808,3 +7859,603 @@ def test_cfn_kms_key_delete_schedules_deletion(cfn, kms_client):
assert meta["KeyState"] == "PendingDeletion"
assert meta["Enabled"] is False
assert "DeletionDate" in meta
+
+
+# ===========================================================================
+# CloudFormation Custom Resource protocol tests
+# (merged from the former tests/test_cfn_custom_resource.py — #603)
+# Reuses this module's _wait_stack / _regional_cfn_test_client helpers.
+# ===========================================================================
+
+_CR_ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
+_CR_LAMBDA_ROLE = "arn:aws:iam::000000000000:role/lambda-role"
+
+
+def _cr_make_zip(code: str) -> bytes:
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", code)
+ return buf.getvalue()
+
+
+def _cfn_custom_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_mod.uuid4())
+ payload = json.dumps({"Status": "SUCCESS", "PhysicalResourceId": "x",
+ "RequestId": "r", "StackId": "s", "LogicalResourceId": "l"}).encode()
+ req = urllib.request.Request(
+ f"{_CR_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)
+"""
+
+
+_CR_HANDLER_CDK_COMPAT = """\
+import json, urllib.request
+
+def handler(event, context):
+ props = event["ResourceProperties"]
+ managed = props.get("Managed", "true").lower() == "true"
+ skip_validation = props.get("SkipDestinationValidation", "false").lower() == "true"
+ payload = json.dumps({
+ "Status": "SUCCESS",
+ "Reason": f"See the details in CloudWatch Log Stream: {context.log_stream_name}",
+ "RequestId": event["RequestId"],
+ "StackId": event["StackId"],
+ "LogicalResourceId": event["LogicalResourceId"],
+ "PhysicalResourceId": "cdk-compatible-resource",
+ "Data": {
+ "Managed": str(managed),
+ "SkipDestinationValidation": str(skip_validation),
+ "NestedEnabled": props["Nested"]["Enabled"],
+ "NestedCount": props["Nested"]["Count"],
+ },
+ }).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=_CR_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _cr_make_zip(_CR_HANDLER_SUCCESS)},
+ )
+ try:
+ cfn.create_stack(
+ StackName="cr-t01",
+ TemplateBody=_cfn_custom_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_cdk_boolean_properties_and_lambda_context(cfn, lam):
+ """CDK-style handlers receive string leaves and standard Lambda context."""
+ lam.create_function(
+ FunctionName="cr-test-cdk-compat",
+ Runtime="python3.12",
+ Role=_CR_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _cr_make_zip(_CR_HANDLER_CDK_COMPAT)},
+ )
+ props = {
+ "ServiceTimeout": "2",
+ "Managed": True,
+ "SkipDestinationValidation": False,
+ "Nested": {"Enabled": True, "Count": 2},
+ }
+ outputs = {
+ "Managed": {"Value": {"Fn::GetAtt": ["CR", "Managed"]}},
+ "SkipDestinationValidation": {
+ "Value": {"Fn::GetAtt": ["CR", "SkipDestinationValidation"]}
+ },
+ "NestedEnabled": {"Value": {"Fn::GetAtt": ["CR", "NestedEnabled"]}},
+ "NestedCount": {"Value": {"Fn::GetAtt": ["CR", "NestedCount"]}},
+ }
+ try:
+ cfn.create_stack(
+ StackName="cr-t01-cdk-compat",
+ TemplateBody=_cfn_custom_template("cr-test-cdk-compat", extra_props=props, outputs=outputs),
+ )
+ stack = _wait_stack(cfn, "cr-t01-cdk-compat")
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ values = {item["OutputKey"]: item["OutputValue"] for item in stack.get("Outputs", [])}
+ assert values == {
+ "Managed": "True",
+ "SkipDestinationValidation": "False",
+ "NestedEnabled": "true",
+ "NestedCount": "2",
+ }
+ finally:
+ cfn.delete_stack(StackName="cr-t01-cdk-compat")
+ _wait_stack(cfn, "cr-t01-cdk-compat")
+ lam.delete_function(FunctionName="cr-test-cdk-compat")
+
+
+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=_CR_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _cr_make_zip(_CR_HANDLER_SUCCESS)},
+ )
+ try:
+ cfn.create_stack(
+ StackName="cr-t02a",
+ TemplateBody=_cfn_custom_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_custom_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=_CR_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _cr_make_zip(_CR_HANDLER_FAILED)},
+ )
+ try:
+ cfn.create_stack(StackName="cr-t03", TemplateBody=_cfn_custom_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=_CR_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _cr_make_zip(_CR_HANDLER_RECORD)},
+ )
+ try:
+ tpl_v1 = _cfn_custom_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_custom_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=_CR_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _cr_make_zip(_CR_DELETE_CHECK)},
+ )
+ try:
+ cfn.create_stack(StackName="cr-t05", TemplateBody=_cfn_custom_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=_CR_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _cr_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=_CR_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _cr_make_zip(_CR_HANDLER_NO_PID)},
+ )
+ try:
+ cfn.create_stack(StackName="cr-t07", TemplateBody=_cfn_custom_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=_CR_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _cr_make_zip(_CR_HANDLER_ASYNC)},
+ )
+ try:
+ cfn.create_stack(StackName="cr-t08", TemplateBody=_cfn_custom_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=_CR_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _cr_make_zip(_CR_HANDLER_SILENT)},
+ )
+ tpl = _cfn_custom_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_custom_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
+
+
+def test_custom_resource_rejects_cross_region_lambda_token(cfn):
+ west_lam = _regional_cfn_test_client("lambda", "us-west-2")
+ fn_name = f"cr-cross-region-{_uuid_mod.uuid4().hex[:8]}"
+ stack_name = f"cr-cross-{_uuid_mod.uuid4().hex[:8]}"
+ west_arn = west_lam.create_function(
+ FunctionName=fn_name,
+ Runtime="python3.12",
+ Role=_CR_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _cr_make_zip(_CR_HANDLER_SUCCESS)},
+ )["FunctionArn"]
+
+ tpl = _cfn_custom_template(fn_name, extra_props={"ServiceToken": west_arn})
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=tpl)
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] in ("ROLLBACK_COMPLETE", "CREATE_FAILED"), stack
+ finally:
+ try:
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+ except Exception:
+ pass
+ west_lam.delete_function(FunctionName=fn_name)
diff --git a/tests/test_cfn_custom_resource.py b/tests/test_cfn_custom_resource.py
deleted file mode 100644
index 4b886202..00000000
--- a/tests/test_cfn_custom_resource.py
+++ /dev/null
@@ -1,638 +0,0 @@
-"""
-CloudFormation Custom Resource integration tests.
-Requires a running Ministack server at MINISTACK_ENDPOINT (default http://localhost:4566).
-"""
-import io
-import json
-import os
-import threading
-import time
-import urllib.request
-import uuid
-import zipfile
-
-import boto3
-import pytest
-from botocore.config import Config
-from botocore.exceptions import ClientError
-
-ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
-_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 _regional_client(service, region):
- return boto3.client(
- service,
- endpoint_url=ENDPOINT,
- aws_access_key_id="test",
- aws_secret_access_key="test",
- region_name=region,
- config=Config(region_name=region, retries={"mode": "standard"}),
- )
-
-
-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)
-"""
-
-
-_CR_HANDLER_CDK_COMPAT = """\
-import json, urllib.request
-
-def handler(event, context):
- props = event["ResourceProperties"]
- managed = props.get("Managed", "true").lower() == "true"
- skip_validation = props.get("SkipDestinationValidation", "false").lower() == "true"
- payload = json.dumps({
- "Status": "SUCCESS",
- "Reason": f"See the details in CloudWatch Log Stream: {context.log_stream_name}",
- "RequestId": event["RequestId"],
- "StackId": event["StackId"],
- "LogicalResourceId": event["LogicalResourceId"],
- "PhysicalResourceId": "cdk-compatible-resource",
- "Data": {
- "Managed": str(managed),
- "SkipDestinationValidation": str(skip_validation),
- "NestedEnabled": props["Nested"]["Enabled"],
- "NestedCount": props["Nested"]["Count"],
- },
- }).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_cdk_boolean_properties_and_lambda_context(cfn, lam):
- """CDK-style handlers receive string leaves and standard Lambda context."""
- lam.create_function(
- FunctionName="cr-test-cdk-compat",
- Runtime="python3.12",
- Role=_LAMBDA_ROLE,
- Handler="index.handler",
- Code={"ZipFile": _make_zip(_CR_HANDLER_CDK_COMPAT)},
- )
- props = {
- "ServiceTimeout": "2",
- "Managed": True,
- "SkipDestinationValidation": False,
- "Nested": {"Enabled": True, "Count": 2},
- }
- outputs = {
- "Managed": {"Value": {"Fn::GetAtt": ["CR", "Managed"]}},
- "SkipDestinationValidation": {
- "Value": {"Fn::GetAtt": ["CR", "SkipDestinationValidation"]}
- },
- "NestedEnabled": {"Value": {"Fn::GetAtt": ["CR", "NestedEnabled"]}},
- "NestedCount": {"Value": {"Fn::GetAtt": ["CR", "NestedCount"]}},
- }
- try:
- cfn.create_stack(
- StackName="cr-t01-cdk-compat",
- TemplateBody=_cfn_template("cr-test-cdk-compat", extra_props=props, outputs=outputs),
- )
- stack = _wait_stack(cfn, "cr-t01-cdk-compat")
- assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
-
- values = {item["OutputKey"]: item["OutputValue"] for item in stack.get("Outputs", [])}
- assert values == {
- "Managed": "True",
- "SkipDestinationValidation": "False",
- "NestedEnabled": "true",
- "NestedCount": "2",
- }
- finally:
- cfn.delete_stack(StackName="cr-t01-cdk-compat")
- _wait_stack(cfn, "cr-t01-cdk-compat")
- lam.delete_function(FunctionName="cr-test-cdk-compat")
-
-
-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
-
-
-def test_custom_resource_rejects_cross_region_lambda_token(cfn):
- west_lam = _regional_client("lambda", "us-west-2")
- fn_name = f"cr-cross-region-{uuid.uuid4().hex[:8]}"
- stack_name = f"cr-cross-{uuid.uuid4().hex[:8]}"
- west_arn = west_lam.create_function(
- FunctionName=fn_name,
- Runtime="python3.12",
- Role=_LAMBDA_ROLE,
- Handler="index.handler",
- Code={"ZipFile": _make_zip(_CR_HANDLER_SUCCESS)},
- )["FunctionArn"]
-
- tpl = _cfn_template(fn_name, extra_props={"ServiceToken": west_arn})
- try:
- cfn.create_stack(StackName=stack_name, TemplateBody=tpl)
- stack = _wait_stack(cfn, stack_name)
- assert stack["StackStatus"] in ("ROLLBACK_COMPLETE", "CREATE_FAILED"), stack
- finally:
- try:
- cfn.delete_stack(StackName=stack_name)
- _wait_stack(cfn, stack_name)
- except Exception:
- pass
- west_lam.delete_function(FunctionName=fn_name)