Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(cloudformation): the stack-operation actions that were routed but unhandled (#1649)
iot-rocket81aab6f71f39
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1ea92612..a091e979 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added+- **CloudFormation — `ListImports`, `UpdateTerminationProtection`, `SetStackPolicy`, `GetStackPolicy`, `CancelUpdateStack` and `ContinueUpdateRollback`** — the first four were routed to the service and answered `InvalidAction`, the last two did not exist, so a stack in `UPDATE_ROLLBACK_FAILED` had no way out short of a reset. `ListImports` names the stacks importing an export (a `ValidationError` when none does); termination protection is set on create or later and makes `DeleteStack` refuse with the stack unchanged (`DescribeStacks` reports `EnableTerminationProtection`); a stack policy is stored and returned (it is not enforced); `CancelUpdateStack` stops an `UPDATE_IN_PROGRESS` update before its next resource and rolls it back ("User Initiated"); `ContinueUpdateRollback` retries the deletes that failed the rollback, skips the `ResourcesToSkip` (their status becomes `UPDATE_COMPLETE`, the resource stays) and lands the stack in `UPDATE_ROLLBACK_COMPLETE`. Contributed by @iot-rocket.### Fixed- **CloudFormation — parameter constraints are enforced** — `AllowedPattern`, `MinLength`, `MaxLength`, `MinValue` and `MaxValue` were ignored (only `AllowedValues` was checked), so a value a real account refuses deployed locally. They are checked before a stack exists, with CloudFormation's message (`Parameter 'P' must match pattern ^[a-z]+$`, measured) and a `ConstraintDescription` in place of the reason; a `CommaDelimitedList` is matched per member and a `List<Number>` is validated as numbers. Contributed by @iot-rocket.- **CloudFormation — an unregistered `AWS::CloudFormation::*` type is unrecognized, not a silent no-op** — `AWS::CloudFormation::Macro`, `HookVersion`, `ModuleVersion` and any typo under that prefix deployed as a placeholder with a fabricated physical id, logged at INFO, while the README promises that unsupported types do not silently succeed. The pre-flight now treats them like every other unrecognized type (`Template format error: Unrecognized resource types`); the registered ones — `WaitCondition`, `WaitConditionHandle`, `Stack`, `CustomResource` — are unaffected. Contributed by @iot-rocket.diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.pyindex e14e9f8f..84063882 100644--- a/ministack/services/cloudformation/handlers.py+++ b/ministack/services/cloudformation/handlers.py@@ -38,6 +38,7 @@ from .helpers import ()from .stacks import (_add_event,+ _continue_update_rollback_async,_create_stack_task_in_region,_delete_stack_async,_deploy_stack_async,@@ -51,6 +52,8 @@ logger = logging.getLogger("cloudformation")def _create_stack(params):from ministack.services.cloudformation import _stack_events, _stacks++ from .helpers import _resolve_documentstack_name = _p(params, "StackName")if not stack_name:return _error("ValidationError", "StackName is required")@@ -96,6 +99,13 @@ def _create_stack(params):f"stack/{stack_name}/{new_uuid()}")+ termination_protection = (+ _p(params, "EnableTerminationProtection", "false").lower() == "true")+ stack_policy, policy_err = _resolve_document(+ params, "StackPolicyBody", "StackPolicyURL", "Stack policy")+ if policy_err:+ return policy_err+stack = {"StackName": stack_name,"StackId": stack_id,@@ -115,6 +125,8 @@ def _create_stack(params):"Tags": tags,"Outputs": [],"DisableRollback": disable_rollback,+ "EnableTerminationProtection": termination_protection,+ "_stack_policy": stack_policy or "","_region": get_region(),"_resources": {},"_template": template,@@ -242,6 +254,9 @@ def _describe_stacks(params):f"<LastUpdatedTime>{s.get('LastUpdatedTime', '')}</LastUpdatedTime>"f"<Description>{_esc(s.get('Description', ''))}</Description>"f"<DisableRollback>{str(s.get('DisableRollback', False)).lower()}</DisableRollback>"+ "<EnableTerminationProtection>"+ f"{str(s.get('EnableTerminationProtection', False)).lower()}"+ "</EnableTerminationProtection>"f"<Parameters>{params_xml}</Parameters>"f"<Outputs>{outputs_xml}</Outputs>"f"<Tags>{tags_xml}</Tags>"@@ -507,6 +522,11 @@ def _delete_stack(params):if stack.get("StackStatus") == "DELETE_COMPLETE":return _xml(200, "DeleteStackResponse", "")+ if stack.get("EnableTerminationProtection"):+ return _error("ValidationError",+ f"Stack [{stack['StackId']}] cannot be deleted while "+ "TerminationProtection is enabled")+# Check for active imports before deletingstack_exports = [out.get("ExportName") for out in stack.get("Outputs", [])@@ -579,6 +599,8 @@ def _stack_has_no_updates(stack, template, param_values, tags,def _update_stack(params):from ministack.services.cloudformation import _stacks++ from .helpers import _resolve_documentstack_name = _p(params, "StackName")if not stack_name:return _error("ValidationError", "StackName is required")@@ -663,6 +685,13 @@ def _update_stack(params):and _cs.get("ExecutionStatus") == "AVAILABLE"):_cs["ExecutionStatus"] = "OBSOLETE"+ stack_policy, policy_err = _resolve_document(+ params, "StackPolicyBody", "StackPolicyURL", "Stack policy")+ if policy_err:+ return policy_err+ if stack_policy:+ stack["_stack_policy"] = stack_policy+stack["StackStatus"] = "UPDATE_IN_PROGRESS"stack["LastUpdatedTime"] = now_iso()stack["_template_body"] = template_body@@ -868,6 +897,122 @@ def _get_template_summary(params):f"</GetTemplateSummaryResult>")+# --- ListImports ---++def _list_imports(params):+ from ministack.services.cloudformation import _stacks+ export_name = _p(params, "ExportName")+ if not export_name:+ return _error("ValidationError", "ExportName is required")+ importers = sorted(+ name for name, stack in _stacks.items()+ if stack.get("StackStatus", "").endswith("_COMPLETE")+ and "DELETE" not in stack.get("StackStatus", "")+ and export_name in _imported_export_names(stack, name)+ )+ if not importers:+ return _error("ValidationError",+ f"Export '{export_name}' is not imported by any stack.")+ members = "".join(f"<member>{_esc(n)}</member>" for n in importers)+ return _xml(200, "ListImportsResponse",+ f"<ListImportsResult><Imports>{members}</Imports></ListImportsResult>")+++# --- UpdateTerminationProtection / stack policy ---++def _update_termination_protection(params):+ stack_name = _p(params, "StackName")+ stack = _resolve_stack(stack_name)+ if not stack or stack.get("StackStatus") in ("DELETE_IN_PROGRESS", "DELETE_COMPLETE"):+ return _error("ValidationError", f"Stack [{stack_name}] does not exist")+ enable = _p(params, "EnableTerminationProtection")+ if not enable:+ return _error("ValidationError", "EnableTerminationProtection is required")+ stack["EnableTerminationProtection"] = enable.lower() == "true"+ return _xml(200, "UpdateTerminationProtectionResponse",+ "<UpdateTerminationProtectionResult>"+ f"<StackId>{_esc(stack['StackId'])}</StackId>"+ "</UpdateTerminationProtectionResult>")+++def _set_stack_policy(params):+ from .helpers import _resolve_document+ stack_name = _p(params, "StackName")+ stack = _resolve_stack(stack_name)+ if not stack or stack.get("StackStatus") == "DELETE_COMPLETE":+ return _error("ValidationError", f"Stack [{stack_name}] does not exist")+ policy, policy_err = _resolve_document(+ params, "StackPolicyBody", "StackPolicyURL", "Stack policy")+ if policy_err:+ return policy_err+ if not policy:+ return _error("ValidationError", "StackPolicyBody or StackPolicyURL is required")+ try:+ json.loads(policy)+ except ValueError:+ return _error("ValidationError", "Error validating stack policy: Invalid stack policy")+ stack["_stack_policy"] = policy+ return _xml(200, "SetStackPolicyResponse", "")+++def _get_stack_policy(params):+ stack_name = _p(params, "StackName")+ stack = _resolve_stack(stack_name)+ if not stack or stack.get("StackStatus") == "DELETE_COMPLETE":+ return _error("ValidationError", f"Stack [{stack_name}] does not exist")+ policy = stack.get("_stack_policy") or ""+ body = f"<StackPolicyBody>{_esc(policy)}</StackPolicyBody>" if policy else ""+ return _xml(200, "GetStackPolicyResponse",+ f"<GetStackPolicyResult>{body}</GetStackPolicyResult>")+++# --- CancelUpdateStack / ContinueUpdateRollback ---++def _cancel_update_stack(params):+ stack_name = _p(params, "StackName")+ stack = _resolve_stack(stack_name)+ if not stack or stack.get("StackStatus") == "DELETE_COMPLETE":+ return _error("ValidationError", f"Stack [{stack_name}] does not exist")+ if stack.get("StackStatus") != "UPDATE_IN_PROGRESS":+ return _error("ValidationError",+ "CancelUpdateStack cannot be called from current stack status")+ # The running update checks the flag before each resource and rolls back.+ stack["_cancel_requested"] = True+ return _xml(200, "CancelUpdateStackResponse", "")+++def _continue_update_rollback(params):+ stack_name = _p(params, "StackName")+ stack = _resolve_stack(stack_name)+ if not stack or stack.get("StackStatus") == "DELETE_COMPLETE":+ return _error("ValidationError", f"Stack [{stack_name}] does not exist")+ stack_name = stack.get("StackName", stack_name)+ if stack.get("StackStatus") != "UPDATE_ROLLBACK_FAILED":+ return _error("ValidationError",+ "ContinueUpdateRollback cannot be called from current stack status")+ # ResourcesToSkip.member.N on the query protocol, a plain list on the JSON one.+ skip = params.get("ResourcesToSkip")+ if not isinstance(skip, list):+ skip = []+ while _p(params, f"ResourcesToSkip.member.{len(skip) + 1}"):+ skip.append(_p(params, f"ResourcesToSkip.member.{len(skip) + 1}"))+ skip = [str(s) for s in skip]+ pending = stack.get("_rollback_failed", {})+ unknown = sorted(set(skip) - set(pending))+ if unknown:+ return _error("ValidationError",+ f"Resource(s) [{', '.join(unknown)}] cannot be skipped: only "+ "resources whose rollback failed can be skipped")+ stack_id = stack["StackId"]+ _create_stack_task_in_region(+ _continue_update_rollback_async(stack_name, stack_id, frozenset(skip)),+ stack,+ stack_id,+ )+ return _xml(200, "ContinueUpdateRollbackResponse",+ "<ContinueUpdateRollbackResult></ContinueUpdateRollbackResult>")++# ===========================================================================# Action Handler Registry# ===========================================================================@@ -891,4 +1036,10 @@ _ACTION_HANDLERS = {"DeleteChangeSet": _delete_change_set,"ListChangeSets": _list_change_sets,"GetTemplateSummary": _get_template_summary,+ "ListImports": _list_imports,+ "UpdateTerminationProtection": _update_termination_protection,+ "SetStackPolicy": _set_stack_policy,+ "GetStackPolicy": _get_stack_policy,+ "CancelUpdateStack": _cancel_update_stack,+ "ContinueUpdateRollback": _continue_update_rollback,}diff --git a/ministack/services/cloudformation/helpers.py b/ministack/services/cloudformation/helpers.pyindex 27ac1673..807dda6f 100644--- a/ministack/services/cloudformation/helpers.py+++ b/ministack/services/cloudformation/helpers.py@@ -67,16 +67,23 @@ def _resolve_template(params):"""Resolve TemplateBody or TemplateURL to a template string.If TemplateURL is provided, fetch the template from S3.Returns (template_body, error_tuple) — error_tuple is None on success."""- template_body = _p(params, "TemplateBody")- template_url = _p(params, "TemplateURL")+ return _resolve_document(params, "TemplateBody", "TemplateURL", "Template")- if template_body:- return template_body, None- if template_url:+def _resolve_document(params, body_key, url_key, label):+ """Resolve an inline document or its S3 URL (``TemplateBody``/``TemplateURL``,+ ``StackPolicyBody``/``StackPolicyURL``) to a string; ``label`` names the+ document in the errors. Returns (body, error_tuple)."""+ body = _p(params, body_key)+ url = _p(params, url_key)++ if body:+ return body, None++ if url:try:from ministack.services import s3 as _s3- parsed = urlparse(template_url)+ parsed = urlparse(url)# Support formats:# http://localhost:4566/bucket/key# https://s3.amazonaws.com/bucket/key@@ -84,18 +91,15 @@ def _resolve_template(params):path = parsed.path.lstrip("/")parts = path.split("/", 1)if len(parts) < 2:- return None, _error("ValidationError",- f"Invalid TemplateURL: {template_url}")+ return None, _error("ValidationError", f"Invalid {url_key}: {url}")bucket_name, key = parts[0], parts[1]obj_data = _s3._get_object_data(bucket_name, key)if obj_data is None:- return None, _error("ValidationError",- f"Template not found at {template_url}")+ return None, _error("ValidationError", f"{label} not found at {url}")return obj_data.decode("utf-8"), Noneexcept Exception as e:- logger.warning("Failed to fetch TemplateURL %s: %s", template_url, e)- return None, _error("ValidationError",- f"Error fetching TemplateURL: {e}")+ logger.warning("Failed to fetch %s %s: %s", url_key, url, e)+ return None, _error("ValidationError", f"Error fetching {url_key}: {e}")return None, None # neither provideddiff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.pyindex 904fa4c7..4fdb8255 100644--- a/ministack/services/cloudformation/stacks.py+++ b/ministack/services/cloudformation/stacks.py@@ -157,6 +157,60 @@ def _resolve_stack_outputs(outputs_defs, conditions, resources, param_values,return resolved_outputs, exports+async def _continue_update_rollback_async(stack_name: str, stack_id: str,+ resources_to_skip):+ """Background task for ContinueUpdateRollback: retry the deletes that+ failed the update rollback, skipping the logical ids the caller named+ (their status becomes UPDATE_COMPLETE and the resource stays, as on AWS),+ and land the stack in UPDATE_ROLLBACK_COMPLETE or, if a delete fails+ again, UPDATE_ROLLBACK_FAILED."""+ from ministack.services.cloudformation import _stacks+ stack = _stacks.get(stack_name)+ if not stack:+ return+ pending = dict(stack.get("_rollback_failed", {}))+ stack["StackStatus"] = "UPDATE_ROLLBACK_IN_PROGRESS"+ _add_event(stack_id, stack_name, stack_name, "AWS::CloudFormation::Stack",+ "UPDATE_ROLLBACK_IN_PROGRESS", "User Initiated", stack_id)+ still_failed = {}+ for logical_id, res in pending.items():+ rtype = res.get("ResourceType", "")+ pid = res.get("PhysicalResourceId", "")+ if logical_id in resources_to_skip:+ _add_event(stack_id, stack_name, logical_id, rtype,+ "UPDATE_COMPLETE", "Resource rollback skipped by user", pid)+ continue+ try:+ if _is_custom_resource(rtype):+ await run_reentrant(_delete_resource, rtype, pid,+ res.get("Properties", {}), stack_name, logical_id)+ else:+ _delete_resource(rtype, pid, res.get("Properties", {}),+ stack_name, logical_id)+ _add_event(stack_id, stack_name, logical_id, rtype,+ "DELETE_COMPLETE", physical_id=pid)+ except Exception as exc:+ logger.error("Continue rollback delete of %s failed: %s", logical_id, exc)+ _add_event(stack_id, stack_name, logical_id, rtype,+ "DELETE_FAILED", str(exc), pid)+ still_failed[logical_id] = res+ await asyncio.sleep(0)+ if still_failed:+ stack["_rollback_failed"] = still_failed+ reason = ("The following resource(s) failed to delete: "+ f"[{', '.join(sorted(still_failed))}].")+ stack["StackStatus"] = "UPDATE_ROLLBACK_FAILED"+ stack["StackStatusReason"] = reason+ _add_event(stack_id, stack_name, stack_name, "AWS::CloudFormation::Stack",+ "UPDATE_ROLLBACK_FAILED", reason, stack_id)+ return+ stack.pop("_rollback_failed", None)+ stack["StackStatus"] = "UPDATE_ROLLBACK_COMPLETE"+ stack["StackStatusReason"] = ""+ _add_event(stack_id, stack_name, stack_name, "AWS::CloudFormation::Stack",+ "UPDATE_ROLLBACK_COMPLETE", physical_id=stack_id)++async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,param_values: dict, disable_rollback: bool,tags: list, is_update: bool = False,@@ -200,9 +254,17 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,failed = Falsefail_reason = ""+ cancelled = Falsereplaced_resources = []+ stack.pop("_cancel_requested", None)for logical_id in ordered:+ if is_update and stack.pop("_cancel_requested", False):+ # CancelUpdateStack: stop before the next resource and roll the+ # update back, as on AWS ("User Initiated").+ failed = cancelled = True+ fail_reason = "User Initiated"+ breakres_def = resources_defs[logical_id]cond = res_def.get("Condition")if cond and not conditions.get(cond, True):@@ -423,9 +485,11 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,stack["StackStatus"] = "ROLLBACK_IN_PROGRESS" if not is_update else "UPDATE_ROLLBACK_IN_PROGRESS"_add_event(stack_id, stack_name, stack_name,"AWS::CloudFormation::Stack", stack["StackStatus"],- "Rollback requested", stack_id)+ "User Initiated" if cancelled else "Rollback requested",+ stack_id)rollback_delete_failures = []+ rollback_failed_records = {}previous_resources = (previous_stack.get("_resources", {})if is_update and previous_stack else {}@@ -472,6 +536,10 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,_add_event(stack_id, stack_name, logical_id, rtype,"DELETE_FAILED", str(del_exc), pid)rollback_delete_failures.append(logical_id)+ rollback_failed_records[logical_id] = {+ "PhysicalResourceId": pid, "ResourceType": rtype,+ "Properties": res_props,+ }provisioned_resources.pop(logical_id, None)if is_update and previous_stack:@@ -503,6 +571,8 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,reason = ("The following resource(s) failed to delete: "f"[{', '.join(sorted(rollback_delete_failures))}].")stack["StackStatusReason"] = reason+ # What ContinueUpdateRollback retries (or skips).+ stack["_rollback_failed"] = rollback_failed_records_add_event(stack_id, stack_name, stack_name,"AWS::CloudFormation::Stack", stack["StackStatus"],reason, stack_id)diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 8e4ad17d..4927fc6e 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -2404,6 +2404,119 @@ def test_cfn_delete_stack_with_active_imports(cfn):with pytest.raises(ClientError):cfn.delete_stack(StackName="cfn-t17-exp")+def test_cfn_list_imports_names_the_importing_stacks(cfn):+ """ListImports lists the stacks whose templates import the export through+ Fn::ImportValue; a template that only mentions the name does not count,+ and an export nobody imports is a ValidationError."""+ uid = _uuid_mod.uuid4().hex[:8]+ export_name = f"cfn-imports-{uid}"+ exporter, importer, mention = (f"cfn-imports-exp-{uid}", f"cfn-imports-imp-{uid}",+ f"cfn-imports-mention-{uid}")+ cfn.create_stack(StackName=exporter, TemplateBody=json.dumps({+ "Resources": {"P": {"Type": "AWS::SSM::Parameter", "Properties": {+ "Name": f"/cfn-imports/{uid}/exp", "Type": "String", "Value": "v"}}},+ "Outputs": {"Out": {"Value": "v", "Export": {"Name": export_name}}}}))+ try:+ assert _wait_stack(cfn, exporter)["StackStatus"] == "CREATE_COMPLETE"+ with pytest.raises(ClientError) as exc:+ cfn.list_imports(ExportName=export_name)+ assert exc.value.response["Error"]["Message"] == (+ f"Export '{export_name}' is not imported by any stack.")++ cfn.create_stack(StackName=importer, TemplateBody=json.dumps({"Resources": {+ "P": {"Type": "AWS::SSM::Parameter", "Properties": {+ "Name": f"/cfn-imports/{uid}/imp", "Type": "String",+ "Value": {"Fn::ImportValue": export_name}}}}}))+ cfn.create_stack(StackName=mention, TemplateBody=json.dumps({"Resources": {+ "P": {"Type": "AWS::SSM::Parameter", "Properties": {+ "Name": f"/cfn-imports/{uid}/mention", "Type": "String",+ "Value": export_name}}}}))+ for name in (importer, mention):+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"+ assert cfn.list_imports(ExportName=export_name)["Imports"] == [importer]+ finally:+ for name in (importer, mention, exporter):+ _delete_cfn_test_stack(cfn, name)+++def test_cfn_termination_protection_blocks_delete_until_disabled(cfn):+ """A stack created with EnableTerminationProtection refuses DeleteStack+ and stays as it is; UpdateTerminationProtection turns it off, DescribeStacks+ reports the flag either way."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-protected-{uid}"+ template = json.dumps({"Resources": {"P": {"Type": "AWS::SSM::Parameter", "Properties": {+ "Name": f"/cfn-protected/{uid}", "Type": "String", "Value": "v"}}}})+ cfn.create_stack(StackName=stack_name, TemplateBody=template,+ EnableTerminationProtection=True)+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ assert stack["EnableTerminationProtection"] is True++ with pytest.raises(ClientError) as exc:+ cfn.delete_stack(StackName=stack_name)+ assert "cannot be deleted while TerminationProtection is enabled" in (+ exc.value.response["Error"]["Message"])+ assert cfn.describe_stacks(StackName=stack_name)["Stacks"][0]["StackStatus"] == (+ "CREATE_COMPLETE")++ result = cfn.update_termination_protection(+ StackName=stack_name, EnableTerminationProtection=False)+ assert result["StackId"] == stack["StackId"]+ assert cfn.describe_stacks(StackName=stack_name)["Stacks"][0][+ "EnableTerminationProtection"] is False+ with pytest.raises(ClientError):+ cfn.update_termination_protection(+ StackName=f"{stack_name}-nope", EnableTerminationProtection=True)+ cfn.delete_stack(StackName=stack_name)+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"+ finally:+ try:+ cfn.update_termination_protection(+ StackName=stack_name, EnableTerminationProtection=False)+ except ClientError:+ pass+ _delete_cfn_test_stack(cfn, stack_name)+++def test_cfn_stack_policy_is_stored_and_returned(cfn):+ """SetStackPolicy stores the policy and GetStackPolicy returns it; a stack+ without one answers no StackPolicyBody; CreateStack takes StackPolicyBody."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-policy-{uid}"+ template = json.dumps({"Resources": {"P": {"Type": "AWS::SSM::Parameter", "Properties": {+ "Name": f"/cfn-policy/{uid}", "Type": "String", "Value": "v"}}}})+ policy = json.dumps({"Statement": [{"Effect": "Deny", "Action": "Update:*",+ "Principal": "*", "Resource": "LogicalResourceId/P"}]})+ cfn.create_stack(StackName=stack_name, TemplateBody=template)+ try:+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"+ assert "StackPolicyBody" not in cfn.get_stack_policy(StackName=stack_name)+ cfn.set_stack_policy(StackName=stack_name, StackPolicyBody=policy)+ assert json.loads(cfn.get_stack_policy(StackName=stack_name)["StackPolicyBody"]) == (+ json.loads(policy))+ with pytest.raises(ClientError):+ cfn.set_stack_policy(StackName=stack_name, StackPolicyBody="not json")++ cfn.create_stack(StackName=f"{stack_name}-b", TemplateBody=template.replace(+ f"/cfn-policy/{uid}", f"/cfn-policy/{uid}/b"), StackPolicyBody=policy)+ assert _wait_stack(cfn, f"{stack_name}-b")["StackStatus"] == "CREATE_COMPLETE"+ assert cfn.get_stack_policy(StackName=f"{stack_name}-b")["StackPolicyBody"]++ replaced = json.dumps({"Statement": [{"Effect": "Allow", "Action": "Update:*",+ "Principal": "*", "Resource": "*"}]})+ cfn.update_stack(StackName=f"{stack_name}-b", TemplateBody=template.replace(+ f"/cfn-policy/{uid}", f"/cfn-policy/{uid}/b").replace('"v"', '"w"'),+ StackPolicyBody=replaced)+ assert _wait_stack(cfn, f"{stack_name}-b")["StackStatus"] == "UPDATE_COMPLETE"+ assert json.loads(cfn.get_stack_policy(StackName=f"{stack_name}-b")["StackPolicyBody"]) == (+ json.loads(replaced))+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ _delete_cfn_test_stack(cfn, f"{stack_name}-b")++def test_cfn_update_rollback_on_failure(cfn, s3):template_v1 = {"AWSTemplateFormatVersion": "2010-09-09",@@ -10704,6 +10817,179 @@ def test_cfn_update_rollback_delete_failure_lands_update_rollback_failed(cfn, lapass+_CR_HANDLER_SLOW = """\+import json, time, urllib.request++def handler(event, context):+ if event["RequestType"] == "Create":+ time.sleep(2)+ payload = json.dumps({+ "Status": "SUCCESS",+ "RequestId": event["RequestId"],+ "StackId": event["StackId"],+ "LogicalResourceId": event["LogicalResourceId"],+ "PhysicalResourceId": event.get("PhysicalResourceId") or "slow-custom-resource",+ "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_cfn_continue_update_rollback_recovers_the_stack(cfn, lam):+ """A stack in UPDATE_ROLLBACK_FAILED is not updatable; ContinueUpdateRollback+ retries the failed deletes (and fails again while the resource still cannot+ be deleted), an unknown ResourcesToSkip entry is refused, and once the+ delete works the retry lands UPDATE_ROLLBACK_COMPLETE and the stack is+ updatable again. Any other status is refused."""+ suffix = _uuid_mod.uuid4().hex[:8]+ fn = f"cr-cur-{suffix}"+ stack_name = f"cfn-continue-rollback-{suffix}"+ lam.create_function(+ FunctionName=fn, Runtime="python3.12", Role=_CR_LAMBDA_ROLE, Handler="index.handler",+ Code={"ZipFile": _cr_make_zip(_CR_HANDLER_DELETE_FAILS)},+ )+ base = {"Resources": {"Topic": {"Type": "AWS::SNS::Topic",+ "Properties": {"TopicName": f"cfn-cur-{suffix}"}}}}+ updated = json.loads(json.dumps(base))+ updated["Resources"]["CR"] = {"Type": "Custom::Tester", "Properties": {+ "ServiceToken": f"arn:aws:lambda:us-east-1:000000000000:function:{fn}"}}+ updated["Resources"]["Bad"] = {**_FAILING_RESOURCE, "DependsOn": "CR"}+ try:+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(base))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ with pytest.raises(ClientError) as exc:+ cfn.continue_update_rollback(StackName=stack_name)+ assert "cannot be called from current stack status" in (+ exc.value.response["Error"]["Message"])++ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(updated))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_FAILED", stack.get("StackStatusReason")++ cfn.continue_update_rollback(StackName=stack_name)+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_FAILED", stack.get("StackStatusReason")++ with pytest.raises(ClientError) as exc:+ cfn.continue_update_rollback(StackName=stack_name, ResourcesToSkip=["Topic"])+ assert "Topic" in exc.value.response["Error"]["Message"]++ # Once the resource can be deleted, the retry completes the rollback+ # without skipping anything.+ lam.update_function_code(FunctionName=fn, ZipFile=_cr_make_zip(_CR_HANDLER_SUCCESS))+ cfn.continue_update_rollback(StackName=stack_name)+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")+ events = cfn.describe_stack_events(StackName=stack_name)["StackEvents"]+ assert any(e["LogicalResourceId"] == "CR" and e["ResourceStatus"] == "DELETE_COMPLETE"+ for e in events)++ again = json.loads(json.dumps(base))+ again["Resources"]["Topic"]["Properties"]["DisplayName"] = "after"+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(again))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ finally:+ try:+ lam.update_function_code(FunctionName=fn, ZipFile=_cr_make_zip(_CR_HANDLER_SUCCESS))+ except ClientError:+ pass+ _delete_cfn_test_stack(cfn, stack_name)+ try:+ lam.delete_function(FunctionName=fn)+ except ClientError:+ pass+++def test_cfn_continue_update_rollback_skips_the_named_resource(cfn, lam):+ """ResourcesToSkip leaves the resource in place (an UPDATE_COMPLETE event)+ and the stack still reaches UPDATE_ROLLBACK_COMPLETE."""+ suffix = _uuid_mod.uuid4().hex[:8]+ fn = f"cr-cur-skip-{suffix}"+ stack_name = f"cfn-continue-skip-{suffix}"+ lam.create_function(+ FunctionName=fn, Runtime="python3.12", Role=_CR_LAMBDA_ROLE, Handler="index.handler",+ Code={"ZipFile": _cr_make_zip(_CR_HANDLER_DELETE_FAILS)},+ )+ base = {"Resources": {"Topic": {"Type": "AWS::SNS::Topic",+ "Properties": {"TopicName": f"cfn-cur-skip-{suffix}"}}}}+ updated = json.loads(json.dumps(base))+ updated["Resources"]["CR"] = {"Type": "Custom::Tester", "Properties": {+ "ServiceToken": f"arn:aws:lambda:us-east-1:000000000000:function:{fn}"}}+ updated["Resources"]["Bad"] = {**_FAILING_RESOURCE, "DependsOn": "CR"}+ try:+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(base))+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(updated))+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_ROLLBACK_FAILED"++ cfn.continue_update_rollback(StackName=stack_name, ResourcesToSkip=["CR"])+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")+ events = cfn.describe_stack_events(StackName=stack_name)["StackEvents"]+ assert any(e["LogicalResourceId"] == "CR" and e["ResourceStatus"] == "UPDATE_COMPLETE"+ for e in events)+ finally:+ try:+ lam.update_function_code(FunctionName=fn, ZipFile=_cr_make_zip(_CR_HANDLER_SUCCESS))+ except ClientError:+ pass+ _delete_cfn_test_stack(cfn, stack_name)+ try:+ lam.delete_function(FunctionName=fn)+ except ClientError:+ pass+++def test_cfn_cancel_update_stack_rolls_the_update_back(cfn, lam):+ """CancelUpdateStack on an UPDATE_IN_PROGRESS stack stops before the next+ resource and rolls back to the previous state ("User Initiated"); on any+ other status it is refused."""+ suffix = _uuid_mod.uuid4().hex[:8]+ fn = f"cr-cancel-{suffix}"+ stack_name = f"cfn-cancel-{suffix}"+ lam.create_function(+ FunctionName=fn, Runtime="python3.12", Role=_CR_LAMBDA_ROLE, Handler="index.handler",+ Code={"ZipFile": _cr_make_zip(_CR_HANDLER_SLOW)}, Timeout=30,+ )+ base = {"Resources": {"Topic": {"Type": "AWS::SNS::Topic",+ "Properties": {"TopicName": f"cfn-cancel-{suffix}"}}}}+ updated = json.loads(json.dumps(base))+ updated["Resources"]["Slow"] = {"Type": "Custom::Tester", "Properties": {+ "ServiceToken": f"arn:aws:lambda:us-east-1:000000000000:function:{fn}"}}+ updated["Resources"]["Later"] = {"Type": "AWS::SNS::Topic", "DependsOn": "Slow",+ "Properties": {"TopicName": f"cfn-cancel-later-{suffix}"}}+ try:+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(base))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ with pytest.raises(ClientError) as exc:+ cfn.cancel_update_stack(StackName=stack_name)+ assert exc.value.response["Error"]["Message"] == (+ "CancelUpdateStack cannot be called from current stack status")++ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(updated))+ assert cfn.describe_stacks(StackName=stack_name)["Stacks"][0]["StackStatus"] == (+ "UPDATE_IN_PROGRESS")+ cfn.cancel_update_stack(StackName=stack_name)+ stack = _wait_stack(cfn, stack_name, timeout=60)+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")+ assert [r["LogicalResourceId"] for r in+ cfn.describe_stack_resources(StackName=stack_name)["StackResources"]] == ["Topic"]+ assert "User Initiated" in _stack_event_reasons(cfn, stack_name)+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ try:+ lam.delete_function(FunctionName=fn)+ except ClientError:+ pass++def test_cfn_lambda_version_stack_delete_removes_version(cfn, lam):"""AWS::Lambda::Version now has a real delete handler: deleting the stackremoves the published version instead of leaking it, and Ref resolves to