Skip to content

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

fix(cfn): preserve S3 bucket physical resource ID on stack update (#560)

Erick Reis5bddb6b7f36f
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index d8777c7e..46424bf3 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -2,6 +2,8 @@
CloudFormation provisioners — resource create/delete handlers for each AWS resource type.
"""
+import base64
+import hashlib
import io
import json
import logging
@@ -118,11 +120,11 @@ def _update_resource(resource_type: str, physical_id: str, old_props: dict,
def _s3_create(logical_id, props, stack_name):
name = props.get("BucketName") or _physical_name(stack_name, logical_id, lowercase=True, max_len=63)
- _s3._buckets[name] = {
+ _s3._buckets.setdefault(name, {
"created": now_iso(),
"objects": {},
"region": get_region(),
- }
+ })
versioning = props.get("VersioningConfiguration", {})
if versioning.get("Status") == "Enabled":
_s3._bucket_versioning[name] = "Enabled"
@@ -135,6 +137,32 @@ def _s3_create(logical_id, props, stack_name):
return name, attrs
+def _s3_update(physical_id, old_props, new_props, stack_name):
+ """Update an S3 bucket in place. Real AWS CloudFormation preserves the
+ physical bucket (and its name) when only mutable properties change.
+ Auto-named buckets (no explicit ``BucketName``) must keep their existing
+ physical resource id so that ``Ref`` keeps resolving to the same bucket
+ where artifacts were uploaded."""
+ old_name = old_props.get("BucketName")
+ new_name = new_props.get("BucketName")
+ if new_name and new_name != physical_id:
+ return _s3_create(new_name, new_props, stack_name)
+ name = physical_id
+ if name in _s3._buckets:
+ versioning = new_props.get("VersioningConfiguration", {})
+ if versioning.get("Status") == "Enabled":
+ _s3._bucket_versioning[name] = "Enabled"
+ else:
+ return _s3_create(name, new_props, stack_name)
+ attrs = {
+ "Arn": f"arn:aws:s3:::{name}",
+ "DomainName": f"{name}.s3.amazonaws.com",
+ "RegionalDomainName": f"{name}.s3.{get_region()}.amazonaws.com",
+ "WebsiteURL": f"http://{name}.s3-website-{get_region()}.amazonaws.com",
+ }
+ return name, attrs
+
+
def _s3_bucket_policy_create(logical_id, props, stack_name):
bucket = props.get("Bucket", "")
policy = props.get("PolicyDocument")
@@ -426,6 +454,12 @@ def _lambda_create(logical_id, props, stack_name):
version_id=code.get("S3ObjectVersion"),
)
+ code_size = len(code_zip) if code_zip else 0
+ code_sha = (
+ base64.b64encode(hashlib.sha256(code_zip).digest()).decode()
+ if code_zip else "cfn-deployed"
+ )
+
func = {
"config": {
"FunctionName": name,
@@ -433,11 +467,12 @@ def _lambda_create(logical_id, props, stack_name):
"Runtime": runtime,
"Role": role,
"Handler": handler,
+ "CodeSize": code_size,
"Description": description,
"Timeout": timeout,
"MemorySize": memory,
"LastModified": now_iso(),
- "CodeSha256": "cfn-deployed",
+ "CodeSha256": code_sha,
"Version": "$LATEST",
"Environment": {"Variables": env_vars},
"Layers": [{"Arn": l} if isinstance(l, str) else l for l in layers],
@@ -2981,7 +3016,7 @@ def _backup_plan_delete(physical_id, props):
_RESOURCE_HANDLERS = {
- "AWS::S3::Bucket": {"create": _s3_create, "delete": _s3_delete},
+ "AWS::S3::Bucket": {"create": _s3_create, "update": _s3_update, "delete": _s3_delete},
"AWS::S3::BucketPolicy": {"create": _s3_bucket_policy_create, "delete": _s3_bucket_policy_delete},
"AWS::SQS::Queue": {"create": _sqs_create, "delete": _sqs_delete},
"AWS::SNS::Topic": {"create": _sns_create, "delete": _sns_delete},
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 786c263c..24b5d171 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -7,8 +7,11 @@ import zipfile
from urllib.parse import urlparse
import pytest
+import urllib.request
from botocore.exceptions import ClientError
+from conftest import ENDPOINT
+
def _wait_stack(cfn, name, timeout=30):
"""Poll until stack reaches terminal status."""
@@ -2727,3 +2730,131 @@ def test_cfn_cloudfront_keyvaluestore_create_update_delete(cfn, cloudfront):
with pytest.raises(ClientError) as exc:
cloudfront.describe_key_value_store(Name=kvs_name)
assert exc.value.response["Error"]["Code"] == "EntityNotFound"
+
+
+def test_cfn_auto_named_s3_bucket_stable_across_updates(cfn, s3):
+ """Regression: auto-named S3 buckets (no explicit BucketName) must keep
+ the same physical resource ID across stack updates. Before the fix,
+ _update_resource fell through to _s3_create which generated a new random
+ name on every update, orphaning the original bucket and all its objects."""
+ stack_name = f"cfn-s3-stable-{_uuid_mod.uuid4().hex[:8]}"
+ template_v1 = json.dumps({
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "DeployBucket": {
+ "Type": "AWS::S3::Bucket",
+ },
+ },
+ "Outputs": {
+ "BucketName": {"Value": {"Ref": "DeployBucket"}},
+ },
+ })
+ cfn.create_stack(StackName=stack_name, TemplateBody=template_v1)
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ bucket_v1 = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}["BucketName"]
+
+ s3.put_object(Bucket=bucket_v1, Key="artifact.zip", Body=b"zipdata")
+
+ template_v2 = json.dumps({
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "DeployBucket": {
+ "Type": "AWS::S3::Bucket",
+ },
+ "LogGroup": {
+ "Type": "AWS::Logs::LogGroup",
+ "Properties": {"LogGroupName": f"/test/{stack_name}"},
+ },
+ },
+ "Outputs": {
+ "BucketName": {"Value": {"Ref": "DeployBucket"}},
+ },
+ })
+ cfn.update_stack(StackName=stack_name, TemplateBody=template_v2)
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE"
+ bucket_v2 = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}["BucketName"]
+
+ assert bucket_v1 == bucket_v2, (
+ f"Auto-named bucket changed from {bucket_v1!r} to {bucket_v2!r} on update"
+ )
+
+ obj = s3.get_object(Bucket=bucket_v2, Key="artifact.zip")
+ assert obj["Body"].read() == b"zipdata"
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+
+
+def test_cfn_lambda_s3_ref_bucket_has_code_size(cfn, lam, s3):
+ """Regression: Lambda deployed via CFN with Code.S3Bucket using
+ {Ref: DeployBucket} must report correct CodeSize and CodeSha256
+ (not NaN / 'cfn-deployed'), and the code must be downloadable."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-lam-s3ref-{uid}"
+ fn_name = f"cfn-lam-s3ref-fn-{uid}"
+
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
+ zf.writestr("index.mjs",
+ 'export async function handler(event) '
+ '{ return { statusCode: 200, body: "ok" }; }')
+ zip_bytes = buf.getvalue()
+
+ template_create = json.dumps({
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "DeployBucket": {"Type": "AWS::S3::Bucket"},
+ },
+ "Outputs": {
+ "BucketName": {"Value": {"Ref": "DeployBucket"}},
+ },
+ })
+ cfn.create_stack(StackName=stack_name, TemplateBody=template_create)
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ bucket = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}["BucketName"]
+
+ s3_key = f"deploy/{uid}/code.zip"
+ s3.put_object(Bucket=bucket, Key=s3_key, Body=zip_bytes)
+
+ template_update = json.dumps({
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {
+ "DeployBucket": {"Type": "AWS::S3::Bucket"},
+ "Fn": {
+ "Type": "AWS::Lambda::Function",
+ "Properties": {
+ "FunctionName": fn_name,
+ "Runtime": "nodejs20.x",
+ "Handler": "index.handler",
+ "Role": "arn:aws:iam::000000000000:role/r",
+ "Code": {"S3Bucket": {"Ref": "DeployBucket"}, "S3Key": s3_key},
+ },
+ },
+ },
+ "Outputs": {
+ "BucketName": {"Value": {"Ref": "DeployBucket"}},
+ },
+ })
+ cfn.update_stack(StackName=stack_name, TemplateBody=template_update)
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE"
+
+ fn = lam.get_function(FunctionName=fn_name)
+ config = fn["Configuration"]
+ assert config["CodeSize"] == len(zip_bytes), (
+ f"CodeSize mismatch: expected {len(zip_bytes)}, got {config.get('CodeSize')}"
+ )
+ assert config["CodeSha256"] != "cfn-deployed", "CodeSha256 still hardcoded"
+
+ code_url = fn["Code"]["Location"]
+ local_url = code_url.replace("localhost", "127.0.0.1")
+ resp = urllib.request.urlopen(local_url, timeout=5)
+ downloaded = resp.read()
+ assert len(downloaded) == len(zip_bytes)
+ assert downloaded == zip_bytes
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)