Skip to content

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

feat(cloudformation): in-place update handlers, batch 1 of #1585 (#1626)

iot-rocket9d7bec55b501
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2248dd73..125b2e5b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,20 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+- **CloudFormation — the Cognito resources update in place** — a stack update that changed an `AWS::Cognito::UserPool`, `UserPoolClient`, `IdentityPool` or `UserPoolGroup` fell through to the type's create handler, and for the three with a generated id that meant a second resource under a new id: `Ref` flipped to the new one, the old one was orphaned together with its data (the users in a pool, the role mapping of an identity pool) and nothing in the stack events said so. The four now update the existing record through the service's own path (`UpdateUserPool`, `UpdateUserPoolClient`, `UpdateIdentityPool`, `AddCustomAttributes` for a grown `Schema`; a group's `Description`, `Precedence` and `RoleArn` directly, since the service has no `UpdateGroup`), keeping the physical id and everything stored behind it, and a property the new template drops reverts to the default `CreateUserPool` / `CreateUserPoolClient` fills in, as the resource reference says Cognito does. The pool and the app client are also created through those two calls now, so the record carries every property the update can change (`DeletionProtection`, `EmailConfiguration`, `AccountRecoverySetting`, token validity, `PreventUserExistenceErrors`, …) instead of the handful the create handler copied, and a replaced client carries its whole template over. The properties the resource references mark *Replacement* replace: a `UserPoolClient` whose `UserPoolId` or `GenerateSecret` changed, and a renamed or moved group, are created before the old one is removed and `Ref` follows the new id, while a move to another pool under an unchanged `GroupName` gets CloudFormation's own refusal for a custom-named resource. `AliasAttributes`, `UsernameAttributes` and `UsernameConfiguration` are marked *No interruption* on the reference, but the first two are fixed at `CreateUserPool` and the reference itself calls the third immutable once set, so a change fails the update with a message naming the property rather than altering the record. A group declared without `Precedence` gets none, the null the reference documents as the default, instead of 0; `Fn::GetAtt` gains `UserPoolId` on the pool, `ClientId` on the client and `Name` on the identity pool. Contributed by @iot-rocket.
+- **CloudFormation — `EnabledMfas` applies on an `AWS::Cognito::UserPool` update** — the property is *No interruption* on the resource reference and creating a pool with `SOFTWARE_TOKEN_MFA` in it already switched the software-token block on, but an update that added or removed the entry left `GetUserPoolMfaConfig` where it was, so a CDK `mfaSecondFactor` change never reached the emulated pool. The update now goes through `SetUserPoolMfaConfig`: the entry arriving switches the block on, its removal or the property being dropped switches it off, and a pool that never listed it is left without the block. Contributed by @iot-rocket.
+- **CloudFormation — `AWS::SecretsManager::Secret` updates in place** — a stack update that changed a secret fell through to the create handler, which minted a second secret under a new ARN: `Ref` and `GetAtt Arn` flipped to it, the original was orphaned together with its versions, and nothing in the stack events said so. The secret now updates through `UpdateSecret` under the same ARN: a changed `SecretString` or `GenerateSecretString` publishes a new `AWSCURRENT` version and the previous one stays behind as `AWSPREVIOUS`; `Description` and `KmsKeyId` are sent only when the template declares or drops them, so a value set outside the stack on a property the template never declared is left alone; `ReplicaRegions` is applied on create and update through `ReplicateSecretToRegions`, and deleting the stack purges the replicas with the secret. `Name` requires replacement and follows the convention already in place: the renamed secret is created before the old one is deleted. Known limits: `Ref` still returns the secret name where AWS returns the ARN (set by the create handler, unchanged here; `GetAtt Arn` carries the ARN, which the reference documents as `Id`), `Type` is not stored by the Secrets Manager service and is ignored, and a region dropped from `ReplicaRegions` keeps its replica because the service has no `RemoveRegionsFromReplication`. Contributed by @iot-rocket.
+- **CloudFormation — `AWS::Events::Rule` updates in place** — a stack update that changed a rule fell through to the create handler, which rebuilt the rule record and its target list from the template alone: a target added with `PutTargets` outside the stack was gone, and a target the template had dropped stayed. The rule now updates through `PutRule`, `PutTargets` and `RemoveTargets` under the same name and ARN — the declared targets are reconciled, an undeclared one rides along — and `EventBusName` moves the rule to the other bus under the same name with its targets and tags, the "some interruptions" the resource reference documents. `Tags` are applied on create and reconciled on update through `TagResource` / `UntagResource`, a tag added outside the stack stays, and `Fn::GetAtt` answers the documented `RuleName`. `Name` requires replacement and follows the convention already in place: the renamed rule is created before the old one is deleted. Contributed by @iot-rocket.
+- **CloudFormation — `AWS::StepFunctions::StateMachine` updates in place** — a stack update that changed a state machine's definition, substitutions, role, logging or tags fell through to the create handler, which overwrote the record wholesale: the executions and versions behind the ARN were gone, `Tags` were never applied, and nothing in the stack events said so. The machine now updates through `UpdateStateMachine` under the same ARN, keeping its executions; a dropped `LoggingConfiguration` reverts to `OFF`, tags reconcile through `TagResource` / `UntagResource`, and `Fn::GetAtt` serves `StateMachineRevisionId`. `StateMachineName` and `StateMachineType` require replacement and follow the conventions already in place: a renamed machine is created before the old one is deleted, a type change under an unchanged custom name gets CloudFormation's own refusal, and under a generated name the update fails with a message naming the property, since the deterministic name cannot yield a fresh identity. `TracingConfiguration` and `EncryptionConfiguration` are accepted without effect, the store has no field for them. Contributed by @iot-rocket.
+- **CloudFormation — `AWS::CloudWatch::Alarm` updates in place** — a stack update that changed an alarm fell through to the create handler, which rewrote the record with a fresh `StateUpdatedTimestamp` on every update, so an alarm that had been in `ALARM` for an hour reported a state change that never happened. The alarm now updates as `PutMetricAlarm` does: the configuration is rewritten under the same name and ARN, a property left out of the template falls back to its default, and the state, its reason, its timestamp and the history stay, as CloudFormation documents. `Tags` are applied on create and update through the alarm's tag set (`PutMetricAlarm` ignores them on an existing alarm). `AlarmName` requires replacement and follows the convention already in place: the renamed alarm is created before the old one is deleted; an alarm deleted behind the stack's back is recreated the same way. `Metrics` (metric math) stays unsupported, as on create. Contributed by @iot-rocket.
+- **CloudFormation — `AWS::IAM::Policy` updates in place** — a stack update that changed an inline policy's document, its name or its `Roles` / `Users` / `Groups` fell through to the create handler, which rebuilt the record under a fresh policy id and attached it again, so `GetAtt Id` changed on every edit and `AttachmentCount` drifted from the attachments the entities actually held. Every property of the resource updates with no interruption on AWS, and now it does here: a new `PolicyDocument` becomes the default version through the IAM module's own `CreatePolicyVersion` (pruning at the five-version cap), the entity lists reconcile through attach and detach — the two steps the `AWS::IAM::ManagedPolicy` handler runs, now shared — and a new `PolicyName` re-keys the record under the ARN derived from it, keeping the policy id, the version history and every entity's attachment, with `Ref` following the new name. Deleting either policy type now detaches it from its entities before the record goes, so a role no longer keeps a dangling ARN in its attached list. Contributed by @iot-rocket.
+
+### Fixed
+- **CloudFormation — `AWS::Events::Rule` reports the rule ARN the EventBridge service reports** — `Fn::GetAtt` `Arn` on a rule was built with the bus name in every case, so a rule on the default bus answered `rule/default/<name>` while `DescribeRule` and `ListRules` for the same rule answered `rule/<name>`; a permission or a target keyed on the template's ARN never matched the service's. The provisioner now derives the ARN through the service's own helper: no bus segment on the default bus, `rule/<bus>/<name>` on a custom one. Contributed by @iot-rocket.
+- **CloudFormation — `AWS::Cognito::UserPool` reads `UserPoolName`** — the provisioner read `PoolName`, the API's name for the property, where the resource reference defines `UserPoolName`, so every pool declared with the documented property came up under a generated `<stack>-<logical id>` name and `ListUserPools` never showed the name the template gave it. `UserPoolName` is honoured now; `PoolName` stays accepted for templates written against MiniStack. Contributed by @iot-rocket.
+- **CloudWatch — `PutMetricAlarm` keeps the state timestamp of an existing alarm** — re-putting an alarm stamped a fresh `StateUpdatedTimestamp` on every call, so an alarm that had been in `ALARM` for an hour reported a state change that never happened whenever its configuration was touched. The state, its reason and its timestamp now stay across the re-put and only `AlarmConfigurationUpdatedTimestamp` moves, as the API reference documents ("its state is left unchanged, but the update completely overwrites the previous configuration of the alarm"); both request encodings. Contributed by @iot-rocket.
+- **CloudFormation — `AWS::Lambda::Permission` is replaced on update and removed on delete** — a stack update that changed a permission fell through to the create handler and appended a second statement under the same Sid, so the function policy carried both the old and the new principal; a permission declared without an `Id` was never removed at all, because the delete looked for an empty Sid where the create had used the logical id; and `EventSourceToken`, `FunctionUrlAuthType`, `InvokedViaFunctionUrl`, `PrincipalOrgID` and `SourceAccount` were dropped on the way to the statement. Every property of the type requires replacement, so an update now removes the old statement before adding the new one, the delete resolves the Sid exactly as the create does, and create and update go through the Lambda service's AddPermission path, which now keeps all nine documented properties as statement conditions. Contributed by @iot-rocket.
### Fixed
- **IAM enforcement — the remaining S3 operations authorize as S3 documents them** — with `AUTH=true`, a browser `POST Object` was checked as `s3:DeleteObject`, a request naming a `versionId` as the unversioned action, `DeleteObjects` once against the bucket ARN (so a grant on `arn:aws:s3:::bucket/*` denied every batch delete), `CopyObject` / `UploadPartCopy` without `s3:GetObject` on the source, `GetObjectAttributes` without its `s3:GetObject` companion, `x-amz-bypass-governance-retention` without `s3:BypassGovernanceRetention`, and the sub-resources without a table row (`accelerate`, `requestPayment`, `publicAccessBlock`, `ownershipControls`, `intelligent-tiering`, `metrics`, `analytics`, `inventory`, `object-lock`, `policyStatus`, `retention`, `legal-hold`, `attributes`, `select`, `torrent`) fell to the method default. Each now maps to the action the S3 reference lists, a `versionId` resolves to the `*Version*` action, and both enforcement sites run the extra per-request checks (per key, source object, attributes pair, governance bypass). Contributed by @iot-rocket.
### Added
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index f4c7bade..62fcfcef 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -137,7 +137,10 @@ def _delete_resource(resource_type: str, physical_id: str, props: dict,
"""Delete a provisioned resource."""
handler = _RESOURCE_HANDLERS.get(resource_type)
if handler and "delete" in handler:
- handler["delete"](physical_id, props)
+ if handler.get("delete_with_logical_id"):
+ handler["delete"](physical_id, props, logical_id)
+ else:
+ handler["delete"](physical_id, props)
return
# Custom resource types
if resource_type.startswith("Custom::") or resource_type == "AWS::CloudFormation::CustomResource":
@@ -178,6 +181,21 @@ def _requires_replacement_dynamodb(old_props, new_props):
return False
+def _requires_replacement_sfn(old_props, new_props):
+ """AWS::StepFunctions::StateMachine requires replacement when
+ StateMachineType changes (the resource reference marks the property
+ "Update requires: Replacement")."""
+ return (old_props.get("StateMachineType", "STANDARD")
+ != new_props.get("StateMachineType", "STANDARD"))
+
+
+def _requires_replacement_cognito_user_pool_group(old_props, new_props):
+ """AWS::Cognito::UserPoolGroup requires replacement when UserPoolId
+ changes (the resource reference marks the property "Update requires:
+ Replacement")."""
+ return old_props.get("UserPoolId") != new_props.get("UserPoolId")
+
+
# Resource types that carry a user-supplied physical name AND can require
# replacement. Real CloudFormation refuses an update that would replace a
# custom-named resource (you must rename it first), so MiniStack must fail the
@@ -188,6 +206,14 @@ _CUSTOM_NAME_REPLACEMENT = {
"name": "TableName",
"requires_replacement": _requires_replacement_dynamodb,
},
+ "AWS::StepFunctions::StateMachine": {
+ "name": "StateMachineName",
+ "requires_replacement": _requires_replacement_sfn,
+ },
+ "AWS::Cognito::UserPoolGroup": {
+ "name": "GroupName",
+ "requires_replacement": _requires_replacement_cognito_user_pool_group,
+ },
}
@@ -1414,10 +1440,16 @@ def _attach_policy_to_entities(arn, props):
_iam.attach_managed_policy(entity, arn)
+def _iam_policy_arn(props, name):
+ """The ARN MiniStack keys an AWS::IAM::Policy record by. Derived from the
+ name, so create and rename must agree on it."""
+ return f"arn:aws:iam::{get_account_id()}:policy{props.get('Path', '/')}{name}"
+
+
def _iam_policy_create(logical_id, props, stack_name):
name = props.get("PolicyName") or _physical_name(stack_name, logical_id, max_len=128)
path = props.get("Path", "/")
- arn = f"arn:aws:iam::{get_account_id()}:policy{path}{name}"
+ arn = _iam_policy_arn(props, name)
pol_doc = props.get("PolicyDocument", {})
if isinstance(pol_doc, dict):
pol_doc = json.dumps(pol_doc)
@@ -1433,16 +1465,107 @@ def _iam_policy_create(logical_id, props, stack_name):
return name, {"Id": record["PolicyId"]}
-def _iam_policy_delete(physical_id, props):
- # The physical id is the policy name (what Ref returns), so find the record
- # by name. Older stacks stored the ARN as the physical id; popping that
- # first keeps them deletable.
- if _iam._policies.pop(physical_id, None) is not None:
- return
- for arn, policy in list(_iam._policies.items()):
+def _iam_policy_record(physical_id):
+ """Find the record behind an AWS::IAM::Policy physical id. The physical id
+ is the policy name (what Ref returns); older stacks stored the ARN."""
+ record = _iam._policies.get(physical_id)
+ if record is not None:
+ return physical_id, record
+ for arn, policy in _iam._policies.items():
if policy.get("PolicyName") == physical_id:
- _iam._policies.pop(arn, None)
- return
+ return arn, policy
+ return None, None
+
+
+def _iam_policy_set_document(arn, record, document, resource_type):
+ """A new PolicyDocument becomes a new default policy version through the
+ IAM module's own CreatePolicyVersion (pruning the oldest non-default
+ version at the five-version cap first, like the CFN handler), so the
+ policy id, the creation date and the attachments stay. Shared by the
+ inline and the managed policy handlers."""
+ versions = record["Versions"]
+ surplus = len(versions) - _IAM_POLICY_VERSION_LIMIT + 1
+ if surplus > 0:
+ prunable = sorted(
+ (v["VersionId"] for v in versions.values() if not v["IsDefaultVersion"]),
+ key=lambda vid: int(vid.lstrip("v")),
+ )
+ for version_id in prunable[:surplus]:
+ _iam._delete_policy_version({"PolicyArn": arn, "VersionId": version_id})
+ if not isinstance(document, str):
+ document = json.dumps(document)
+ resp = _iam._create_policy_version({
+ "PolicyArn": arn,
+ "PolicyDocument": document,
+ "SetAsDefault": "true",
+ })
+ if resp[0] >= 400:
+ raise ValueError(f"{resource_type} update failed: {resp[2]!r}")
+
+
+def _iam_policy_reconcile_entities(arn, old_props, new_props):
+ """Attach the policy to the Roles / Users / Groups the new template names
+ and detach it from the ones the old template named, through the IAM
+ helpers so AttachmentCount stays in step. Shared by the inline and the
+ managed policy handlers."""
+ for prop, store in (("Roles", _iam._roles),
+ ("Users", _iam._users),
+ ("Groups", _iam._groups)):
+ old_names = set(old_props.get(prop, []) or [])
+ new_names = set(new_props.get(prop, []) or [])
+ for entity_name in sorted(old_names - new_names):
+ entity = store.get(entity_name)
+ if entity is not None:
+ _iam.detach_managed_policy(entity, arn)
+ for entity_name in sorted(new_names - old_names):
+ entity = store.get(entity_name)
+ if entity is not None:
+ _iam.attach_managed_policy(entity, arn)
+
+
+def _iam_policy_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update an inline policy in place, as PutRolePolicy / PutUserPolicy /
+ PutGroupPolicy do on AWS: every property of AWS::IAM::Policy, PolicyName
+ included, updates with no interruption
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-policy.html).
+ A new PolicyDocument becomes the default version under the same policy
+ id, the Roles / Users / Groups lists reconcile through attach/detach,
+ and a new PolicyName re-keys the record (MiniStack keys it by an ARN
+ derived from the name) with its id, versions and attachments intact;
+ Ref follows the new name, as it does on AWS.
+ """
+ name = new_props.get("PolicyName") or _physical_name(
+ stack_name, logical_id or physical_id, max_len=128
+ )
+ arn, record = _iam_policy_record(physical_id)
+ if record is None:
+ return _iam_policy_create(logical_id or physical_id, new_props, stack_name)
+
+ new_arn = _iam_policy_arn(new_props, name)
+ if new_arn != arn or name != record.get("PolicyName"):
+ _iam.rename_policy(arn, new_arn, name)
+ arn = new_arn
+
+ if new_props.get("PolicyDocument") != old_props.get("PolicyDocument"):
+ _iam_policy_set_document(
+ arn, record, new_props.get("PolicyDocument", {}), "AWS::IAM::Policy"
+ )
+ _iam_policy_reconcile_entities(arn, old_props, new_props)
+ return name, {"Id": record["PolicyId"]}
+
+
+def _iam_policy_remove(arn, props):
+ """Detach the policy from every Role / User / Group the template named,
+ through the IAM helpers so AttachmentCount follows, then drop the
+ record. Shared by the inline and the managed policy delete handlers."""
+ _iam_policy_reconcile_entities(arn, props, {})
+ _iam._policies.pop(arn, None)
+
+
+def _iam_policy_delete(physical_id, props):
+ arn, _record = _iam_policy_record(physical_id)
+ if arn is not None:
+ _iam_policy_remove(arn, props)
# --- IAM InstanceProfile ---
@@ -1916,7 +2039,8 @@ def _eb_rule_create(logical_id, props, stack_name):
name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=64)
bus = props.get("EventBusName", "default")
key = _eb._rule_key(name, bus)
- arn = f"arn:aws:events:{get_region()}:{get_account_id()}:rule/{bus}/{name}"
+ # The service's own ARN shape: a default-bus rule has no bus segment.
+ arn = _eb._rule_arn(name, bus)
_eb._rules[key] = {
"Name": name,
@@ -1934,14 +2058,100 @@ def _eb_rule_create(logical_id, props, stack_name):
for t in targets:
_eb._targets[key].append(t)
- return name, {"Arn": arn}
+ _eb_rule_apply_tags(arn, [], props.get("Tags") or [])
+ return name, {"Arn": arn, "RuleName": name}
+
+
+def _eb_rule_apply_tags(arn, old_tags, new_tags):
+ """Reconcile the template's tags on a rule through TagResource /
+ UntagResource: a key the template dropped is removed, the declared ones
+ are written, and a tag added outside the stack is left alone.
+ """
+ declared = {t["Key"] for t in new_tags}
+ dropped = sorted({t["Key"] for t in old_tags} - declared)
+ if dropped:
+ _eb._untag_resource({"ResourceARN": arn, "TagKeys": dropped})
+ if new_tags:
+ resp = _eb._tag_resource({"ResourceARN": arn, "Tags": new_tags})
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::Events::Rule TagResource failed: {resp[2]!r}")
+
+
+def _eb_rule_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update a rule in place through PutRule / PutTargets / RemoveTargets, so
+ the rule keeps its name and ARN and any target added outside the
+ template survives. Name is the one create-only property
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html):
+ a rename is a replacement, the new rule created before the old one is
+ removed. EventBusName updates with "some interruptions": the rule moves
+ to the other bus under the same name, carrying its targets and tags
+ along. Tags update without interruption: the template's tag set is
+ reconciled the same way the targets are.
+ """
+ name = new_props.get("Name") or _physical_name(
+ stack_name, logical_id or physical_id, max_len=64
+ )
+ old_bus = old_props.get("EventBusName", "default")
+ new_bus = new_props.get("EventBusName", "default")
+ old_key = _eb._rule_key(physical_id, old_bus)
+ rule = _eb._rules.get(old_key)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ name, rule.get("Name") if rule else None, _eb_rule_create, _eb_rule_delete,
+ )
+ if replaced is not None:
+ return replaced
+
+ _eb._ensure_default_bus()
+ pattern = new_props.get("EventPattern", "")
+ resp = _eb._put_rule({
+ "Name": name,
+ "EventBusName": new_bus,
+ "State": new_props.get("State", "ENABLED"),
+ "Description": new_props.get("Description", ""),
+ "ScheduleExpression": new_props.get("ScheduleExpression", ""),
+ "EventPattern": json.dumps(pattern) if isinstance(pattern, dict) else pattern,
+ "RoleArn": new_props.get("RoleArn", ""),
+ })
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::Events::Rule update failed: {resp[2]!r}")
+ new_key = _eb._rule_key(name, new_bus)
+ if new_bus != old_bus:
+ # PutRule accepted the new bus, so the rule exists there now: the
+ # old record goes, and its targets (the template's and any added
+ # outside the stack, reconciled below) and tags move over. A move
+ # onto a bus that does not exist fails above, leaving the rule as
+ # it was.
+ old_rule = _eb._rules.pop(old_key, None) or {}
+ _eb._targets[new_key] = list(_eb._targets.pop(old_key, []))
+ if old_rule.get("Arn") in _eb._tags:
+ _eb._tags[_eb._rules[new_key]["Arn"]] = _eb._tags.pop(old_rule["Arn"])
+
+ old_ids = {t.get("Id") for t in old_props.get("Targets", []) or []}
+ new_targets = new_props.get("Targets", []) or []
+ new_ids = {t.get("Id") for t in new_targets}
+ if old_ids - new_ids:
+ _eb._remove_targets({
+ "Rule": name, "EventBusName": new_bus, "Ids": sorted(old_ids - new_ids),
+ })
+ if new_targets:
+ resp = _eb._put_targets({
+ "Rule": name, "EventBusName": new_bus, "Targets": new_targets,
+ })
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::Events::Rule PutTargets failed: {resp[2]!r}")
+ arn = _eb._rules[new_key]["Arn"]
+ _eb_rule_apply_tags(arn, old_props.get("Tags") or [], new_props.get("Tags") or [])
+ return name, {"Arn": arn, "RuleName": name}
def _eb_rule_delete(physical_id, props):
bus = props.get("EventBusName", "default")
key = _eb._rule_key(physical_id, bus)
- _eb._rules.pop(key, None)
+ rule = _eb._rules.pop(key, None)
_eb._targets.pop(key, None)
+ if rule:
+ _eb._tags.pop(rule["Arn"], None)
# --- IoT Topic Rule (AWS::IoT::TopicRule) ---
@@ -2195,31 +2405,66 @@ def _lambda_function_for_cfn_ref(function_ref: str) -> tuple[dict | None, str, s
return func, name, resource_arn, qualifier
+# Every property of the type, all create-only
+# (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-permission.html),
+# forwarded to AddPermission under the same names.
+_LAMBDA_PERMISSION_PROPERTIES = (
+ "Action",
+ "Principal",
+ "SourceArn",
+ "SourceAccount",
+ "PrincipalOrgID",
+ "FunctionUrlAuthType",
+ "InvokedViaFunctionUrl",
+ "EventSourceToken",
+)
+
+
+def _lambda_permission_sid(props, logical_id):
+ # ``Id`` is not an AWS property, but templates written against earlier
+ # releases rely on it; otherwise the logical id is the Sid.
+ return props.get("Id") or logical_id or ""
+
+
def _lambda_permission_create(logical_id, props, stack_name):
- func, _func_name, resource_arn, _qualifier = _lambda_function_for_cfn_ref(props.get("FunctionName", ""))
+ func, func_name, _resource_arn, qualifier = _lambda_function_for_cfn_ref(props.get("FunctionName", ""))
if func:
- stmt = {
- "Sid": props.get("Id") or logical_id,
- "Effect": "Allow",
- "Principal": props.get("Principal", "*"),
- "Action": props.get("Action", "lambda:InvokeFunction"),
- "Resource": resource_arn,
- }
- source_arn = props.get("SourceArn")
- if source_arn:
- stmt["Condition"] = {"ArnLike": {"AWS:SourceArn": source_arn}}
- func["policy"]["Statement"].append(stmt)
+ data = {"StatementId": _lambda_permission_sid(props, logical_id), "Principal": "*"}
+ data.update({key: props[key] for key in _LAMBDA_PERMISSION_PROPERTIES if props.get(key) is not None})
+ status, _headers, body = _lambda_svc._add_permission(func_name, data, path_qualifier=qualifier)
+ if status >= 400:
+ raise ValueError(
+ f"AWS::Lambda::Permission AddPermission failed: {body.decode() if isinstance(body, bytes) else body}"
+ )
pid = f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
return pid, {}
-def _lambda_permission_delete(physical_id, props):
- func, _func_name, _resource_arn, _qualifier = _lambda_function_for_cfn_ref(props.get("FunctionName", ""))
+def _lambda_permission_remove_statement(props, sid):
+ func, func_name, _resource_arn, qualifier = _lambda_function_for_cfn_ref(props.get("FunctionName", ""))
if func:
- sid = props.get("Id") or ""
- func["policy"]["Statement"] = [
- s for s in func["policy"]["Statement"] if s.get("Sid") != sid
- ]
+ # A statement already gone (removed by hand, or the function policy
+ # rewritten) is nothing to fail a stack delete over.
+ _lambda_svc._remove_permission(func_name, sid, {}, path_qualifier=qualifier)
+
+
+def _lambda_permission_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Every AWS::Lambda::Permission property requires replacement
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-permission.html),
+ so any change is RemovePermission followed by AddPermission under a fresh
+ physical id, as on AWS. Removal goes first: both statements carry the
+ same Sid unless the template's Id changed (the default Sid is the
+ logical id), so the reverse order would remove the statement just added.
+ """
+ _lambda_permission_remove_statement(old_props, _lambda_permission_sid(old_props, logical_id))
+ return _lambda_permission_create(logical_id or physical_id, new_props, stack_name)
+
+
+def _lambda_permission_delete(physical_id, props, logical_id=None):
+ # The Sid defaults to the logical id exactly as in create, so a
+ # permission declared without an Id removes the statement it added —
+ # on stack delete, and on the rollback of a replacement.
+ _lambda_permission_remove_statement(props, _lambda_permission_sid(props, logical_id))
# --- Lambda Version ---
@@ -3861,9 +4106,10 @@ def _appsync_apikey_delete(physical_id, props):
# --- SecretsManager resource provisioners ---
-def _sm_secret_create(logical_id, props, stack_name):
+def _sm_secret_string(props):
+ """The secret value a template declares: SecretString verbatim, or one
+ generated from GenerateSecretString."""
import string as _string
- name = props.get("Name") or _physical_name(stack_name, logical_id)
secret_string = props.get("SecretString", "")
gen = props.get("GenerateSecretString")
if gen and not secret_string:
@@ -3876,7 +4122,6 @@ def _sm_secret_create(logical_id, props, stack_name):
template = gen.get("SecretStringTemplate")
gen_key = gen.get("GenerateStringKey", "password")
if template:
- import json
try:
obj = json.loads(template)
obj[gen_key] = generated
@@ -3885,6 +4130,12 @@ def _sm_secret_create(logical_id, props, stack_name):
secret_string = generated
else:
secret_string = generated
+ return secret_string
+
+
+def _sm_secret_create(logical_id, props, stack_name):
+ name = props.get("Name") or _physical_name(stack_name, logical_id)
+ secret_string = _sm_secret_string(props)
arn = f"arn:aws:secretsmanager:{get_region()}:{get_account_id()}:secret:{name}-{new_uuid()[:6]}"
import time as _time
@@ -3905,64 +4156,259 @@ def _sm_secret_create(logical_id, props, stack_name):
}
},
}
+ if props.get("ReplicaRegions"):
+ _sm_secret_replicate(name, props["ReplicaRegions"])
return name, {"Arn": arn}
+def _sm_secret_replicate(secret_id, regions):
+ """Replicate a secret to the regions a template declares, through the
+ service's ReplicateSecretToRegions: a region already replicated keeps its
+ replica (the KmsKeyId is refreshed), a new one gets a copy of the secret.
+ The template's ReplicaRegion entries carry Region and KmsKeyId, the shape
+ AddReplicaRegions expects, so they are passed through as they are."""
+ resp = _sm._replicate_secret_to_regions({"SecretId": secret_id, "AddReplicaRegions": list(regions)})
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::SecretsManager::Secret replication failed: {resp[2]!r}")
+
+
+def _sm_secret_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update a secret in place through UpdateSecret, keeping its ARN and every
+ stored version. Name is the one create-only property
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-secretsmanager-secret.html):
+ a rename is a replacement, the new secret created before the old one is
+ removed. A changed SecretString or GenerateSecretString publishes a new
+ AWSCURRENT version, as the reference documents; the previous version
+ stays behind as AWSPREVIOUS. ReplicaRegions is applied through
+ ReplicateSecretToRegions. Type is not stored by the service and is
+ ignored.
+ """
+ name = new_props.get("Name") or _physical_name(stack_name, logical_id or physical_id)
+ secret = _sm._secrets.get(physical_id)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ name, secret.get("Name") if secret else None, _sm_secret_create, _sm_secret_delete,
+ )
+ if replaced is not None:
+ return replaced
+
+ data = {"SecretId": physical_id}
+ # Sent only when the template speaks to the property: declared, or
+ # dropped since the previous template, which clears it as
+ # CloudFormation does. A value set outside the stack on a property
+ # the template never declared is left alone.
+ data.update(_declared_or_default(old_props, new_props, {"Description": "", "KmsKeyId": None}))
+ if (new_props.get("SecretString") != old_props.get("SecretString")
+ or new_props.get("GenerateSecretString") != old_props.get("GenerateSecretString")):
+ data["SecretString"] = _sm_secret_string(new_props)
+ resp = _sm._update_secret(data)
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::SecretsManager::Secret update failed: {resp[2]!r}")
+ if "Tags" in new_props or "Tags" in old_props:
+ # Same rule as above: tags applied through TagResource on a secret
+ # whose template never declared any are not the stack's to clear.
+ secret["Tags"] = list(new_props.get("Tags", []))
+ if new_props.get("ReplicaRegions") and new_props["ReplicaRegions"] != old_props.get("ReplicaRegions"):
+ # Regions added or re-keyed since the previous template are applied;
+ # a region dropped from the template keeps its replica, the service
+ # has no RemoveRegionsFromReplication to take it down with.
+ _sm_secret_replicate(physical_id, new_props["ReplicaRegions"])
+ return physical_id, {"Arn": secret["ARN"]}
+
+
def _sm_secret_delete(physical_id, props):
- _sm._secrets.pop(physical_id, None)
+ secret = _sm._secrets.get(physical_id)
+ if secret is not None:
+ # Takes the replicas and the resource policy down with the secret.
+ _sm._purge_secret(physical_id, secret)
# --- Cognito UserPool ---
-def _cognito_user_pool_create(logical_id, props, stack_name):
- name = props.get("PoolName") or _physical_name(stack_name, logical_id, max_len=128)
- pid = _cognito._pool_id()
- now = _cognito._now_epoch()
- pool = {
- "Id": pid,
- "Name": name,
+def _cognito_user_pool_name(props, stack_name, logical_id):
+ # UserPoolName is the CloudFormation property; PoolName (the API's name for
+ # it) stays accepted because earlier templates written against MiniStack
+ # used it.
+ return (props.get("UserPoolName") or props.get("PoolName")
+ or _physical_name(stack_name, logical_id, max_len=128))
+
+
+# UpdateUserPool's parameters, with the value CloudFormation applies when the
+# template drops the property. The resource reference says "If you don't
+# specify a value for a parameter, Amazon Cognito sets it to a default value",
+# and the defaults here are what the service's CreateUserPool fills in, so a
+# dropped property ends up as it would on a pool created without it. A
+# property absent from both templates is never touched.
+_COGNITO_USER_POOL_UPDATABLE = {
+ "Policies": {
+ "PasswordPolicy": {
+ "MinimumLength": 8,
+ "RequireUppercase": True,
+ "RequireLowercase": True,
+ "RequireNumbers": True,
+ "RequireSymbols": True,
+ "TemporaryPasswordValidityDays": 7,
+ }
+ },
+ "DeletionProtection": "INACTIVE",
+ "AutoVerifiedAttributes": [],
+ "SmsVerificationMessage": "",
+ "EmailVerificationMessage": "",
+ "EmailVerificationSubject": "",
+ "SmsAuthenticationMessage": "",
+ "MfaConfiguration": "OFF",
+ "DeviceConfiguration": {},
+ "EmailConfiguration": {},
+ "SmsConfiguration": {},
+ "UserPoolTags": {},
+ "AdminCreateUserConfig": {
+ "AllowAdminCreateUserOnly": False,
+ "UnusedAccountValidityDays": 7,
+ },
+ "UserPoolAddOns": {},
+ "VerificationMessageTemplate": {},
+ "AccountRecoverySetting": {},
+ "LambdaConfig": {},
+ "UserAttributeUpdateSettings": {},
+}
+
+# Properties CreateUserPool takes that no later API call changes: the sign-in
+# attributes are fixed at creation, and the resource reference says of
+# UsernameConfiguration "This configuration is immutable after you set it".
+# Schema is create-time too, but AddCustomAttributes can grow it afterwards.
+_COGNITO_USER_POOL_CREATE_ONLY = ("Schema", "AliasAttributes", "UsernameAttributes",
+ "UsernameConfiguration")
+
+# The rest of the AWS::Cognito::UserPool reference (UserPoolTier, the
+# EmailAuthentication* and WebAuthn* properties, IssuerConfiguration,
+# KeyConfiguration) has no field on the service's record and is not
+# modelled: it is accepted and ignored on create and on update alike.
+
+
+def _cognito_user_pool_attributes(pid):
+ return {
"Arn": _cognito._pool_arn(pid),
- "CreationDate": now,
- "LastModifiedDate": now,
- "Policies": props.get("Policies", {
- "PasswordPolicy": {
- "MinimumLength": 8,
- "RequireUppercase": True,
- "RequireLowercase": True,
- "RequireNumbers": True,
- "RequireSymbols": True,
- "TemporaryPasswordValidityDays": 7,
- }
- }),
- "SchemaAttributes": _cognito._build_schema_attributes(props.get("Schema")),
- "AutoVerifiedAttributes": props.get("AutoVerifiedAttributes", []),
- "AliasAttributes": props.get("AliasAttributes", []),
- "UsernameAttributes": props.get("UsernameAttributes", []),
- "MfaConfiguration": props.get("MfaConfiguration", "OFF"),
- # EnabledMfas (what CDK emits for mfaSecondFactor) maps onto the per
- # method config blocks GetUserPoolMfaConfig reports. Only the software
- # token block carries an Enabled flag in the API model; SMS and email
- # configs are message/role shapes that come from their own properties,
- # so a bare SMS_MFA/EMAIL_OTP entry has nothing faithful to invent.
- **({"SoftwareTokenMfaConfiguration": {"Enabled": True}}
- if "SOFTWARE_TOKEN_MFA" in (props.get("EnabledMfas") or []) else {}),
- "EstimatedNumberOfUsers": 0,
- "UserPoolTags": props.get("UserPoolTags", {}),
- "AdminCreateUserConfig": props.get("AdminCreateUserConfig", {
- "AllowAdminCreateUserOnly": False,
- "UnusedAccountValidityDays": 7,
- }),
- "LambdaConfig": props.get("LambdaConfig", {}),
- "Domain": None,
- "_clients": {},
- "_users": {},
- "_groups": {},
- "_resource_servers": {},
+ "ProviderName": f"cognito-idp.{get_region()}.amazonaws.com/{pid}",
+ "UserPoolId": pid,
}
- _cognito._user_pools[pid] = pool
- arn = _cognito._pool_arn(pid)
- provider_name = f"cognito-idp.{get_region()}.amazonaws.com/{pid}"
- return pid, {"Arn": arn, "ProviderName": provider_name}
+
+
+def _cognito_user_pool_create(logical_id, props, stack_name):
+ """Create the pool through the service's CreateUserPool so the record
+ carries every property the API stores, the same set
+ _cognito_user_pool_update applies later."""
+ payload = {
+ key: props[key]
+ for key in (*_COGNITO_USER_POOL_CREATE_ONLY, *_COGNITO_USER_POOL_UPDATABLE)
+ if key in props
+ }
+ payload["PoolName"] = _cognito_user_pool_name(props, stack_name, logical_id)
+ status, _, body = _cognito._create_user_pool(payload)
+ if status >= 400:
+ raise ValueError(f"AWS::Cognito::UserPool create failed: {body!r}")
+ pid = json.loads(body)["UserPool"]["Id"]
+ _cognito_user_pool_software_token_mfa(pid, {}, props)
+ return pid, _cognito_user_pool_attributes(pid)
+
+
+def _cognito_user_pool_software_token_mfa(pid, old_props, new_props):
+ """Apply an EnabledMfas change through SetUserPoolMfaConfig. EnabledMfas
+ (what CDK emits for mfaSecondFactor) maps onto the per method config
+ blocks GetUserPoolMfaConfig reports. Only the software token block
+ carries an Enabled flag in the API model; SMS and email configs are
+ message/role shapes that come from their own properties, so a bare
+ SMS_MFA/EMAIL_OTP entry has nothing faithful to invent. SOFTWARE_TOKEN_MFA
+ arriving switches the block on, its removal (or the property being
+ dropped) switches it off; a pool that never listed it is left without
+ the block, since a disabled block nobody asked for reads as drift to a
+ client that diffs the config.
+ """
+ was = "SOFTWARE_TOKEN_MFA" in (old_props.get("EnabledMfas") or [])
+ now = "SOFTWARE_TOKEN_MFA" in (new_props.get("EnabledMfas") or [])
+ if was == now:
+ return
+ status, _, body = _cognito._set_user_pool_mfa_config({
+ "UserPoolId": pid, "SoftwareTokenMfaConfiguration": {"Enabled": now},
+ })
+ if status >= 400:
+ raise ValueError(f"AWS::Cognito::UserPool EnabledMfas update failed: {body!r}")
+
+
+def _declared_or_default(old_props, new_props, defaults):
+ """The API payload for a set of updatable properties: each one the new
+ template declares, plus the default for each one the old template
+ declared and the new one dropped."""
+ payload = {}
+ for key, default in defaults.items():
+ if key in new_props:
+ payload[key] = new_props[key]
+ elif key in old_props:
+ payload[key] = copy.deepcopy(default)
+ return payload
+
+
+def _cognito_user_pool_add_attributes(physical_id, pool, schema):
+ """Send the Schema entries the pool does not carry yet through
+ AddCustomAttributes, the one API call that changes a pool's schema after
+ CreateUserPool. It adds and never removes or redefines, so an entry the
+ pool already has (a standard attribute, or a custom one from an earlier
+ template) is left as it is, and it takes at most 25 attributes per call,
+ so a larger addition goes in batches. The service validates the rest: a
+ Required custom attribute, or more than the pool's custom-attribute
+ limit, fails the update.
+ """
+ known = {a["Name"] for a in _cognito._ensure_schema_attributes(pool)["SchemaAttributes"]}
+ additions = [
+ raw for raw in schema or []
+ if isinstance(raw, dict) and _cognito._schema_attribute_name(raw) not in known
+ ]
+ for start in range(0, len(additions), 25):
+ status, _, body = _cognito._add_custom_attributes({
+ "UserPoolId": physical_id, "CustomAttributes": additions[start:start + 25],
+ })
+ if status >= 400:
+ raise ValueError(f"AWS::Cognito::UserPool Schema update failed: {body!r}")
+
+
+def _cognito_user_pool_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update a user pool in place: no AWS::Cognito::UserPool property
+ requires replacement
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html),
+ so the pool keeps its generated id, its ARN and its users, clients and
+ groups. What UpdateUserPool accepts goes through that path; the name,
+ create-only on the API but not in CloudFormation, is applied to the
+ record directly. AliasAttributes, UsernameAttributes and
+ UsernameConfiguration are fixed at CreateUserPool and no API call
+ changes them afterwards, so a change fails the update with a message
+ naming the property rather than altering the record behind the
+ service's back. A Schema change can only add attributes, through
+ AddCustomAttributes.
+ """
+ pool = _cognito._user_pools.get(physical_id)
+ if pool is None:
+ raise ValueError(f"AWS::Cognito::UserPool {physical_id} no longer exists")
+ for prop in _COGNITO_USER_POOL_CREATE_ONLY[1:]:
+ if new_props.get(prop) != old_props.get(prop) and (new_props.get(prop) or old_props.get(prop)):
+ raise ValueError(
+ f"AWS::Cognito::UserPool {prop} is set at CreateUserPool and no "
+ f"API call changes it afterwards, so MiniStack fails the update "
+ f"for pool {physical_id} instead of altering the record; declare "
+ "a new UserPool resource instead."
+ )
+ payload = _declared_or_default(old_props, new_props, _COGNITO_USER_POOL_UPDATABLE)
+ if payload:
+ payload["UserPoolId"] = physical_id
+ status, _, body = _cognito._update_user_pool(payload)
+ if status >= 400:
+ raise ValueError(f"AWS::Cognito::UserPool update failed: {body!r}")
+
+ _cognito_user_pool_software_token_mfa(physical_id, old_props, new_props)
+ pool["Name"] = _cognito_user_pool_name(new_props, stack_name, logical_id or physical_id)
+ if new_props.get("Schema") != old_props.get("Schema"):
+ _cognito_user_pool_add_attributes(physical_id, pool, new_props.get("Schema"))
+ pool["LastModifiedDate"] = _cognito._now_epoch()
+ return physical_id, _cognito_user_pool_attributes(physical_id)
def _cognito_user_pool_delete(physical_id, props):
@@ -3973,30 +4419,81 @@ def _cognito_user_pool_delete(physical_id, props):
# --- Cognito UserPoolClient ---
-def _cognito_user_pool_client_create(logical_id, props, stack_name):
- pid = props.get("UserPoolId", "")
- pool = _cognito._user_pools.get(pid)
- if not pool:
- raise ValueError(f"UserPool {pid} not found for UserPoolClient")
+# UpdateUserPoolClient's parameters, with the value a dropped property
+# reverts to: what the service's CreateUserPoolClient fills in when the
+# request omits it, since the resource reference says a parameter without a
+# value is set to its default. None clears AnalyticsConfiguration, which the
+# client record omits on read. RefreshTokenRotation has no field on the
+# record and is not modelled.
+_COGNITO_USER_POOL_CLIENT_UPDATABLE = {
+ "ClientName": "",
+ "RefreshTokenValidity": 30,
+ "AccessTokenValidity": 60,
+ "IdTokenValidity": 60,
+ "TokenValidityUnits": {},
+ "ReadAttributes": [],
+ "WriteAttributes": [],
+ "ExplicitAuthFlows": [],
+ "SupportedIdentityProviders": [],
+ "CallbackURLs": [],
+ "LogoutURLs": [],
+ "DefaultRedirectURI": "",
+ "AllowedOAuthFlows": [],
+ "AllowedOAuthScopes": [],
+ "AllowedOAuthFlowsUserPoolClient": False,
+ "AnalyticsConfiguration": None,
+ "PreventUserExistenceErrors": "LEGACY",
+ "EnableTokenRevocation": True,
+ "EnablePropagateAdditionalUserContextData": False,
+ "AuthSessionValidity": 3,
+}
- cid = _cognito._client_id()
- now = _cognito._now_epoch()
- client = {
- "UserPoolId": pid,
- "ClientName": props.get("ClientName", ""),
- "ClientId": cid,
- "ClientSecret": props.get("GenerateSecret", False) and _cognito._client_secret() or None,
- "CreationDate": now,
- "LastModifiedDate": now,
- "ExplicitAuthFlows": props.get("ExplicitAuthFlows", []),
- "AllowedOAuthFlows": props.get("AllowedOAuthFlows", []),
- "AllowedOAuthScopes": props.get("AllowedOAuthScopes", []),
- "CallbackURLs": props.get("CallbackURLs", []),
- "LogoutURLs": props.get("LogoutURLs", []),
- "SupportedIdentityProviders": props.get("SupportedIdentityProviders", []),
- }
- pool["_clients"][cid] = client
- return cid, {}
+
+def _cognito_user_pool_client_create(logical_id, props, stack_name):
+ """Create the app client through the service's CreateUserPoolClient so
+ the record carries every property UpdateUserPoolClient can change
+ later, and a replacement (UserPoolId or GenerateSecret changed) carries
+ the whole template over."""
+ payload = {key: props[key] for key in _COGNITO_USER_POOL_CLIENT_UPDATABLE if key in props}
+ payload["UserPoolId"] = props.get("UserPoolId", "")
+ payload["GenerateSecret"] = bool(props.get("GenerateSecret", False))
+ status, _, body = _cognito._create_user_pool_client(payload)
+ if status >= 400:
+ raise ValueError(f"AWS::Cognito::UserPoolClient create failed: {body!r}")
+ cid = json.loads(body)["UserPoolClient"]["ClientId"]
+ return cid, {"ClientId": cid}
+
+
+def _cognito_user_pool_client_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update an app client in place through UpdateUserPoolClient, keeping
+ its ClientId (what Ref returns) and its secret. UserPoolId and
+ GenerateSecret require replacement
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolclient.html):
+ the client id is generated, so the new client is created before the old
+ one is removed and Ref moves to the new id, as on AWS.
+
+ The replacement prologue is spelled out here rather than going through
+ _rename_replacement because that helper keys on a create-only name
+ property, and the two properties that replace a client are not its
+ name: ClientName changes in place, while UserPoolId and GenerateSecret
+ replace.
+ """
+ if (new_props.get("UserPoolId") != old_props.get("UserPoolId")
+ or bool(new_props.get("GenerateSecret")) != bool(old_props.get("GenerateSecret"))):
+ created = _cognito_user_pool_client_create(logical_id or physical_id, new_props, stack_name)
+ _cognito_user_pool_client_delete(physical_id, old_props)
+ return created
+ payload = _declared_or_default(
+ old_props, new_props, _COGNITO_USER_POOL_CLIENT_UPDATABLE
+ )
+ if payload:
+ payload["UserPoolId"] = new_props.get("UserPoolId", "")
+ payload["ClientId"] = physical_id
+ status, _, body = _cognito._update_user_pool_client(payload)
+ if status >= 400:
+ raise ValueError(f"AWS::Cognito::UserPoolClient update failed: {body!r}")
+ return physical_id, {"ClientId": physical_id}
def _cognito_user_pool_client_delete(physical_id, props):
@@ -4046,17 +4543,64 @@ def _cognito_user_pool_group_create(logical_id, props, stack_name):
"UserPoolId": pid,
"Description": props.get("Description", ""),
"RoleArn": props.get("RoleArn", ""),
- "Precedence": props.get("Precedence", 0),
"CreationDate": now,
"LastModifiedDate": now,
"_members": [],
}
+ # "The default Precedence value is null" on the resource reference, so a
+ # template that does not set it gets a group without one.
+ if "Precedence" in props:
+ group["Precedence"] = props["Precedence"]
pool["_groups"][name] = group
# Ref on this resource type returns the GroupName (matches real AWS —
# see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolgroup.html#aws-resource-cognito-userpoolgroup-return-values).
return name, {}
+def _cognito_user_pool_group_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update a group in place, keeping its name (what Ref returns) and its
+ members. GroupName and UserPoolId require replacement
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolgroup.html):
+ a rename, or a move to another pool, creates the new group before the
+ old one is removed; a move that keeps an explicit GroupName was already
+ refused by _custom_named_replacement_error, the way CloudFormation
+ refuses to replace a custom-named resource. Description, Precedence and
+ RoleArn are what UpdateGroup takes, applied to the record directly since
+ the service has no UpdateGroup handler.
+
+ The replacement prologue is spelled out here rather than going through
+ _rename_replacement because a group is keyed by (pool, name), and the
+ helper only compares names: a move to another pool under a generated
+ name keeps the same name, so the helper would see no replacement and
+ the old group would stay stranded in the old pool. The pool has to be
+ part of the replacement test.
+ """
+ name = new_props.get("GroupName") or _physical_name(
+ stack_name, logical_id or physical_id, max_len=128
+ )
+ old_pid = old_props.get("UserPoolId", "")
+ new_pid = new_props.get("UserPoolId", "")
+ pool = _cognito._user_pools.get(old_pid)
+ group = pool["_groups"].get(physical_id) if pool else None
+ if group is None or name != physical_id or new_pid != old_pid:
+ created = _cognito_user_pool_group_create(
+ logical_id or physical_id, new_props, stack_name
+ )
+ if group is not None:
+ _cognito_user_pool_group_delete(physical_id, old_props)
+ return created
+
+ group["Description"] = new_props.get("Description", "")
+ group["RoleArn"] = new_props.get("RoleArn", "")
+ if "Precedence" in new_props:
+ group["Precedence"] = new_props["Precedence"]
+ else:
+ group.pop("Precedence", None)
+ group["LastModifiedDate"] = _cognito._now_epoch()
+ return name, {}
+
+
def _cognito_user_pool_group_delete(physical_id, props):
pid = props.get("UserPoolId", "")
pool = _cognito._user_pools.get(pid)
@@ -4073,8 +4617,12 @@ def _cognito_user_pool_group_delete(physical_id, props):
# --- Cognito IdentityPool ---
+def _cognito_identity_pool_name(props, stack_name, logical_id):
+ return props.get("IdentityPoolName") or _physical_name(stack_name, logical_id, max_len=128)
+
+
def _cognito_identity_pool_create(logical_id, props, stack_name):
- name = props.get("IdentityPoolName") or _physical_name(stack_name, logical_id, max_len=128)
+ name = _cognito_identity_pool_name(props, stack_name, logical_id)
iid = _cognito._identity_pool_id()
pool = {
"IdentityPoolId": iid,
@@ -4091,7 +4639,45 @@ def _cognito_identity_pool_create(logical_id, props, stack_name):
"_identities": {},
}
_cognito._identity_pools[iid] = pool
- return iid, {}
+ # The one Fn::GetAtt the resource reference lists is Name.
+ return iid, {"Name": name}
+
+
+# UpdateIdentityPool's parameters, with the value a dropped property reverts
+# to (the create handler's defaults). CognitoEvents, CognitoStreams and
+# PushSync have no field on the record and are not modelled.
+_COGNITO_IDENTITY_POOL_UPDATABLE = {
+ "AllowUnauthenticatedIdentities": False,
+ "AllowClassicFlow": False,
+ "SupportedLoginProviders": {},
+ "DeveloperProviderName": "",
+ "OpenIdConnectProviderARNs": [],
+ "CognitoIdentityProviders": [],
+ "SamlProviderARNs": [],
+ "IdentityPoolTags": {},
+}
+
+
+def _cognito_identity_pool_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update an identity pool in place through UpdateIdentityPool: no
+ AWS::Cognito::IdentityPool property requires replacement
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-identitypool.html),
+ so the pool keeps its generated id, its role mapping, its principal-tag
+ mappings and its identities.
+ """
+ if physical_id not in _cognito._identity_pools:
+ raise ValueError(f"AWS::Cognito::IdentityPool {physical_id} no longer exists")
+ payload = _declared_or_default(
+ old_props, new_props, _COGNITO_IDENTITY_POOL_UPDATABLE
+ )
+ name = _cognito_identity_pool_name(new_props, stack_name, logical_id or physical_id)
+ payload["IdentityPoolId"] = physical_id
+ payload["IdentityPoolName"] = name
+ status, _, body = _cognito._update_identity_pool(payload)
+ if status >= 400:
+ raise ValueError(f"AWS::Cognito::IdentityPool update failed: {body!r}")
+ return physical_id, {"Name": name}
def _cognito_identity_pool_delete(physical_id, props):
@@ -4238,41 +4824,10 @@ def _iam_managed_policy_update(physical_id, old_props, new_props, stack_name, lo
return _iam_managed_policy_create(logical_id or physical_id, new_props, stack_name)
if new_props.get("PolicyDocument") != old_props.get("PolicyDocument"):
- versions = record["Versions"]
- surplus = len(versions) - _IAM_POLICY_VERSION_LIMIT + 1
- if surplus > 0:
- prunable = sorted(
- (v["VersionId"] for v in versions.values() if not v["IsDefaultVersion"]),
- key=lambda vid: int(vid.lstrip("v")),
- )
- for version_id in prunable[:surplus]:
- _iam._delete_policy_version(
- {"PolicyArn": physical_id, "VersionId": version_id}
- )
- document = new_props.get("PolicyDocument", {})
- if not isinstance(document, str):
- document = json.dumps(document)
- resp = _iam._create_policy_version({
- "PolicyArn": physical_id,
- "PolicyDocument": document,
- "SetAsDefault": "true",
- })
- if resp[0] >= 400:
- raise ValueError(f"AWS::IAM::ManagedPolicy update failed: {resp[2]!r}")
-
- for prop, store in (("Roles", _iam._roles),
- ("Users", _iam._users),
- ("Groups", _iam._groups)):
- old_names = set(old_props.get(prop, []) or [])
- new_names = set(new_props.get(prop, []) or [])
- for entity_name in sorted(old_names - new_names):
- entity = store.get(entity_name)
- if entity is not None:
- _iam.detach_managed_policy(entity, physical_id)
- for entity_name in sorted(new_names - old_names):
- entity = store.get(entity_name)
- if entity is not None:
- _iam.attach_managed_policy(entity, physical_id)
+ _iam_policy_set_document(
+ physical_id, record, new_props.get("PolicyDocument", {}), "AWS::IAM::ManagedPolicy"
+ )
+ _iam_policy_reconcile_entities(physical_id, old_props, new_props)
return physical_id, {
"PolicyArn": physical_id,
@@ -4287,7 +4842,7 @@ def _iam_managed_policy_update(physical_id, old_props, new_props, stack_name, lo
def _iam_managed_policy_delete(physical_id, props):
- _iam._policies.pop(physical_id, None)
+ _iam_policy_remove(physical_id, props)
# --- KMS resource provisioners ---
@@ -5157,9 +5712,10 @@ def _lambda_layer_version_permission_delete(physical_id, props):
# StepFunctions StateMachine
# ---------------------------------------------------------------------------
-def _sfn_state_machine_create(logical_id, props, stack_name):
- name = props.get("StateMachineName") or _physical_name(stack_name, logical_id, max_len=80)
- role_arn = props.get("RoleArn", f"arn:aws:iam::{get_account_id()}:role/StepFunctionsRole")
+def _sfn_definition(props):
+ """The Amazon States Language definition a template declares, resolved
+ from whichever of the three sources it uses, with DefinitionSubstitutions
+ applied."""
import json as _json
# Real CFN accepts three mutually-exclusive definition shapes:
@@ -5201,11 +5757,38 @@ def _sfn_state_machine_create(logical_id, props, stack_name):
if subs:
for k, v in subs.items():
definition = definition.replace("${" + str(k) + "}", str(v))
+ return definition
+
+def _sfn_tags(props):
+ """CloudFormation ``Tags`` ([{Key, Value}]) in the shape the Step
+ Functions tag store keeps ([{key, value}])."""
+ return [{"key": t.get("Key", ""), "value": t.get("Value", "")} for t in props.get("Tags") or []]
+
+
+def _sfn_attrs(arn, name):
+ """Ref is the ARN; Fn::GetAtt serves Arn, Name and StateMachineRevisionId,
+ the revision the record carries (rotated by every create and update)."""
+ attrs = {"Arn": arn, "Name": name}
+ sm = _sfn._state_machines.get(arn)
+ if sm and sm.get("revisionId"):
+ attrs["StateMachineRevisionId"] = sm["revisionId"]
+ return attrs
+
+
+def _sfn_state_machine_create(logical_id, props, stack_name):
+ name = props.get("StateMachineName") or _physical_name(stack_name, logical_id, max_len=80)
+ role_arn = props.get("RoleArn", f"arn:aws:iam::{get_account_id()}:role/StepFunctionsRole")
+ definition = _sfn_definition(props)
sm_type = props.get("StateMachineType", "STANDARD")
arn = f"arn:aws:states:{get_region()}:{get_account_id()}:stateMachine:{name}"
ts = now_iso()
+ # The record mirrors what CreateStateMachine writes, revision id and
+ # version counter included, so versions published later behave the same
+ # for a template-created machine. TracingConfiguration and
+ # EncryptionConfiguration have no field in the store and are accepted
+ # without effect.
_sfn._state_machines[arn] = {
"stateMachineArn": arn,
"name": name,
@@ -5215,12 +5798,87 @@ def _sfn_state_machine_create(logical_id, props, stack_name):
"creationDate": ts,
"status": "ACTIVE",
"loggingConfiguration": props.get("LoggingConfiguration", {"level": "OFF", "includeExecutionData": False}),
+ "revisionId": new_uuid(),
+ "lastVersionNumber": 0,
+ }
+ tags = _sfn_tags(props)
+ if tags:
+ _sfn._tag_resource({"resourceArn": arn, "tags": tags})
+ return arn, _sfn_attrs(arn, name)
+
+
+def _sfn_state_machine_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update a state machine in place through UpdateStateMachine, keeping
+ its ARN (what Ref returns), its executions and its published versions.
+ StateMachineName and StateMachineType require replacement
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-stepfunctions-statemachine.html):
+ a rename creates the new machine before the old one is removed; a type
+ change under an unchanged name is refused — for a custom name by
+ _custom_named_replacement_error, as CloudFormation refuses it, and here
+ for a generated name, whose deterministic derivation cannot yield a
+ fresh identity. Definition, DefinitionSubstitutions, RoleArn,
+ LoggingConfiguration and Tags update without interruption;
+ TracingConfiguration and EncryptionConfiguration are accepted without
+ effect, the store has no field for them.
+ """
+ name = new_props.get("StateMachineName") or _physical_name(
+ stack_name, logical_id or physical_id, max_len=80
+ )
+ sm = _sfn._state_machines.get(physical_id)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ name, sm.get("name") if sm else None,
+ _sfn_state_machine_create, _sfn_state_machine_delete,
+ )
+ if replaced is not None:
+ return replaced
+
+ old_type = old_props.get("StateMachineType", "STANDARD")
+ new_type = new_props.get("StateMachineType", "STANDARD")
+ if new_type != old_type:
+ raise ValueError(
+ f"AWS::StepFunctions::StateMachine StateMachineType ({old_type} -> "
+ f"{new_type}) requires replacement, which MiniStack does not perform "
+ f"for {name}; set a StateMachineName to create the replacement."
+ )
+
+ data = {
+ "stateMachineArn": physical_id,
+ "definition": _sfn_definition(new_props),
+ "roleArn": new_props.get(
+ "RoleArn", f"arn:aws:iam::{get_account_id()}:role/StepFunctionsRole"
+ ),
}
- return arn, {"Arn": arn, "Name": name}
+ # Sent only when the template speaks to the property: declared, or
+ # dropped since the previous template, which reverts it to the default
+ # the create applies. A logging configuration set outside the stack on a
+ # machine whose template never declared one is left alone.
+ logging = _declared_or_default(old_props, new_props, {
+ "LoggingConfiguration": {"level": "OFF", "includeExecutionData": False}})
+ if logging:
+ data["loggingConfiguration"] = logging["LoggingConfiguration"]
+ resp = _sfn._update_state_machine(data)
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::StepFunctions::StateMachine update failed: {resp[2]!r}")
+
+ # Tags reconcile through TagResource / UntagResource as on AWS: keys the
+ # template dropped are removed, the rest are written in place.
+ old_tags = {t["key"]: t["value"] for t in _sfn_tags(old_props)}
+ new_tags = {t["key"]: t["value"] for t in _sfn_tags(new_props)}
+ if old_tags != new_tags:
+ dropped = sorted(old_tags.keys() - new_tags.keys())
+ if dropped:
+ _sfn._untag_resource({"resourceArn": physical_id, "tagKeys": dropped})
+ changed = [t for t in _sfn_tags(new_props) if old_tags.get(t["key"]) != t["value"]]
+ if changed:
+ _sfn._tag_resource({"resourceArn": physical_id, "tags": changed})
+ return physical_id, _sfn_attrs(physical_id, name)
def _sfn_state_machine_delete(physical_id, props):
_sfn._state_machines.pop(physical_id, None)
+ _sfn._tags.pop(physical_id, None)
# ---------------------------------------------------------------------------
@@ -5558,13 +6216,15 @@ def _r53_record_set_delete(physical_id, props):
# ---------------------------------------------------------------------------
-def _cw_metric_alarm_create(logical_id, props, stack_name):
+def _cw_metric_alarm_record(name, props):
+ """The PutMetricAlarm-shaped record for a template's alarm properties.
+ An existing alarm of that name keeps its state: CloudFormation leaves
+ the state untouched on update and only rewrites the configuration."""
if props.get("Metrics"):
raise ValueError(
"AWS::CloudWatch::Alarm Properties.Metrics (metric math) is not supported; "
"use MetricName and Namespace."
)
- name = props.get("AlarmName") or _physical_name(stack_name, logical_id, max_len=255)
metric_name = props.get("MetricName")
namespace = props.get("Namespace")
if not metric_name or not namespace:
@@ -5625,7 +6285,9 @@ def _cw_metric_alarm_create(logical_id, props, stack_name):
"StateReason": _cw._alarms[name]["StateReason"]
if name in _cw._alarms
else "Unchecked: Initial alarm creation",
- "StateUpdatedTimestamp": int(time.time()),
+ "StateUpdatedTimestamp": _cw._alarms[name].get("StateUpdatedTimestamp", int(time.time()))
+ if name in _cw._alarms
+ else int(time.time()),
"ActionsEnabled": ae,
"AlarmActions": alarm_actions,
"OKActions": ok_actions,
@@ -5634,9 +6296,50 @@ def _cw_metric_alarm_create(logical_id, props, stack_name):
"Unit": props.get("Unit"),
"AlarmConfigurationUpdatedTimestamp": int(time.time()),
}
+ return alarm
+
+
+def _cw_metric_alarm_put(name, props):
+ """Create or overwrite the alarm and apply the template's Tags. Every
+ property but AlarmName is "No interruption", so create and update run the
+ same path; Tags go through the tag store because PutMetricAlarm ignores
+ Tags on an existing alarm (its reference: "To change the tags of an
+ existing alarm, use TagResource or UntagResource")."""
+ alarm = _cw_metric_alarm_record(name, props)
_cw.cloudformation_put_metric_alarm(alarm)
- arn = alarm["AlarmArn"]
- return name, {"Arn": arn}
+ tags = props.get("Tags") or []
+ _cw.cloudformation_set_metric_alarm_tags(
+ name, [t for t in tags if isinstance(t, dict) and t.get("Key")]
+ )
+ return name, {"Arn": alarm["AlarmArn"]}
+
+
+def _cw_metric_alarm_create(logical_id, props, stack_name):
+ name = props.get("AlarmName") or _physical_name(stack_name, logical_id, max_len=255)
+ return _cw_metric_alarm_put(name, props)
+
+
+def _cw_metric_alarm_update(physical_id, old_props, new_props, stack_name,
+ logical_id=None):
+ """Update an alarm in place as PutMetricAlarm does: the configuration is
+ rewritten under the same name (what Ref returns) and the alarm state and
+ history stay. AlarmName is the one property with "Update requires:
+ Replacement"
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudwatch-alarm.html):
+ a rename creates the new alarm before the old one is removed. An alarm
+ deleted behind CloudFormation's back is recreated the same way.
+ """
+ name = new_props.get("AlarmName") or _physical_name(
+ stack_name, logical_id or physical_id, max_len=255
+ )
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ name, physical_id if physical_id in _cw._alarms else None,
+ _cw_metric_alarm_create, _cw_metric_alarm_delete,
+ )
+ if replaced is not None:
+ return replaced
+ return _cw_metric_alarm_put(name, new_props)
def _cw_metric_alarm_delete(physical_id, props):
@@ -7024,7 +7727,12 @@ _RESOURCE_HANDLERS = {
"update_with_logical_id": True,
"delete": _iam_role_delete,
},
- "AWS::IAM::Policy": {"create": _iam_policy_create, "delete": _iam_policy_delete},
+ "AWS::IAM::Policy": {
+ "create": _iam_policy_create,
+ "update": _iam_policy_update,
+ "update_with_logical_id": True,
+ "delete": _iam_policy_delete,
+ },
"AWS::IAM::InstanceProfile": {"create": _iam_ip_create, "delete": _iam_ip_delete},
"AWS::SSM::Parameter": {"create": _ssm_create, "update": _ssm_update, "delete": _ssm_delete},
"AWS::AppConfig::Application": {
@@ -7063,7 +7771,12 @@ _RESOURCE_HANDLERS = {
"delete": _cwlogs_resource_policy_delete,
},
"AWS::Logs::SubscriptionFilter": {"create": _cwlogs_subfilter_create, "delete": _cwlogs_subfilter_delete},
- "AWS::Events::Rule": {"create": _eb_rule_create, "delete": _eb_rule_delete},
+ "AWS::Events::Rule": {
+ "create": _eb_rule_create,
+ "update": _eb_rule_update,
+ "update_with_logical_id": True,
+ "delete": _eb_rule_delete,
+ },
"AWS::Events::EventBus": {"create": _eb_event_bus_create, "delete": _eb_event_bus_delete},
"AWS::Kinesis::Stream": {"create": _kinesis_stream_create, "delete": _kinesis_stream_delete},
"AWS::KinesisFirehose::DeliveryStream": {
@@ -7071,7 +7784,13 @@ _RESOURCE_HANDLERS = {
"update": _firehose_delivery_stream_update,
"delete": _firehose_delivery_stream_delete,
},
- "AWS::Lambda::Permission": {"create": _lambda_permission_create, "delete": _lambda_permission_delete},
+ "AWS::Lambda::Permission": {
+ "create": _lambda_permission_create,
+ "update": _lambda_permission_update,
+ "update_with_logical_id": True,
+ "delete": _lambda_permission_delete,
+ "delete_with_logical_id": True,
+ },
"AWS::Lambda::Version": {"create": _lambda_version_create, "delete": _lambda_version_delete},
"AWS::CloudFormation::WaitCondition": {"create": _cfn_wait_condition_create, "delete": _cfn_noop_delete},
"AWS::CloudFormation::WaitConditionHandle": {"create": _cfn_wait_condition_handle_create, "delete": _cfn_noop_delete},
@@ -7180,12 +7899,37 @@ _RESOURCE_HANDLERS = {
"AWS::AppSync::Resolver": {"create": _appsync_resolver_create, "delete": _appsync_resolver_delete},
"AWS::AppSync::GraphQLSchema": {"create": _appsync_schema_create, "delete": _appsync_schema_delete},
"AWS::AppSync::ApiKey": {"create": _appsync_apikey_create, "delete": _appsync_apikey_delete},
- "AWS::SecretsManager::Secret": {"create": _sm_secret_create, "delete": _sm_secret_delete},
- "AWS::Cognito::UserPool": {"create": _cognito_user_pool_create, "delete": _cognito_user_pool_delete},
- "AWS::Cognito::UserPoolClient": {"create": _cognito_user_pool_client_create, "delete": _cognito_user_pool_client_delete},
+ "AWS::SecretsManager::Secret": {
+ "create": _sm_secret_create,
+ "update": _sm_secret_update,
+ "update_with_logical_id": True,
+ "delete": _sm_secret_delete,
+ },
+ "AWS::Cognito::UserPool": {
+ "create": _cognito_user_pool_create,
+ "update": _cognito_user_pool_update,
+ "update_with_logical_id": True,
+ "delete": _cognito_user_pool_delete,
+ },
+ "AWS::Cognito::UserPoolClient": {
+ "create": _cognito_user_pool_client_create,
+ "update": _cognito_user_pool_client_update,
+ "update_with_logical_id": True,
+ "delete": _cognito_user_pool_client_delete,
+ },
"AWS::Cognito::UserPoolResourceServer": {"create": _cognito_user_pool_resource_server_create, "delete": _cognito_user_pool_resource_server_delete},
- "AWS::Cognito::UserPoolGroup": {"create": _cognito_user_pool_group_create, "delete": _cognito_user_pool_group_delete},
- "AWS::Cognito::IdentityPool": {"create": _cognito_identity_pool_create, "delete": _cognito_identity_pool_delete},
+ "AWS::Cognito::UserPoolGroup": {
+ "create": _cognito_user_pool_group_create,
+ "update": _cognito_user_pool_group_update,
+ "update_with_logical_id": True,
+ "delete": _cognito_user_pool_group_delete,
+ },
+ "AWS::Cognito::IdentityPool": {
+ "create": _cognito_identity_pool_create,
+ "update": _cognito_identity_pool_update,
+ "update_with_logical_id": True,
+ "delete": _cognito_identity_pool_delete,
+ },
"AWS::Cognito::UserPoolDomain": {"create": _cognito_user_pool_domain_create, "delete": _cognito_user_pool_domain_delete},
"AWS::ECR::Repository": {"create": _ecr_repo_create, "delete": _ecr_repo_delete},
"AWS::CertificateManager::Certificate": {"create": _acm_certificate_create, "delete": _acm_certificate_delete},
@@ -7228,7 +7972,12 @@ _RESOURCE_HANDLERS = {
"create": _lambda_layer_version_permission_create,
"delete": _lambda_layer_version_permission_delete,
},
- "AWS::StepFunctions::StateMachine": {"create": _sfn_state_machine_create, "delete": _sfn_state_machine_delete},
+ "AWS::StepFunctions::StateMachine": {
+ "create": _sfn_state_machine_create,
+ "update": _sfn_state_machine_update,
+ "update_with_logical_id": True,
+ "delete": _sfn_state_machine_delete,
+ },
"AWS::Route53::HostedZone": {"create": _r53_hosted_zone_create, "delete": _r53_hosted_zone_delete},
"AWS::Route53::RecordSet": {"create": _r53_record_set_create, "delete": _r53_record_set_delete},
"AWS::ApiGatewayV2::Api": {"create": _apigw_v2_api_create, "delete": _apigw_v2_api_delete},
@@ -7247,7 +7996,12 @@ _RESOURCE_HANDLERS = {
},
"AWS::CloudFront::Distribution": {"create": _cf_distribution_create, "delete": _cf_distribution_delete},
"AWS::CloudFront::KeyValueStore": {"create": _cf_kvs_create, "update": _cf_kvs_update, "delete": _cf_kvs_delete},
- "AWS::CloudWatch::Alarm": {"create": _cw_metric_alarm_create, "delete": _cw_metric_alarm_delete},
+ "AWS::CloudWatch::Alarm": {
+ "create": _cw_metric_alarm_create,
+ "update": _cw_metric_alarm_update,
+ "update_with_logical_id": True,
+ "delete": _cw_metric_alarm_delete,
+ },
"AWS::CloudWatch::Dashboard": {
"create": _cw_dashboard_create,
"update": _cw_dashboard_update,
diff --git a/ministack/services/cloudwatch.py b/ministack/services/cloudwatch.py
index 8455d63c..72948cf7 100644
--- a/ministack/services/cloudwatch.py
+++ b/ministack/services/cloudwatch.py
@@ -920,7 +920,9 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):
"StateReason": _alarms[name]["StateReason"]
if name in _alarms
else "Unchecked: Initial alarm creation",
- "StateUpdatedTimestamp": int(time.time()),
+ "StateUpdatedTimestamp": _alarms[name].get("StateUpdatedTimestamp", int(time.time()))
+ if name in _alarms
+ else int(time.time()),
"ActionsEnabled": cbor_data.get("ActionsEnabled", True),
"AlarmActions": cbor_data.get("AlarmActions", []),
"OKActions": cbor_data.get("OKActions", []),
@@ -975,7 +977,9 @@ def _put_metric_alarm(params, cbor_data, is_cbor, is_json=False):
"StateReason": _alarms[name]["StateReason"]
if name in _alarms
else "Unchecked: Initial alarm creation",
- "StateUpdatedTimestamp": int(time.time()),
+ "StateUpdatedTimestamp": _alarms[name].get("StateUpdatedTimestamp", int(time.time()))
+ if name in _alarms
+ else int(time.time()),
"ActionsEnabled": _p(params, "ActionsEnabled") != "false",
"AlarmActions": alarm_actions,
"OKActions": ok_actions,
@@ -1802,6 +1806,15 @@ def cloudformation_put_metric_alarm(alarm: dict) -> None:
_evaluate_alarm(alarm)
+def cloudformation_set_metric_alarm_tags(name: str, tags: list) -> None:
+ """Replace the tag set of a metric alarm created from a template. PutMetricAlarm
+ ignores Tags on an existing alarm, so a template's Tags are applied the way
+ CloudFormation does it: the full set replaces what is there (TagResource for
+ what is declared, UntagResource for what was dropped)."""
+ arn = f"arn:aws:cloudwatch:{get_region()}:{get_account_id()}:alarm:{name}"
+ _resource_tags[arn] = {t["Key"]: t.get("Value", "") for t in tags}
+
+
def cloudformation_delete_metric_alarm(name: str) -> None:
"""Remove a metric alarm created from a template (not composite alarms)."""
_alarms.pop(name, None)
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index 15115e7f..36cb4a1a 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -2344,6 +2344,10 @@ def _update_user_pool(data):
"AdminCreateUserConfig", "UserPoolAddOns", "VerificationMessageTemplate",
"AccountRecoverySetting", "LambdaConfig",
"UserAttributeUpdateSettings",
+ # Deletion protection is switched off through UpdateUserPool before a
+ # protected pool can be deleted (per the DeletionProtection property
+ # on the CloudFormation resource reference).
+ "DeletionProtection",
}
for k in updatable:
if k in data:
diff --git a/ministack/services/iam.py b/ministack/services/iam.py
index 32aca4ea..953143a1 100644
--- a/ministack/services/iam.py
+++ b/ministack/services/iam.py
@@ -693,6 +693,36 @@ def store_policy(arn: str, name: str, path: str, document, *,
return record
+def rename_policy(old_arn: str, new_arn: str, new_name: str) -> dict:
+ """Re-key a customer-managed policy record under a new ARN and name.
+
+ Everything else about the record stays — PolicyId, Versions,
+ DefaultVersionId, CreateDate, AttachmentCount — and every role, user and
+ group that holds the old ARN in ``AttachedPolicies`` is rewritten to the
+ new one, so ListAttachedRolePolicies, ListEntitiesForPolicy and
+ GetAccountAuthorizationDetails keep resolving the attachment. Used by the
+ CloudFormation provisioner for a PolicyName change, which AWS applies
+ without replacing the resource.
+ """
+ if new_arn == old_arn:
+ record = _policies[old_arn]
+ record["PolicyName"] = new_name
+ return record
+ if new_arn in _policies:
+ raise ValueError(f"A policy called {new_name} already exists.")
+ record = _policies.pop(old_arn)
+ record["PolicyName"] = new_name
+ record["Arn"] = new_arn
+ record["UpdateDate"] = _now()
+ _policies[new_arn] = record
+ for store in (_roles, _users, _groups):
+ for entity in store.values():
+ attached = entity.get("AttachedPolicies") or []
+ if old_arn in attached:
+ attached[attached.index(old_arn)] = new_arn
+ return record
+
+
def _create_policy(p):
name = _p(p, "PolicyName")
path = _p(p, "Path") or "/"
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index f6d07054..0942fc1e 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -5650,6 +5650,15 @@ def _add_permission(
condition.setdefault("StringEquals", {})["aws:PrincipalOrgID"] = data["PrincipalOrgID"]
if "FunctionUrlAuthType" in data:
condition.setdefault("StringEquals", {})["lambda:FunctionUrlAuthType"] = data["FunctionUrlAuthType"]
+ if "EventSourceToken" in data:
+ condition.setdefault("StringEquals", {})["lambda:EventSourceToken"] = data["EventSourceToken"]
+ if "InvokedViaFunctionUrl" in data:
+ # Lambda writes this one as a Bool condition with a string value
+ # (https://docs.aws.amazon.com/lambda/latest/dg/urls-auth.html).
+ invoked = data["InvokedViaFunctionUrl"]
+ if not isinstance(invoked, bool):
+ invoked = str(invoked).lower() == "true"
+ condition["Bool"] = {"lambda:InvokedViaFunctionUrl": "true" if invoked else "false"}
if condition:
statement["Condition"] = condition
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 688c9989..283009f7 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -87,6 +87,17 @@ def _delete_cfn_test_stack(cfn, stack_name):
pass
+def _output(stack, key):
+ return next(o["OutputValue"] for o in stack["Outputs"] if o["OutputKey"] == key)
+
+
+def _stack_event_reasons(cfn, stack_name):
+ return " ".join(
+ e.get("ResourceStatusReason", "")
+ for e in cfn.describe_stack_events(StackName=stack_name)["StackEvents"]
+ )
+
+
def test_cfn_region_scopes_stacks_change_sets_and_events():
suffix = _uuid_mod.uuid4().hex[:8]
stack_name = f"cfn-regional-{suffix}"
@@ -10898,6 +10909,2758 @@ def test_cfn_cognito_user_pool_enabled_mfas(cfn, cognito_idp):
_wait_stack(cfn, "cfn-enabled-mfas")
+def test_cfn_events_rule_arn_matches_the_service(cfn, eb):
+ """GetAtt Arn on a rule is the ARN the EventBridge service reports for
+ it: no bus segment on the default bus, rule/<bus>/<name> on a custom
+ bus. The provisioner used to put a default/ segment in that the service
+ itself never produces."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-rule-arn-{uid}"
+ bus_name = f"cfn-rule-arn-bus-{uid}"
+ default_rule, bus_rule = f"cfn-rule-arn-def-{uid}", f"cfn-rule-arn-on-bus-{uid}"
+ template = json.dumps({
+ "Resources": {
+ "Bus": {"Type": "AWS::Events::EventBus", "Properties": {"Name": bus_name}},
+ "OnDefault": {"Type": "AWS::Events::Rule", "Properties": {
+ "Name": default_rule, "ScheduleExpression": "rate(1 hour)"}},
+ "OnBus": {"Type": "AWS::Events::Rule", "Properties": {
+ "Name": bus_rule, "EventBusName": {"Ref": "Bus"},
+ "EventPattern": {"source": ["cfn.test"]}}},
+ },
+ "Outputs": {"DefaultArn": {"Value": {"Fn::GetAtt": ["OnDefault", "Arn"]}},
+ "BusArn": {"Value": {"Fn::GetAtt": ["OnBus", "Arn"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}
+ prefix = f"arn:aws:events:{eb.meta.region_name}:000000000000:rule/"
+
+ assert outputs["DefaultArn"] == f"{prefix}{default_rule}"
+ assert outputs["DefaultArn"] == eb.describe_rule(Name=default_rule)["Arn"]
+ assert outputs["BusArn"] == f"{prefix}{bus_name}/{bus_rule}"
+ assert outputs["BusArn"] == eb.describe_rule(Name=bus_rule, EventBusName=bus_name)["Arn"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cognito_user_pool_name_is_the_userpoolname_property(cfn, cognito_idp):
+ """UserPoolName is the template property the resource reference defines;
+ DescribeUserPool reports it. PoolName, the API's name for the same
+ thing, stays accepted for templates written against MiniStack."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-poolname-{uid}"
+ template = json.dumps({
+ "Resources": {
+ "Named": {"Type": "AWS::Cognito::UserPool",
+ "Properties": {"UserPoolName": f"cfn-named-pool-{uid}"}},
+ "Legacy": {"Type": "AWS::Cognito::UserPool",
+ "Properties": {"PoolName": f"cfn-legacy-pool-{uid}"}},
+ },
+ "Outputs": {"NamedId": {"Value": {"Ref": "Named"}},
+ "LegacyId": {"Value": {"Ref": "Legacy"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}
+
+ named = cognito_idp.describe_user_pool(UserPoolId=outputs["NamedId"])["UserPool"]
+ assert named["Name"] == f"cfn-named-pool-{uid}"
+ legacy = cognito_idp.describe_user_pool(UserPoolId=outputs["LegacyId"])["UserPool"]
+ assert legacy["Name"] == f"cfn-legacy-pool-{uid}"
+ listed, token = {}, None
+ while True:
+ page = cognito_idp.list_user_pools(MaxResults=60, **({"NextToken": token} if token else {}))
+ listed.update({p["Id"]: p["Name"] for p in page["UserPools"]})
+ token = page.get("NextToken")
+ if not token:
+ break
+ assert listed[outputs["NamedId"]] == f"cfn-named-pool-{uid}"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _user_pool_ids_named(cognito_idp, name):
+ ids, token = [], None
+ while True:
+ page = cognito_idp.list_user_pools(MaxResults=60, **({"NextToken": token} if token else {}))
+ ids += [p["Id"] for p in page["UserPools"] if p["Name"] == name]
+ token = page.get("NextToken")
+ if not token:
+ return ids
+
+
+def test_cfn_cognito_user_pool_update_keeps_id_and_users(cfn, cognito_idp):
+ """Changing MfaConfiguration and the password policy updates the pool in
+ place: same pool id, the user created before the update is still there,
+ and DescribeUserPool reports the new settings."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-pool-upd-{uid}"
+
+ def template(mfa, min_len):
+ return json.dumps({
+ "Resources": {"Pool": {"Type": "AWS::Cognito::UserPool", "Properties": {
+ "UserPoolName": f"cfn-pool-upd-{uid}",
+ "MfaConfiguration": mfa,
+ "Policies": {"PasswordPolicy": {"MinimumLength": min_len}},
+ }}},
+ "Outputs": {"PoolId": {"Value": {"Ref": "Pool"}},
+ "PoolArn": {"Value": {"Fn::GetAtt": ["Pool", "Arn"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("OFF", 8))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ pool_id, pool_arn = _output(stack, "PoolId"), _output(stack, "PoolArn")
+ assert cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"]["Name"] == (
+ f"cfn-pool-upd-{uid}"
+ )
+ cognito_idp.admin_create_user(UserPoolId=pool_id, Username="alice")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("OPTIONAL", 12))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "PoolId") == pool_id
+ assert _output(stack, "PoolArn") == pool_arn
+
+ pool = cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"]
+ assert pool["MfaConfiguration"] == "OPTIONAL"
+ assert pool["Policies"]["PasswordPolicy"]["MinimumLength"] == 12
+ users = cognito_idp.list_users(UserPoolId=pool_id)["Users"]
+ assert [u["Username"] for u in users] == ["alice"]
+ assert _user_pool_ids_named(cognito_idp, f"cfn-pool-upd-{uid}") == [pool_id]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cognito_user_pool_rename_keeps_id_and_users(cfn, cognito_idp):
+ """UserPoolName updates without interruption per the resource reference:
+ the pool keeps its id and its users and DescribeUserPool reports the
+ new name."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-pool-ren-{uid}"
+
+ def template(name):
+ return json.dumps({
+ "Resources": {"Pool": {"Type": "AWS::Cognito::UserPool",
+ "Properties": {"UserPoolName": name}}},
+ "Outputs": {"PoolId": {"Value": {"Ref": "Pool"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(f"cfn-pool-a-{uid}"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ pool_id = _output(stack, "PoolId")
+ cognito_idp.admin_create_user(UserPoolId=pool_id, Username="alice")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(f"cfn-pool-b-{uid}"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "PoolId") == pool_id
+ assert cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"]["Name"] == (
+ f"cfn-pool-b-{uid}"
+ )
+ users = cognito_idp.list_users(UserPoolId=pool_id)["Users"]
+ assert [u["Username"] for u in users] == ["alice"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
[email protected]("prop", ["AliasAttributes", "UsernameAttributes"])
+def test_cfn_cognito_user_pool_sign_in_attributes_change_fails_loudly(cfn, cognito_idp, prop):
+ """AliasAttributes and UsernameAttributes are fixed at CreateUserPool and
+ no API call changes them afterwards, so MiniStack refuses the update
+ instead of altering the record: the stack rolls back, the pool keeps
+ its id, its users and its sign-in settings."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-pool-attr-{uid}"
+
+ def template(attributes):
+ props = {"UserPoolName": f"cfn-pool-attr-{uid}"}
+ if attributes:
+ props[prop] = attributes
+ return json.dumps({
+ "Resources": {"Pool": {"Type": "AWS::Cognito::UserPool", "Properties": props}},
+ "Outputs": {"PoolId": {"Value": {"Ref": "Pool"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(None))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ pool_id = _output(stack, "PoolId")
+ cognito_idp.admin_create_user(UserPoolId=pool_id, Username="alice")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(["email"]))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ assert f"AWS::Cognito::UserPool {prop} is set at CreateUserPool" in _stack_event_reasons(cfn, stack_name)
+ assert _output(stack, "PoolId") == pool_id
+
+ pool = cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"]
+ assert pool.get(prop, []) == []
+ users = cognito_idp.list_users(UserPoolId=pool_id)["Users"]
+ assert [u["Username"] for u in users] == ["alice"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cognito_user_pool_client_update_keeps_client_id(cfn, cognito_idp):
+ """ClientName and CallbackURLs update in place through
+ UpdateUserPoolClient; Ref keeps returning the same ClientId."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-client-upd-{uid}"
+
+ def template(client_name, callbacks):
+ props = {"UserPoolId": {"Ref": "Pool"}, "ClientName": client_name,
+ "ExplicitAuthFlows": ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"]}
+ if callbacks:
+ props["CallbackURLs"] = callbacks
+ return json.dumps({
+ "Resources": {
+ "Pool": {"Type": "AWS::Cognito::UserPool",
+ "Properties": {"UserPoolName": f"cfn-client-pool-{uid}"}},
+ "Client": {"Type": "AWS::Cognito::UserPoolClient", "Properties": props},
+ },
+ "Outputs": {"PoolId": {"Value": {"Ref": "Pool"}},
+ "ClientId": {"Value": {"Ref": "Client"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("app-v1", None))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ pool_id, client_id = _output(stack, "PoolId"), _output(stack, "ClientId")
+
+ cfn.update_stack(
+ StackName=stack_name,
+ TemplateBody=template("app-v2", ["https://example.com/callback"]),
+ )
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "ClientId") == client_id
+
+ client = cognito_idp.describe_user_pool_client(
+ UserPoolId=pool_id, ClientId=client_id
+ )["UserPoolClient"]
+ assert client["ClientName"] == "app-v2"
+ assert client["CallbackURLs"] == ["https://example.com/callback"]
+ assert client["ExplicitAuthFlows"] == ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"]
+ clients = cognito_idp.list_user_pool_clients(UserPoolId=pool_id, MaxResults=60)
+ assert [c["ClientId"] for c in clients["UserPoolClients"]] == [client_id]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cognito_user_pool_client_generate_secret_change_replaces_the_client(cfn, cognito_idp):
+ """GenerateSecret requires replacement: the new client is created before
+ the old one is removed, Ref moves to the new ClientId, and the new
+ client carries the secret. The pool lives outside the stack, so the
+ stack delete leaves it alone."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-client-repl-{uid}"
+ pool_id = cognito_idp.create_user_pool(PoolName=f"cfn-client-repl-pool-{uid}")["UserPool"]["Id"]
+
+ def template(generate_secret):
+ return json.dumps({
+ "Resources": {"Client": {"Type": "AWS::Cognito::UserPoolClient", "Properties": {
+ "UserPoolId": pool_id, "ClientName": "app",
+ "GenerateSecret": generate_secret}}},
+ "Outputs": {"ClientId": {"Value": {"Ref": "Client"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(False))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ client_id = _output(stack, "ClientId")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(True))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ new_id = _output(stack, "ClientId")
+ assert new_id != client_id
+ clients = cognito_idp.list_user_pool_clients(UserPoolId=pool_id, MaxResults=60)
+ assert [c["ClientId"] for c in clients["UserPoolClients"]] == [new_id]
+ client = cognito_idp.describe_user_pool_client(
+ UserPoolId=pool_id, ClientId=new_id
+ )["UserPoolClient"]
+ assert client["ClientSecret"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ cognito_idp.delete_user_pool(UserPoolId=pool_id)
+
+
+def test_cfn_cognito_user_pool_client_pool_move_replaces_the_client(cfn, cognito_idp):
+ """UserPoolId requires replacement: the client is created in the new
+ pool before the old one is removed from the old pool, and Ref moves to
+ the new ClientId. The pools live outside the stack."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-client-move-{uid}"
+ pool_a = cognito_idp.create_user_pool(PoolName=f"cfn-client-move-a-{uid}")["UserPool"]["Id"]
+ pool_b = cognito_idp.create_user_pool(PoolName=f"cfn-client-move-b-{uid}")["UserPool"]["Id"]
+
+ def template(pool_id):
+ return json.dumps({
+ "Resources": {"Client": {"Type": "AWS::Cognito::UserPoolClient", "Properties": {
+ "UserPoolId": pool_id, "ClientName": "app"}}},
+ "Outputs": {"ClientId": {"Value": {"Ref": "Client"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(pool_a))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ client_id = _output(stack, "ClientId")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(pool_b))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ new_id = _output(stack, "ClientId")
+ assert new_id != client_id
+ assert cognito_idp.list_user_pool_clients(UserPoolId=pool_a, MaxResults=60)["UserPoolClients"] == []
+ clients = cognito_idp.list_user_pool_clients(UserPoolId=pool_b, MaxResults=60)
+ assert [c["ClientId"] for c in clients["UserPoolClients"]] == [new_id]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ left = cognito_idp.list_user_pool_clients(UserPoolId=pool_b, MaxResults=60)["UserPoolClients"]
+ for pool_id in (pool_a, pool_b):
+ cognito_idp.delete_user_pool(UserPoolId=pool_id)
+ assert left == []
+
+
+def test_cfn_cognito_user_pool_dropped_property_reverts_to_default(cfn, cognito_idp):
+ """A property the new template no longer declares reverts to the default
+ the create handler applies, as CloudFormation does: MfaConfiguration
+ goes back to OFF and AutoVerifiedAttributes is cleared, while the pool
+ keeps its id and its user."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-pool-drop-{uid}"
+
+ def template(declared):
+ props = {"UserPoolName": f"cfn-pool-drop-{uid}"}
+ if declared:
+ props["MfaConfiguration"] = "OPTIONAL"
+ props["AutoVerifiedAttributes"] = ["email"]
+ return json.dumps({
+ "Resources": {"Pool": {"Type": "AWS::Cognito::UserPool", "Properties": props}},
+ "Outputs": {"PoolId": {"Value": {"Ref": "Pool"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(True))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ pool_id = _output(stack, "PoolId")
+ pool = cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"]
+ assert pool["MfaConfiguration"] == "OPTIONAL"
+ assert pool["AutoVerifiedAttributes"] == ["email"]
+ cognito_idp.admin_create_user(UserPoolId=pool_id, Username="alice")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(False))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "PoolId") == pool_id
+ pool = cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"]
+ assert pool["MfaConfiguration"] == "OFF"
+ assert pool.get("AutoVerifiedAttributes", []) == []
+ users = cognito_idp.list_users(UserPoolId=pool_id)["Users"]
+ assert [u["Username"] for u in users] == ["alice"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cognito_identity_pool_update_keeps_id_and_roles(cfn, cognito_identity):
+ """AllowUnauthenticatedIdentities flips in place through
+ UpdateIdentityPool: same IdentityPoolId, and the role mapping set outside
+ the template survives."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-idp-upd-{uid}"
+
+ def template(allow_unauth):
+ return json.dumps({
+ "Resources": {"IdPool": {"Type": "AWS::Cognito::IdentityPool", "Properties": {
+ "IdentityPoolName": f"cfn_idp_upd_{uid}",
+ "AllowUnauthenticatedIdentities": allow_unauth,
+ }}},
+ "Outputs": {"PoolId": {"Value": {"Ref": "IdPool"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(False))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ pool_id = _output(stack, "PoolId")
+ cognito_identity.set_identity_pool_roles(
+ IdentityPoolId=pool_id,
+ Roles={"authenticated": "arn:aws:iam::000000000000:role/auth-upd"},
+ )
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(True))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "PoolId") == pool_id
+
+ pool = cognito_identity.describe_identity_pool(IdentityPoolId=pool_id)
+ assert pool["AllowUnauthenticatedIdentities"] is True
+ assert pool["IdentityPoolName"] == f"cfn_idp_upd_{uid}"
+ roles = cognito_identity.get_identity_pool_roles(IdentityPoolId=pool_id)["Roles"]
+ assert roles == {"authenticated": "arn:aws:iam::000000000000:role/auth-upd"}
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cognito_user_pool_group_update_keeps_members(cfn, cognito_idp):
+ """Description and Precedence update the group in place: Ref still
+ returns the group name and the user added to the group stays a member."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-group-upd-{uid}"
+
+ def template(description, precedence):
+ return json.dumps({
+ "Resources": {
+ "Pool": {"Type": "AWS::Cognito::UserPool",
+ "Properties": {"UserPoolName": f"cfn-group-upd-pool-{uid}"}},
+ "Group": {"Type": "AWS::Cognito::UserPoolGroup", "Properties": {
+ "UserPoolId": {"Ref": "Pool"}, "GroupName": "admins",
+ "Description": description, "Precedence": precedence}},
+ },
+ "Outputs": {"PoolId": {"Value": {"Ref": "Pool"}},
+ "GroupRef": {"Value": {"Ref": "Group"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("Administrators", 1))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ pool_id = _output(stack, "PoolId")
+ cognito_idp.admin_create_user(UserPoolId=pool_id, Username="alice")
+ cognito_idp.admin_add_user_to_group(UserPoolId=pool_id, Username="alice", GroupName="admins")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("Platform admins", 5))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "GroupRef") == "admins"
+
+ group = cognito_idp.get_group(UserPoolId=pool_id, GroupName="admins")["Group"]
+ assert group["Description"] == "Platform admins"
+ assert group["Precedence"] == 5
+ members = cognito_idp.list_users_in_group(UserPoolId=pool_id, GroupName="admins")["Users"]
+ assert [u["Username"] for u in members] == ["alice"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cognito_user_pool_group_rename_replaces_the_group(cfn, cognito_idp):
+ """GroupName requires replacement: the renamed group is created before
+ the old one is removed, and Ref follows the new name."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-group-ren-{uid}"
+
+ def template(group_name):
+ return json.dumps({
+ "Resources": {
+ "Pool": {"Type": "AWS::Cognito::UserPool",
+ "Properties": {"UserPoolName": f"cfn-group-ren-pool-{uid}"}},
+ "Group": {"Type": "AWS::Cognito::UserPoolGroup", "Properties": {
+ "UserPoolId": {"Ref": "Pool"}, "GroupName": group_name}},
+ },
+ "Outputs": {"PoolId": {"Value": {"Ref": "Pool"}},
+ "GroupRef": {"Value": {"Ref": "Group"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("admins"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ pool_id = _output(stack, "PoolId")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("operators"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "GroupRef") == "operators"
+ groups = cognito_idp.list_groups(UserPoolId=pool_id)["Groups"]
+ assert [g["GroupName"] for g in groups] == ["operators"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cognito_user_pool_group_move_under_custom_name_fails_loudly(cfn, cognito_idp):
+ """UserPoolId requires replacement, which CloudFormation refuses for a
+ custom-named group: the stack rolls back and the group stays in its
+ pool with its members. The pools live outside the stack, so the
+ rollback has nothing else to undo."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-group-move-{uid}"
+ pool_a = cognito_idp.create_user_pool(PoolName=f"cfn-group-move-a-{uid}")["UserPool"]["Id"]
+ pool_b = cognito_idp.create_user_pool(PoolName=f"cfn-group-move-b-{uid}")["UserPool"]["Id"]
+
+ def template(pool_id):
+ return json.dumps({
+ "Resources": {"Group": {"Type": "AWS::Cognito::UserPoolGroup", "Properties": {
+ "UserPoolId": pool_id, "GroupName": "admins"}}},
+ "Outputs": {"GroupRef": {"Value": {"Ref": "Group"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(pool_a))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ cognito_idp.admin_create_user(UserPoolId=pool_a, Username="alice")
+ cognito_idp.admin_add_user_to_group(UserPoolId=pool_a, Username="alice", GroupName="admins")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(pool_b))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ assert "custom-named resource requires replacing" in _stack_event_reasons(cfn, stack_name)
+ assert _output(stack, "GroupRef") == "admins"
+
+ members = cognito_idp.list_users_in_group(UserPoolId=pool_a, GroupName="admins")["Users"]
+ assert [u["Username"] for u in members] == ["alice"]
+ assert cognito_idp.list_groups(UserPoolId=pool_b)["Groups"] == []
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ for pool_id in (pool_a, pool_b):
+ cognito_idp.delete_user_pool(UserPoolId=pool_id)
+
+
+def test_cfn_cognito_user_pool_client_dropped_properties_revert_to_defaults(cfn, cognito_idp):
+ """A client property the new template drops goes back to the default
+ CreateUserPoolClient applies ("If you don't specify a value for a
+ parameter, Amazon Cognito sets it to a default value" on the resource
+ reference): the callback list empties, PreventUserExistenceErrors is
+ LEGACY again and RefreshTokenValidity is the service default, while
+ Ref keeps the ClientId."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-client-drop-{uid}"
+
+ def template(declared):
+ props = {"UserPoolId": {"Ref": "Pool"}, "ClientName": "app"}
+ if declared:
+ props.update({"CallbackURLs": ["https://example.com/cb"],
+ "PreventUserExistenceErrors": "ENABLED",
+ "RefreshTokenValidity": 10})
+ return json.dumps({
+ "Resources": {
+ "Pool": {"Type": "AWS::Cognito::UserPool",
+ "Properties": {"UserPoolName": f"cfn-client-drop-pool-{uid}"}},
+ "Client": {"Type": "AWS::Cognito::UserPoolClient", "Properties": props},
+ },
+ "Outputs": {"PoolId": {"Value": {"Ref": "Pool"}},
+ "ClientId": {"Value": {"Ref": "Client"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(True))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ pool_id, client_id = _output(stack, "PoolId"), _output(stack, "ClientId")
+ client = cognito_idp.describe_user_pool_client(
+ UserPoolId=pool_id, ClientId=client_id
+ )["UserPoolClient"]
+ assert client["CallbackURLs"] == ["https://example.com/cb"]
+ assert client["PreventUserExistenceErrors"] == "ENABLED"
+ assert client["RefreshTokenValidity"] == 10
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(False))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "ClientId") == client_id
+ client = cognito_idp.describe_user_pool_client(
+ UserPoolId=pool_id, ClientId=client_id
+ )["UserPoolClient"]
+ assert client.get("CallbackURLs", []) == []
+ assert client["PreventUserExistenceErrors"] == "LEGACY"
+ assert client["RefreshTokenValidity"] == 30
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cognito_user_pool_client_replacement_carries_the_template_over(cfn, cognito_idp):
+ """The replacement a GenerateSecret change forces creates the new client
+ from the whole template: token validity, PreventUserExistenceErrors and
+ the OAuth settings arrive on the new ClientId, not only the six
+ properties the old create handler copied."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-client-carry-{uid}"
+ pool_id = cognito_idp.create_user_pool(PoolName=f"cfn-client-carry-pool-{uid}")["UserPool"]["Id"]
+
+ def template(generate_secret):
+ return json.dumps({
+ "Resources": {"Client": {"Type": "AWS::Cognito::UserPoolClient", "Properties": {
+ "UserPoolId": pool_id, "ClientName": "app", "GenerateSecret": generate_secret,
+ "AccessTokenValidity": 15, "TokenValidityUnits": {"AccessToken": "minutes"},
+ "PreventUserExistenceErrors": "ENABLED",
+ "AllowedOAuthFlowsUserPoolClient": True,
+ "AllowedOAuthFlows": ["code"], "AllowedOAuthScopes": ["openid"],
+ "ReadAttributes": ["email"], "AuthSessionValidity": 5}}},
+ "Outputs": {"ClientId": {"Value": {"Ref": "Client"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(False))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ client_id = _output(stack, "ClientId")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(True))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ new_id = _output(stack, "ClientId")
+ assert new_id != client_id
+ client = cognito_idp.describe_user_pool_client(
+ UserPoolId=pool_id, ClientId=new_id
+ )["UserPoolClient"]
+ assert client["ClientSecret"]
+ assert client["AccessTokenValidity"] == 15
+ assert client["TokenValidityUnits"] == {"AccessToken": "minutes"}
+ assert client["PreventUserExistenceErrors"] == "ENABLED"
+ assert client["AllowedOAuthFlowsUserPoolClient"] is True
+ assert client["AllowedOAuthFlows"] == ["code"]
+ assert client["AllowedOAuthScopes"] == ["openid"]
+ assert client["ReadAttributes"] == ["email"]
+ assert client["AuthSessionValidity"] == 5
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ cognito_idp.delete_user_pool(UserPoolId=pool_id)
+
+
+def test_cfn_cognito_identity_pool_dropped_properties_revert_and_principal_tags_survive(
+ cfn, cognito_identity
+):
+ """An identity pool property the new template drops reverts to the create
+ default (AllowClassicFlow false, no DeveloperProviderName) while the
+ pool keeps its id, the principal-tag mapping set outside the template
+ is still there after the update, and Fn::GetAtt Name is the name the
+ resource reference documents."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-idp-drop-{uid}"
+ provider = f"cognito-idp.us-east-1.amazonaws.com/us-east-1_{uid}"
+
+ def template(declared):
+ props = {"IdentityPoolName": f"cfn_idp_drop_{uid}",
+ "AllowUnauthenticatedIdentities": False}
+ if declared:
+ props.update({"AllowClassicFlow": True, "DeveloperProviderName": "login.example"})
+ return json.dumps({
+ "Resources": {"IdPool": {"Type": "AWS::Cognito::IdentityPool", "Properties": props}},
+ "Outputs": {"PoolId": {"Value": {"Ref": "IdPool"}},
+ "PoolName": {"Value": {"Fn::GetAtt": ["IdPool", "Name"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(True))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ pool_id = _output(stack, "PoolId")
+ assert _output(stack, "PoolName") == f"cfn_idp_drop_{uid}"
+ pool = cognito_identity.describe_identity_pool(IdentityPoolId=pool_id)
+ assert pool["AllowClassicFlow"] is True
+ assert pool["DeveloperProviderName"] == "login.example"
+ cognito_identity.set_principal_tag_attribute_map(
+ IdentityPoolId=pool_id, IdentityProviderName=provider,
+ PrincipalTags={"tenant": "custom:tenant"},
+ )
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(False))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "PoolId") == pool_id
+ assert _output(stack, "PoolName") == f"cfn_idp_drop_{uid}"
+ pool = cognito_identity.describe_identity_pool(IdentityPoolId=pool_id)
+ assert pool["AllowClassicFlow"] is False
+ assert pool.get("DeveloperProviderName", "") == ""
+ mapping = cognito_identity.get_principal_tag_attribute_map(
+ IdentityPoolId=pool_id, IdentityProviderName=provider
+ )
+ assert mapping["PrincipalTags"] == {"tenant": "custom:tenant"}
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cognito_user_pool_group_dropped_properties_revert(cfn, cognito_idp):
+ """Dropping Description and Precedence from a group reverts them: the
+ description empties and the precedence goes away, since "The default
+ Precedence value is null" on the resource reference. The group keeps
+ its name and its member."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-group-drop-{uid}"
+
+ def template(declared):
+ props = {"UserPoolId": {"Ref": "Pool"}, "GroupName": "admins"}
+ if declared:
+ props.update({"Description": "Administrators", "Precedence": 3})
+ return json.dumps({
+ "Resources": {
+ "Pool": {"Type": "AWS::Cognito::UserPool",
+ "Properties": {"UserPoolName": f"cfn-group-drop-pool-{uid}"}},
+ "Group": {"Type": "AWS::Cognito::UserPoolGroup", "Properties": props},
+ },
+ "Outputs": {"PoolId": {"Value": {"Ref": "Pool"}},
+ "GroupRef": {"Value": {"Ref": "Group"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(True))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ pool_id = _output(stack, "PoolId")
+ group = cognito_idp.get_group(UserPoolId=pool_id, GroupName="admins")["Group"]
+ assert group["Precedence"] == 3
+ cognito_idp.admin_create_user(UserPoolId=pool_id, Username="alice")
+ cognito_idp.admin_add_user_to_group(UserPoolId=pool_id, Username="alice", GroupName="admins")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(False))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "GroupRef") == "admins"
+ group = cognito_idp.get_group(UserPoolId=pool_id, GroupName="admins")["Group"]
+ assert group.get("Description", "") == ""
+ assert "Precedence" not in group
+ members = cognito_idp.list_users_in_group(UserPoolId=pool_id, GroupName="admins")["Users"]
+ assert [u["Username"] for u in members] == ["alice"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cognito_user_pool_group_under_generated_name_moves_and_renames(cfn, cognito_idp):
+ """A group without a GroupName carries a generated name, which
+ CloudFormation may replace: a UserPoolId change moves it to the other
+ pool (same generated name, so Ref is unchanged, and the old pool is
+ left without it), and declaring a GroupName afterwards replaces it once
+ more with Ref following the new name. The pools live outside the
+ stack."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-group-gen-{uid}"
+ pool_a = cognito_idp.create_user_pool(PoolName=f"cfn-group-gen-a-{uid}")["UserPool"]["Id"]
+ pool_b = cognito_idp.create_user_pool(PoolName=f"cfn-group-gen-b-{uid}")["UserPool"]["Id"]
+
+ def template(pool_id, group_name=None):
+ props = {"UserPoolId": pool_id, "Description": "generated"}
+ if group_name:
+ props["GroupName"] = group_name
+ return json.dumps({
+ "Resources": {"Group": {"Type": "AWS::Cognito::UserPoolGroup", "Properties": props}},
+ "Outputs": {"GroupRef": {"Value": {"Ref": "Group"}}},
+ })
+
+ def group_names(pool_id):
+ return [g["GroupName"] for g in cognito_idp.list_groups(UserPoolId=pool_id)["Groups"]]
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(pool_a))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ generated = _output(stack, "GroupRef")
+ assert group_names(pool_a) == [generated]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(pool_b))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "GroupRef") == generated
+ assert group_names(pool_a) == []
+ assert group_names(pool_b) == [generated]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(pool_b, "admins"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "GroupRef") == "admins"
+ assert group_names(pool_b) == ["admins"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ for pool_id in (pool_a, pool_b):
+ cognito_idp.delete_user_pool(UserPoolId=pool_id)
+
+
+_COGNITO_POOL_PROPERTY_CHANGES = [
+ ("LambdaConfig",
+ {"PreSignUp": "arn:aws:lambda:us-east-1:000000000000:function:pre-signup-v1"},
+ {"PreSignUp": "arn:aws:lambda:us-east-1:000000000000:function:pre-signup-v2",
+ "PostConfirmation": "arn:aws:lambda:us-east-1:000000000000:function:post-confirm"}),
+ ("AdminCreateUserConfig",
+ {"AllowAdminCreateUserOnly": False, "UnusedAccountValidityDays": 7},
+ {"AllowAdminCreateUserOnly": True, "UnusedAccountValidityDays": 3}),
+ ("UserPoolTags", {"env": "dev"}, {"env": "prod", "team": "platform"}),
+ ("AccountRecoverySetting",
+ {"RecoveryMechanisms": [{"Name": "verified_email", "Priority": 1}]},
+ {"RecoveryMechanisms": [{"Name": "verified_phone_number", "Priority": 1},
+ {"Name": "verified_email", "Priority": 2}]}),
+ ("DeviceConfiguration",
+ {"ChallengeRequiredOnNewDevice": False},
+ {"ChallengeRequiredOnNewDevice": True, "DeviceOnlyRememberedOnUserPrompt": True}),
+]
+
+
[email protected]("prop,before,after", _COGNITO_POOL_PROPERTY_CHANGES,
+ ids=[c[0] for c in _COGNITO_POOL_PROPERTY_CHANGES])
+def test_cfn_cognito_user_pool_property_changes_in_place(cfn, cognito_idp, prop, before, after):
+ """Each of these properties is "Update requires: No interruption" on the
+ resource reference: the change lands on the same pool id and
+ DescribeUserPool reports the new value, with the user kept."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-pool-{prop.lower()[:12]}-{uid}"
+
+ def template(value):
+ return json.dumps({
+ "Resources": {"Pool": {"Type": "AWS::Cognito::UserPool", "Properties": {
+ "UserPoolName": f"cfn-pool-prop-{uid}", prop: value}}},
+ "Outputs": {"PoolId": {"Value": {"Ref": "Pool"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(before))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ pool_id = _output(stack, "PoolId")
+ assert cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"][prop] == before
+ cognito_idp.admin_create_user(UserPoolId=pool_id, Username="alice")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(after))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "PoolId") == pool_id
+ assert cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"][prop] == after
+ users = cognito_idp.list_users(UserPoolId=pool_id)["Users"]
+ assert [u["Username"] for u in users] == ["alice"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cognito_user_pool_schema_update_adds_custom_attributes(cfn, cognito_idp):
+ """A Schema entry the pool does not have yet is added through
+ AddCustomAttributes on update: the pool keeps its id and its user, the
+ attribute from the first template is still there, and the new one shows
+ up under its custom: prefix. A standard attribute the template also
+ lists (email) is left as it is."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-pool-schema-{uid}"
+
+ def template(names):
+ schema = [{"Name": "email", "AttributeDataType": "String", "Required": True}]
+ schema += [{"Name": n, "AttributeDataType": "String", "Mutable": True} for n in names]
+ return json.dumps({
+ "Resources": {"Pool": {"Type": "AWS::Cognito::UserPool", "Properties": {
+ "UserPoolName": f"cfn-pool-schema-{uid}", "Schema": schema}}},
+ "Outputs": {"PoolId": {"Value": {"Ref": "Pool"}}},
+ })
+
+ def custom_names(pool_id):
+ attrs = cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"]["SchemaAttributes"]
+ return sorted(a["Name"] for a in attrs if a["Name"].startswith("custom:"))
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(["tier"]))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ pool_id = _output(stack, "PoolId")
+ assert custom_names(pool_id) == ["custom:tier"]
+ cognito_idp.admin_create_user(UserPoolId=pool_id, Username="alice")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(["tier", "plan"]))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "PoolId") == pool_id
+ assert custom_names(pool_id) == ["custom:plan", "custom:tier"]
+ attrs = cognito_idp.describe_user_pool(UserPoolId=pool_id)["UserPool"]["SchemaAttributes"]
+ email = next(a for a in attrs if a["Name"] == "email")
+ assert email["Required"] is True
+ users = cognito_idp.list_users(UserPoolId=pool_id)["Users"]
+ assert [u["Username"] for u in users] == ["alice"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cognito_user_pool_enabled_mfas_update(cfn, cognito_idp):
+ """EnabledMfas is "Update requires: No interruption" on the resource
+ reference: adding SOFTWARE_TOKEN_MFA on update switches the software
+ token block on in GetUserPoolMfaConfig, and dropping the property
+ switches it off again, on the same pool id with its user kept."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-pool-mfas-{uid}"
+
+ def template(enabled_mfas):
+ props = {"UserPoolName": f"cfn-pool-mfas-{uid}", "MfaConfiguration": "OPTIONAL"}
+ if enabled_mfas is not None:
+ props["EnabledMfas"] = enabled_mfas
+ return json.dumps({
+ "Resources": {"Pool": {"Type": "AWS::Cognito::UserPool", "Properties": props}},
+ "Outputs": {"PoolId": {"Value": {"Ref": "Pool"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(None))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ pool_id = _output(stack, "PoolId")
+ cfg = cognito_idp.get_user_pool_mfa_config(UserPoolId=pool_id)
+ assert "SoftwareTokenMfaConfiguration" not in cfg
+ cognito_idp.admin_create_user(UserPoolId=pool_id, Username="alice")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(["SOFTWARE_TOKEN_MFA"]))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "PoolId") == pool_id
+ cfg = cognito_idp.get_user_pool_mfa_config(UserPoolId=pool_id)
+ assert cfg["MfaConfiguration"] == "OPTIONAL"
+ assert cfg["SoftwareTokenMfaConfiguration"]["Enabled"] is True
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(None))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "PoolId") == pool_id
+ cfg = cognito_idp.get_user_pool_mfa_config(UserPoolId=pool_id)
+ assert cfg["SoftwareTokenMfaConfiguration"]["Enabled"] is False
+ users = cognito_idp.list_users(UserPoolId=pool_id)["Users"]
+ assert [u["Username"] for u in users] == ["alice"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_secret_update_publishes_a_new_version(cfn, sm):
+ """A changed SecretString publishes a new AWSCURRENT version of the same
+ secret: same ARN, the first value still there as AWSPREVIOUS, and the
+ Description updated alongside."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-secret-upd-{uid}"
+ secret_name = f"cfn/secret-upd-{uid}"
+
+ def template(value, description):
+ return json.dumps({
+ "Resources": {"Secret": {"Type": "AWS::SecretsManager::Secret", "Properties": {
+ "Name": secret_name, "Description": description, "SecretString": value,
+ "Tags": [{"Key": "stage", "Value": description}],
+ }}},
+ "Outputs": {"SecretRef": {"Value": {"Ref": "Secret"}},
+ "SecretArn": {"Value": {"Fn::GetAtt": ["Secret", "Arn"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("v1", "first"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ ref, arn = _output(stack, "SecretRef"), _output(stack, "SecretArn")
+ first = sm.get_secret_value(SecretId=secret_name)
+ assert first["SecretString"] == "v1"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("v2", "second"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "SecretRef") == ref
+ assert _output(stack, "SecretArn") == arn
+
+ current = sm.get_secret_value(SecretId=secret_name)
+ assert current["SecretString"] == "v2"
+ assert current["ARN"] == arn
+ assert current["VersionId"] != first["VersionId"]
+ previous = sm.get_secret_value(SecretId=secret_name, VersionStage="AWSPREVIOUS")
+ assert previous["SecretString"] == "v1"
+ assert previous["VersionId"] == first["VersionId"]
+ described = sm.describe_secret(SecretId=secret_name)
+ assert described["Description"] == "second"
+ assert described["Tags"] == [{"Key": "stage", "Value": "second"}]
+ assert set(described["VersionIdsToStages"]) == {first["VersionId"], current["VersionId"]}
+
+ _delete_cfn_test_stack(cfn, stack_name)
+ with pytest.raises(ClientError):
+ sm.describe_secret(SecretId=secret_name)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_secret_update_keeps_an_undeclared_kms_key(cfn, sm):
+ """A property the template never declared is not the stack's to clear: a
+ KmsKeyId set through UpdateSecret outside the stack survives an update
+ that changes the Description, and one that drops it."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-secret-kms-{uid}"
+ secret_name = f"cfn/secret-kms-{uid}"
+
+ def template(value, description=None):
+ props = {"Name": secret_name, "SecretString": value}
+ if description is not None:
+ props["Description"] = description
+ return json.dumps({
+ "Resources": {"Secret": {"Type": "AWS::SecretsManager::Secret", "Properties": props}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("v1", "declared"))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ sm.update_secret(SecretId=secret_name, KmsKeyId=f"alias/cfn-secret-kms-{uid}")
+ assert sm.describe_secret(SecretId=secret_name)["KmsKeyId"] == f"alias/cfn-secret-kms-{uid}"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("v1", "changed"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ described = sm.describe_secret(SecretId=secret_name)
+ assert described["KmsKeyId"] == f"alias/cfn-secret-kms-{uid}"
+ assert described["Description"] == "changed"
+
+ # Dropping the Description from the template clears it, as on AWS.
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("v2"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ described = sm.describe_secret(SecretId=secret_name)
+ assert described.get("Description", "") == ""
+ assert described["KmsKeyId"] == f"alias/cfn-secret-kms-{uid}"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_secret_rename_replaces_the_secret(cfn, sm):
+ """Name is create-only: renaming creates the new secret and removes the
+ old one, in CloudFormation's replacement order."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-secret-ren-{uid}"
+
+ def template(name):
+ return json.dumps({
+ "Resources": {"Secret": {"Type": "AWS::SecretsManager::Secret", "Properties": {
+ "Name": name, "SecretString": "same"}}},
+ "Outputs": {"SecretRef": {"Value": {"Ref": "Secret"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(f"cfn-secret-a-{uid}"))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(f"cfn-secret-b-{uid}"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "SecretRef") == f"cfn-secret-b-{uid}"
+ assert sm.get_secret_value(SecretId=f"cfn-secret-b-{uid}")["SecretString"] == "same"
+ with pytest.raises(ClientError):
+ sm.describe_secret(SecretId=f"cfn-secret-a-{uid}")
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_secret_generate_secret_string_change_publishes_a_new_version(cfn, sm):
+ """"When you make a change to this property, a new secret version is
+ created" (GenerateSecretString, AWS::SecretsManager::Secret reference):
+ a changed PasswordLength regenerates the value as a new AWSCURRENT version
+ of the same secret, the previous one staying behind as AWSPREVIOUS."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-secret-gen-{uid}"
+ secret_name = f"cfn/secret-gen-{uid}"
+
+ def template(length):
+ return json.dumps({
+ "Resources": {"Secret": {"Type": "AWS::SecretsManager::Secret", "Properties": {
+ "Name": secret_name,
+ "GenerateSecretString": {
+ "SecretStringTemplate": '{"username": "admin"}',
+ "GenerateStringKey": "password",
+ "PasswordLength": length,
+ "ExcludeCharacters": '"@/\\',
+ },
+ }}},
+ "Outputs": {"SecretArn": {"Value": {"Fn::GetAtt": ["Secret", "Arn"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(16))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "SecretArn")
+ first = sm.get_secret_value(SecretId=secret_name)
+ assert len(json.loads(first["SecretString"])["password"]) == 16
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(24))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "SecretArn") == arn
+
+ current = sm.get_secret_value(SecretId=secret_name)
+ assert current["ARN"] == arn
+ assert current["VersionId"] != first["VersionId"]
+ assert current["VersionStages"] == ["AWSCURRENT"]
+ generated = json.loads(current["SecretString"])
+ assert generated["username"] == "admin"
+ assert len(generated["password"]) == 24
+ previous = sm.get_secret_value(SecretId=secret_name, VersionStage="AWSPREVIOUS")
+ assert previous["VersionId"] == first["VersionId"]
+ assert previous["SecretString"] == first["SecretString"]
+
+ # An update that leaves GenerateSecretString alone does not regenerate.
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(24), Tags=[{"Key": "touch", "Value": "1"}])
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert sm.get_secret_value(SecretId=secret_name)["VersionId"] == current["VersionId"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_secret_replica_regions_apply_on_create_and_update(cfn, sm):
+ """ReplicaRegions is "Update requires: No interruption" (reference): the
+ regions a template declares are replicated on create, a region added or
+ re-keyed on update is applied to the same secret, a new value reaches the
+ replicas, and the replicas go away with the stack."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-secret-rep-{uid}"
+ secret_name = f"cfn/secret-rep-{uid}"
+ home = sm.meta.region_name
+ west = _regional_cfn_test_client("secretsmanager", "us-west-2")
+ frankfurt = _regional_cfn_test_client("secretsmanager", "eu-central-1")
+
+ def template(value, replicas):
+ return json.dumps({
+ "Resources": {"Secret": {"Type": "AWS::SecretsManager::Secret", "Properties": {
+ "Name": secret_name, "SecretString": value, "ReplicaRegions": replicas,
+ }}},
+ "Outputs": {"SecretArn": {"Value": {"Fn::GetAtt": ["Secret", "Arn"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("v1", [{"Region": "us-west-2"}]))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "SecretArn")
+ primary = sm.describe_secret(SecretId=secret_name)
+ assert [s["Region"] for s in primary["ReplicationStatus"]] == ["us-west-2"]
+ replica = west.describe_secret(SecretId=secret_name)
+ assert replica["PrimaryRegion"] == home
+ assert replica["ARN"] == arn.replace(f":{home}:", ":us-west-2:")
+ assert west.get_secret_value(SecretId=secret_name)["SecretString"] == "v1"
+ with pytest.raises(ClientError):
+ frankfurt.describe_secret(SecretId=secret_name)
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("v2", [
+ {"Region": "us-west-2", "KmsKeyId": f"alias/cfn-secret-rep-{uid}"},
+ {"Region": "eu-central-1"},
+ ]))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "SecretArn") == arn
+ primary = sm.describe_secret(SecretId=secret_name)
+ assert sorted(s["Region"] for s in primary["ReplicationStatus"]) == ["eu-central-1", "us-west-2"]
+ assert west.describe_secret(SecretId=secret_name)["KmsKeyId"] == f"alias/cfn-secret-rep-{uid}"
+ assert west.get_secret_value(SecretId=secret_name)["SecretString"] == "v2"
+ assert frankfurt.get_secret_value(SecretId=secret_name)["SecretString"] == "v2"
+
+ _delete_cfn_test_stack(cfn, stack_name)
+ for client in (sm, west, frankfurt):
+ with pytest.raises(ClientError):
+ client.describe_secret(SecretId=secret_name)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_events_rule_update_keeps_arn_and_foreign_targets(cfn, eb, sqs):
+ """Schedule, description and the declared targets update in place through
+ PutRule / PutTargets / RemoveTargets: same rule ARN, a target added with
+ PutTargets outside the template survives, a target dropped from the
+ template is removed and a changed one is rewritten."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-rule-upd-{uid}"
+ rule_name = f"cfn-rule-upd-{uid}"
+ queues, queue_urls = {}, {}
+ for label in ("a", "b", "c"):
+ queue_urls[label] = sqs.create_queue(QueueName=f"cfn-rule-upd-{uid}-{label}")["QueueUrl"]
+ queues[label] = sqs.get_queue_attributes(
+ QueueUrl=queue_urls[label], AttributeNames=["QueueArn"]
+ )["Attributes"]["QueueArn"]
+
+ def template(schedule, description, targets):
+ return json.dumps({
+ "Resources": {"Rule": {"Type": "AWS::Events::Rule", "Properties": {
+ "Name": rule_name, "ScheduleExpression": schedule,
+ "Description": description, "State": "ENABLED", "Targets": targets,
+ }}},
+ "Outputs": {"RuleRef": {"Value": {"Ref": "Rule"}},
+ "RuleArn": {"Value": {"Fn::GetAtt": ["Rule", "Arn"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(
+ "rate(5 minutes)", "before",
+ [{"Id": "A", "Arn": queues["a"], "Input": '{"v": 1}'},
+ {"Id": "B", "Arn": queues["b"]}],
+ ))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "RuleArn")
+ assert eb.describe_rule(Name=rule_name)["Arn"] == arn
+ eb.put_targets(Rule=rule_name, Targets=[{"Id": "Foreign", "Arn": queues["c"]}])
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(
+ "rate(10 minutes)", "after",
+ [{"Id": "A", "Arn": queues["a"], "Input": '{"v": 2}'},
+ {"Id": "C", "Arn": queues["c"]}],
+ ))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "RuleRef") == rule_name
+ assert _output(stack, "RuleArn") == arn
+
+ rule = eb.describe_rule(Name=rule_name)
+ assert rule["Arn"] == arn
+ assert rule["ScheduleExpression"] == "rate(10 minutes)"
+ assert rule["Description"] == "after"
+ assert rule["State"] == "ENABLED"
+ targets = {t["Id"]: t for t in eb.list_targets_by_rule(Rule=rule_name)["Targets"]}
+ assert set(targets) == {"A", "C", "Foreign"}
+ assert targets["A"]["Input"] == '{"v": 2}'
+ assert targets["Foreign"]["Arn"] == queues["c"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ for queue_url in queue_urls.values():
+ sqs.delete_queue(QueueUrl=queue_url)
+ with pytest.raises(ClientError):
+ eb.describe_rule(Name=rule_name)
+
+
+def test_cfn_events_rule_rename_replaces_the_rule(cfn, eb):
+ """Name is create-only: renaming creates the new rule and removes the old
+ one, and Ref follows the new name."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-rule-ren-{uid}"
+
+ def template(name):
+ return json.dumps({
+ "Resources": {"Rule": {"Type": "AWS::Events::Rule", "Properties": {
+ "Name": name, "ScheduleExpression": "rate(1 hour)"}}},
+ "Outputs": {"RuleRef": {"Value": {"Ref": "Rule"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(f"cfn-rule-a-{uid}"))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(f"cfn-rule-b-{uid}"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "RuleRef") == f"cfn-rule-b-{uid}"
+ assert eb.describe_rule(Name=f"cfn-rule-b-{uid}")["ScheduleExpression"] == "rate(1 hour)"
+ with pytest.raises(ClientError):
+ eb.describe_rule(Name=f"cfn-rule-a-{uid}")
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_events_rule_bus_move_keeps_name_and_targets(cfn, eb, sqs):
+ """EventBusName updates with some interruptions per the resource
+ reference: the rule moves to the other bus under the same name, its
+ targets come along, GetAtt Arn follows the bus, and nothing is left on
+ the bus it came from."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-rule-move-{uid}"
+ rule_name = f"cfn-rule-move-{uid}"
+ bus_name = f"cfn-rule-move-bus-{uid}"
+ url = sqs.create_queue(QueueName=f"cfn-rule-move-{uid}")["QueueUrl"]
+ queue_arn = sqs.get_queue_attributes(
+ QueueUrl=url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+
+ def template(on_bus):
+ props = {"Name": rule_name, "EventPattern": {"source": ["cfn.test"]},
+ "Targets": [{"Id": "Q", "Arn": queue_arn}]}
+ if on_bus:
+ props["EventBusName"] = {"Ref": "Bus"}
+ return json.dumps({
+ "Resources": {
+ "Bus": {"Type": "AWS::Events::EventBus", "Properties": {"Name": bus_name}},
+ "Rule": {"Type": "AWS::Events::Rule", "Properties": props},
+ },
+ "Outputs": {"RuleRef": {"Value": {"Ref": "Rule"}},
+ "RuleArn": {"Value": {"Fn::GetAtt": ["Rule", "Arn"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(False))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "RuleArn") == eb.describe_rule(Name=rule_name)["Arn"]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(True))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "RuleRef") == rule_name
+ moved = eb.describe_rule(Name=rule_name, EventBusName=bus_name)
+ assert moved["Arn"].endswith(f"rule/{bus_name}/{rule_name}")
+ assert _output(stack, "RuleArn") == moved["Arn"]
+ targets = eb.list_targets_by_rule(Rule=rule_name, EventBusName=bus_name)["Targets"]
+ assert [t["Arn"] for t in targets] == [queue_arn]
+ with pytest.raises(ClientError):
+ eb.describe_rule(Name=rule_name)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ sqs.delete_queue(QueueUrl=url)
+ with pytest.raises(ClientError):
+ eb.describe_rule(Name=rule_name, EventBusName=bus_name)
+
+
+def test_cfn_events_rule_move_to_a_missing_bus_rolls_back(cfn, eb, sqs):
+ """A move onto a bus that does not exist fails the update before the
+ rule is touched: the stack rolls back, the rule stays on the default
+ bus with its target, and nothing is left under the other bus name."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-rule-nobus-{uid}"
+ rule_name = f"cfn-rule-nobus-{uid}"
+ missing_bus = f"cfn-rule-nobus-missing-{uid}"
+ url = sqs.create_queue(QueueName=f"cfn-rule-nobus-{uid}")["QueueUrl"]
+ queue_arn = sqs.get_queue_attributes(
+ QueueUrl=url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+
+ def template(bus):
+ props = {"Name": rule_name, "EventPattern": {"source": ["cfn.test"]},
+ "Targets": [{"Id": "Q", "Arn": queue_arn}]}
+ if bus:
+ props["EventBusName"] = bus
+ return json.dumps({
+ "Resources": {"Rule": {"Type": "AWS::Events::Rule", "Properties": props}},
+ "Outputs": {"RuleArn": {"Value": {"Fn::GetAtt": ["Rule", "Arn"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(None))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "RuleArn")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(missing_bus))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert "AWS::Events::Rule update failed" in _stack_event_reasons(cfn, stack_name)
+ assert _output(stack, "RuleArn") == arn
+ assert eb.describe_rule(Name=rule_name)["Arn"] == arn
+ targets = eb.list_targets_by_rule(Rule=rule_name)["Targets"]
+ assert [t["Arn"] for t in targets] == [queue_arn]
+ with pytest.raises(ClientError):
+ eb.describe_rule(Name=rule_name, EventBusName=missing_bus)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ sqs.delete_queue(QueueUrl=url)
+
+
+def test_cfn_events_rule_tags_apply_on_create_and_update(cfn, eb):
+ """Tags update with no interruption per the resource reference: the
+ template's tags are on the rule after create, a changed value and a new
+ key are written on update, a key the template dropped is removed, and a
+ tag added with TagResource outside the stack survives."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-rule-tags-{uid}"
+ rule_name = f"cfn-rule-tags-{uid}"
+
+ def template(tags):
+ return json.dumps({
+ "Resources": {"Rule": {"Type": "AWS::Events::Rule", "Properties": {
+ "Name": rule_name, "ScheduleExpression": "rate(1 hour)",
+ "Tags": [{"Key": k, "Value": v} for k, v in tags.items()],
+ }}},
+ "Outputs": {"RuleArn": {"Value": {"Fn::GetAtt": ["Rule", "Arn"]}}},
+ })
+
+ def tags_of(arn):
+ return {t["Key"]: t["Value"] for t in eb.list_tags_for_resource(ResourceARN=arn)["Tags"]}
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template({"env": "dev", "team": "a"}))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "RuleArn")
+ assert tags_of(arn) == {"env": "dev", "team": "a"}
+ eb.tag_resource(ResourceARN=arn, Tags=[{"Key": "foreign", "Value": "kept"}])
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template({"env": "prod", "owner": "b"}))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "RuleArn") == arn
+ assert tags_of(arn) == {"env": "prod", "owner": "b", "foreign": "kept"}
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ with pytest.raises(ClientError):
+ eb.list_tags_for_resource(ResourceARN=arn)
+
+
+def test_cfn_events_rule_tags_follow_a_bus_move(cfn, eb):
+ """A rule moved to another bus by an EventBusName update keeps its tags
+ under the new ARN, a tag changed in the same update applies there, and
+ nothing is left under the ARN it had on the default bus."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-rule-tagmove-{uid}"
+ rule_name = f"cfn-rule-tagmove-{uid}"
+ bus_name = f"cfn-rule-tagmove-bus-{uid}"
+
+ def template(on_bus, env):
+ props = {"Name": rule_name, "EventPattern": {"source": ["cfn.test"]},
+ "Tags": [{"Key": "env", "Value": env}, {"Key": "team", "Value": "a"}]}
+ if on_bus:
+ props["EventBusName"] = {"Ref": "Bus"}
+ return json.dumps({
+ "Resources": {
+ "Bus": {"Type": "AWS::Events::EventBus", "Properties": {"Name": bus_name}},
+ "Rule": {"Type": "AWS::Events::Rule", "Properties": props},
+ },
+ "Outputs": {"RuleArn": {"Value": {"Fn::GetAtt": ["Rule", "Arn"]}}},
+ })
+
+ def tags_of(arn):
+ return {t["Key"]: t["Value"] for t in eb.list_tags_for_resource(ResourceARN=arn)["Tags"]}
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(False, "dev"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ old_arn = _output(stack, "RuleArn")
+ eb.tag_resource(ResourceARN=old_arn, Tags=[{"Key": "foreign", "Value": "kept"}])
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(True, "prod"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ new_arn = _output(stack, "RuleArn")
+ assert new_arn == eb.describe_rule(Name=rule_name, EventBusName=bus_name)["Arn"]
+ assert new_arn != old_arn
+ assert tags_of(new_arn) == {"env": "prod", "team": "a", "foreign": "kept"}
+ with pytest.raises(ClientError):
+ eb.list_tags_for_resource(ResourceARN=old_arn)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_events_rule_dropped_description_reverts(cfn, eb):
+ """Description updates with no interruption, and per the resource
+ reference an argument omitted from PutRule is not kept: a Description
+ dropped from the template is gone from the rule after the update."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-rule-desc-{uid}"
+ rule_name = f"cfn-rule-desc-{uid}"
+
+ def template(description):
+ props = {"Name": rule_name, "ScheduleExpression": "rate(1 hour)"}
+ if description is not None:
+ props["Description"] = description
+ return json.dumps({"Resources": {"Rule": {"Type": "AWS::Events::Rule", "Properties": props}}})
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("described"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert eb.describe_rule(Name=rule_name)["Description"] == "described"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(None))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ rule = eb.describe_rule(Name=rule_name)
+ assert "Description" not in rule
+ assert rule["ScheduleExpression"] == "rate(1 hour)"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_events_rule_removing_every_target_removes_them(cfn, eb, sqs):
+ """Targets update with no interruption: a template that drops all of
+ its targets leaves the rule with none of them, while a target added
+ with PutTargets outside the stack stays."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-rule-notgt-{uid}"
+ rule_name = f"cfn-rule-notgt-{uid}"
+ queue_urls, queue_arns = [], []
+ for label in ("a", "b", "c"):
+ url = sqs.create_queue(QueueName=f"cfn-rule-notgt-{uid}-{label}")["QueueUrl"]
+ queue_urls.append(url)
+ queue_arns.append(sqs.get_queue_attributes(
+ QueueUrl=url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"])
+
+ def template(targets):
+ props = {"Name": rule_name, "ScheduleExpression": "rate(1 hour)"}
+ if targets is not None:
+ props["Targets"] = targets
+ return json.dumps({"Resources": {"Rule": {"Type": "AWS::Events::Rule", "Properties": props}}})
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(
+ [{"Id": "A", "Arn": queue_arns[0]}, {"Id": "B", "Arn": queue_arns[1]}]))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert {t["Id"] for t in eb.list_targets_by_rule(Rule=rule_name)["Targets"]} == {"A", "B"}
+ eb.put_targets(Rule=rule_name, Targets=[{"Id": "Foreign", "Arn": queue_arns[2]}])
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(None))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ targets = eb.list_targets_by_rule(Rule=rule_name)["Targets"]
+ assert [t["Id"] for t in targets] == ["Foreign"]
+ assert eb.describe_rule(Name=rule_name)["ScheduleExpression"] == "rate(1 hour)"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ for url in queue_urls:
+ sqs.delete_queue(QueueUrl=url)
+
+
+def test_cfn_events_rule_generated_name_updates_in_place(cfn, eb):
+ """A rule without Name gets a generated physical ID (Ref returns the
+ rule ID, such as mystack-ScheduledRule-ABCDEFGHIJK, per the resource
+ reference) and updates in place: Ref, GetAtt Arn and GetAtt RuleName
+ are unchanged across a schedule change, and the service shows the new
+ schedule under that name."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-rule-gen-{uid}"
+
+ def template(schedule):
+ return json.dumps({
+ "Resources": {"Rule": {"Type": "AWS::Events::Rule", "Properties": {
+ "ScheduleExpression": schedule}}},
+ "Outputs": {"RuleRef": {"Value": {"Ref": "Rule"}},
+ "RuleArn": {"Value": {"Fn::GetAtt": ["Rule", "Arn"]}},
+ "RuleName": {"Value": {"Fn::GetAtt": ["Rule", "RuleName"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("rate(5 minutes)"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ name, arn = _output(stack, "RuleRef"), _output(stack, "RuleArn")
+ assert name.startswith(f"{stack_name}-Rule-")
+ assert _output(stack, "RuleName") == name
+ assert eb.describe_rule(Name=name)["Arn"] == arn
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("rate(10 minutes)"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "RuleRef") == name
+ assert _output(stack, "RuleArn") == arn
+ assert _output(stack, "RuleName") == name
+ rule = eb.describe_rule(Name=name)
+ assert rule["Arn"] == arn
+ assert rule["ScheduleExpression"] == "rate(10 minutes)"
+ assert len(eb.list_rules(NamePrefix=f"{stack_name}-Rule-")["Rules"]) == 1
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ with pytest.raises(ClientError):
+ eb.describe_rule(Name=name)
+
+
+def _sfn_definition_json(comment):
+ return json.dumps({
+ "Comment": comment,
+ "StartAt": "Done",
+ "States": {"Done": {"Type": "Pass", "End": True}},
+ })
+
+
+def test_cfn_state_machine_update_keeps_arn_and_executions(cfn, sfn):
+ """A changed definition and role update the machine in place through
+ UpdateStateMachine: same ARN, the execution started before the update is
+ still listed, DescribeStateMachine shows the new definition."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-sfn-upd-{uid}"
+
+ def template(comment, role):
+ return json.dumps({
+ "Resources": {"SM": {"Type": "AWS::StepFunctions::StateMachine", "Properties": {
+ "StateMachineName": f"cfn-sfn-upd-{uid}",
+ "DefinitionString": _sfn_definition_json(comment),
+ "RoleArn": f"arn:aws:iam::000000000000:role/{role}",
+ }}},
+ "Outputs": {"Arn": {"Value": {"Ref": "SM"}},
+ "Name": {"Value": {"Fn::GetAtt": ["SM", "Name"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("v1", "sfn-role-a"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "Arn")
+ execution = sfn.start_execution(stateMachineArn=arn, input="{}")["executionArn"]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("v2", "sfn-role-b"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Arn") == arn
+ assert _output(stack, "Name") == f"cfn-sfn-upd-{uid}"
+
+ described = sfn.describe_state_machine(stateMachineArn=arn)
+ assert json.loads(described["definition"])["Comment"] == "v2"
+ assert described["roleArn"] == "arn:aws:iam::000000000000:role/sfn-role-b"
+ executions = sfn.list_executions(stateMachineArn=arn)["executions"]
+ assert [e["executionArn"] for e in executions] == [execution]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_state_machine_type_change_under_custom_name_fails_loudly(cfn, sfn):
+ """StateMachineType requires replacement, which CloudFormation refuses
+ for a custom-named machine: the stack rolls back and the machine keeps
+ its type."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-sfn-type-{uid}"
+
+ def template(sm_type):
+ return json.dumps({
+ "Resources": {"SM": {"Type": "AWS::StepFunctions::StateMachine", "Properties": {
+ "StateMachineName": f"cfn-sfn-type-{uid}",
+ "StateMachineType": sm_type,
+ "DefinitionString": _sfn_definition_json("typed"),
+ "RoleArn": "arn:aws:iam::000000000000:role/sfn-role",
+ }}},
+ "Outputs": {"Arn": {"Value": {"Ref": "SM"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("STANDARD"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "Arn")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("EXPRESS"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ reasons = _stack_event_reasons(cfn, stack_name)
+ assert "custom-named resource requires replacing" in reasons
+ assert sfn.describe_state_machine(stateMachineArn=arn)["type"] == "STANDARD"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_state_machine_type_change_under_generated_name_fails_loudly(cfn, sfn):
+ """Under a generated name the deterministic derivation cannot yield a
+ fresh identity for the replacement, so MiniStack fails the update
+ naming the property instead of rebuilding the machine in place: the
+ stack rolls back and the machine keeps its ARN and type."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-sfn-gentype-{uid}"
+
+ def template(sm_type):
+ return json.dumps({
+ "Resources": {"SM": {"Type": "AWS::StepFunctions::StateMachine", "Properties": {
+ "StateMachineType": sm_type,
+ "DefinitionString": _sfn_definition_json("generated"),
+ "RoleArn": "arn:aws:iam::000000000000:role/sfn-role",
+ }}},
+ "Outputs": {"Arn": {"Value": {"Ref": "SM"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("STANDARD"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "Arn")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("EXPRESS"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ reasons = _stack_event_reasons(cfn, stack_name)
+ assert "StateMachineType (STANDARD -> EXPRESS) requires replacement" in reasons
+ assert _output(stack, "Arn") == arn
+ assert sfn.describe_state_machine(stateMachineArn=arn)["type"] == "STANDARD"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_state_machine_rename_replaces_the_machine(cfn, sfn):
+ """StateMachineName requires replacement: the renamed machine is created
+ before the old one is removed, Ref follows the new ARN, and a logging
+ configuration set outside the stack on the old machine does not carry
+ over, since the new one is created from the template alone."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-sfn-ren-{uid}"
+
+ def template(name):
+ return json.dumps({
+ "Resources": {"SM": {"Type": "AWS::StepFunctions::StateMachine", "Properties": {
+ "StateMachineName": name,
+ "DefinitionString": _sfn_definition_json("renamed"),
+ "RoleArn": "arn:aws:iam::000000000000:role/sfn-role",
+ }}},
+ "Outputs": {"Arn": {"Value": {"Ref": "SM"}},
+ "Name": {"Value": {"Fn::GetAtt": ["SM", "Name"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(f"cfn-sfn-a-{uid}"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ old_arn = _output(stack, "Arn")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(f"cfn-sfn-b-{uid}"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ new_arn = _output(stack, "Arn")
+ assert new_arn != old_arn
+ assert _output(stack, "Name") == f"cfn-sfn-b-{uid}"
+ assert sfn.describe_state_machine(stateMachineArn=new_arn)["name"] == f"cfn-sfn-b-{uid}"
+ with pytest.raises(ClientError):
+ sfn.describe_state_machine(stateMachineArn=old_arn)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_state_machine_update_keeps_an_undeclared_logging_configuration(cfn, sfn):
+ """A property the template never declared is not the stack's to reset: a
+ LoggingConfiguration set through UpdateStateMachine outside the stack
+ survives an update that only changes the definition."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-sfn-log-{uid}"
+
+ def template(comment):
+ return json.dumps({
+ "Resources": {"SM": {"Type": "AWS::StepFunctions::StateMachine", "Properties": {
+ "StateMachineName": f"cfn-sfn-log-{uid}",
+ "DefinitionString": _sfn_definition_json(comment),
+ "RoleArn": "arn:aws:iam::000000000000:role/sfn-role",
+ }}},
+ "Outputs": {"Arn": {"Value": {"Ref": "SM"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("v1"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "Arn")
+ sfn.update_state_machine(
+ stateMachineArn=arn,
+ loggingConfiguration={"level": "ALL", "includeExecutionData": True},
+ )
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("v2"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ described = sfn.describe_state_machine(stateMachineArn=arn)
+ assert json.loads(described["definition"])["Comment"] == "v2"
+ assert described["loggingConfiguration"]["level"] == "ALL"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_state_machine_update_drops_a_declared_logging_configuration(cfn, sfn):
+ """LoggingConfiguration updates without interruption ("By default, the
+ level is set to OFF", AWS::StepFunctions::StateMachine reference): a
+ template that stops declaring it reverts the machine to OFF, since the
+ property was the stack's to set."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-sfn-unlog-{uid}"
+
+ def template(logging):
+ props = {
+ "StateMachineName": f"cfn-sfn-unlog-{uid}",
+ "DefinitionString": _sfn_definition_json("logged"),
+ "RoleArn": "arn:aws:iam::000000000000:role/sfn-role",
+ }
+ if logging:
+ props["LoggingConfiguration"] = {"level": "ALL", "includeExecutionData": True}
+ return json.dumps({
+ "Resources": {"SM": {"Type": "AWS::StepFunctions::StateMachine", "Properties": props}},
+ "Outputs": {"Arn": {"Value": {"Ref": "SM"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(True))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "Arn")
+ assert sfn.describe_state_machine(stateMachineArn=arn)["loggingConfiguration"]["level"] == "ALL"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(False))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ described = sfn.describe_state_machine(stateMachineArn=arn)
+ assert described["loggingConfiguration"] == {"level": "OFF", "includeExecutionData": False}
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_state_machine_update_applies_definition_substitutions(cfn, sfn):
+ """DefinitionSubstitutions updates without interruption: a changed value
+ lands in the definition through UpdateStateMachine, and the
+ StateMachineRevisionId attribute ("Identifier for a state machine
+ revision", AWS::StepFunctions::StateMachine reference) moves with it."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-sfn-subs-{uid}"
+ definition = json.dumps({
+ "StartAt": "Call",
+ "States": {"Call": {"Type": "Task", "Resource": "${Target}", "End": True}},
+ })
+
+ def template(target):
+ return json.dumps({
+ "Resources": {"SM": {"Type": "AWS::StepFunctions::StateMachine", "Properties": {
+ "StateMachineName": f"cfn-sfn-subs-{uid}",
+ "DefinitionString": definition,
+ "DefinitionSubstitutions": {"Target": target},
+ "RoleArn": "arn:aws:iam::000000000000:role/sfn-role",
+ }}},
+ "Outputs": {"Arn": {"Value": {"Ref": "SM"}},
+ "Revision": {"Value": {"Fn::GetAtt": ["SM", "StateMachineRevisionId"]}}},
+ })
+
+ fn_a = "arn:aws:lambda:us-east-1:000000000000:function:target-a"
+ fn_b = "arn:aws:lambda:us-east-1:000000000000:function:target-b"
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(fn_a))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "Arn")
+ described = sfn.describe_state_machine(stateMachineArn=arn)
+ assert json.loads(described["definition"])["States"]["Call"]["Resource"] == fn_a
+ revision = _output(stack, "Revision")
+ assert revision == described["revisionId"]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(fn_b))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Arn") == arn
+ described = sfn.describe_state_machine(stateMachineArn=arn)
+ assert json.loads(described["definition"])["States"]["Call"]["Resource"] == fn_b
+ assert _output(stack, "Revision") == described["revisionId"]
+ assert _output(stack, "Revision") != revision
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_state_machine_update_changes_tags_in_place(cfn, sfn):
+ """Tags update without interruption (AWS::StepFunctions::StateMachine
+ reference): the machine is tagged on create, and an update rewrites a
+ value, adds a key and drops another under the same ARN."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-sfn-tags-{uid}"
+
+ def template(tags):
+ return json.dumps({
+ "Resources": {"SM": {"Type": "AWS::StepFunctions::StateMachine", "Properties": {
+ "StateMachineName": f"cfn-sfn-tags-{uid}",
+ "DefinitionString": _sfn_definition_json("tagged"),
+ "RoleArn": "arn:aws:iam::000000000000:role/sfn-role",
+ "Tags": [{"Key": k, "Value": v} for k, v in tags.items()],
+ }}},
+ "Outputs": {"Arn": {"Value": {"Ref": "SM"}}},
+ })
+
+ def tags_of(arn):
+ return {t["key"]: t["value"] for t in sfn.list_tags_for_resource(resourceArn=arn)["tags"]}
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template({"env": "dev", "team": "iot"}))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "Arn")
+ assert tags_of(arn) == {"env": "dev", "team": "iot"}
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template({"env": "prod", "owner": "ops"}))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Arn") == arn
+ assert tags_of(arn) == {"env": "prod", "owner": "ops"}
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cloudwatch_alarm_update_keeps_name_and_state(cfn, cw):
+ """Threshold and description update the alarm in place as PutMetricAlarm
+ does: same name and ARN, and the alarm state set before the update is
+ left unchanged, as CloudFormation documents — its timestamp included,
+ since the state did not change."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-alarm-upd-{uid}"
+ alarm_name = f"cfn-alarm-upd-{uid}"
+
+ def template(threshold, description):
+ return json.dumps({
+ "Resources": {"Alarm": {"Type": "AWS::CloudWatch::Alarm", "Properties": {
+ "AlarmName": alarm_name, "AlarmDescription": description,
+ "MetricName": "CPUUtilization", "Namespace": f"CfnAlarmUpd/{uid}",
+ "Statistic": "Average", "Period": 60, "EvaluationPeriods": 1,
+ "Threshold": threshold, "ComparisonOperator": "GreaterThanThreshold",
+ }}},
+ "Outputs": {"Name": {"Value": {"Ref": "Alarm"}},
+ "Arn": {"Value": {"Fn::GetAtt": ["Alarm", "Arn"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(80, "before"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "Arn")
+ cw.set_alarm_state(AlarmName=alarm_name, StateValue="ALARM", StateReason="seeded")
+ seeded = cw.describe_alarms(AlarmNames=[alarm_name])["MetricAlarms"][0]
+ time.sleep(1.1) # timestamps are whole seconds; a reset must be visible
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(90, "after"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Name") == alarm_name
+ assert _output(stack, "Arn") == arn
+
+ alarms = cw.describe_alarms(AlarmNames=[alarm_name])["MetricAlarms"]
+ assert len(alarms) == 1
+ assert float(alarms[0]["Threshold"]) == 90.0
+ assert alarms[0]["AlarmDescription"] == "after"
+ assert alarms[0]["AlarmArn"] == arn
+ assert alarms[0]["StateValue"] == "ALARM"
+ assert alarms[0]["StateReason"] == "seeded"
+ assert alarms[0]["StateUpdatedTimestamp"] == seeded["StateUpdatedTimestamp"]
+ assert alarms[0]["AlarmConfigurationUpdatedTimestamp"] > seeded["AlarmConfigurationUpdatedTimestamp"]
+
+ _delete_cfn_test_stack(cfn, stack_name)
+ assert cw.describe_alarms(AlarmNames=[alarm_name])["MetricAlarms"] == []
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cloudwatch_alarm_rename_replaces_the_alarm(cfn, cw):
+ """AlarmName is create-only: renaming creates the new alarm and removes
+ the old one."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-alarm-ren-{uid}"
+
+ def template(name):
+ return json.dumps({
+ "Resources": {"Alarm": {"Type": "AWS::CloudWatch::Alarm", "Properties": {
+ "AlarmName": name, "MetricName": "Errors", "Namespace": f"CfnAlarmRen/{uid}",
+ "Statistic": "Sum", "Period": 60, "EvaluationPeriods": 1,
+ "Threshold": 1, "ComparisonOperator": "GreaterThanOrEqualToThreshold",
+ }}},
+ "Outputs": {"Name": {"Value": {"Ref": "Alarm"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(f"cfn-alarm-a-{uid}"))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(f"cfn-alarm-b-{uid}"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Name") == f"cfn-alarm-b-{uid}"
+ names = {a["AlarmName"] for a in cw.describe_alarms(
+ AlarmNamePrefix="cfn-alarm-")["MetricAlarms"]}
+ assert f"cfn-alarm-b-{uid}" in names
+ assert f"cfn-alarm-a-{uid}" not in names
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cloudwatch_alarm_update_drops_omitted_properties(cfn, cw):
+ """"the update completely overwrites the previous configuration of the
+ alarm" (aws-resource-cloudwatch-alarm.html): a property left out of the
+ new template falls back to its default rather than surviving from the
+ old one."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-alarm-drop-{uid}"
+ alarm_name = f"cfn-alarm-drop-{uid}"
+ base = {
+ "AlarmName": alarm_name, "MetricName": "Errors", "Namespace": f"CfnAlarmDrop/{uid}",
+ "Statistic": "Sum", "Period": 60, "EvaluationPeriods": 1,
+ "Threshold": 1, "ComparisonOperator": "GreaterThanThreshold",
+ }
+
+ def template(**extra):
+ return json.dumps({"Resources": {"Alarm": {
+ "Type": "AWS::CloudWatch::Alarm", "Properties": {**base, **extra}}}})
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(
+ AlarmDescription="described", TreatMissingData="notBreaching",
+ OKActions=[f"arn:aws:sns:us-east-1:000000000000:ok-{uid}"], Unit="Count"))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ before = cw.describe_alarms(AlarmNames=[alarm_name])["MetricAlarms"][0]
+ assert before["AlarmDescription"] == "described"
+ assert before["TreatMissingData"] == "notBreaching"
+ assert before["OKActions"] == [f"arn:aws:sns:us-east-1:000000000000:ok-{uid}"]
+ assert before["Unit"] == "Count"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(Threshold=2))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ after = cw.describe_alarms(AlarmNames=[alarm_name])["MetricAlarms"][0]
+ assert float(after["Threshold"]) == 2.0
+ assert after.get("AlarmDescription", "") == ""
+ assert after["TreatMissingData"] == "missing"
+ assert after["OKActions"] == []
+ assert "Unit" not in after
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cloudwatch_alarm_update_recreates_an_alarm_deleted_out_of_band(cfn, cw):
+ """An alarm removed through DeleteAlarms while its stack still declares it
+ is created again by the next update (the replacement path), under the
+ same name so Ref and the ARN stay what the stack reported."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-alarm-oob-{uid}"
+ alarm_name = f"cfn-alarm-oob-{uid}"
+
+ def template(threshold):
+ return json.dumps({
+ "Resources": {"Alarm": {"Type": "AWS::CloudWatch::Alarm", "Properties": {
+ "AlarmName": alarm_name, "MetricName": "Errors", "Namespace": f"CfnAlarmOob/{uid}",
+ "Statistic": "Sum", "Period": 60, "EvaluationPeriods": 1,
+ "Threshold": threshold, "ComparisonOperator": "GreaterThanThreshold",
+ }}},
+ "Outputs": {"Name": {"Value": {"Ref": "Alarm"}},
+ "Arn": {"Value": {"Fn::GetAtt": ["Alarm", "Arn"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(1))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "Arn")
+ cw.delete_alarms(AlarmNames=[alarm_name])
+ assert cw.describe_alarms(AlarmNames=[alarm_name])["MetricAlarms"] == []
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(2))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Name") == alarm_name
+ assert _output(stack, "Arn") == arn
+ alarms = cw.describe_alarms(AlarmNames=[alarm_name])["MetricAlarms"]
+ assert len(alarms) == 1
+ assert float(alarms[0]["Threshold"]) == 2.0
+ assert alarms[0]["StateValue"] == "INSUFFICIENT_DATA"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cloudwatch_alarm_tags_apply_on_create_and_update(cfn, cw):
+ """Tags is "No interruption" (aws-resource-cloudwatch-alarm.html) and
+ PutMetricAlarm ignores Tags on an existing alarm ("To change the tags of
+ an existing alarm, use TagResource or UntagResource"), so the template's
+ Tags are applied as a whole: a changed value lands, a dropped key goes,
+ and the tags leave with the alarm."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-alarm-tags-{uid}"
+ alarm_name = f"cfn-alarm-tags-{uid}"
+
+ def template(tags):
+ return json.dumps({
+ "Resources": {"Alarm": {"Type": "AWS::CloudWatch::Alarm", "Properties": {
+ "AlarmName": alarm_name, "MetricName": "Errors", "Namespace": f"CfnAlarmTags/{uid}",
+ "Statistic": "Sum", "Period": 60, "EvaluationPeriods": 1,
+ "Threshold": 1, "ComparisonOperator": "GreaterThanThreshold",
+ "Tags": [{"Key": k, "Value": v} for k, v in tags.items()],
+ }}},
+ "Outputs": {"Arn": {"Value": {"Fn::GetAtt": ["Alarm", "Arn"]}}},
+ })
+
+ def tags_of(arn):
+ return {t["Key"]: t["Value"] for t in cw.list_tags_for_resource(ResourceARN=arn)["Tags"]}
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template({"env": "dev", "team": "a"}))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ arn = _output(stack, "Arn")
+ assert tags_of(arn) == {"env": "dev", "team": "a"}
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template({"env": "prod"}))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert tags_of(arn) == {"env": "prod"}
+
+ _delete_cfn_test_stack(cfn, stack_name)
+ with pytest.raises(ClientError) as exc:
+ cw.list_tags_for_resource(ResourceARN=arn)
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFound"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _cfn_permission_test_function(lam, fn_name):
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", "def handler(e, c): return {}")
+ lam.create_function(
+ FunctionName=fn_name, Runtime="python3.11",
+ Role="arn:aws:iam::000000000000:role/r", Handler="index.handler",
+ Code={"ZipFile": buf.getvalue()},
+ )
+
+
+def _lambda_policy_statements(lam, fn_name):
+ try:
+ return json.loads(lam.get_policy(FunctionName=fn_name)["Policy"])["Statement"]
+ except ClientError as exc:
+ assert exc.response["Error"]["Code"] == "ResourceNotFoundException"
+ return []
+
+
+def test_cfn_lambda_permission_update_replaces_the_statement(cfn, lam):
+ """Every AWS::Lambda::Permission property is create-only, so a changed
+ Principal removes the old statement and adds the new one: the function
+ policy ends up with exactly one statement carrying the new principal,
+ not two under the same Sid."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-perm-upd-{uid}"
+ fn_name = f"cfn-perm-upd-{uid}"
+ _cfn_permission_test_function(lam, fn_name)
+
+ def template(principal, source_arn):
+ return json.dumps({
+ "Resources": {"Perm": {"Type": "AWS::Lambda::Permission", "Properties": {
+ "FunctionName": fn_name, "Action": "lambda:InvokeFunction",
+ "Principal": principal, "SourceArn": source_arn,
+ }}},
+ })
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(
+ "s3.amazonaws.com", f"arn:aws:s3:::cfn-perm-upd-{uid}"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ statements = _lambda_policy_statements(lam, fn_name)
+ assert len(statements) == 1
+ assert "s3.amazonaws.com" in json.dumps(statements[0]["Principal"])
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(
+ "events.amazonaws.com", f"arn:aws:events:us-east-1:000000000000:rule/cfn-perm-{uid}"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ statements = _lambda_policy_statements(lam, fn_name)
+ assert len(statements) == 1
+ assert statements[0]["Sid"] == "Perm"
+ assert "events.amazonaws.com" in json.dumps(statements[0]["Principal"])
+ assert statements[0]["Condition"]["ArnLike"]["AWS:SourceArn"].endswith(f"rule/cfn-perm-{uid}")
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ lam.delete_function(FunctionName=fn_name)
+
+
+def test_cfn_lambda_permission_delete_removes_the_statement_it_added(cfn, lam):
+ """A permission declared without an Id gets the logical id as its Sid on
+ create; the delete resolves the same default, so deleting the stack
+ removes the statement instead of leaving it on the function."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-perm-del-{uid}"
+ fn_name = f"cfn-perm-del-{uid}"
+ _cfn_permission_test_function(lam, fn_name)
+ lam.add_permission(
+ FunctionName=fn_name, StatementId="kept", Action="lambda:InvokeFunction",
+ Principal="sns.amazonaws.com",
+ )
+ template = json.dumps({
+ "Resources": {"Perm": {"Type": "AWS::Lambda::Permission", "Properties": {
+ "FunctionName": fn_name, "Action": "lambda:InvokeFunction",
+ "Principal": "s3.amazonaws.com",
+ }}},
+ })
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert {s["Sid"] for s in _lambda_policy_statements(lam, fn_name)} == {"kept", "Perm"}
+
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+ assert {s["Sid"] for s in _lambda_policy_statements(lam, fn_name)} == {"kept"}
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ lam.delete_function(FunctionName=fn_name)
+
+
+def test_cfn_lambda_permission_id_change_replaces_the_statement(cfn, lam):
+ """Id is create-only like every other property: changing it removes the
+ statement under the old Sid and adds one under the new, so the function
+ policy never carries both."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-perm-sid-{uid}"
+ fn_name = f"cfn-perm-sid-{uid}"
+ _cfn_permission_test_function(lam, fn_name)
+
+ def template(sid):
+ return json.dumps({
+ "Resources": {"Perm": {"Type": "AWS::Lambda::Permission", "Properties": {
+ "FunctionName": fn_name, "Action": "lambda:InvokeFunction",
+ "Principal": "s3.amazonaws.com", "Id": sid,
+ }}},
+ })
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("first"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert {s["Sid"] for s in _lambda_policy_statements(lam, fn_name)} == {"first"}
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("second"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert {s["Sid"] for s in _lambda_policy_statements(lam, fn_name)} == {"second"}
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ lam.delete_function(FunctionName=fn_name)
+
+
+def test_cfn_lambda_permission_rollback_of_a_replacement_removes_the_new_statement(cfn, lam, ddb):
+ """When an update that replaced the permission fails later in the run,
+ the rollback removes the statement the replacement added, since the
+ delete resolves the Sid the way the create did. The previous statement
+ is not re-added: the rollback restores the stack record without
+ re-provisioning, which is disclosed in the PR."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-perm-rb-{uid}"
+ fn_name = f"cfn-perm-rb-{uid}"
+ table_name = f"cfn-perm-rb-{uid}"
+ _cfn_permission_test_function(lam, fn_name)
+ lam.add_permission(
+ FunctionName=fn_name, StatementId="kept", Action="lambda:InvokeFunction",
+ Principal="sns.amazonaws.com",
+ )
+
+ def template(principal, key_type):
+ return json.dumps({
+ "Resources": {
+ "Perm": {"Type": "AWS::Lambda::Permission", "Properties": {
+ "FunctionName": fn_name, "Action": "lambda:InvokeFunction",
+ "Principal": principal,
+ }},
+ "Table": {"Type": "AWS::DynamoDB::Table", "DependsOn": "Perm", "Properties": {
+ "TableName": table_name,
+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": key_type}],
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
+ "BillingMode": "PAY_PER_REQUEST",
+ }},
+ },
+ })
+
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("s3.amazonaws.com", "S"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert {s["Sid"] for s in _lambda_policy_statements(lam, fn_name)} == {"kept", "Perm"}
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("events.amazonaws.com", "N"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ statements = _lambda_policy_statements(lam, fn_name)
+ assert {s["Sid"] for s in statements} == {"kept"}
+ assert ddb.describe_table(TableName=table_name)["Table"]["AttributeDefinitions"] == [
+ {"AttributeName": "pk", "AttributeType": "S"}]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ lam.delete_function(FunctionName=fn_name)
+
+
+def _cfn_permission_template(fn_name, **props):
+ return json.dumps({
+ "Resources": {"Perm": {"Type": "AWS::Lambda::Permission", "Properties": {
+ "FunctionName": fn_name, "Action": "lambda:InvokeFunction",
+ "Principal": "s3.amazonaws.com", **props,
+ }}},
+ })
+
+
+def test_cfn_lambda_permission_create_keeps_every_condition_property(cfn, lam):
+ """AWS::Lambda::Permission forwards all of EventSourceToken,
+ FunctionUrlAuthType, InvokedViaFunctionUrl, PrincipalOrgID, SourceAccount
+ and SourceArn to AddPermission (the nine documented properties, per the
+ AWS::Lambda::Permission reference), so the statement carries them as
+ conditions instead of silently dropping them."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-perm-props-{uid}"
+ fn_name = f"cfn-perm-props-{uid}"
+ _cfn_permission_test_function(lam, fn_name)
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_permission_template(
+ fn_name, SourceArn=f"arn:aws:s3:::cfn-perm-props-{uid}", SourceAccount="111122223333",
+ PrincipalOrgID="o-a1b2c3d4e5", FunctionUrlAuthType="AWS_IAM", InvokedViaFunctionUrl=True,
+ EventSourceToken="amzn1.ask.skill.cfn-perm-props",
+ ))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ statements = _lambda_policy_statements(lam, fn_name)
+ assert len(statements) == 1
+ assert statements[0]["Condition"] == {
+ "ArnLike": {"AWS:SourceArn": f"arn:aws:s3:::cfn-perm-props-{uid}"},
+ "StringEquals": {
+ "AWS:SourceAccount": "111122223333",
+ "aws:PrincipalOrgID": "o-a1b2c3d4e5",
+ "lambda:FunctionUrlAuthType": "AWS_IAM",
+ "lambda:EventSourceToken": "amzn1.ask.skill.cfn-perm-props",
+ },
+ "Bool": {"lambda:InvokedViaFunctionUrl": "true"},
+ }
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ lam.delete_function(FunctionName=fn_name)
+
+
+def test_cfn_lambda_permission_function_name_change_replaces_the_statement(cfn, lam):
+ """FunctionName is create-only (AWS::Lambda::Permission reference: Update
+ requires Replacement), so pointing the permission at another function
+ removes the statement from the old function's policy and adds exactly one
+ to the new function's."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-perm-fn-{uid}"
+ old_fn, new_fn = f"cfn-perm-fn-old-{uid}", f"cfn-perm-fn-new-{uid}"
+ _cfn_permission_test_function(lam, old_fn)
+ _cfn_permission_test_function(lam, new_fn)
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_permission_template(old_fn))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert {s["Sid"] for s in _lambda_policy_statements(lam, old_fn)} == {"Perm"}
+ assert _lambda_policy_statements(lam, new_fn) == []
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_permission_template(new_fn))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _lambda_policy_statements(lam, old_fn) == []
+ statements = _lambda_policy_statements(lam, new_fn)
+ assert len(statements) == 1
+ assert statements[0]["Sid"] == "Perm"
+ assert statements[0]["Resource"].endswith(f":function:{new_fn}")
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ lam.delete_function(FunctionName=old_fn)
+ lam.delete_function(FunctionName=new_fn)
+
+
+def test_cfn_lambda_permission_action_change_replaces_the_statement(cfn, lam):
+ """Action is create-only (AWS::Lambda::Permission reference), so a changed
+ Action leaves exactly one statement, carrying the new action."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-perm-action-{uid}"
+ fn_name = f"cfn-perm-action-{uid}"
+ _cfn_permission_test_function(lam, fn_name)
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_permission_template(fn_name))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert [s["Action"] for s in _lambda_policy_statements(lam, fn_name)] == ["lambda:InvokeFunction"]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_permission_template(
+ fn_name, Action="lambda:InvokeFunctionUrl"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ statements = _lambda_policy_statements(lam, fn_name)
+ assert len(statements) == 1
+ assert statements[0]["Sid"] == "Perm"
+ assert statements[0]["Action"] == "lambda:InvokeFunctionUrl"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ lam.delete_function(FunctionName=fn_name)
+
+
+def test_cfn_lambda_permission_source_account_change_replaces_the_statement(cfn, lam):
+ """SourceAccount is create-only (AWS::Lambda::Permission reference) and
+ reaches the statement as an AWS:SourceAccount condition, so a changed
+ account leaves exactly one statement carrying the new value."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-perm-acct-{uid}"
+ fn_name = f"cfn-perm-acct-{uid}"
+ _cfn_permission_test_function(lam, fn_name)
+ source_arn = f"arn:aws:s3:::cfn-perm-acct-{uid}"
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_permission_template(
+ fn_name, SourceArn=source_arn, SourceAccount="111111111111"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ statements = _lambda_policy_statements(lam, fn_name)
+ assert len(statements) == 1
+ assert statements[0]["Condition"]["StringEquals"] == {"AWS:SourceAccount": "111111111111"}
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_permission_template(
+ fn_name, SourceArn=source_arn, SourceAccount="222222222222"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ statements = _lambda_policy_statements(lam, fn_name)
+ assert len(statements) == 1
+ assert statements[0]["Sid"] == "Perm"
+ assert statements[0]["Condition"] == {
+ "ArnLike": {"AWS:SourceArn": source_arn},
+ "StringEquals": {"AWS:SourceAccount": "222222222222"},
+ }
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ lam.delete_function(FunctionName=fn_name)
+
+
+def test_cfn_lambda_permission_qualified_arn_update_replaces_on_the_qualified_resource(cfn, lam):
+ """The update counterpart of the qualified-ARN create: a permission on an
+ alias ARN is replaced in the base function's policy, and the one statement
+ left still names the alias ARN as its Resource (AWS::Lambda::Permission
+ reference: "specify a qualifier to restrict access to a single version or
+ alias")."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-perm-qual-upd-{uid}"
+ fn_name = f"cfn-perm-qual-upd-{uid}"
+ _cfn_permission_test_function(lam, fn_name)
+ try:
+ version = lam.publish_version(FunctionName=fn_name)["Version"]
+ alias_arn = lam.create_alias(FunctionName=fn_name, Name="live", FunctionVersion=version)["AliasArn"]
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_permission_template(alias_arn))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert [s["Resource"] for s in _lambda_policy_statements(lam, fn_name)] == [alias_arn]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_permission_template(
+ alias_arn, Principal="events.amazonaws.com"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ statements = _lambda_policy_statements(lam, fn_name)
+ assert len(statements) == 1
+ assert statements[0]["Sid"] == "Perm"
+ assert statements[0]["Resource"] == alias_arn
+ assert "events.amazonaws.com" in json.dumps(statements[0]["Principal"])
+ assert _lambda_policy_statements(lam, f"{fn_name}:live") == statements
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ lam.delete_function(FunctionName=fn_name)
+
+
+def _cfn_policy_test_roles(iam, roles):
+ assume = json.dumps({"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"},
+ "Action": "sts:AssumeRole"}]})
+ for role in roles:
+ iam.create_role(RoleName=role, AssumeRolePolicyDocument=assume)
+
+
+def _cfn_policy_test_roles_cleanup(iam, roles):
+ for role in roles:
+ for p in iam.list_attached_role_policies(RoleName=role)["AttachedPolicies"]:
+ iam.detach_role_policy(RoleName=role, PolicyArn=p["PolicyArn"])
+ iam.delete_role(RoleName=role)
+
+
+def test_cfn_iam_policy_update_in_place(cfn, iam):
+ """PolicyDocument and Roles update the inline policy in place, as
+ PutRolePolicy does: Ref keeps the policy name, GetAtt Id the same policy
+ id, the document is rewritten and the second role gets the attachment."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-iam-pol-upd-{uid}"
+ roles = [f"cfn-pol-role-a-{uid}", f"cfn-pol-role-b-{uid}"]
+ _cfn_policy_test_roles(iam, roles)
+
+ def template(actions, role_names):
+ return json.dumps({
+ "Resources": {"Pol": {"Type": "AWS::IAM::Policy", "Properties": {
+ "PolicyName": f"cfn-pol-upd-{uid}",
+ "PolicyDocument": {"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": actions, "Resource": "*"}]},
+ "Roles": role_names,
+ }}},
+ "Outputs": {"Name": {"Value": {"Ref": "Pol"}},
+ "Id": {"Value": {"Fn::GetAtt": ["Pol", "Id"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(["s3:GetObject"], roles[:1]))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ policy_id = _output(stack, "Id")
+ attached = iam.list_attached_role_policies(RoleName=roles[0])["AttachedPolicies"]
+ assert [p["PolicyName"] for p in attached] == [f"cfn-pol-upd-{uid}"]
+ policy_arn = attached[0]["PolicyArn"]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(
+ ["s3:GetObject", "s3:PutObject"], roles))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Name") == f"cfn-pol-upd-{uid}"
+ assert _output(stack, "Id") == policy_id
+
+ policy = iam.get_policy(PolicyArn=policy_arn)["Policy"]
+ assert policy["PolicyId"] == policy_id
+ assert policy["AttachmentCount"] == 2
+ assert policy["DefaultVersionId"] == "v2"
+ version = iam.get_policy_version(
+ PolicyArn=policy_arn, VersionId=policy["DefaultVersionId"])["PolicyVersion"]
+ document = version["Document"]
+ if isinstance(document, str):
+ document = json.loads(document)
+ assert document["Statement"][0]["Action"] == ["s3:GetObject", "s3:PutObject"]
+ for role in roles:
+ attached = iam.list_attached_role_policies(RoleName=role)["AttachedPolicies"]
+ assert [p["PolicyArn"] for p in attached] == [policy_arn]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ _cfn_policy_test_roles_cleanup(iam, roles)
+
+
+def test_cfn_iam_policy_rename_keeps_id_versions_and_attachments(cfn, iam):
+ """"PolicyName ... Update requires: No interruption", and "GetAtt Id: The
+ stable and unique string identifying the policy"
+ (aws-resource-iam-policy.html) — a renamed policy keeps its id, its
+ version history and its attachments; Ref follows the new name."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-iam-pol-ren-{uid}"
+ role = f"cfn-pol-ren-role-{uid}"
+ _cfn_policy_test_roles(iam, [role])
+
+ def template(name, action):
+ return json.dumps({
+ "Resources": {"Pol": {"Type": "AWS::IAM::Policy", "Properties": {
+ "PolicyName": name,
+ "PolicyDocument": {"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": action, "Resource": "*"}]},
+ "Roles": [role],
+ }}},
+ "Outputs": {"Name": {"Value": {"Ref": "Pol"}},
+ "Id": {"Value": {"Fn::GetAtt": ["Pol", "Id"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(f"cfn-pol-a-{uid}", "s3:GetObject"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ policy_id = _output(stack, "Id")
+ old_arn = iam.list_attached_role_policies(RoleName=role)["AttachedPolicies"][0]["PolicyArn"]
+ created = iam.get_policy(PolicyArn=old_arn)["Policy"]["CreateDate"]
+
+ # A document change first, so the rename has a version history to keep.
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(f"cfn-pol-a-{uid}", "s3:PutObject"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert iam.get_policy(PolicyArn=old_arn)["Policy"]["DefaultVersionId"] == "v2"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(f"cfn-pol-b-{uid}", "s3:PutObject"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Name") == f"cfn-pol-b-{uid}"
+ assert _output(stack, "Id") == policy_id
+
+ attached = iam.list_attached_role_policies(RoleName=role)["AttachedPolicies"]
+ assert [p["PolicyName"] for p in attached] == [f"cfn-pol-b-{uid}"]
+ new_arn = attached[0]["PolicyArn"]
+ assert new_arn != old_arn
+ policy = iam.get_policy(PolicyArn=new_arn)["Policy"]
+ assert policy["PolicyId"] == policy_id
+ assert policy["PolicyName"] == f"cfn-pol-b-{uid}"
+ assert policy["AttachmentCount"] == 1
+ assert policy["DefaultVersionId"] == "v2"
+ assert policy["CreateDate"] == created
+ versions = iam.list_policy_versions(PolicyArn=new_arn)["Versions"]
+ assert sorted(v["VersionId"] for v in versions) == ["v1", "v2"]
+ entities = iam.list_entities_for_policy(PolicyArn=new_arn)
+ assert [r["RoleName"] for r in entities["PolicyRoles"]] == [role]
+ with pytest.raises(ClientError) as exc_info:
+ iam.get_policy(PolicyArn=old_arn)
+ assert exc_info.value.response["Error"]["Code"] == "NoSuchEntity"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ _cfn_policy_test_roles_cleanup(iam, [role])
+
+
+def test_cfn_iam_policy_role_removed_from_roles_is_detached(cfn, iam):
+ """A role dropped from Roles loses the policy, the way the inline policy
+ goes away on AWS, while the document, the policy id and the other
+ role's attachment stay."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-iam-pol-rm-{uid}"
+ roles = [f"cfn-pol-rm-role-a-{uid}", f"cfn-pol-rm-role-b-{uid}"]
+ _cfn_policy_test_roles(iam, roles)
+
+ def template(role_names):
+ return json.dumps({
+ "Resources": {"Pol": {"Type": "AWS::IAM::Policy", "Properties": {
+ "PolicyName": f"cfn-pol-rm-{uid}",
+ "PolicyDocument": {"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]},
+ "Roles": role_names,
+ }}},
+ "Outputs": {"Id": {"Value": {"Fn::GetAtt": ["Pol", "Id"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(roles))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ policy_id = _output(stack, "Id")
+ policy_arn = iam.list_attached_role_policies(RoleName=roles[0])["AttachedPolicies"][0]["PolicyArn"]
+ assert iam.get_policy(PolicyArn=policy_arn)["Policy"]["AttachmentCount"] == 2
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(roles[1:]))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Id") == policy_id
+ assert iam.list_attached_role_policies(RoleName=roles[0])["AttachedPolicies"] == []
+ attached = iam.list_attached_role_policies(RoleName=roles[1])["AttachedPolicies"]
+ assert [p["PolicyArn"] for p in attached] == [policy_arn]
+ policy = iam.get_policy(PolicyArn=policy_arn)["Policy"]
+ assert policy["PolicyId"] == policy_id
+ assert policy["AttachmentCount"] == 1
+ assert policy["DefaultVersionId"] == "v1"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ _cfn_policy_test_roles_cleanup(iam, roles)
+
+
+def test_cfn_iam_policy_users_and_groups_reconcile(cfn, iam):
+ """"Users ... Update requires: No interruption" and "Groups ... Update
+ requires: No interruption" (aws-resource-iam-policy.html) — a user or
+ group dropped from the list is detached, one added is attached, and the
+ policy id survives the update."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-iam-pol-ug-{uid}"
+ users = [f"cfn-pol-user-a-{uid}", f"cfn-pol-user-b-{uid}"]
+ groups = [f"cfn-pol-group-a-{uid}", f"cfn-pol-group-b-{uid}"]
+ for user in users:
+ iam.create_user(UserName=user)
+ for group in groups:
+ iam.create_group(GroupName=group)
+
+ def template(user_names, group_names):
+ return json.dumps({
+ "Resources": {"Pol": {"Type": "AWS::IAM::Policy", "Properties": {
+ "PolicyName": f"cfn-pol-ug-{uid}",
+ "PolicyDocument": {"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]},
+ "Users": user_names,
+ "Groups": group_names,
+ }}},
+ "Outputs": {"Id": {"Value": {"Fn::GetAtt": ["Pol", "Id"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(users[:1], groups[:1]))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ policy_id = _output(stack, "Id")
+ policy_arn = iam.list_attached_user_policies(UserName=users[0])["AttachedPolicies"][0]["PolicyArn"]
+ assert [p["PolicyArn"] for p in
+ iam.list_attached_group_policies(GroupName=groups[0])["AttachedPolicies"]] == [policy_arn]
+ assert iam.get_policy(PolicyArn=policy_arn)["Policy"]["AttachmentCount"] == 2
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(users[1:], groups[1:]))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Id") == policy_id
+ assert iam.list_attached_user_policies(UserName=users[0])["AttachedPolicies"] == []
+ assert iam.list_attached_group_policies(GroupName=groups[0])["AttachedPolicies"] == []
+ assert [p["PolicyArn"] for p in
+ iam.list_attached_user_policies(UserName=users[1])["AttachedPolicies"]] == [policy_arn]
+ assert [p["PolicyArn"] for p in
+ iam.list_attached_group_policies(GroupName=groups[1])["AttachedPolicies"]] == [policy_arn]
+ policy = iam.get_policy(PolicyArn=policy_arn)["Policy"]
+ assert policy["PolicyId"] == policy_id
+ assert policy["AttachmentCount"] == 2
+ entities = iam.list_entities_for_policy(PolicyArn=policy_arn)
+ assert [u["UserName"] for u in entities["PolicyUsers"]] == users[1:]
+ assert [g["GroupName"] for g in entities["PolicyGroups"]] == groups[1:]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ for user in users:
+ for p in iam.list_attached_user_policies(UserName=user)["AttachedPolicies"]:
+ iam.detach_user_policy(UserName=user, PolicyArn=p["PolicyArn"])
+ iam.delete_user(UserName=user)
+ for group in groups:
+ iam.delete_group(GroupName=group)
+
+
+def test_cfn_iam_policy_delete_detaches_entities(cfn, iam):
+ """Deleting the stack takes the inline policy off the role it was
+ embedded in ("Adds or updates an inline policy document that is embedded
+ in the specified IAM group, user or role", aws-resource-iam-policy.html):
+ the role's attached list is empty and the policy is gone once the stack
+ reports DELETE_COMPLETE — checked before the fixture cleanup, which
+ would otherwise mask a leftover attachment."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-iam-pol-del-{uid}"
+ role = f"cfn-pol-del-role-{uid}"
+ _cfn_policy_test_roles(iam, [role])
+ template = json.dumps({
+ "Resources": {"Pol": {"Type": "AWS::IAM::Policy", "Properties": {
+ "PolicyName": f"cfn-pol-del-{uid}",
+ "PolicyDocument": {"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]},
+ "Roles": [role],
+ }}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ attached = iam.list_attached_role_policies(RoleName=role)["AttachedPolicies"]
+ assert [p["PolicyName"] for p in attached] == [f"cfn-pol-del-{uid}"]
+ policy_arn = attached[0]["PolicyArn"]
+
+ cfn.delete_stack(StackName=stack_name)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"
+ assert iam.list_attached_role_policies(RoleName=role)["AttachedPolicies"] == []
+ with pytest.raises(ClientError) as exc_info:
+ iam.get_policy(PolicyArn=policy_arn)
+ assert exc_info.value.response["Error"]["Code"] == "NoSuchEntity"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ _cfn_policy_test_roles_cleanup(iam, [role])
+
+
+def test_cfn_iam_managed_policy_delete_detaches_entities(cfn, iam):
+ """Deleting a stack detaches its AWS::IAM::ManagedPolicy from the role it
+ named before the policy goes, so the role does not keep a dangling ARN
+ in its attached list — checked before the fixture cleanup runs."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-iam-mpol-del-{uid}"
+ role = f"cfn-mpol-del-role-{uid}"
+ _cfn_policy_test_roles(iam, [role])
+ template = json.dumps({
+ "Resources": {"Pol": {"Type": "AWS::IAM::ManagedPolicy", "Properties": {
+ "ManagedPolicyName": f"cfn-mpol-del-{uid}",
+ "PolicyDocument": {"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]},
+ "Roles": [role],
+ }}},
+ "Outputs": {"Arn": {"Value": {"Ref": "Pol"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template)
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ policy_arn = _output(stack, "Arn")
+ assert [p["PolicyArn"] for p in
+ iam.list_attached_role_policies(RoleName=role)["AttachedPolicies"]] == [policy_arn]
+
+ cfn.delete_stack(StackName=stack_name)
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"
+ assert iam.list_attached_role_policies(RoleName=role)["AttachedPolicies"] == []
+ with pytest.raises(ClientError) as exc_info:
+ iam.get_policy(PolicyArn=policy_arn)
+ assert exc_info.value.response["Error"]["Code"] == "NoSuchEntity"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ _cfn_policy_test_roles_cleanup(iam, [role])
+
+
+def test_cfn_iam_policy_version_cap_prunes_on_sixth_document(cfn, iam):
+ """Every PolicyDocument change becomes a new default version; at the IAM
+ five-version cap the oldest non-default version is pruned first, so the
+ sixth document lands as v6 with five versions listed and the policy id
+ unchanged throughout."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-iam-pol-cap-{uid}"
+ role = f"cfn-pol-cap-role-{uid}"
+ _cfn_policy_test_roles(iam, [role])
+
+ def template(n):
+ return json.dumps({
+ "Resources": {"Pol": {"Type": "AWS::IAM::Policy", "Properties": {
+ "PolicyName": f"cfn-pol-cap-{uid}",
+ "PolicyDocument": {"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "s3:GetObject", "Resource": f"arn:aws:s3:::bucket-{n}/*"}]},
+ "Roles": [role],
+ }}},
+ "Outputs": {"Id": {"Value": {"Fn::GetAtt": ["Pol", "Id"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(1))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ policy_id = _output(stack, "Id")
+ policy_arn = iam.list_attached_role_policies(RoleName=role)["AttachedPolicies"][0]["PolicyArn"]
+
+ for n in range(2, 7):
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(n))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Id") == policy_id
+ assert iam.get_policy(PolicyArn=policy_arn)["Policy"]["DefaultVersionId"] == f"v{n}"
+
+ versions = iam.list_policy_versions(PolicyArn=policy_arn)["Versions"]
+ assert sorted(v["VersionId"] for v in versions) == ["v2", "v3", "v4", "v5", "v6"]
+ assert [v["VersionId"] for v in versions if v["IsDefaultVersion"]] == ["v6"]
+ document = iam.get_policy_version(PolicyArn=policy_arn, VersionId="v6")["PolicyVersion"]["Document"]
+ if isinstance(document, str):
+ document = json.loads(document)
+ assert document["Statement"][0]["Resource"] == "arn:aws:s3:::bucket-6/*"
+ assert iam.get_policy(PolicyArn=policy_arn)["Policy"]["AttachmentCount"] == 1
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ _cfn_policy_test_roles_cleanup(iam, [role])
def test_cfn_update_rollback_keeps_the_resources_that_existed_before(cfn, sqs, ddb):
"""A failed update rolls back only what the update created. The queue
existed before the update and kept its physical id through an in-place
diff --git a/tests/test_cloudwatch.py b/tests/test_cloudwatch.py
index f5d8bc1e..6c39c3cd 100644
--- a/tests/test_cloudwatch.py
+++ b/tests/test_cloudwatch.py
@@ -192,6 +192,87 @@ def test_cloudwatch_set_alarm_state_v2(cw):
assert after["StateValue"] == "ALARM"
assert after["StateReason"] == "Manual trigger for testing"
+def test_cloudwatch_put_metric_alarm_keeps_state_of_existing_alarm(cw):
+ """PutMetricAlarm on an existing alarm: "its state is left unchanged, but
+ the update completely overwrites the previous configuration of the alarm"
+ (https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_PutMetricAlarm.html).
+ The state timestamp is part of the state: only the configuration timestamp
+ moves. Goes over the wire, which botocore sends as smithy-rpc-v2-cbor."""
+ name = f"cw-keep-state-{_uuid_mod.uuid4().hex[:8]}"
+
+ def put(threshold):
+ cw.put_metric_alarm(
+ AlarmName=name,
+ MetricName="Errors",
+ Namespace=f"CwKeepState/{name}",
+ Statistic="Sum",
+ Period=60,
+ EvaluationPeriods=1,
+ Threshold=threshold,
+ ComparisonOperator="GreaterThanThreshold",
+ )
+
+ put(1.0)
+ try:
+ cw.set_alarm_state(AlarmName=name, StateValue="ALARM", StateReason="seeded")
+ seeded = cw.describe_alarms(AlarmNames=[name])["MetricAlarms"][0]
+ time.sleep(1.1) # timestamps are whole seconds; a reset must be visible
+
+ put(2.0)
+ after = cw.describe_alarms(AlarmNames=[name])["MetricAlarms"][0]
+ assert after["Threshold"] == 2.0
+ assert after["StateValue"] == "ALARM"
+ assert after["StateReason"] == "seeded"
+ assert after["StateUpdatedTimestamp"] == seeded["StateUpdatedTimestamp"]
+ assert after["AlarmConfigurationUpdatedTimestamp"] > seeded["AlarmConfigurationUpdatedTimestamp"]
+ finally:
+ cw.delete_alarms(AlarmNames=[name])
+
+
+def test_cloudwatch_put_metric_alarm_query_keeps_state_of_existing_alarm():
+ """The query-protocol branch of PutMetricAlarm (what the AWS CLI v1 and
+ older SDKs send) keeps the state of an existing alarm the same way:
+ "its state is left unchanged" per the PutMetricAlarm reference."""
+ from ministack.core import responses as _resp
+ from ministack.services import cloudwatch as _cw
+
+ acct_tok = _resp._request_account_id.set("000000000000")
+ region_tok = _resp._request_region.set("us-east-1")
+ name = f"query-keep-state-{_uuid_mod.uuid4().hex[:8]}"
+
+ def put(threshold):
+ status, _headers, _body = _cw._put_metric_alarm({
+ "AlarmName": [name],
+ "MetricName": ["Errors"],
+ "Namespace": [f"QueryKeepState/{name}"],
+ "Statistic": ["Sum"],
+ "Period": ["60"],
+ "EvaluationPeriods": ["1"],
+ "Threshold": [threshold],
+ "ComparisonOperator": ["GreaterThanThreshold"],
+ }, {}, is_cbor=False)
+ assert status == 200
+
+ try:
+ put("1")
+ _cw._alarms[name]["StateValue"] = "ALARM"
+ _cw._alarms[name]["StateReason"] = "seeded"
+ _cw._alarms[name]["StateUpdatedTimestamp"] = 1_000_000
+ _cw._alarms[name]["AlarmConfigurationUpdatedTimestamp"] = 1_000_000
+
+ put("2")
+ alarm = _cw._alarms[name]
+ assert alarm["Threshold"] == 2.0
+ assert alarm["StateValue"] == "ALARM"
+ assert alarm["StateReason"] == "seeded"
+ assert alarm["StateUpdatedTimestamp"] == 1_000_000
+ assert alarm["AlarmConfigurationUpdatedTimestamp"] > 1_000_000
+ finally:
+ _cw._alarms.pop_scoped("000000000000", "us-east-1", name, None)
+ _resp._request_region.reset(region_tok)
+ _resp._request_account_id.reset(acct_tok)
+
+
def test_cloudwatch_get_metric_data_v2(cw):
cw.put_metric_data(
Namespace="CWData2",
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index ce9bdb58..68a9c7a9 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -2711,6 +2711,37 @@ def test_lambda_add_remove_permission(lam):
policy2 = json.loads(lam.get_policy(FunctionName="qa-lam-policy")["Policy"])
assert not any(s["Sid"] == "allow-s3" for s in policy2["Statement"])
+def test_lambda_add_permission_keeps_event_source_token_and_invoked_via_function_url(lam):
+ """EventSourceToken lands as a StringEquals on lambda:EventSourceToken and
+ InvokedViaFunctionUrl as a Bool on lambda:InvokedViaFunctionUrl with a
+ string value, the shape Lambda writes for function URL statements
+ (https://docs.aws.amazon.com/lambda/latest/dg/urls-auth.html)."""
+ fn = f"qa-lam-policy-cond-{_uuid_mod.uuid4().hex[:8]}"
+ lam.create_function(
+ FunctionName=fn,
+ Runtime="python3.12",
+ Role="arn:aws:iam::000000000000:role/r",
+ Handler="index.handler",
+ Code={"ZipFile": _zip_lambda("def handler(e,c): return {}")},
+ )
+ try:
+ added = json.loads(lam.add_permission(
+ FunctionName=fn,
+ StatementId="alexa",
+ Action="lambda:InvokeFunction",
+ Principal="alexa-appkit.amazon.com",
+ EventSourceToken="amzn1.ask.skill.qa-lam-policy-cond",
+ InvokedViaFunctionUrl=True,
+ )["Statement"])
+ assert added["Condition"] == {
+ "StringEquals": {"lambda:EventSourceToken": "amzn1.ask.skill.qa-lam-policy-cond"},
+ "Bool": {"lambda:InvokedViaFunctionUrl": "true"},
+ }
+ policy = json.loads(lam.get_policy(FunctionName=fn)["Policy"])
+ assert [s["Condition"] for s in policy["Statement"]] == [added["Condition"]]
+ finally:
+ lam.delete_function(FunctionName=fn)
+
def test_lambda_list_functions_pagination(lam):
"""ListFunctions pagination with Marker works correctly."""
for i in range(5):