Skip to content

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

fix CDK S3 notification custom resource hangs (#1139)

robert-pitt-foodhub8380fcb02c78
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 87498644..9cfeab40 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **Region scoping — EventBridge Scheduler, CodeBuild, and Resource Groups** — state is now isolated by account and region, so same-named resources in different regions no longer collide. Persisted state carries a versioned regional schema that an older binary refuses rather than misreads. Contributed by @Areson.
### Fixed
+- **CloudFormation/Lambda — CDK S3 bucket notification custom resources no longer hang** — `Custom::S3BucketNotifications` received boolean properties as Python `bool` values even though CloudFormation serializes custom-resource primitive leaves as strings, so CDK's bundled handler crashed when it called `.lower()` on `Managed`. Its failure-reporting path then crashed again because the warm Python Lambda context omitted `log_stream_name`, preventing the handler from PUTting `FAILED` to the CloudFormation `ResponseURL` and leaving the stack in `CREATE_IN_PROGRESS` until the one-hour service timeout. Custom-resource properties now use CloudFormation's string wire representation, and warm Python workers expose the standard Lambda context fields, including log group/stream names, function version, client/identity placeholders, and remaining execution time.
- **Batch — `UpdateComputeEnvironment`** — Terraform `aws_batch_compute_environment` with an `update_policy` block failed with `InvalidAction`. `UpdateComputeEnvironment` now resolves the compute environment by name or ARN and applies `state`, `serviceRole`, `computeResources`, `updatePolicy`, `unmanagedvCpus`, and `context`. Reported by @smoores-dev.
- **S3 — empty object tag value** — a bare `x-amz-tagging` key with no `=value` was dropped instead of stored. Empty tag values are now preserved as a tag with an empty value, matching real S3. Contributed by @murlock.
- **EC2 — `DescribeSecurityGroupRules` by rule id** — the operation ignored `SecurityGroupRuleIds` (a group filter was required) and rule ids shifted when another rule on the group was revoked. Rule ids are now stable and content-derived and `SecurityGroupRuleIds` is honored, fixing Terraform `aws_vpc_security_group_ingress_rule` refresh. Reported by @staranto.
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.py
index 5b8bcc97..52b31459 100644
--- a/ministack/core/lambda_runtime.py
+++ b/ministack/core/lambda_runtime.py
@@ -81,7 +81,7 @@ _lock = threading.Lock()
# ---------------------------------------------------------------------------
_PYTHON_WORKER_SCRIPT = '''
-import sys, json, importlib, traceback, os
+import sys, json, importlib, traceback, os, time
def run():
# Redirect print() to stderr so stdout stays clean for JSON-line protocol
@@ -133,11 +133,19 @@ def run():
os.environ["_X_AMZN_TRACE_ID"] = _xray_tid
elif "_X_AMZN_TRACE_ID" in os.environ:
del os.environ["_X_AMZN_TRACE_ID"]
+ _function_name = init.get("function_name", "")
+ _deadline = time.time() + float(os.environ.get("_LAMBDA_TIMEOUT", "3"))
context = type("Context", (), {
"function_name": init.get("function_name", ""),
+ "function_version": os.environ.get("AWS_LAMBDA_FUNCTION_VERSION", "$LATEST"),
"memory_limit_in_mb": init.get("memory", 128),
"invoked_function_arn": init.get("arn", ""),
"aws_request_id": event.pop("_request_id", ""),
+ "log_group_name": os.environ.get("AWS_LAMBDA_LOG_GROUP_NAME", "/aws/lambda/" + _function_name),
+ "log_stream_name": os.environ.get("AWS_LAMBDA_LOG_STREAM_NAME", ""),
+ "identity": None,
+ "client_context": None,
+ "get_remaining_time_in_millis": lambda self: max(0, int((_deadline - time.time()) * 1000)),
})()
try:
result = handler_fn(event, context)
diff --git a/ministack/services/cloudformation/custom_resource.py b/ministack/services/cloudformation/custom_resource.py
index ba66167d..ac2b52d2 100644
--- a/ministack/services/cloudformation/custom_resource.py
+++ b/ministack/services/cloudformation/custom_resource.py
@@ -42,6 +42,25 @@ def _response_url(token: str) -> str:
return f"http://{_HOST}:{_PORT}/_ministack/cfn-response/{token}"
+def _normalise_resource_properties(value):
+ """Match CloudFormation's custom-resource property wire representation.
+
+ CloudFormation preserves maps and lists in ``ResourceProperties`` but
+ serialises primitive property values as strings. CDK's bundled custom
+ resource handlers rely on this behaviour (for example, the S3 bucket
+ notifications handler calls ``.lower()`` on boolean template properties).
+ """
+ if isinstance(value, dict):
+ return {key: _normalise_resource_properties(item) for key, item in value.items()}
+ if isinstance(value, list):
+ return [_normalise_resource_properties(item) for item in value]
+ if isinstance(value, bool):
+ return "true" if value else "false"
+ if isinstance(value, (int, float)):
+ return str(value)
+ return value
+
+
def invoke_custom_resource(
request_type: str,
logical_id: str,
@@ -102,12 +121,12 @@ def invoke_custom_resource(
"ResponseURL": _response_url(token),
"ResourceType": resource_type,
"LogicalResourceId": logical_id,
- "ResourceProperties": dict(props),
+ "ResourceProperties": _normalise_resource_properties(props),
}
if physical_id is not None:
cfn_event["PhysicalResourceId"] = physical_id
if old_props is not None:
- cfn_event["OldResourceProperties"] = dict(old_props)
+ cfn_event["OldResourceProperties"] = _normalise_resource_properties(old_props)
event_obj = register_token(token)
diff --git a/tests/test_cfn_custom_resource.py b/tests/test_cfn_custom_resource.py
index 8c314d8f..7efdbba1 100644
--- a/tests/test_cfn_custom_resource.py
+++ b/tests/test_cfn_custom_resource.py
@@ -114,6 +114,37 @@ def handler(event, context):
"""
+_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",
@@ -138,6 +169,50 @@ def test_custom_resource_create_success(cfn, lam):
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(
diff --git a/tests/test_lambda_runtime_worker.py b/tests/test_lambda_runtime_worker.py
index d0d7864b..fe5ee0e6 100644
--- a/tests/test_lambda_runtime_worker.py
+++ b/tests/test_lambda_runtime_worker.py
@@ -1,5 +1,5 @@
"""
-Unit tests for Worker resource-cleanup fixes:
+Unit tests for the Lambda warm-worker runtime:
test_tmpdir_cleaned_before_respawn
-- _spawn() must shutil.rmtree the old tmpdir before mkdtemp on re-spawn.
@@ -7,10 +7,13 @@ Unit tests for Worker resource-cleanup fixes:
test_process_terminated_on_error_response
-- invoke() must call proc.terminate() when the handler returns status=error.
-Both tests mock subprocess so no running Docker/Ministack instance is required.
+The cleanup/protocol tests mock subprocesses; context coverage runs a real local
+Python worker. No Docker or running Ministack instance is required.
"""
+import io
import json
+import zipfile
from unittest.mock import MagicMock, mock_open, patch
from ministack.core.lambda_runtime import Worker
@@ -143,6 +146,53 @@ def test_process_terminated_on_error_response():
assert worker._proc is None, "_proc must be cleared after an error response"
+def test_python_worker_exposes_standard_lambda_context_fields():
+ """Warm Python workers expose the context fields documented by Lambda."""
+ code = """\
+import os
+
+def handler(event, context):
+ return {
+ "function_name": context.function_name,
+ "function_version": context.function_version,
+ "memory_limit_in_mb": context.memory_limit_in_mb,
+ "invoked_function_arn": context.invoked_function_arn,
+ "aws_request_id": context.aws_request_id,
+ "log_group_name": context.log_group_name,
+ "log_stream_name": context.log_stream_name,
+ "env_log_stream_name": os.environ["AWS_LAMBDA_LOG_STREAM_NAME"],
+ "identity": context.identity,
+ "client_context": context.client_context,
+ "remaining_time": context.get_remaining_time_in_millis(),
+ }
+"""
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as archive:
+ archive.writestr("index.py", code)
+
+ config = _config()
+ config["Version"] = "$LATEST"
+ worker = Worker("test-fn", config, buf.getvalue())
+ try:
+ result = worker.invoke({}, request_id="context-request-id")
+ finally:
+ worker.kill()
+
+ assert result["status"] == "ok", result
+ context = result["result"]
+ assert context["function_name"] == "test-fn"
+ assert context["function_version"] == "$LATEST"
+ assert context["memory_limit_in_mb"] == 128
+ assert context["invoked_function_arn"] == config["FunctionArn"]
+ assert context["aws_request_id"] == "context-request-id"
+ assert context["log_group_name"] == "/aws/lambda/test-fn"
+ assert context["log_stream_name"]
+ assert context["log_stream_name"] == context["env_log_stream_name"]
+ assert context["identity"] is None
+ assert context["client_context"] is None
+ assert 0 < context["remaining_time"] <= 30_000
+
+
def test_invoke_ignores_json_logs_on_stdout():
"""Pino-style JSON on fd 1 must not be mistaken for the protocol response."""
ok_line = _protocol_line("ok", result={"ok": True})