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
fix(cloudformation): honor OnFailure, DeletionMode, TemplateStage and ClientRequestToken (#1877)
Fábio André Ramos Rodrigues29f5cda2d98e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fcea0887..1e39c9ec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,11 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **CloudFormation — `OnFailure` and `OnStackFailure` are honoured** — CreateStack `OnFailure=DO_NOTHING` leaves a failed create in `CREATE_FAILED`, as `DisableRollback=true` does, and `DELETE` rolls the create back and then deletes the stack, which ends `DELETE_COMPLETE` (or `DELETE_FAILED` when a resource does not delete). `OnFailure` together with `DisableRollback` is a `ValidationError`. CreateChangeSet `OnStackFailure` makes the same choice when the change set executes; `DELETE` is refused unless `ChangeSetType` is `CREATE`, DescribeChangeSet reports the value, and ExecuteChangeSet refuses `DisableRollback` for such a change set. ExecuteChangeSet ignored `DisableRollback=true` and rolled back anyway; it now leaves the failed operation in `CREATE_FAILED` or `UPDATE_FAILED`.+- **CloudFormation — `DeleteStack` takes `DeletionMode=FORCE_DELETE_STACK`** — on a `DELETE_FAILED` stack, the resources that failed to delete and the resources they depend on are retained with a `DELETE_SKIPPED` event, and the stack reaches `DELETE_COMPLETE`. On any other status the call is a `ValidationError`, and DescribeStacks reports the stack's `DeletionMode`.+- **CloudFormation — `GetTemplate` reads `TemplateStage` and `ChangeSetName`** — `Processed` returns the template after its SAM, `AWS::LanguageExtensions` and `AWS::Include` transforms as JSON; a template without a transform is the same at both stages. `Original` stays the default. The response lists `StagesAvailable` (`Original`, `Processed`), and `ChangeSetName` returns a change set's template, answering `ChangeSetNotFound` (404) for an unknown one.+- **CloudFormation — stack events carry `ClientRequestToken`** — every event recorded by CreateStack, UpdateStack, DeleteStack, ExecuteChangeSet and ContinueUpdateRollback carries the token of that call, and the rollback events of a CancelUpdateStack carry the cancel's token. A token outside `[a-zA-Z0-9][-a-zA-Z0-9]*` or longer than 128 characters is a `ValidationError`.+- **Bedrock AgentCore — `InvokeAgentRuntime` enforces IAM policies** — with `AUTH=true`, runtime invocations now resolve to `bedrock-agentcore:InvokeAgentRuntime` and authorize against the ARN in the request path, so a policy can allow one runtime and deny another. Previously, the action was not extracted and the request bypassed identity-policy evaluation.- **IAM — a negated condition operator is true when its key is absent** — the evaluator treated an absent key as a failed condition for every operator, so a `Deny` guarded by `StringNotEquals`, `StringNotLike`, `ArnNotLike`, `NotIpAddress` or another negated operator never applied to a request without that key. AWS evaluates such a condition as true and denies. The single-valued negated operators now do the same, while `ForAnyValue` and the affirmative operators still fail on an absent key. Contributed by @iot-rocket.- **KMS — `GenerateDataKey` returns `KeyMaterialId`** — requests without `Recipient` now include the identifier of the wrapping key material. The identifier remains stable across requests and persistence reloads, and changes when the wrapping material changes. Fixes #1853.diff --git a/README.md b/README.mdindex 69c9d24c..832acef1 100644--- a/README.md+++ b/README.md@@ -470,7 +470,10 @@ subnet = ec2.create_subnet(| **Conditions** | Fn::Equals, Fn::And, Fn::Or, Fn::Not — conditional resource creation || **Rules** | The `Rules` section runs after the parameters resolve and before any resource is touched (CreateStack, UpdateStack, CreateChangeSet): `RuleCondition`, `Assertions` with `AssertDescription`, Fn::And/Or/Not/Equals/If/Contains/EachMemberEquals/EachMemberIn and Ref; Fn::RefAll, Fn::ValueOf and Fn::ValueOfAll read the EC2 store for VPC, subnet and security-group ids || **Transforms** | `AWS::Serverless-2016-10-31` (SAM, in the `full` image), `AWS::LanguageExtensions` (`Fn::ForEach` over a literal list, a `CommaDelimitedList` parameter, `Fn::FindInMap` or `Fn::Split`, nested and inside `Properties`; `${Id}` / `&{Id}` in the fragment keys, `${Id}` in `Fn::Sub` and a `Ref` to the identifier; `Fn::Length`, `Fn::ToJsonString`) and the embedded `AWS::Include` transform (`Fn::Transform` with an `s3://` `Location`, JSON or YAML snippets) |-| **Rollback** | Configurable via `DisableRollback` — on failure, previously created resources are cleaned up in reverse dependency order |+| **Rollback** | Configurable via `DisableRollback`, CreateStack `OnFailure` (`ROLLBACK`, `DO_NOTHING`, `DELETE`) and CreateChangeSet `OnStackFailure` (`DELETE` for CREATE change sets only); ExecuteChangeSet honours `DisableRollback`. On failure, previously created resources are cleaned up in reverse dependency order; `DELETE` then deletes the stack |+| **Stack Deletion** | `RetainResources` and `DeletionMode=FORCE_DELETE_STACK` on a `DELETE_FAILED` stack: the resources that failed to delete, and what they depend on, are retained (`DELETE_SKIPPED`) and the stack reaches `DELETE_COMPLETE` |+| **Templates** | GetTemplate `TemplateStage` (`Original`, the default here, or `Processed`, the template after SAM, `AWS::LanguageExtensions` and `AWS::Include`), `StagesAvailable`, and a change set's template through `ChangeSetName` |+| **Client Request Tokens** | The `ClientRequestToken` of CreateStack, UpdateStack, DeleteStack, ExecuteChangeSet, ContinueUpdateRollback and CancelUpdateStack is reported on every stack event the operation records || **Async Status** | Stacks deploy asynchronously (`CREATE_IN_PROGRESS` → `CREATE_COMPLETE`) — poll with DescribeStacks || **Quotas** | The template and stack quotas of the CloudFormation quotas page are enforced before a stack exists: 51,200 bytes of `TemplateBody`, 1,000,000 bytes behind `TemplateURL`, 500 resources, 200 parameters / outputs / mappings, 200 attributes per mapping, 255-character names, a 1,024-byte description, 4,096-byte parameter values, and a stack name of up to 128 alphanumeric characters and hyphens starting with a letter |diff --git a/ministack/services/cloudformation/__init__.py b/ministack/services/cloudformation/__init__.pyindex 43bbb250..2a1c9a05 100644--- a/ministack/services/cloudformation/__init__.py+++ b/ministack/services/cloudformation/__init__.py@@ -61,7 +61,27 @@ async def handle_request(method: str, path: str, headers: dict,if not handler:from .helpers import _errorreturn _error("InvalidAction", f"Unknown action: {action}", 400)- return handler(params)+ if action not in _TOKEN_ACTIONS:+ return handler(params)+ from .helpers import _error, client_request_token_problems, validation_error_message+ from .stacks import CLIENT_REQUEST_TOKEN+ token = _p(params, "ClientRequestToken")+ if token and (problems := client_request_token_problems(token)):+ return _error("ValidationError", validation_error_message(problems))+ # The events the operation records, now and from the task it schedules+ # (which copies this context), carry the token.+ scope = CLIENT_REQUEST_TOKEN.set(token)+ try:+ return handler(params)+ finally:+ CLIENT_REQUEST_TOKEN.reset(scope)+++# The stack operations that take a ClientRequestToken and record stack events.+_TOKEN_ACTIONS = frozenset({+ "CreateStack", "UpdateStack", "DeleteStack", "ExecuteChangeSet",+ "ContinueUpdateRollback", "CancelUpdateStack",+})def reset():diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.pyindex 1f69b821..7fb22f8d 100644--- a/ministack/services/cloudformation/changesets.py+++ b/ministack/services/cloudformation/changesets.py@@ -23,6 +23,7 @@ from .engine import (validate_template_support,)from .helpers import (+ ON_FAILURE_VALUES,_error,_esc,_extract_members,@@ -32,12 +33,14 @@ from .helpers import (_request_problems,_resolve_template,_xml,+ enum_problems,stack_name_problems,validation_error_message,)from .stacks import (_add_event,_create_stack_task_in_region,+ _create_then_delete_on_failure,_deploy_stack_async,_diff_resources,_stack_region,@@ -355,6 +358,15 @@ def _create_change_set(params):# The request-level constraints of a new stack, joined as the API does.if request_error := _request_problems(params, stack_name):return request_error+ if problems := enum_problems(params, "OnStackFailure", "onStackFailure",+ ON_FAILURE_VALUES):+ return _error("ValidationError", validation_error_message(problems))+ on_stack_failure = _p(params, "OnStackFailure")+ # "DELETE ... is only valid when the ChangeSetType parameter is set to+ # CREATE" (API_CreateChangeSet); the error wording is not measured.+ if on_stack_failure == "DELETE" and cs_type != "CREATE":+ return _error("ValidationError",+ "OnStackFailure DELETE is only valid when ChangeSetType is CREATE.")template_body, resolve_err = _resolve_template(params)if resolve_err:@@ -555,6 +567,7 @@ def _create_change_set(params):],"Tags": tags,"Capabilities": _extract_string_members(params, "Capabilities"),+ "OnStackFailure": on_stack_failure,"_tags_given": tags_given,"_template": template,"_template_body": template_body,@@ -664,6 +677,8 @@ def _describe_change_set(params):f"<Changes>{changes_xml}</Changes>"f"<Tags>{tags_xml}</Tags>")+ if cs.get("OnStackFailure"):+ inner += f"<OnStackFailure>{cs['OnStackFailure']}</OnStackFailure>"return _xml(200, "DescribeChangeSetResponse",f"<DescribeChangeSetResult>{inner}</DescribeChangeSetResult>")@@ -683,7 +698,9 @@ async def _track_change_set_execution(change_set, stack, deploy_coro):await deploy_corofinally:status = stack.get("StackStatus", "")- if status.endswith("_COMPLETE") and "ROLLBACK" not in status:+ # A DELETE_* status is the OnStackFailure=DELETE cleanup of a failed create.+ if (status.endswith("_COMPLETE") and "ROLLBACK" not in status+ and not status.startswith("DELETE")):change_set["ExecutionStatus"] = "EXECUTE_COMPLETE"else:change_set["ExecutionStatus"] = "EXECUTE_FAILED"@@ -711,6 +728,21 @@ def _execute_change_set(params):return _error("InvalidChangeSetStatus",f"ChangeSet [{cs_name}] is in {cs['ExecutionStatus']} status")+ # DisableRollback "can't be specified when the OnStackFailure parameter to+ # the CreateChangeSet API operation was specified" (API_ExecuteChangeSet);+ # the error wording is not measured.+ on_stack_failure = cs.get("OnStackFailure", "")+ if on_stack_failure and "DisableRollback" in params:+ return _error("ValidationError",+ "You can't specify DisableRollback when the change set was "+ "created with OnStackFailure.")+ # DO_NOTHING is DisableRollback=true, ROLLBACK is false, DELETE rolls back+ # and then deletes the new stack. Without either, the stack rolls back as+ # it always did here; the API reference says "Default: True" for+ # DisableRollback, which is not measured and not followed.+ disable_rollback = (on_stack_failure == "DO_NOTHING"+ or _p(params, "DisableRollback", "false").lower() == "true")+cs["ExecutionStatus"] = "EXECUTE_IN_PROGRESS"real_stack_name = cs["StackName"]stack = _stacks.get(real_stack_name)@@ -742,6 +774,8 @@ def _execute_change_set(params):retain_except_on_create = _p(params, "RetainExceptOnCreate", "false").lower() == "true"status_prefix = "UPDATE" if is_update else "CREATE"+ if not is_update:+ stack["DisableRollback"] = disable_rollbackstack["StackStatus"] = f"{status_prefix}_IN_PROGRESS"stack["LastUpdatedTime"] = now_iso()stack["_template_body"] = template_body@@ -761,16 +795,15 @@ def _execute_change_set(params):"AWS::CloudFormation::Stack", f"{status_prefix}_IN_PROGRESS",physical_id=stack_id)+ deploy = _deploy_stack_async(real_stack_name, stack_id, template,+ param_values, disable_rollback, tags,+ is_update=is_update,+ previous_stack=previous_stack,+ retain_except_on_create=retain_except_on_create)+ if on_stack_failure == "DELETE" and not is_update:+ deploy = _create_then_delete_on_failure(real_stack_name, stack_id, deploy)_create_stack_task_in_region(- _track_change_set_execution(- cs,- stack,- _deploy_stack_async(real_stack_name, stack_id, template,- param_values, False, tags,- is_update=is_update,- previous_stack=previous_stack,- retain_except_on_create=retain_except_on_create),- ),+ _track_change_set_execution(cs, stack, deploy),stack,stack_id,)diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.pyindex 15655630..70c28053 100644--- a/ministack/services/cloudformation/handlers.py+++ b/ministack/services/cloudformation/handlers.py@@ -31,6 +31,9 @@ from .engine import (validate_template_support,)from .helpers import (+ DELETION_MODE_VALUES,+ ON_FAILURE_VALUES,+ TEMPLATE_STAGE_VALUES,_error,_esc,_extract_members,@@ -41,11 +44,15 @@ from .helpers import (_request_problems,_resolve_template,_xml,+ enum_problems,+ validation_error_message,)from .stacks import (+ CLIENT_REQUEST_TOKEN,_add_event,_continue_update_rollback_async,_create_stack_task_in_region,+ _create_then_delete_on_failure,_delete_stack_async,_deploy_stack_async,_stack_region_context,@@ -253,6 +260,14 @@ def _create_stack(params):# The request-level constraints, joined into one message as the API does.if request_error := _request_problems(params, stack_name):return request_error+ if problems := enum_problems(params, "OnFailure", "onFailure", ON_FAILURE_VALUES):+ return _error("ValidationError", validation_error_message(problems))+ on_failure = _p(params, "OnFailure")+ # "You can specify either OnFailure or DisableRollback, but not both"+ # (API_CreateStack); the error wording is not measured.+ if on_failure and "DisableRollback" in params:+ return _error("ValidationError",+ "You can specify either DisableRollback or OnFailure, but not both.")template_body, resolve_err = _resolve_template(params)if resolve_err:@@ -275,7 +290,10 @@ def _create_stack(params):except Exception as e:return _error("ValidationError", f"Template format error: {e}")tags = _extract_members(params, "Tags")- disable_rollback = _p(params, "DisableRollback", "false").lower() == "true"+ # OnFailure=DO_NOTHING is DisableRollback=true; DELETE rolls back and then+ # deletes the stack; ROLLBACK is the default.+ disable_rollback = (_p(params, "DisableRollback", "false").lower() == "true"+ or on_failure == "DO_NOTHING")retain_except_on_create = _p(params, "RetainExceptOnCreate", "false").lower() == "true"from .helpers import _validate_stack_tagstags_error = _validate_stack_tags(tags)@@ -348,13 +366,12 @@ def _create_stack(params):"AWS::CloudFormation::Stack", "CREATE_IN_PROGRESS",physical_id=stack_id)- _create_stack_task_in_region(- _deploy_stack_async(stack_name, stack_id, template,- param_values, disable_rollback, tags,- retain_except_on_create=retain_except_on_create),- stack,- stack_id,- )+ deploy = _deploy_stack_async(stack_name, stack_id, template,+ param_values, disable_rollback, tags,+ retain_except_on_create=retain_except_on_create)+ if on_failure == "DELETE":+ deploy = _create_then_delete_on_failure(stack_name, stack_id, deploy)+ _create_stack_task_in_region(deploy, stack, stack_id)return _xml(200, "CreateStackResponse",f"<CreateStackResult><StackId>{stack_id}</StackId></CreateStackResult>")@@ -456,6 +473,8 @@ def _describe_stacks(params):caps_xml = "".join(f"<member>{_esc(c)}</member>" for c in s.get("Capabilities", []))+ deletion_mode_xml = (f"<DeletionMode>{s['DeletionMode']}</DeletionMode>"+ if s.get("DeletionMode") else "")members += ("<member>"@@ -470,6 +489,7 @@ def _describe_stacks(params):"<EnableTerminationProtection>"f"{str(s.get('EnableTerminationProtection', False)).lower()}""</EnableTerminationProtection>"+ f"{deletion_mode_xml}"f"<Capabilities>{caps_xml}</Capabilities>"f"<Parameters>{params_xml}</Parameters>"f"<Outputs>{outputs_xml}</Outputs>"@@ -547,6 +567,8 @@ def _describe_stack_events(params):members = ""for e in events_sorted:+ token_xml = (f"<ClientRequestToken>{_esc(e['ClientRequestToken'])}</ClientRequestToken>"+ if e.get("ClientRequestToken") else "")members += ("<member>"f"<StackId>{_esc(e.get('StackId', ''))}</StackId>"@@ -558,6 +580,7 @@ def _describe_stack_events(params):f"<ResourceStatus>{e.get('ResourceStatus', '')}</ResourceStatus>"f"<ResourceStatusReason>{_esc(e.get('ResourceStatusReason', ''))}</ResourceStatusReason>"f"<Timestamp>{e.get('Timestamp', '')}</Timestamp>"+ f"{token_xml}""</member>")@@ -715,18 +738,64 @@ def _list_stack_resources(params):# --- GetTemplate ---+def _processed_template_body(record):+ """The ``Processed`` stage of a stack's or change set's template: the+ template after its transforms (SAM, ``AWS::LanguageExtensions``,+ ``AWS::Include``) as JSON. A template that declares no transform is+ returned as it was sent: "If the template doesn't include transforms,+ Original and Processed return the same template" (API_GetTemplate)."""+ body = record.get("_template_body") or "{}"+ try:+ uses_transform = _uses_macro(_parse_template(body))+ except Exception:+ uses_transform = False+ if not uses_transform or not record.get("_template"):+ return body+ return json.dumps(record["_template"], default=str)++def _get_template(params):+ from .changesets import _find_change_set+ if problems := enum_problems(params, "TemplateStage", "templateStage",+ TEMPLATE_STAGE_VALUES):+ return _error("ValidationError", validation_error_message(problems))stack_name = _p(params, "StackName")+ cs_name = _p(params, "ChangeSetName")- stack = _resolve_stack(stack_name)- if not stack:- return _error("ValidationError",- f"Stack [{stack_name}] does not exist")+ if cs_name:+ # "If you specify a name, you must also specify the StackName"+ # (API_GetTemplate); the error wording is not measured.+ if not stack_name and not cs_name.startswith("arn:"):+ return _error("ValidationError",+ "StackName must be specified if ChangeSetName is not specified as an ARN.")+ stack = _resolve_stack(stack_name) if stack_name else None+ _, record = _find_change_set(+ cs_name, stack.get("StackName", stack_name) if stack else stack_name)+ if not record:+ return _error("ChangeSetNotFound",+ f"ChangeSet [{cs_name}] does not exist", 404)+ else:+ record = _resolve_stack(stack_name)+ if not record:+ return _error("ValidationError",+ f"Stack [{stack_name}] does not exist")- template_body = stack.get("_template_body", "{}")+ # The API reference defaults TemplateStage to Processed; Original stays the+ # default here, which is what GetTemplate has always answered and what the+ # tests of transform templates expect. For a template without a transform+ # the two stages are the same.+ if _p(params, "TemplateStage") == "Processed":+ template_body = _processed_template_body(record)+ else:+ template_body = record.get("_template_body") or "{}"+ # Both stages of a stack are always available; a change set's Processed+ # stage is available once it is created, which CreateChangeSet finishes+ # before it answers.+ stages_xml = "".join(f"<member>{s}</member>" for s in TEMPLATE_STAGE_VALUES)return _xml(200, "GetTemplateResponse",f"<GetTemplateResult>"f"<TemplateBody>{_esc(template_body)}</TemplateBody>"+ f"<StagesAvailable>{stages_xml}</StagesAvailable>"f"</GetTemplateResult>")@@ -773,6 +842,9 @@ def _delete_stack(params):stack_name = _p(params, "StackName")if not stack_name:return _error("ValidationError", "StackName is required")+ if problems := enum_problems(params, "DeletionMode", "deletionMode", DELETION_MODE_VALUES):+ return _error("ValidationError", validation_error_message(problems))+ force = _p(params, "DeletionMode") == "FORCE_DELETE_STACK"stack = _resolve_stack(stack_name)if not stack:@@ -811,6 +883,15 @@ def _delete_stack(params):stack_id = stack["StackId"]+ # FORCE_DELETE_STACK: only for a DELETE_FAILED stack. The wording is the+ # one a third party recorded from AWS (DevelopersIO, ap-northeast-3),+ # not measured here.+ if force and stack.get("StackStatus") != "DELETE_FAILED":+ return _error("ValidationError",+ f"Invalid operation on stack [{stack_id}]. You can activate "+ "DeletionMode FORCE_DELETE_STACK in a delete stack operation only "+ "when the stack is in the DELETE_FAILED state.")+# RetainResources: only for a DELETE_FAILED stack, only its own resources.retain = _extract_string_members(params, "RetainResources")if retain:@@ -832,8 +913,11 @@ def _delete_stack(params):if v.get("StackId") == stack_id]:_change_sets.pop(_cid, None)+ if _p(params, "DeletionMode"):+ stack["DeletionMode"] = _p(params, "DeletionMode")+_create_stack_task_in_region(- _delete_stack_async(stack_name, stack_id, frozenset(retain)),+ _delete_stack_async(stack_name, stack_id, frozenset(retain), force=force),stack,stack_id,)@@ -1252,8 +1336,10 @@ def _cancel_update_stack(params):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.+ # The running update checks the flag before each resource and rolls back;+ # the rollback events carry the cancel's ClientRequestToken.stack["_cancel_requested"] = True+ stack["_cancel_token"] = CLIENT_REQUEST_TOKEN.get()return _xml(200, "CancelUpdateStackResponse", "")diff --git a/ministack/services/cloudformation/helpers.py b/ministack/services/cloudformation/helpers.pyindex c4ab6a3d..b5c3682d 100644--- a/ministack/services/cloudformation/helpers.py+++ b/ministack/services/cloudformation/helpers.py@@ -146,6 +146,45 @@ def capabilities_problems(values: list[str]) -> list[str]:f"[{', '.join(CAPABILITY_VALUES)}]"]+# Valid values of the stack operation enums, in the botocore model's order.+# OnFailure (CreateStack) and OnStackFailure (CreateChangeSet) share one.+ON_FAILURE_VALUES = ("DO_NOTHING", "ROLLBACK", "DELETE")+DELETION_MODE_VALUES = ("STANDARD", "FORCE_DELETE_STACK")+TEMPLATE_STAGE_VALUES = ("Original", "Processed")+++def enum_problems(params, key: str, wire_name: str, values: tuple) -> list[str]:+ """The enum constraint of one string parameter (``OnFailure``,+ ``DeletionMode``, ``TemplateStage``, ...), in the API's parameter+ validation wording; the valid values are the API reference's, in the+ botocore model's order. Empty when the parameter is absent or valid."""+ value = _p(params, key)+ if not value or value in values:+ return []+ return [f"Value '{value}' at '{wire_name}' failed to satisfy constraint: "+ f"Member must satisfy enum value set: [{', '.join(values)}]"]+++CLIENT_REQUEST_TOKEN_PATTERN = "[a-zA-Z0-9][-a-zA-Z0-9]*"+CLIENT_REQUEST_TOKEN_RE = re.compile(CLIENT_REQUEST_TOKEN_PATTERN)+CLIENT_REQUEST_TOKEN_MAX_CHARS = 128+++def client_request_token_problems(token: str) -> list[str]:+ """The ``ClientRequestToken`` constraints of the stack operations: 1 to+ 128 characters matching ``[a-zA-Z0-9][-a-zA-Z0-9]*`` (API reference)."""+ problems = []+ if len(token) > CLIENT_REQUEST_TOKEN_MAX_CHARS:+ problems.append(+ f"Value '{token}' at 'clientRequestToken' failed to satisfy constraint: Member "+ f"must have length less than or equal to {CLIENT_REQUEST_TOKEN_MAX_CHARS}")+ if not CLIENT_REQUEST_TOKEN_RE.fullmatch(token):+ problems.append(+ f"Value '{token}' at 'clientRequestToken' failed to satisfy constraint: Member "+ f"must satisfy regular expression pattern: {CLIENT_REQUEST_TOKEN_PATTERN}")+ return problems++def _template_body_problem(body: str) -> str | None:"""The request-level constraint on ``TemplateBody`` (the quota page:"Template body size in a request", 51,200 bytes), as one sentence of thediff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.pyindex 2d4182e6..ac580ff8 100644--- a/ministack/services/cloudformation/stacks.py+++ b/ministack/services/cloudformation/stacks.py@@ -5,6 +5,7 @@ CloudFormation stacks — async stack lifecycle (deploy, delete, update, diff)."""import asyncio+import contextvarsimport copyimport loggingfrom contextlib import contextmanager@@ -15,6 +16,7 @@ from ministack.core.responses import get_region, new_uuid, now_iso, set_request_from .engine import (_NO_VALUE,_evaluate_conditions,+ _extract_deps,_resolve_dynamic_references,_resolve_refs,_topological_sort,@@ -121,6 +123,14 @@ def _resource_policy(res_def, attribute, resources, params, conditions, mappingsreturn str(value)+# The ClientRequestToken of the stack operation that is running. The request+# handler sets it around the operation's handler; the background task of the+# operation copies the context when it is scheduled, so every event the+# operation records carries the token ("All events triggered by a given stack+# operation are assigned the same client request token", API reference).+CLIENT_REQUEST_TOKEN = contextvars.ContextVar("cfn_client_request_token", default="")++def _add_event(stack_id, stack_name, logical_id, resource_type, status,reason="", physical_id=""):"""Record a stack event."""@@ -136,6 +146,9 @@ def _add_event(stack_id, stack_name, logical_id, resource_type, status,"ResourceStatusReason": reason,"Timestamp": now_iso(),}+ token = CLIENT_REQUEST_TOKEN.get()+ if token:+ event["ClientRequestToken"] = tokenif stack_id not in _stack_events:_stack_events[stack_id] = []_stack_events[stack_id].append(event)@@ -360,11 +373,14 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,failed_update = Nonefailed_logical_id = Nonestack.pop("_cancel_requested", None)+ stack.pop("_cancel_token", 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").+ # update back, as on AWS ("User Initiated"). The rollback events+ # are the cancel's, so they carry its ClientRequestToken.+ CLIENT_REQUEST_TOKEN.set(stack.pop("_cancel_token", ""))failed = cancelled = Truefail_reason = "User Initiated"break@@ -809,14 +825,37 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,physical_id=stack_id)+def _with_dependencies(logical_ids, res_defs, remaining):+ """``logical_ids`` plus every resource of ``remaining`` they depend on,+ directly or through another one (Ref, Fn::GetAtt, Fn::Sub, DependsOn)."""+ result = set(logical_ids)+ pending = list(logical_ids)+ while pending:+ res_def = res_defs.get(pending.pop())+ if not res_def:+ continue+ for dep in _extract_deps(res_def, remaining):+ if dep not in result:+ result.add(dep)+ pending.append(dep)+ return result++async def _delete_stack_async(stack_name: str, stack_id: str,- retain_resources=()):+ retain_resources=(), force=False):"""Background task: delete all resources and mark stack DELETE_COMPLETE.A resource whose ``DeletionPolicy`` is ``Retain`` or``RetainExceptOnCreate``, or whose logical id is in ``retain_resources``(the ``RetainResources`` parameter of a DeleteStack on a ``DELETE_FAILED``- stack), is skipped with a ``DELETE_SKIPPED`` event and keeps existing."""+ stack), is skipped with a ``DELETE_SKIPPED`` event and keeps existing.++ ``force`` is ``DeletionMode=FORCE_DELETE_STACK``: the console's "Force+ delete this entire stack" "retains all resources that failed to delete,+ and retains dependencies of those resources" (cfn-console-delete-stack),+ and the retained ones show ``DELETE_SKIPPED``. A resource that fails to+ delete during the forced delete is retained the same way, so the stack+ reaches ``DELETE_COMPLETE``."""from ministack.services.cloudformation import _exports, _stacksstack = _stacks.get(stack_name)if not stack:@@ -844,6 +883,13 @@ async def _delete_stack_async(stack_name: str, stack_id: str,# it goes first, so a retried delete reaches it.ordered += [lid for lid in resources if lid not in ordered]+ forced_retain = set()+ if force:+ forced_retain = _with_dependencies(+ [lid for lid, res in resources.items()+ if res.get("ResourceStatus") == "DELETE_FAILED"],+ res_defs, set(resources))+delete_failures = []for logical_id in reversed(ordered):res = resources.get(logical_id)@@ -857,7 +903,8 @@ async def _delete_stack_async(stack_name: str, stack_id: str,res_defs.get(logical_id), "DeletionPolicy", resources,stack.get("_resolved_params", {}), conditions,template.get("Mappings", {}) if template else {}, stack_name, stack_id)- if policy in _RETAINING_POLICIES or logical_id in retain_resources:+ if (policy in _RETAINING_POLICIES or logical_id in retain_resources+ or logical_id in forced_retain):_add_event(stack_id, stack_name, logical_id, rtype,"DELETE_SKIPPED", physical_id=pid)resources.pop(logical_id, None)@@ -880,6 +927,13 @@ async def _delete_stack_async(stack_name: str, stack_id: str,resources.pop(logical_id, None)except Exception as exc:logger.error("Delete of %s (%s) failed: %s", logical_id, pid, exc)+ if force:+ # A forced delete retains the resource, and what it depends on.+ _add_event(stack_id, stack_name, logical_id, rtype,+ "DELETE_SKIPPED", str(exc), pid)+ resources.pop(logical_id, None)+ forced_retain |= _with_dependencies([logical_id], res_defs, set(resources))+ continue_add_event(stack_id, stack_name, logical_id, rtype,"DELETE_FAILED", str(exc), pid)res["ResourceStatus"] = "DELETE_FAILED"@@ -914,6 +968,30 @@ async def _delete_stack_async(stack_name: str, stack_id: str,physical_id=stack_id)+# The states a stack create ends in when it failed, rolled back or not.+_FAILED_CREATE_STATUSES = frozenset({"CREATE_FAILED", "ROLLBACK_COMPLETE", "ROLLBACK_FAILED"})+++async def _create_then_delete_on_failure(stack_name: str, stack_id: str, deploy_coro):+ """``OnFailure=DELETE`` (CreateStack) and ``OnStackFailure=DELETE``+ (CreateChangeSet of type CREATE): run the create, and when it fails,+ delete the stack once the rollback is over. The stack ends+ ``DELETE_COMPLETE``, or ``DELETE_FAILED`` when a resource does not delete+ ("If the deletion of the stack fails, the status of the stack is+ DELETE_FAILED", API_CreateChangeSet)."""+ from ministack.services.cloudformation import _change_sets, _stacks+ await deploy_coro+ stack = _stacks.get(stack_name)+ if not stack or stack.get("StackId") != stack_id:+ return+ if stack.get("StackStatus") not in _FAILED_CREATE_STATUSES:+ return+ await _delete_stack_async(stack_name, stack_id)+ # A deleted stack takes its change sets with it, as DeleteStack does.+ for cs_id in [c for c, v in _change_sets.items() if v.get("StackId") == stack_id]:+ _change_sets.pop(cs_id, None)++# ===========================================================================# Change Set Helpers# ===========================================================================diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 20c4784e..1c77b7eb 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -27805,3 +27805,427 @@ def test_cfn_update_rollback_does_not_resend_a_refused_resource_update(cfn):assert _cfn_events_since_rollback(cfn, stack_name, "Api") == ["UPDATE_COMPLETE"]finally:_delete_cfn_test_stack(cfn, stack_name)+++# ---------------------------------------------------------------------------+# OnFailure, OnStackFailure, DeletionMode, TemplateStage, ClientRequestToken+# ---------------------------------------------------------------------------++def _queue_then_failing_template(queue_name):+ """A queue that provisions, then _FAILING_RESOURCE after it."""+ return _cfn_with_failing_resource(json.dumps({"Resources": {+ "Queue": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": queue_name}},+ }}), "Queue")+++def _stack_id_of(cfn, stack_name):+ return cfn.describe_stacks(StackName=stack_name)["Stacks"][0]["StackId"]+++def _wait_change_set(cfn, stack_name, cs_name):+ for _ in range(40):+ described = cfn.describe_change_set(StackName=stack_name, ChangeSetName=cs_name)+ if described["Status"] in ("CREATE_COMPLETE", "FAILED"):+ return described+ time.sleep(0.25)+ return described+++def test_cfn_create_stack_on_failure_validation(cfn):+ """OnFailure with DisableRollback is refused (the API reference allows one+ of them), and so is a value outside the enum. No stack is created."""+ stack_name = f"cfn-onfailure-invalid-{_uuid_mod.uuid4().hex[:8]}"+ body = json.dumps({"Resources": {"T": {"Type": "AWS::SNS::Topic"}}})+ for extra in ({"OnFailure": "DELETE", "DisableRollback": False},+ {"OnFailure": "DO_NOTHING", "DisableRollback": True},+ {"OnFailure": "KEEP"}):+ with pytest.raises(ClientError) as exc:+ cfn.create_stack(StackName=stack_name, TemplateBody=body, **extra)+ assert exc.value.response["Error"]["Code"] == "ValidationError"+ assert "enum value set: [DO_NOTHING, ROLLBACK, DELETE]" in (+ exc.value.response["Error"]["Message"])+ with pytest.raises(ClientError):+ cfn.describe_stacks(StackName=stack_name)+++def test_cfn_create_stack_on_failure_do_nothing_keeps_resources(cfn, sqs):+ """OnFailure=DO_NOTHING behaves as DisableRollback=true: the stack stays+ CREATE_FAILED and what was created stays."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-onfailure-nothing-{uid}"+ queue = f"cfn-onfailure-nothing-{uid}"+ try:+ cfn.create_stack(StackName=stack_name, TemplateBody=_queue_then_failing_template(queue),+ OnFailure="DO_NOTHING")+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_FAILED", stack.get("StackStatusReason")+ assert stack["DisableRollback"] is True+ assert _queue_exists(sqs, queue)+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ _delete_queue_if_present(sqs, queue)+++def test_cfn_create_stack_on_failure_rollback_is_the_default(cfn, sqs):+ """OnFailure=ROLLBACK rolls the failed create back to ROLLBACK_COMPLETE."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-onfailure-rollback-{uid}"+ queue = f"cfn-onfailure-rollback-{uid}"+ try:+ cfn.create_stack(StackName=stack_name, TemplateBody=_queue_then_failing_template(queue),+ OnFailure="ROLLBACK")+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "ROLLBACK_COMPLETE", stack.get("StackStatusReason")+ assert not _queue_exists(sqs, queue)+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ _delete_queue_if_present(sqs, queue)+++def test_cfn_create_stack_on_failure_delete_deletes_the_stack(cfn, sqs):+ """OnFailure=DELETE rolls the failed create back and then deletes the+ stack: the name is free, the stack is listed as DELETE_COMPLETE and its+ events run through ROLLBACK_COMPLETE to DELETE_COMPLETE."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-onfailure-delete-{uid}"+ queue = f"cfn-onfailure-delete-{uid}"+ try:+ stack_id = cfn.create_stack(StackName=stack_name,+ TemplateBody=_queue_then_failing_template(queue),+ OnFailure="DELETE")["StackId"]+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"+ deleted = cfn.describe_stacks(StackName=stack_id)["Stacks"][0]+ assert deleted["StackStatus"] == "DELETE_COMPLETE"+ listed = _all_pages(cfn, "list_stacks", "StackSummaries",+ StackStatusFilter=["DELETE_COMPLETE"])+ assert stack_id in [s["StackId"] for s in listed]+ assert not _queue_exists(sqs, queue)+ stack_events = [e["ResourceStatus"] for e in reversed(+ cfn.describe_stack_events(StackName=stack_id)["StackEvents"])+ if e["LogicalResourceId"] == stack_name]+ assert stack_events == ["CREATE_IN_PROGRESS", "ROLLBACK_IN_PROGRESS", "ROLLBACK_COMPLETE",+ "DELETE_IN_PROGRESS", "DELETE_COMPLETE"]+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ _delete_queue_if_present(sqs, queue)+++def test_cfn_change_set_on_stack_failure_validation(cfn):+ """OnStackFailure=DELETE is only valid for a CREATE change set, a value+ outside the enum is refused, and ExecuteChangeSet refuses DisableRollback+ for a change set created with OnStackFailure. DescribeChangeSet reports it."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-osf-validate-{uid}"+ body = json.dumps({"Resources": {"T": {"Type": "AWS::SNS::Topic",+ "Properties": {"TopicName": f"cfn-osf-{uid}"}}}})+ try:+ with pytest.raises(ClientError) as exc:+ cfn.create_change_set(StackName=stack_name, ChangeSetName="cs", TemplateBody=body,+ ChangeSetType="CREATE", OnStackFailure="KEEP")+ assert exc.value.response["Error"]["Code"] == "ValidationError"++ cfn.create_stack(StackName=stack_name, TemplateBody=body)+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"+ changed = body.replace(f"cfn-osf-{uid}", f"cfn-osf-{uid}-2")+ with pytest.raises(ClientError) as exc:+ cfn.create_change_set(StackName=stack_name, ChangeSetName="upd",+ TemplateBody=changed, OnStackFailure="DELETE")+ assert exc.value.response["Error"]["Code"] == "ValidationError"+ assert "CREATE" in exc.value.response["Error"]["Message"]++ cfn.create_change_set(StackName=stack_name, ChangeSetName="upd",+ TemplateBody=changed, OnStackFailure="ROLLBACK")+ described = _wait_change_set(cfn, stack_name, "upd")+ assert described["OnStackFailure"] == "ROLLBACK"+ with pytest.raises(ClientError) as exc:+ cfn.execute_change_set(StackName=stack_name, ChangeSetName="upd",+ DisableRollback=False)+ assert exc.value.response["Error"]["Code"] == "ValidationError"+ assert "OnStackFailure" in exc.value.response["Error"]["Message"]+ assert cfn.describe_change_set(StackName=stack_name, ChangeSetName="upd")[+ "ExecutionStatus"] == "AVAILABLE"+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+++def test_cfn_change_set_on_stack_failure_delete_and_do_nothing(cfn, sqs):+ """A CREATE change set executed with OnStackFailure=DELETE ends with the+ stack deleted; DO_NOTHING leaves it CREATE_FAILED with what it created,+ as ExecuteChangeSet DisableRollback=true does for a change set without+ OnStackFailure."""+ uid = _uuid_mod.uuid4().hex[:8]+ cases = {+ f"cfn-osf-delete-{uid}": ({"OnStackFailure": "DELETE"}, {}),+ f"cfn-osf-nothing-{uid}": ({"OnStackFailure": "DO_NOTHING"}, {}),+ f"cfn-osf-disable-{uid}": ({}, {"DisableRollback": True}),+ }+ try:+ stack_ids = {}+ for name, (create_extra, execute_extra) in cases.items():+ stack_ids[name] = cfn.create_change_set(+ StackName=name, ChangeSetName="cs", ChangeSetType="CREATE",+ TemplateBody=_queue_then_failing_template(name), **create_extra)["StackId"]+ assert _wait_change_set(cfn, name, "cs")["Status"] == "CREATE_COMPLETE"+ cfn.execute_change_set(StackName=name, ChangeSetName="cs", **execute_extra)+ delete_name, nothing_name, disable_name = cases+ assert _wait_stack(cfn, delete_name)["StackStatus"] == "DELETE_COMPLETE"+ assert cfn.describe_stacks(StackName=stack_ids[delete_name])["Stacks"][0][+ "StackStatus"] == "DELETE_COMPLETE"+ assert not _queue_exists(sqs, delete_name)+ for name in (nothing_name, disable_name):+ stack = _wait_stack(cfn, name)+ assert stack["StackStatus"] == "CREATE_FAILED", stack.get("StackStatusReason")+ assert stack["DisableRollback"] is True+ assert _queue_exists(sqs, name)+ assert cfn.describe_change_set(StackName=name, ChangeSetName="cs")[+ "ExecutionStatus"] == "EXECUTE_FAILED"+ finally:+ for name in cases:+ _delete_cfn_test_stack(cfn, name)+ _delete_queue_if_present(sqs, name)+++def test_cfn_delete_stack_force_delete_stack(cfn, sqs, lam):+ """DeletionMode=FORCE_DELETE_STACK is refused for a stack that is not in+ DELETE_FAILED; on a DELETE_FAILED stack it retains the resource that failed+ to delete (DELETE_SKIPPED) and the stack reaches DELETE_COMPLETE."""+ suffix = _uuid_mod.uuid4().hex[:8]+ fn = f"cr-force-del-{suffix}"+ stack_name = f"cfn-force-delete-{suffix}"+ queue = f"cfn-force-delete-{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)},+ )+ template = json.dumps({"Resources": {+ "Queue": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": queue}},+ "CR": {"Type": "Custom::Tester", "Properties": {+ "ServiceToken": f"arn:aws:lambda:us-east-1:000000000000:function:{fn}"}},+ }})+ try:+ stack_id = cfn.create_stack(StackName=stack_name, TemplateBody=template)["StackId"]+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")++ with pytest.raises(ClientError) as exc:+ cfn.delete_stack(StackName=stack_name, DeletionMode="FORCE_DELETE_STACK")+ assert exc.value.response["Error"]["Code"] == "ValidationError"+ assert exc.value.response["Error"]["Message"] == (+ f"Invalid operation on stack [{stack_id}]. You can activate DeletionMode "+ "FORCE_DELETE_STACK in a delete stack operation only when the stack is in "+ "the DELETE_FAILED state.")+ with pytest.raises(ClientError) as exc:+ cfn.delete_stack(StackName=stack_name, DeletionMode="EVERYTHING")+ assert "enum value set: [STANDARD, FORCE_DELETE_STACK]" in (+ exc.value.response["Error"]["Message"])++ cfn.delete_stack(StackName=stack_name, DeletionMode="STANDARD")+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "DELETE_FAILED", stack.get("StackStatusReason")++ cfn.delete_stack(StackName=stack_name, DeletionMode="FORCE_DELETE_STACK")+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"+ deleted = cfn.describe_stacks(StackName=stack_id)["Stacks"][0]+ assert deleted["StackStatus"] == "DELETE_COMPLETE"+ assert deleted["DeletionMode"] == "FORCE_DELETE_STACK"+ events = cfn.describe_stack_events(StackName=stack_id)["StackEvents"]+ assert events[0]["ResourceStatus"] == "DELETE_COMPLETE"+ assert any(e["LogicalResourceId"] == "CR" and e["ResourceStatus"] == "DELETE_SKIPPED"+ for e in events)+ assert not _queue_exists(sqs, queue)+ 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)+ _delete_queue_if_present(sqs, queue)+ try:+ lam.delete_function(FunctionName=fn)+ except ClientError:+ pass+++def test_cfn_get_template_stages(cfn):+ """GetTemplate answers the template as sent by default and with+ TemplateStage=Original, the expanded one with TemplateStage=Processed,+ and lists both stages. A template without a transform is the same at+ both stages. A change set's template is read with ChangeSetName."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-template-stage-{uid}"+ plain_name = f"cfn-template-stage-plain-{uid}"+ template = json.dumps({+ "Transform": "AWS::LanguageExtensions",+ "Resources": {"Fn::ForEach::Topics": ["Name", ["A", "B"], {+ "Topic${Name}": {"Type": "AWS::SNS::Topic",+ "Properties": {"TopicName": {"Fn::Sub": f"{uid}-${{Name}}"}}}}]},+ })+ plain = json.dumps({"Resources": {"T": {"Type": "AWS::SNS::Topic",+ "Properties": {"TopicName": f"{uid}-plain"}}}})+ try:+ cfn.create_stack(StackName=stack_name, TemplateBody=template)+ cfn.create_stack(StackName=plain_name, TemplateBody=plain)+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"+ assert _wait_stack(cfn, plain_name)["StackStatus"] == "CREATE_COMPLETE"++ default = cfn.get_template(StackName=stack_name)+ assert default["StagesAvailable"] == ["Original", "Processed"]+ assert "Fn::ForEach::Topics" in default["TemplateBody"]["Resources"]+ original = cfn.get_template(StackName=stack_name, TemplateStage="Original")+ assert original["TemplateBody"] == default["TemplateBody"]+ processed = cfn.get_template(StackName=stack_name, TemplateStage="Processed")+ assert sorted(processed["TemplateBody"]["Resources"]) == ["TopicA", "TopicB"]+ assert processed["StagesAvailable"] == ["Original", "Processed"]++ assert (cfn.get_template(StackName=plain_name, TemplateStage="Processed")["TemplateBody"]+ == json.loads(plain))+ with pytest.raises(ClientError) as exc:+ cfn.get_template(StackName=plain_name, TemplateStage="Final")+ assert exc.value.response["Error"]["Code"] == "ValidationError"++ more = json.loads(template)+ more["Resources"]["Fn::ForEach::Topics"][1].append("C")+ cs_id = cfn.create_change_set(StackName=stack_name, ChangeSetName="more",+ TemplateBody=json.dumps(more))["Id"]+ assert _wait_change_set(cfn, stack_name, "more")["Status"] == "CREATE_COMPLETE"+ cs_original = cfn.get_template(StackName=stack_name, ChangeSetName="more")+ assert cs_original["TemplateBody"]["Resources"]["Fn::ForEach::Topics"][1] == [+ "A", "B", "C"]+ cs_processed = cfn.get_template(ChangeSetName=cs_id, TemplateStage="Processed")+ assert sorted(cs_processed["TemplateBody"]["Resources"]) == ["TopicA", "TopicB", "TopicC"]+ assert cs_processed["StagesAvailable"] == ["Original", "Processed"]+ with pytest.raises(ClientError) as exc:+ cfn.get_template(StackName=stack_name, ChangeSetName="missing")+ assert exc.value.response["Error"]["Code"] == "ChangeSetNotFound"+ with pytest.raises(ClientError) as exc:+ cfn.get_template(ChangeSetName="more")+ assert exc.value.response["Error"]["Code"] == "ValidationError"+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ _delete_cfn_test_stack(cfn, plain_name)+++def _tokens_of_new_events(cfn, stack_id, seen):+ """The ClientRequestToken of each event not in ``seen`` (which it extends)."""+ tokens = []+ for event in cfn.describe_stack_events(StackName=stack_id)["StackEvents"]:+ if event["EventId"] not in seen:+ seen.add(event["EventId"])+ tokens.append(event.get("ClientRequestToken"))+ return tokens+++def test_cfn_client_request_token_on_stack_events(cfn):+ """Every event of CreateStack, UpdateStack, ExecuteChangeSet and+ DeleteStack carries the operation's ClientRequestToken; an operation+ without a token records events without one, and a token outside the+ documented pattern is refused."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-token-{uid}"++ def body(display):+ return json.dumps({"Resources": {"T": {"Type": "AWS::SNS::Topic", "Properties": {+ "TopicName": f"cfn-token-{uid}", "DisplayName": display}}}})++ try:+ with pytest.raises(ClientError) as exc:+ cfn.create_stack(StackName=stack_name, TemplateBody=body("a"),+ ClientRequestToken="-starts-with-a-hyphen")+ assert exc.value.response["Error"]["Code"] == "ValidationError"+ assert "clientRequestToken" in exc.value.response["Error"]["Message"]++ stack_id = cfn.create_stack(StackName=stack_name, TemplateBody=body("a"),+ ClientRequestToken=f"create-{uid}")["StackId"]+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"+ seen = set()+ created = _tokens_of_new_events(cfn, stack_id, seen)+ assert len(created) >= 4 and set(created) == {f"create-{uid}"}++ cfn.update_stack(StackName=stack_name, TemplateBody=body("b"),+ ClientRequestToken=f"update-{uid}")+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"+ assert set(_tokens_of_new_events(cfn, stack_id, seen)) == {f"update-{uid}"}++ cfn.update_stack(StackName=stack_name, TemplateBody=body("c"))+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"+ assert set(_tokens_of_new_events(cfn, stack_id, seen)) == {None}++ cfn.create_change_set(StackName=stack_name, ChangeSetName="cs", TemplateBody=body("d"))+ assert _wait_change_set(cfn, stack_name, "cs")["Status"] == "CREATE_COMPLETE"+ cfn.execute_change_set(StackName=stack_name, ChangeSetName="cs",+ ClientRequestToken=f"execute-{uid}")+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"+ assert set(_tokens_of_new_events(cfn, stack_id, seen)) == {f"execute-{uid}"}++ cfn.delete_stack(StackName=stack_name, ClientRequestToken=f"delete-{uid}")+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"+ assert set(_tokens_of_new_events(cfn, stack_id, seen)) == {f"delete-{uid}"}+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+++def test_cfn_client_request_token_on_cancel_and_continue_rollback(cfn, lam):+ """The rollback events of CancelUpdateStack and of ContinueUpdateRollback+ carry the token of that call."""+ suffix = _uuid_mod.uuid4().hex[:8]+ slow_fn = f"cr-token-slow-{suffix}"+ mode_fn = f"cr-token-mode-{suffix}"+ cancel_stack = f"cfn-token-cancel-{suffix}"+ continue_stack = f"cfn-token-continue-{suffix}"+ lam.create_function(+ FunctionName=slow_fn, Runtime="python3.12", Role=_CR_LAMBDA_ROLE,+ Handler="index.handler", Code={"ZipFile": _cr_make_zip(_CR_HANDLER_SLOW)}, Timeout=30,+ )+ lam.create_function(+ FunctionName=mode_fn, Runtime="python3.12", Role=_CR_LAMBDA_ROLE,+ Handler="index.handler", Code={"ZipFile": _cr_make_zip(_cr_mode_handler("before"))},+ )+ base = {"Resources": {"Topic": {"Type": "AWS::SNS::Topic",+ "Properties": {"TopicName": f"cfn-token-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:{slow_fn}"}}+ updated["Resources"]["Later"] = {"Type": "AWS::SNS::Topic", "DependsOn": "Slow",+ "Properties": {"TopicName": f"cfn-token-later-{suffix}"}}+ try:+ stack_id = cfn.create_stack(StackName=cancel_stack,+ TemplateBody=json.dumps(base))["StackId"]+ assert _wait_stack(cfn, cancel_stack)["StackStatus"] == "CREATE_COMPLETE"+ seen = set()+ _tokens_of_new_events(cfn, stack_id, seen)+ cfn.update_stack(StackName=cancel_stack, TemplateBody=json.dumps(updated),+ ClientRequestToken=f"update-{suffix}")+ cfn.cancel_update_stack(StackName=cancel_stack, ClientRequestToken=f"cancel-{suffix}")+ stack = _wait_stack(cfn, cancel_stack, timeout=60)+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")+ events = cfn.describe_stack_events(StackName=stack_id)["StackEvents"]+ by_status = {e["ResourceStatus"]: e.get("ClientRequestToken") for e in events+ if e["LogicalResourceId"] == cancel_stack and e["EventId"] not in seen}+ assert by_status["UPDATE_IN_PROGRESS"] == f"update-{suffix}"+ assert by_status["UPDATE_ROLLBACK_IN_PROGRESS"] == f"cancel-{suffix}"+ assert by_status["UPDATE_ROLLBACK_COMPLETE"] == f"cancel-{suffix}"++ first, second = _cr_revert_fails_templates(mode_fn, f"cfn-token-cur-{suffix}")+ continue_id = cfn.create_stack(StackName=continue_stack, TemplateBody=first)["StackId"]+ assert _wait_stack(cfn, continue_stack)["StackStatus"] == "CREATE_COMPLETE"+ cfn.update_stack(StackName=continue_stack, TemplateBody=second)+ assert _wait_stack(cfn, continue_stack)["StackStatus"] == "UPDATE_ROLLBACK_FAILED"+ seen = set()+ _tokens_of_new_events(cfn, continue_id, seen)+ cfn.continue_update_rollback(StackName=continue_stack, ResourcesToSkip=["CR"],+ ClientRequestToken=f"continue-{suffix}")+ assert _wait_stack(cfn, continue_stack)["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"+ assert set(_tokens_of_new_events(cfn, continue_id, seen)) == {f"continue-{suffix}"}+ finally:+ try:+ lam.update_function_code(FunctionName=mode_fn,+ ZipFile=_cr_make_zip(_CR_HANDLER_SUCCESS))+ except ClientError:+ pass+ _delete_cfn_test_stack(cfn, cancel_stack)+ _delete_cfn_test_stack(cfn, continue_stack)+ for fn in (slow_fn, mode_fn):+ try:+ lam.delete_function(FunctionName=fn)+ except ClientError:+ pass