Skip to content

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

feat(cloudformation): update handlers for thirteen more types (Cognito, SQS, SNS, Lambda, Logs, IAM, API Gateway v2, CloudFront) (#1702)

iot-rocket4b60a6c95f11
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dabc6386..74bfc0b3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,35 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **Transcribe — `StartTranscriptionJob` returns a job already `IN_PROGRESS`** — the start response reported `QUEUED` with no `StartTime`, and the job reached `IN_PROGRESS` only from the background worker, after the response had been sent. A caller that reads the status off the start response and then waits for the terminal `Transcribe Job State Change` event, rather than polling, therefore never saw an in-progress state at all: the job went straight from queued to complete. Jobs now start `IN_PROGRESS` with `StartTime` set, matching the response the AWS CLI walkthrough documents, and `TRANSCRIBE_JOB_RUN_SECONDS` covers the whole run rather than half of it. `QUEUED`, which AWS reaches only for a request that opted into job queueing through `JobExecutionSettings.AllowDeferredExecution` while the account is at its concurrent job limit, stays reachable through the new `TRANSCRIBE_JOB_QUEUE_SECONDS` (default `0`); both knobs are settable at runtime through `/_ministack/config`. Contributed by @ppettitau.
+- **Cognito — `SetIdentityPoolRoles` keeps the role mappings it is given** — the call stored `Roles` only and `GetIdentityPoolRoles` answered a hard-coded `RoleMappings: {}`, so a mapping set through the API, or declared on a CloudFormation `AWS::Cognito::IdentityPoolRoleAttachment`, was accepted and silently dropped. Both members are stored on the identity pool and served back now; the call sets the whole configuration and the API has no call that removes a mapping on its own, so an omitted `RoleMappings` clears what was there (reasoned from the API surface, not measured against a live account). The map is stored as sent rather than validated, and takes no part in credential vending, which still picks the role by `authenticated` or `unauthenticated`. Contributed by @iot-rocket.
+
+- **CloudFormation — `AWS::Cognito::IdentityPoolRoleAttachment` updates in place** — the type had no update handler, so a stack update fell through to the create handler and nothing in the code said which property may change in place and which one replaces. `Roles` and `RoleMappings` are "Update requires: No interruption" on the resource reference and are re-applied to the pool the attachment already sits on, a property the template drops reverts to its create default (`SetIdentityPoolRoles` takes the whole configuration), and `IdentityPoolId` requires replacement, so the new pool is configured before the old one is cleared. Contributed by @iot-rocket.
+
+- **CloudFormation — `AWS::Cognito::UserPoolResourceServer` updates in place, and a move between pools is refused** — the type had no update handler either. The physical id of a resource server is its `Identifier` alone while the record is keyed by pool and identifier, so a template that repointed `UserPoolId` provisioned a second resource server in the new pool and left the old one behind in the old pool, with no replacement for the engine to clean up: two live copies of a resource server the template declares once, both vending scopes. `Name` and `Scopes` now go through `UpdateResourceServer` on the resource server that is already there, a dropped `Scopes` reverts to the empty list `UpdateResourceServer` defaults it to, a changed `Identifier` is the rename CloudFormation allows and replaces (retained when the resource says so), and a changed `UserPoolId` under an unchanged identifier gets CloudFormation's own refusal, since `Identifier` is always a custom name. Contributed by @iot-rocket.
+
+- **CloudFormation — `AWS::SQS::QueuePolicy` updates in place** — the type had no update handler, so a stack update that changed the policy fell through to create, which minted a new physical id; the engine recorded a replacement and the cleanup delete then removed `Policy` from the very queues the new document had just been written to (measured: after the update the queue had no policy at all). `PolicyDocument` and `Queues` are both No interruption on the resource reference, so the resource now keeps its physical id, writes the new document on every queue the template names and removes it from a queue dropped from `Queues`. Contributed by @iot-rocket.
+
+- **CloudFormation — `AWS::SNS::TopicPolicy` updates in place** — the same defect as the queue policy: no update handler, so a changed policy fell through to create under a fresh physical id, the engine recorded a replacement and the cleanup delete removed `Policy` from the topics the new document had just been written to (measured: after the update `GetTopicAttributes` returned no policy). `PolicyDocument` and `Topics` are both No interruption on the resource reference, so the resource now keeps its physical id, writes the new document on every topic the template names and removes it from a topic dropped from `Topics`. Contributed by @iot-rocket.
+
+- **CloudFormation — `AWS::SNS::Subscription` updates in place** — the type had no update handler, so a changed `FilterPolicy` or `RawMessageDelivery` re-subscribed under a fresh `SubscriptionArn` and the old subscription was deleted (measured: the `Ref` changed on every update), while the resource reference marks `DeliveryPolicy`, `FilterPolicy`, `FilterPolicyScope`, `RawMessageDelivery`, `RedrivePolicy` and `SubscriptionRoleArn` No interruption. Those now go through `SetSubscriptionAttributes` on the existing subscription, a dropped property reverts to what the create stores without it, and only `TopicArn`, `Protocol` or `Endpoint` replaces the subscription. The create also stores `DeliveryPolicy`, `RedrivePolicy` and `SubscriptionRoleArn`, which it dropped, and `SetSubscriptionAttributes` accepts `SubscriptionRoleArn` as the API does. Contributed by @iot-rocket.
+
+- **CloudFormation — `AWS::Lambda::Alias` updates in place, and `ProvisionedConcurrencyConfig` reaches the service** — the type had no update handler and its create ignored `ProvisionedConcurrencyConfig` and stored `RoutingConfig` in the template's list shape (measured: `GetProvisionedConcurrencyConfig` on the alias answered `ProvisionedConcurrencyConfigNotFoundException` right after the deploy, and boto3's `GetAlias` on an alias with a `RoutingConfig` failed on the list where it expects a map). `FunctionVersion`, `Description`, `RoutingConfig` and `ProvisionedConcurrencyConfig` are No interruption on the resource reference and now go through `UpdateAlias` and `PutProvisionedConcurrencyConfig` on the existing alias, a dropped `Description` empties, a dropped `RoutingConfig` or `ProvisionedConcurrencyConfig` is removed, and `Name` or `FunctionName` replaces the alias. The routing weights are stored as the `{version: weight}` map `GetAlias` returns, on create as well. Contributed by @iot-rocket.
+
+- **CloudFormation — `AWS::Logs::SubscriptionFilter` updates in place, and a group change moves it** — the type had no update handler; a changed `LogGroupName` fell through to create, which wrote the filter on the new group under its unchanged name, so the engine saw no replacement and the old group kept its copy (measured: two groups carried the filter after the update). `FilterPattern`, `DestinationArn`, `RoleArn` and `Distribution` are No interruption on the resource reference and now go through `PutSubscriptionFilter` on the existing filter, a dropped property reverts to what the create stores without it, and a changed `FilterName` or `LogGroupName` creates the new filter before the old one is removed. Contributed by @iot-rocket.
+
+- **CloudFormation — `AWS::IAM::InstanceProfile` updates in place, and a named profile refuses a `Path` change** — the type had no update handler, so a `Roles` change fell through to create, which rebuilt the record with no tags and stored the roles as whole role records, on which `GetInstanceProfile` failed (measured: HTTP 500 on any CloudFormation-provisioned profile that has a role); a `Path` change on a custom-named profile was silently executed. `Roles` is No interruption on the resource reference and is now applied to the existing record, which keeps its ARN, id and API-set tags; `InstanceProfileName` and `Path` are Replacement, so a custom-named profile whose `Path` changes fails the update with CloudFormation's "cannot update a stack when a custom-named resource requires replacing" and a generated-name profile is re-created under the new path. The create stores role names, so the profile reads back. Contributed by @iot-rocket.
+
+- **CloudFormation — `AWS::ApiGatewayV2::Api` updates in place** — a stack update that changed an API fell through to the create handler: a new `ApiId` and `ApiEndpoint` on every change, every route, integration and stage re-created under the new id, and with an `ms-custom-id` tag the second lookup refused the pinned id as already in use and rolled the stack back. Every property but `ProtocolType` is *No interruption* on the resource reference, so the API now keeps its id, its endpoint and the children stored under it; a property the template drops reverts to the create's default (no `CorsConfiguration`, the protocol's route selection expression, which the create hard-coded to the HTTP value for both protocols), `Tags` are reconciled, and a `ProtocolType` change replaces the API in CloudFormation's order. `Description` is stored, as `CreateApi` does. Contributed by @iot-rocket.
+
+- **CloudFormation — `AWS::ApiGatewayV2::Integration` updates in place** — a stack update that changed an integration fell through to the create handler: a second integration under a new id, `Ref` flipping to it, the old one left on the API while every route's `Target` still named it. Every property but `ApiId` is *No interruption* on the resource reference, so the integration now keeps its id as `UpdateIntegration` does; a property the template drops reverts to the create's default (no `RequestParameters`, a 30 s timeout, the `POST` method), and an `ApiId` change creates the integration on the new API before the old one is removed. Contributed by @iot-rocket.
+
+- **CloudFormation — `AWS::ApiGatewayV2::Route` updates in place** — a stack update that changed a route fell through to the create handler: a second route under a new id, `Ref` flipping to it, the old one left on the API with its route key still matching requests. Every property but `ApiId` is *No interruption* on the resource reference, so the route now keeps its id as `UpdateRoute` does; a property the template drops reverts to the create's default (no `AuthorizationScopes`, `AuthorizationType` `NONE`, no `AuthorizerId`), and an `ApiId` change creates the route on the new API before the old one is removed. Contributed by @iot-rocket.
+
+- **CloudFormation — `AWS::ApiGatewayV2::Stage` updates in place** — a stack update that changed a stage fell through to the create handler, which rebuilt the record under the same name: `CreatedDate` reset to now and the tags map `GetStage` reports was replaced instead of reconciled. Every property but `ApiId` and `StageName` is *No interruption* on the resource reference, so the stage now keeps its record as `UpdateStage` does and refreshes `LastUpdatedDate`; a property the template drops reverts to the create's default (`AutoDeploy` false, no stage variables), `Tags` are reconciled, and a `StageName` or `ApiId` change creates the new stage before the old one is removed. Contributed by @iot-rocket.
+
+- **CloudFormation — `AWS::CloudFront::Distribution` updates in place, and a provisioned distribution is readable** — a stack update that changed a distribution fell through to the create handler: a new `Id` and `DomainName` on every change, the old distribution deleted by the engine, while `DistributionConfig` and `Tags`, the type's two properties, are both *No interruption* on the resource reference. And the create stored an empty configuration, so `GetDistribution` and `GetDistributionConfig` answered a 500 on every CloudFormation-provisioned distribution and `ListDistributions` showed empty blocks. The create now renders the template's `DistributionConfig` into what `CreateDistribution` stores, in the API's shape (a plain list becomes a `Quantity`/`Items` block, `CachedMethods` nests under `AllowedMethods`, `IPV6Enabled` is `IsIPV6Enabled`, `OriginCustomHeaders` is `CustomHeaders`, an empty block carries no `Items`, the legacy `CNAMEs`, `CustomOrigin` and `S3Origin` are dropped), with a `CallerReference` of its own and the resource `Tags`; the update keeps `Id`, `ARN`, `DomainName` and the invalidation history, stores the new configuration, rolls the `ETag`, refreshes `LastModifiedTime` and reconciles the tags, as `UpdateDistribution` does; deleting the distribution removes its tags with it. Now that the type has a tag store, it joins the table that merges the stack's own tags and the three `aws:cloudformation:` tags into a resource, as every other tag-storing type already did. Contributed by @iot-rocket.
+
+- **API Gateway v2 — `UpdateApi` keeps the description and the API key selection expression** — the call applied five members and silently discarded `Description` and `ApiKeySelectionExpression`, so an update through the API lost what the create had stored. Both are applied now, and `CorsConfiguration` follows the call's own semantics: `UpdateApi` carries the whole configuration, so an empty one removes it instead of storing a blank block. Contributed by @iot-rocket.
- **CloudFormation — a nested stack's IAM resources need the parent's capabilities** — the check under `AUTH=true` read the parent template only, so a parent deployed without `--capabilities` provisioned a child full of IAM roles through `AWS::CloudFormation::Stack`. The child template is now checked against the set the parent acknowledged when it is read, and a child's child reads the same set, as AWS asks for the capabilities on the parent for every level of nesting; a missing one fails the nested-stack resource with the message of `InsufficientCapabilitiesException` (`Requires capabilities : [CAPABILITY_IAM]`) and the parent rolls back unless rollback is disabled. Under `AUTH=true` the child's record carries the parent's set, so `DescribeStacks` reports it there too; without `AUTH` nothing is recorded and nothing changes. Contributed by @iot-rocket.
- **CloudFormation — the SAM transform reads the transforms the response reports** — `ValidateTemplate` normalises the `Transform` section in every form it takes, but the deploy path had its own normalisation that left the macro object (`Transform: {Name: AWS::Serverless-2016-10-31}`) in the list, so a template written that way was reported as declaring the SAM transform and then deployed untransformed: its `AWS::Serverless::Function` resources stayed as they were and the stack failed on an unsupported type. Both read one function now, so the response and the deploy agree about what a template declares. Contributed by @iot-rocket.
diff --git a/ministack/services/apigateway.py b/ministack/services/apigateway.py
index 427c2330..20bb8034 100644
--- a/ministack/services/apigateway.py
+++ b/ministack/services/apigateway.py
@@ -1838,10 +1838,18 @@ def _update_api(api_id, data):
api = _apis.get(api_id)
if not api:
return _apigw_error("NotFoundException", f"API {api_id} not found", 404)
- for k in ("name", "corsConfiguration", "routeSelectionExpression",
- "disableSchemaValidation", "disableExecuteApiEndpoint", "version"):
+ for k in ("name", "routeSelectionExpression", "apiKeySelectionExpression",
+ "disableSchemaValidation", "disableExecuteApiEndpoint", "version",
+ "description"):
if k in data:
api[k] = data[k]
+ # UpdateApi takes the whole CORS configuration, so an empty one removes it
+ # rather than storing a blank block the reader would have to interpret.
+ if "corsConfiguration" in data:
+ if data["corsConfiguration"]:
+ api["corsConfiguration"] = data["corsConfiguration"]
+ else:
+ api.pop("corsConfiguration", None)
return _apigw_response(api)
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 4ccf3687..4328c6d6 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -566,6 +566,16 @@ def _requires_replacement_cognito_user_pool_group(old_props, new_props):
return old_props.get("UserPoolId") != new_props.get("UserPoolId")
+def _requires_replacement_cognito_resource_server(old_props, new_props):
+ """AWS::Cognito::UserPoolResourceServer requires replacement when
+ UserPoolId changes (the resource reference marks the property "Update
+ requires: Replacement"). Identifier is "Replacement" as well, but it is
+ also the physical name, so a change to it is a replacement under a new
+ name, which the custom-name guard does not block; only the pool move is
+ a replacement under an unchanged name."""
+ 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
@@ -584,6 +594,12 @@ _CUSTOM_NAME_REPLACEMENT = {
"name": "GroupName",
"requires_replacement": _requires_replacement_cognito_user_pool_group,
},
+ "AWS::Cognito::UserPoolResourceServer": {
+ # Identifier is the physical id of the resource server and the prefix
+ # of every scope string it vends, so it is always a custom name.
+ "name": "Identifier",
+ "requires_replacement": _requires_replacement_cognito_resource_server,
+ },
"AWS::IoT::ThingGroup": {
"name": "ThingGroupName",
"requires_replacement": lambda old, new: old.get("ParentGroupName") != new.get("ParentGroupName"),
@@ -593,6 +609,10 @@ _CUSTOM_NAME_REPLACEMENT = {
"name": "TrackerName",
"requires_replacement": lambda old, new: old.get("KmsKeyId") != new.get("KmsKeyId"),
},
+ "AWS::IAM::InstanceProfile": {
+ "name": "InstanceProfileName",
+ "requires_replacement": lambda old, new: old.get("Path", "/") != new.get("Path", "/"),
+ },
}
@@ -627,18 +647,27 @@ _RETAIN_REPLACED = contextvars.ContextVar("cfn_retain_replaced", default=False)
def _rename_replacement(physical_id, old_props, new_props, stack_name, logical_id,
- declared_name, current_name, create_fn, delete_fn):
+ declared_name, current_name, create_fn, delete_fn,
+ delete_when_id_unchanged=False):
"""Shared prologue for the name-keyed update handlers: when the resource
record is gone (current_name is None) or its create-only name property
changed, the update is a replacement — create the new resource first, then
delete the old one, in CloudFormation's replacement order (unless the
resource's UpdateReplacePolicy retains it). Returns the create result, or
None when the update can proceed in place.
+
+ The predecessor is normally left alone when the create returns the same
+ physical id, because then it IS the predecessor. A type whose physical id
+ does not carry its whole identity (a subscription filter keyed by group
+ and name, a resource server keyed by pool and identifier) replaces under
+ an unchanged id and has to delete the old record itself: those pass
+ ``delete_when_id_unchanged``.
"""
if current_name is not None and declared_name == current_name:
return None
created = create_fn(logical_id or physical_id, new_props, stack_name)
- if current_name is not None and created[0] != physical_id and not _RETAIN_REPLACED.get():
+ replaced = created[0] != physical_id or delete_when_id_unchanged
+ if current_name is not None and replaced and not _RETAIN_REPLACED.get():
delete_fn(physical_id, old_props)
return created
@@ -754,7 +783,7 @@ def _reconcile_tag_list(store: list, old_props: dict, new_props: dict,
# The types whose provisioner stores a tag property, with that property's name
# and shape. Stack-level tags and the three ``aws:cloudformation:`` tags are
# merged into the property before the resource is created or updated; a type
-# outside this table has no tag store the stack tags could reach.
+# outside this table has no tag store to merge them into.
_STACK_TAG_PROPERTY: dict[str, tuple[str, str]] = {
"AWS::ApiGateway::ApiKey": ("Tags", "list"),
"AWS::ApiGateway::DomainName": ("Tags", "list"),
@@ -773,6 +802,7 @@ _STACK_TAG_PROPERTY: dict[str, tuple[str, str]] = {
"AWS::Backup::BackupVault": ("BackupVaultTags", "map"),
"AWS::CertificateManager::Certificate": ("Tags", "list"),
"AWS::CloudFormation::Stack": ("Tags", "list"),
+ "AWS::CloudFront::Distribution": ("Tags", "list"),
"AWS::CloudWatch::Alarm": ("Tags", "list"),
"AWS::CodeBuild::Project": ("Tags", "list"),
"AWS::Cognito::IdentityPool": ("IdentityPoolTags", "map"),
@@ -1123,10 +1153,8 @@ def _s3_update(physical_id, old_props, new_props, stack_name):
def _s3_bucket_policy_create(logical_id, props, stack_name):
bucket = props.get("Bucket", "")
- policy = props.get("PolicyDocument")
- if bucket and policy:
- import json
- _s3._bucket_policies[bucket] = json.dumps(policy) if isinstance(policy, dict) else policy
+ if bucket and props.get("PolicyDocument"):
+ _s3._bucket_policies[bucket] = _policy_document_json(props)
return f"{bucket}-policy", {}
@@ -1366,6 +1394,42 @@ def _sns_delete(physical_id, props):
# --- SNS Subscription (standalone) ---
+# The properties of the type that are subscription attributes, with the value
+# the create stores when the template leaves the property out. They are the
+# No-interruption properties of the resource reference
+# (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sns-subscription.html),
+# minus ReplayPolicy, which the service does not store.
+_SNS_SUBSCRIPTION_ATTRIBUTE_DEFAULTS = {
+ "DeliveryPolicy": "",
+ "FilterPolicy": "",
+ "FilterPolicyScope": "MessageAttributes",
+ "RawMessageDelivery": False,
+ "RedrivePolicy": "",
+ "SubscriptionRoleArn": "",
+}
+
+# The properties whose change replaces the subscription (Update requires:
+# Replacement on the resource reference).
+_SNS_SUBSCRIPTION_IDENTITY = ("TopicArn", "Protocol", "Endpoint")
+
+
+def _sns_sub_attributes(props):
+ """The subscription attributes ``props`` declares, as the strings the
+ service stores: a JSON property rendered, RawMessageDelivery normalised
+ to ``true``/``false``."""
+ attrs = {}
+ for name in _SNS_SUBSCRIPTION_ATTRIBUTE_DEFAULTS:
+ if name not in props:
+ continue
+ value = props[name]
+ if name == "RawMessageDelivery":
+ value = "true" if (value is True or str(value).lower() == "true") else "false"
+ elif isinstance(value, (dict, list)):
+ value = json.dumps(value)
+ attrs[name] = "" if value is None else str(value)
+ return attrs
+
+
def _sns_sub_create(logical_id, props, stack_name):
topic_arn = props.get("TopicArn", "")
protocol = props.get("Protocol", "")
@@ -1376,8 +1440,12 @@ def _sns_sub_create(logical_id, props, stack_name):
return sub_arn, {"SubscriptionArn": sub_arn}
sub_arn = f"{topic_arn}:{new_uuid()}"
- raw = props.get("RawMessageDelivery", False)
- raw_str = "true" if (raw is True or str(raw).lower() == "true") else "false"
+ attributes = {
+ "FilterPolicyScope": "MessageAttributes",
+ "FilterPolicy": "",
+ "RawMessageDelivery": "false",
+ }
+ attributes.update(_sns_sub_attributes(props))
sub = {
"arn": sub_arn,
"topic_arn": topic_arn,
@@ -1385,21 +1453,48 @@ def _sns_sub_create(logical_id, props, stack_name):
"endpoint": endpoint,
"confirmed": protocol not in ("http", "https"),
"owner": get_account_id(),
- "attributes": {
- "FilterPolicyScope": props.get("FilterPolicyScope", "MessageAttributes"),
- "FilterPolicy": (
- json.dumps(props.get("FilterPolicy"))
- if isinstance(props.get("FilterPolicy"), (dict, list))
- else (props.get("FilterPolicy", "") or "")
- ),
- "RawMessageDelivery": raw_str,
- },
+ "attributes": attributes,
}
topic["subscriptions"].append(sub)
_sns._sub_arn_to_topic[sub_arn] = topic_arn
return sub_arn, {"SubscriptionArn": sub_arn}
+def _sns_sub_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update a subscription in place through SetSubscriptionAttributes,
+ keeping its ARN, for the No-interruption properties of the resource
+ reference (DeliveryPolicy, FilterPolicy, FilterPolicyScope,
+ RawMessageDelivery, RedrivePolicy, SubscriptionRoleArn). A property the
+ template drops reverts to what the create stores without it. TopicArn,
+ Protocol and Endpoint require replacement: the new subscription is
+ created before the old one is removed, so the ARN changes there, as on
+ AWS. Region (Some interruptions) and ReplayPolicy are not stored by the
+ service and are ignored."""
+ topic_arn = _sns._sub_arn_to_topic.get(physical_id, "")
+ sub = _sns._find_subscription(topic_arn, physical_id) if topic_arn else None
+ identity = tuple(new_props.get(key, "") for key in _SNS_SUBSCRIPTION_IDENTITY)
+ current = (sub["topic_arn"], sub["protocol"], sub["endpoint"]) if sub else None
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ identity, current, _sns_sub_create, _sns_sub_delete,
+ )
+ if replaced is not None:
+ return replaced
+
+ attributes = _sns_sub_attributes(
+ _declared_or_default(old_props, new_props, _SNS_SUBSCRIPTION_ATTRIBUTE_DEFAULTS)
+ )
+ for name, value in attributes.items():
+ resp = _sns._set_subscription_attributes({
+ "SubscriptionArn": physical_id,
+ "AttributeName": name,
+ "AttributeValue": value,
+ })
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::SNS::Subscription update failed: {resp[2]!r}")
+ return physical_id, {"SubscriptionArn": physical_id}
+
+
def _sns_sub_delete(physical_id, props):
topic_arn = _sns._sub_arn_to_topic.pop(physical_id, None)
if topic_arn:
@@ -2158,29 +2253,56 @@ def _iam_policy_delete(physical_id, props):
# --- IAM InstanceProfile ---
+def _iam_ip_roles(props):
+ """The role names of the Roles property that exist, the shape the
+ service keeps on the record (its XML resolves them against the role
+ store); a role the template names that does not exist is skipped."""
+ return [rname for rname in props.get("Roles", []) if rname in _iam._roles]
+
+
def _iam_ip_create(logical_id, props, stack_name):
name = props.get("InstanceProfileName") or _physical_name(stack_name, logical_id, max_len=128)
path = props.get("Path", "/")
- arn = f"arn:aws:iam::{get_account_id()}:instance-profile{path}{name}"
- ip_id = new_uuid().replace("-", "")[:21].upper()
-
- roles = []
- for rname in props.get("Roles", []):
- role = _iam._roles.get(rname)
- if role:
- roles.append(role)
-
- profile = {
- "InstanceProfileName": name,
- "InstanceProfileId": ip_id,
- "Arn": arn,
- "Path": path,
- "Roles": roles,
- "CreateDate": now_iso(),
- "Tags": [],
- }
- _iam._instance_profiles[name] = profile
- return arn, {"Arn": arn}
+ # A generated name is the emulator's deterministic one, so a replacement
+ # lands under the same name (AWS would mint a new one) and must not be
+ # refused; a custom name goes through CreateInstanceProfile as it is, and
+ # its EntityAlreadyExists keeps one stack from writing over a profile
+ # another stack or the API owns.
+ if not props.get("InstanceProfileName"):
+ _iam._instance_profiles.pop(name, None)
+ resp = _iam._create_instance_profile({"InstanceProfileName": [name], "Path": [path]})
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::IAM::InstanceProfile create failed: {resp[2]!r}")
+ profile = _iam._instance_profiles[name]
+ profile["Roles"] = _iam_ip_roles(props)
+ return profile["Arn"], {"Arn": profile["Arn"]}
+
+
+def _iam_ip_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update an instance profile in place: Roles is No interruption on the
+ resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-instanceprofile.html),
+ so the role list is replaced on the record, which keeps its ARN, id,
+ creation date and the tags set through TagInstanceProfile (the create
+ rebuilt the record with no tags). InstanceProfileName and Path require
+ replacement: the profile under the new ARN is created before the old
+ one is removed; a custom-named profile whose Path changes was already
+ refused by _custom_named_replacement_error, as CloudFormation refuses
+ to replace a custom-named resource."""
+ name = new_props.get("InstanceProfileName") or _physical_name(
+ stack_name, logical_id or physical_id, max_len=128)
+ profile = next(
+ (ip for ip in _iam._instance_profiles.values() if ip.get("Arn") == physical_id), None)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ _iam.instance_profile_arn(name, new_props.get("Path", "/")),
+ profile["Arn"] if profile else None,
+ _iam_ip_create, _iam_ip_delete,
+ )
+ if replaced is not None:
+ return replaced
+ profile["Roles"] = _iam_ip_roles(new_props)
+ return physical_id, {"Arn": physical_id}
def _iam_ip_delete(physical_id, props):
@@ -2592,6 +2714,20 @@ def _cwlogs_resource_policy_delete(physical_id, props):
# --- CloudWatch Logs SubscriptionFilter (#896) ---
+def _cwlogs_subfilter_payload(group, filter_name, props):
+ """The PutSubscriptionFilter request a template's properties describe.
+ PutSubscriptionFilter creates or updates, so the create and the
+ in-place update send the same mapping through the same service call."""
+ return {
+ "logGroupName": group,
+ "filterName": filter_name,
+ "filterPattern": props.get("FilterPattern", ""),
+ "destinationArn": props.get("DestinationArn", ""),
+ "roleArn": props.get("RoleArn", ""),
+ "distribution": props.get("Distribution", "ByLogStream"),
+ }
+
+
def _cwlogs_subfilter_create(logical_id, props, stack_name):
group = props.get("LogGroupName")
if not group:
@@ -2610,18 +2746,55 @@ def _cwlogs_subfilter_create(logical_id, props, stack_name):
"streams": {},
"subscriptionFilters": {},
}
- grp.setdefault("subscriptionFilters", {})[filter_name] = {
- "filterName": filter_name,
- "logGroupName": group,
- "filterPattern": props.get("FilterPattern", ""),
- "destinationArn": props.get("DestinationArn", ""),
- "roleArn": props.get("RoleArn", ""),
- "distribution": props.get("Distribution", "ByLogStream"),
- "creationTime": int(time.time() * 1000),
- }
+ resp = _cw_logs._put_subscription_filter(_cwlogs_subfilter_payload(group, filter_name, props))
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::Logs::SubscriptionFilter create failed: {resp[2]!r}")
return filter_name, {}
+def _cwlogs_subfilter_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update a subscription filter in place through PutSubscriptionFilter,
+ keeping its name (what Ref returns), for the No-interruption properties
+ of the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-subscriptionfilter.html):
+ FilterPattern, DestinationArn, RoleArn and Distribution. The record is
+ put whole, so a property the template drops reverts to what the create
+ stores without it (empty pattern and role, ByLogStream). FilterName and
+ LogGroupName require replacement: the new filter is created before the
+ old one is removed.
+
+ The replacement is spelled out rather than going through
+ _rename_replacement, because a filter is keyed by (group, name): a move
+ to another group under the same name keeps the physical id, so the
+ engine records no replacement and the helper would see none either,
+ leaving the old filter behind in the old group. ApplyOnTransformedLogs,
+ EmitSystemFields and FieldSelectionCriteria are not stored by the
+ service and are ignored.
+ """
+ old_group = old_props.get("LogGroupName")
+ new_group = new_props.get("LogGroupName")
+ if not new_group:
+ raise ValueError("AWS::Logs::SubscriptionFilter requires LogGroupName")
+ filter_name = new_props.get("FilterName") or _physical_name(
+ stack_name, logical_id or physical_id, max_len=512)
+ grp = _cw_logs._log_groups.get(old_group)
+ current = grp.get("subscriptionFilters", {}).get(physical_id) if grp else None
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ (new_group, filter_name), (old_group, physical_id) if current else None,
+ _cwlogs_subfilter_create, _cwlogs_subfilter_delete,
+ delete_when_id_unchanged=True,
+ )
+ if replaced is not None:
+ return replaced
+
+ resp = _cw_logs._put_subscription_filter(
+ _cwlogs_subfilter_payload(new_group, physical_id, new_props))
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::Logs::SubscriptionFilter update failed: {resp[2]!r}")
+ return physical_id, {}
+
+
def _cwlogs_subfilter_delete(physical_id, props):
grp = _cw_logs._log_groups.get(props.get("LogGroupName"))
if grp:
@@ -4734,12 +4907,55 @@ def _pipes_pipe_delete(physical_id, props):
# --- Lambda Alias ---
+def _lambda_alias_routing_config(props):
+ """The template's RoutingConfig in the shape the API stores: the
+ AliasRoutingConfiguration property type lists AdditionalVersionWeights
+ as ``{FunctionVersion, FunctionWeight}`` entries, the API keeps a
+ ``{version: weight}`` map, which is what GetAlias returns. None when
+ the template declares no routing."""
+ rc = props.get("RoutingConfig")
+ if not rc:
+ return None
+ weights = rc.get("AdditionalVersionWeights") or {}
+ if isinstance(weights, list):
+ try:
+ weights = {str(w["FunctionVersion"]): float(w["FunctionWeight"]) for w in weights}
+ except (KeyError, TypeError, ValueError):
+ raise ValueError(
+ "AWS::Lambda::Alias: every AdditionalVersionWeights entry needs a "
+ "FunctionVersion and a numeric FunctionWeight") from None
+ return {"AdditionalVersionWeights": weights}
+
+
+def _lambda_alias_provisioned_concurrency(func_name, alias_name, old_props, new_props):
+ """Apply the ProvisionedConcurrencyConfig property to the alias
+ qualifier through the service's put and delete: declared, it is put;
+ dropped since the previous template, it is deleted; never declared,
+ a configuration set through the API is left alone."""
+ payload = _declared_or_default(old_props, new_props, {"ProvisionedConcurrencyConfig": None})
+ if "ProvisionedConcurrencyConfig" not in payload:
+ return
+ config = payload["ProvisionedConcurrencyConfig"]
+ if config:
+ resp = _lambda_svc._put_provisioned_concurrency(func_name, alias_name, {
+ "ProvisionedConcurrentExecutions": int(config.get("ProvisionedConcurrentExecutions", 0)),
+ })
+ else:
+ resp = _lambda_svc._delete_provisioned_concurrency(func_name, alias_name)
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::Lambda::Alias ProvisionedConcurrencyConfig failed: {resp[2]!r}")
+
+
def _lambda_alias_create(logical_id, props, stack_name):
func, func_name, _resource_arn, _qualifier = _lambda_function_for_cfn_ref(props.get("FunctionName", ""))
alias_name = props.get("Name", "")
func_version = props.get("FunctionVersion", "$LATEST")
if func:
+ if alias_name in func.get("aliases", {}):
+ # CreateAlias answers ResourceConflictException; a stack must not
+ # write over an alias it does not own, on a create or on a rename.
+ raise ValueError(f"AWS::Lambda::Alias: {func_name}:{alias_name} already exists")
alias = {
"AliasArn": f"arn:aws:lambda:{get_region()}:{get_account_id()}:function:{func_name}:{alias_name}",
"Name": alias_name,
@@ -4747,68 +4963,143 @@ def _lambda_alias_create(logical_id, props, stack_name):
"Description": props.get("Description", ""),
"RevisionId": new_uuid(),
}
- rc = props.get("RoutingConfig")
- if rc:
+ rc = _lambda_alias_routing_config(props)
+ if rc and rc["AdditionalVersionWeights"]:
alias["RoutingConfig"] = rc
func["aliases"][alias_name] = alias
+ _lambda_alias_provisioned_concurrency(func_name, alias_name, {}, props)
return alias["AliasArn"], {"AliasArn": alias["AliasArn"]}
alias_arn = f"arn:aws:lambda:{get_region()}:{get_account_id()}:function:{func_name}:{alias_name}"
return alias_arn, {"AliasArn": alias_arn}
+def _lambda_alias_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update an alias in place through UpdateAlias, keeping its ARN, for
+ the No-interruption properties of the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-alias.html):
+ FunctionVersion, Description, RoutingConfig and
+ ProvisionedConcurrencyConfig. A dropped Description empties, a dropped
+ RoutingConfig or ProvisionedConcurrencyConfig is removed. Name and
+ FunctionName require replacement: the new alias is created before the
+ old one is removed."""
+ func, func_name, _resource_arn, _qualifier = _lambda_function_for_cfn_ref(
+ old_props.get("FunctionName", ""))
+ _new_func, new_func_name, _new_arn, _new_qualifier = _lambda_function_for_cfn_ref(
+ new_props.get("FunctionName", ""))
+ alias_name = old_props.get("Name", "")
+ current = (func_name, alias_name) if func and alias_name in func["aliases"] else None
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ (new_func_name, new_props.get("Name", "")), current,
+ _lambda_alias_create, _lambda_alias_delete,
+ )
+ if replaced is not None:
+ return replaced
+
+ data = _declared_or_default(old_props, new_props, {
+ "FunctionVersion": "$LATEST", "Description": "", "RoutingConfig": None,
+ })
+ if "RoutingConfig" in data:
+ data["RoutingConfig"] = _lambda_alias_routing_config(new_props)
+ resp = _lambda_svc._update_alias(func_name, alias_name, data)
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::Lambda::Alias update failed: {resp[2]!r}")
+ _lambda_alias_provisioned_concurrency(func_name, alias_name, old_props, new_props)
+ return physical_id, {"AliasArn": physical_id}
+
+
def _lambda_alias_delete(physical_id, props):
func, _func_name, _resource_arn, _qualifier = _lambda_function_for_cfn_ref(props.get("FunctionName", ""))
alias_name = props.get("Name", "")
if func:
func["aliases"].pop(alias_name, None)
+ # The alias qualifier's provisioned concurrency goes with the alias.
+ func.get("provisioned_concurrency", {}).pop(alias_name, None)
-# --- SQS QueuePolicy ---
+# --- Resource policy attachments (SQS QueuePolicy, SNS TopicPolicy) ---
-def _sqs_queue_policy_create(logical_id, props, stack_name):
+def _policy_document_json(props):
+ """The PolicyDocument of a policy-attachment resource as the JSON string
+ the service stores under the ``Policy`` attribute."""
policy_doc = props.get("PolicyDocument", {})
if isinstance(policy_doc, dict):
policy_doc = json.dumps(policy_doc)
- queues = props.get("Queues", [])
- for queue_url in queues:
- queue = _sqs._queues.get(queue_url)
- if queue:
- queue["attributes"]["Policy"] = policy_doc
- pid = f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
- return pid, {}
+ return policy_doc
+
+
+def _policy_attachment_update(physical_id, old_props, new_props, members, store):
+ """Shared update for the two policy-attachment types, AWS::SQS::QueuePolicy
+ and AWS::SNS::TopicPolicy: PolicyDocument and the member list (Queues,
+ Topics) are both No interruption on the resource references, so the
+ physical id is kept, the new document is written on every member the
+ new template names, and it is removed from a member the old template
+ named and the new one dropped. ``store`` is the service's record map,
+ keyed the way the member list refers to it (queue URL, topic ARN).
+ A member dropped from the list loses its policy even when another resource
+ put it there: last writer wins, as on AWS.
+ """
+ policy_doc = _policy_document_json(new_props)
+ new_members = new_props.get(members, [])
+ for member in old_props.get(members, []):
+ record = store.get(member)
+ if record and member not in new_members:
+ record["attributes"].pop("Policy", None)
+ for member in new_members:
+ record = store.get(member)
+ if record:
+ record["attributes"]["Policy"] = policy_doc
+ return physical_id, {}
+
+
+def _policy_attachment_create(logical_id, props, stack_name, members, store):
+ """Shared create for the two policy-attachment types: the document is
+ written on every member the template names, and the physical id is the
+ generated one CloudFormation mints for a type with no name of its own."""
+ policy_doc = _policy_document_json(props)
+ for member in props.get(members, []):
+ record = store.get(member)
+ if record:
+ record["attributes"]["Policy"] = policy_doc
+ return f"{stack_name}-{logical_id}-{new_uuid()[:8]}", {}
+
+
+def _policy_attachment_delete(props, members, store):
+ """Shared delete for the two policy-attachment types: the member goes
+ back to the service's default, which is no Policy attribute at all."""
+ for member in props.get(members, []):
+ record = store.get(member)
+ if record:
+ record["attributes"].pop("Policy", None)
+
+
+# --- SQS QueuePolicy ---
+
+def _sqs_queue_policy_create(logical_id, props, stack_name):
+ return _policy_attachment_create(logical_id, props, stack_name, "Queues", _sqs._queues)
+
+
+def _sqs_queue_policy_update(physical_id, old_props, new_props, stack_name):
+ return _policy_attachment_update(physical_id, old_props, new_props, "Queues", _sqs._queues)
def _sqs_queue_policy_delete(physical_id, props):
- queues = props.get("Queues", [])
- for queue_url in queues:
- queue = _sqs._queues.get(queue_url)
- if queue:
- queue["attributes"].pop("Policy", None)
+ _policy_attachment_delete(props, "Queues", _sqs._queues)
# --- SNS TopicPolicy ---
def _sns_topic_policy_create(logical_id, props, stack_name):
- policy_doc = props.get("PolicyDocument", {})
- if isinstance(policy_doc, dict):
- policy_doc = json.dumps(policy_doc)
- topics = props.get("Topics", [])
- for topic_arn in topics:
- topic = _sns._topics.get(topic_arn)
- if topic:
- topic["attributes"]["Policy"] = policy_doc
- pid = f"{stack_name}-{logical_id}-{new_uuid()[:8]}"
- return pid, {}
+ return _policy_attachment_create(logical_id, props, stack_name, "Topics", _sns._topics)
+
+
+def _sns_topic_policy_update(physical_id, old_props, new_props, stack_name):
+ return _policy_attachment_update(physical_id, old_props, new_props, "Topics", _sns._topics)
def _sns_topic_policy_delete(physical_id, props):
- topics = props.get("Topics", [])
- for topic_arn in topics:
- topic = _sns._topics.get(topic_arn)
- if topic:
- # Restore default policy
- topic["attributes"].pop("Policy", None)
+ _policy_attachment_delete(props, "Topics", _sns._topics)
# --- AppSync resource provisioners ---
@@ -5387,6 +5678,57 @@ def _cognito_user_pool_resource_server_create(logical_id, props, stack_name):
return identifier, {}
+def _cognito_user_pool_resource_server_update(physical_id, old_props, new_props,
+ stack_name, logical_id=None):
+ """Update a resource server in place, keeping its Identifier (what Ref
+ returns). Name and Scopes are "Update requires: No interruption" on the
+ resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolresourceserver.html)
+ and go through UpdateResourceServer; a dropped Scopes goes back to the
+ empty list the call defaults it to ("If you don't provide a value for an
+ attribute, it is set to the default value"). Name is "Required: Yes" on
+ the reference; a template that leaves it off gets the Identifier as
+ MiniStack's own fallback. Identifier and UserPoolId require replacement,
+ and the new resource server is created before the old one is removed.
+
+ A resource server is keyed by (pool, identifier) while its physical id is
+ the identifier alone, so a move to another pool keeps the id and the
+ engine's cleanup never sees the replacement: the handler passes the pair
+ as the identity and asks the shared helper to delete under an unchanged
+ id. Under a declared Identifier the move is refused before we get here
+ (_custom_named_replacement_error, the way CloudFormation refuses to
+ replace a custom-named resource); this branch carries the case where the
+ template leaves the Identifier off. A resource server the template
+ retains on replacement is left where it is, since the engine's own
+ cleanup does not see a replacement it can skip when the identifier
+ stayed the same.
+ """
+ identifier = new_props.get("Identifier", "")
+ old_pid = old_props.get("UserPoolId", "")
+ new_pid = new_props.get("UserPoolId", "")
+ pool = _cognito._user_pools.get(old_pid)
+ server = _cognito._pool_resource_servers(pool).get(physical_id) if pool else None
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ (new_pid, identifier), (old_pid, physical_id) if server else None,
+ _cognito_user_pool_resource_server_create,
+ _cognito_user_pool_resource_server_delete,
+ delete_when_id_unchanged=True,
+ )
+ if replaced is not None:
+ return replaced
+
+ status, _, body = _cognito._update_resource_server({
+ "UserPoolId": new_pid,
+ "Identifier": identifier,
+ "Name": new_props.get("Name", identifier),
+ "Scopes": new_props.get("Scopes", []),
+ })
+ if status >= 400:
+ raise ValueError(f"AWS::Cognito::UserPoolResourceServer update failed: {body!r}")
+ return identifier, {}
+
+
def _cognito_user_pool_resource_server_delete(physical_id, props):
pid = props.get("UserPoolId", "")
pool = _cognito._user_pools.get(pid)
@@ -7307,22 +7649,36 @@ def _cw_dashboard_delete(physical_id, props):
# ApiGatewayV2 Api
# ---------------------------------------------------------------------------
+def _apigw_v2_api_props(props, stack_name, logical_id):
+ """The mutable part of an API record from its template properties, with
+ the create's defaults: what the create stores and what an update writes
+ over the existing record."""
+ # The HTTP default is the documented one; AWS requires the expression
+ # for a WebSocket API, and "$request.body.action" is the emulator's own
+ # fallback, the one its CreateApi uses.
+ default_rse = ("$request.body.action" if props.get("ProtocolType") == "WEBSOCKET"
+ else "$request.method $request.path")
+ return {
+ "name": props.get("Name") or _physical_name(stack_name, logical_id, max_len=128),
+ "routeSelectionExpression": props.get("RouteSelectionExpression", default_rse),
+ "apiKeySelectionExpression": props.get("ApiKeySelectionExpression", "$request.header.x-api-key"),
+ "disableSchemaValidation": props.get("DisableSchemaValidation", False),
+ "disableExecuteApiEndpoint": props.get("DisableExecuteApiEndpoint", False),
+ "version": props.get("Version", ""),
+ "description": props.get("Description", ""),
+ }
+
+
def _apigw_v2_api_create(logical_id, props, stack_name):
api_id = _apigw_v2._resolve_custom_api_id(props.get("Tags", {}), _apigw_v2._apis) or new_uuid()[:8]
- name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=128)
protocol = props.get("ProtocolType", "HTTP")
api = {
"apiId": api_id,
- "name": name,
"protocolType": protocol,
"apiEndpoint": f"http://{api_id}.execute-api.{_MINISTACK_HOST}:{os.environ.get('GATEWAY_PORT', '4566')}",
"createdDate": now_iso(),
- "routeSelectionExpression": props.get("RouteSelectionExpression", "$request.method $request.path"),
- "apiKeySelectionExpression": props.get("ApiKeySelectionExpression", "$request.header.x-api-key"),
- "tags": props.get("Tags", {}),
- "disableSchemaValidation": props.get("DisableSchemaValidation", False),
- "disableExecuteApiEndpoint": props.get("DisableExecuteApiEndpoint", False),
- "version": props.get("Version", ""),
+ "tags": dict(props.get("Tags") or {}),
+ **_apigw_v2_api_props(props, stack_name, logical_id),
}
if props.get("CorsConfiguration"):
api["corsConfiguration"] = props["CorsConfiguration"]
@@ -7334,6 +7690,37 @@ def _apigw_v2_api_create(logical_id, props, stack_name):
return api_id, {"ApiId": api_id, "ApiEndpoint": api["apiEndpoint"]}
+def _apigw_v2_api_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update an API in place: every property but ProtocolType is No
+ interruption on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-api.html),
+ so the update goes through the service's own UpdateApi and the record
+ keeps its apiId, its apiEndpoint and the routes, integrations and
+ stages stored under the id. The
+ create fallback minted a new id on every change, which re-created every
+ child that Refs the API, and with an ms-custom-id tag its second
+ _resolve_custom_api_id call refused the pinned id as already in use and
+ rolled the stack back. A property the template drops reverts to the
+ create's default. ProtocolType requires replacement: the new API is
+ created before the old one is removed (a pinned id cannot be replaced,
+ and the create's own refusal fails the update)."""
+ api = _apigw_v2._apis.get(physical_id)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ new_props.get("ProtocolType", "HTTP"), api["protocolType"] if api else None,
+ _apigw_v2_api_create, _apigw_v2_api_delete,
+ )
+ if replaced is not None:
+ return replaced
+ payload = _apigw_v2_api_props(new_props, stack_name, logical_id or physical_id)
+ payload["corsConfiguration"] = new_props.get("CorsConfiguration") or {}
+ resp = _apigw_v2._update_api(physical_id, payload)
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::ApiGatewayV2::Api update failed: {resp[2]!r}")
+ _reconcile_tag_map(api.setdefault("tags", {}), old_props, new_props)
+ return physical_id, {"ApiId": physical_id, "ApiEndpoint": api["apiEndpoint"]}
+
+
def _apigw_v2_api_delete(physical_id, props):
_apigw_v2._apis.pop(physical_id, None)
_apigw_v2._routes.pop(physical_id, None)
@@ -7346,25 +7733,62 @@ def _apigw_v2_api_delete(physical_id, props):
# ApiGatewayV2 Stage
# ---------------------------------------------------------------------------
-def _apigw_v2_stage_create(logical_id, props, stack_name):
- api_id = props.get("ApiId", "")
- stage_name = props.get("StageName", "$default")
- stage = {
- "stageName": stage_name,
+def _apigw_v2_stage_props(props):
+ """The mutable part of a stage record from its template properties,
+ with the create's defaults: what the create stores and what an update
+ writes over the existing record."""
+ return {
"autoDeploy": props.get("AutoDeploy", False),
- "createdDate": now_iso(),
"lastUpdatedDate": now_iso(),
"stageVariables": props.get("StageVariables", {}),
"description": props.get("Description", ""),
"defaultRouteSettings": props.get("DefaultRouteSettings", {}),
"routeSettings": props.get("RouteSettings", {}),
- "tags": props.get("Tags", {}),
+ }
+
+
+def _apigw_v2_stage_create(logical_id, props, stack_name):
+ api_id = props.get("ApiId", "")
+ stage_name = props.get("StageName", "$default")
+ stage = {
+ "stageName": stage_name,
+ "createdDate": now_iso(),
+ "tags": dict(props.get("Tags") or {}),
+ **_apigw_v2_stage_props(props),
}
_apigw_v2._stages.setdefault(api_id, {})[stage_name] = stage
physical_id = f"{api_id}/{stage_name}"
return physical_id, {"StageName": stage_name}
+def _apigw_v2_stage_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update a stage in place: every property but ApiId and StageName is No
+ interruption on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-stage.html),
+ so the update goes through the service's own UpdateStage, which keeps
+ the name and the creation date and refreshes lastUpdatedDate. The
+ create fallback rebuilt the
+ record under the same name, which reset createdDate and the tags set
+ through the service's own API. A property the template drops reverts to
+ the create's default. ApiId and StageName require replacement: the new
+ stage is created before the old one is removed."""
+ api_id, _, stage_name = physical_id.partition("/")
+ stage = _apigw_v2._stages.get(api_id, {}).get(stage_name)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ (new_props.get("ApiId", ""), new_props.get("StageName", "$default")),
+ (api_id, stage_name) if stage else None,
+ _apigw_v2_stage_create, _apigw_v2_stage_delete,
+ )
+ if replaced is not None:
+ return replaced
+ resp = _apigw_v2._update_stage(api_id, stage_name, _apigw_v2_stage_props(new_props))
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::ApiGatewayV2::Stage update failed: {resp[2]!r}")
+ _reconcile_tag_map(stage.setdefault("tags", {}), old_props, new_props)
+ return physical_id, {"StageName": stage_name}
+
+
def _apigw_v2_stage_delete(physical_id, props):
parts = physical_id.split("/", 1)
if len(parts) == 2:
@@ -7377,11 +7801,11 @@ def _apigw_v2_stage_delete(physical_id, props):
# ApiGatewayV2 Integration
# ---------------------------------------------------------------------------
-def _apigw_v2_integration_create(logical_id, props, stack_name):
- api_id = props.get("ApiId", "")
- int_id = new_uuid()[:8]
- integration = {
- "integrationId": int_id,
+def _apigw_v2_integration_props(props):
+ """The mutable part of an integration record from its template
+ properties, with the create's defaults: what the create stores and what
+ an update writes over the existing record."""
+ return {
"integrationType": props.get("IntegrationType", "AWS_PROXY"),
"integrationUri": props.get("IntegrationUri", ""),
"integrationMethod": props.get("IntegrationMethod", "POST"),
@@ -7395,12 +7819,46 @@ def _apigw_v2_integration_create(logical_id, props, stack_name):
"responseParameters": props.get("ResponseParameters", {}),
"contentHandlingStrategy": props.get("ContentHandlingStrategy"),
}
+
+
+def _apigw_v2_integration_create(logical_id, props, stack_name):
+ api_id = props.get("ApiId", "")
+ int_id = new_uuid()[:8]
+ integration = {"integrationId": int_id, **_apigw_v2_integration_props(props)}
_apigw_v2._integrations.setdefault(api_id, {})[int_id] = integration
# AWS returns just the integration ID as the physical ID (Ref).
# Store apiId in outputs so delete can find the right API.
return int_id, {"IntegrationId": int_id, "ApiId": api_id}
+def _apigw_v2_integration_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update an integration in place: every property but ApiId is No
+ interruption on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-integration.html),
+ so the update goes through the service's own UpdateIntegration and the
+ record keeps its integrationId, which every Route's Target names. The
+ create fallback minted a new id
+ on every change and left the old integration on the API. A property the
+ template drops reverts to the create's default. ApiId requires
+ replacement: the integration is created on the new API before the old
+ one is removed."""
+ old_api_id = old_props.get("ApiId", "")
+ int_id = physical_id.split("/", 1)[1] if "/" in physical_id else physical_id
+ integration = _apigw_v2._integrations.get(old_api_id, {}).get(int_id)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ new_props.get("ApiId", ""), old_api_id if integration else None,
+ _apigw_v2_integration_create, _apigw_v2_integration_delete,
+ )
+ if replaced is not None:
+ return replaced
+ resp = _apigw_v2._update_integration(old_api_id, int_id,
+ _apigw_v2_integration_props(new_props))
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::ApiGatewayV2::Integration update failed: {resp[2]!r}")
+ return physical_id, {"IntegrationId": int_id, "ApiId": old_api_id}
+
+
def _apigw_v2_integration_delete(physical_id, props):
api_id = props.get("ApiId", "")
int_id = physical_id
@@ -7417,11 +7875,11 @@ def _apigw_v2_integration_delete(physical_id, props):
# ApiGatewayV2 Route
# ---------------------------------------------------------------------------
-def _apigw_v2_route_create(logical_id, props, stack_name):
- api_id = props.get("ApiId", "")
- route_id = new_uuid()[:8]
- route = {
- "routeId": route_id,
+def _apigw_v2_route_props(props):
+ """The mutable part of a route record from its template properties,
+ with the create's defaults: what the create stores and what an update
+ writes over the existing record."""
+ return {
"routeKey": props.get("RouteKey", "$default"),
"target": props.get("Target", ""),
"authorizationType": props.get("AuthorizationType", "NONE"),
@@ -7432,11 +7890,42 @@ def _apigw_v2_route_create(logical_id, props, stack_name):
"requestModels": props.get("RequestModels", {}),
"requestParameters": props.get("RequestParameters", {}),
}
+
+
+def _apigw_v2_route_create(logical_id, props, stack_name):
+ api_id = props.get("ApiId", "")
+ route_id = new_uuid()[:8]
+ route = {"routeId": route_id, **_apigw_v2_route_props(props)}
_apigw_v2._routes.setdefault(api_id, {})[route_id] = route
physical_id = f"{api_id}/{route_id}"
return physical_id, {"RouteId": route_id}
+def _apigw_v2_route_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update a route in place: every property but ApiId is No interruption
+ on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigatewayv2-route.html),
+ so the update goes through the service's own UpdateRoute and the record
+ keeps its routeId. The create fallback
+ minted a new id on every change and left the old route on the API,
+ where its route key kept matching requests. A property the template
+ drops reverts to the create's default. ApiId requires replacement: the
+ route is created on the new API before the old one is removed."""
+ api_id, _, route_id = physical_id.partition("/")
+ route = _apigw_v2._routes.get(api_id, {}).get(route_id)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ new_props.get("ApiId", ""), api_id if route else None,
+ _apigw_v2_route_create, _apigw_v2_route_delete,
+ )
+ if replaced is not None:
+ return replaced
+ resp = _apigw_v2._update_route(api_id, route_id, _apigw_v2_route_props(new_props))
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::ApiGatewayV2::Route update failed: {resp[2]!r}")
+ return physical_id, {"RouteId": route_id}
+
+
def _apigw_v2_route_delete(physical_id, props):
parts = physical_id.split("/", 1)
if len(parts) == 2:
@@ -7640,31 +8129,69 @@ def _cf_oai_delete(physical_id, props):
# CloudFront Distribution
# ---------------------------------------------------------------------------
+def _cf_distribution_config(props, caller_reference):
+ """The DistributionConfig element the service stores, rendered from the
+ template's JSON with the CallerReference the record carries."""
+ # DistributionConfig is Required: Yes on the resource reference; a
+ # template without it renders an empty configuration rather than the
+ # resource's other properties (Tags) as if they were one.
+ dist_config = props.get("DistributionConfig") or {}
+ return _cf._distribution_config_xml({"CallerReference": caller_reference, **dist_config})
+
+
def _cf_distribution_create(logical_id, props, stack_name):
- dist_config = props.get("DistributionConfig", props)
dist_id = _cf._dist_id()
arn = f"arn:aws:cloudfront::{get_account_id()}:distribution/{dist_id}"
-
- origins = dist_config.get("Origins", [])
- default_cache = dist_config.get("DefaultCacheBehavior", {})
-
+ # The API's DistributionConfig carries a CallerReference and a template
+ # has none; without one GetDistributionConfig would answer a config
+ # missing a member the SDKs expect. The update keeps it.
+ caller_reference = new_uuid()
+ config_el = _cf_distribution_config(props, caller_reference)
_cf._distributions[dist_id] = {
"Id": dist_id,
"ARN": arn,
"Status": "Deployed",
"DomainName": f"{dist_id}.cloudfront.net",
- "LastModifiedTime": now_iso(),
+ "LastModifiedTime": _cf._now_iso(),
"ETag": new_uuid(),
- "config_xml": "",
- "enabled": dist_config.get("Enabled", True),
+ "CallerReference": caller_reference,
+ "config_xml": _cf.tostring(config_el, encoding="unicode"),
+ "enabled": _cf._get_enabled(config_el),
}
_cf._invalidations[dist_id] = []
+ _cf._tags[arn] = [{"Key": k, "Value": v} for k, v in _tag_map(props.get("Tags")).items()]
return dist_id, {"Arn": arn, "DomainName": f"{dist_id}.cloudfront.net", "Id": dist_id}
+def _cf_distribution_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update a distribution in place: DistributionConfig and Tags, the two
+ properties of the type, are both No interruption on the resource
+ reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudfront-distribution.html),
+ so there is no replacement path at all. The record keeps its Id, ARN
+ and DomainName and its invalidation history; the configuration is
+ stored anew, the ETag rolls and LastModifiedTime moves, as
+ UpdateDistribution does. The create fallback minted a new id and domain
+ name on every change and the engine then deleted the old distribution."""
+ dist = _cf._distributions.get(physical_id)
+ if dist is None:
+ return _cf_distribution_create(logical_id or physical_id, new_props, stack_name)
+ config_el = _cf_distribution_config(new_props, dist.get("CallerReference") or new_uuid())
+ dist["config_xml"] = _cf.tostring(config_el, encoding="unicode")
+ dist["enabled"] = _cf._get_enabled(config_el)
+ dist["ETag"] = new_uuid()
+ dist["LastModifiedTime"] = _cf._now_iso()
+ _reconcile_tag_list(_cf._tags.setdefault(dist["ARN"], []), old_props, new_props)
+ return physical_id, {"Arn": dist["ARN"], "DomainName": dist["DomainName"], "Id": physical_id}
+
+
def _cf_distribution_delete(physical_id, props):
- _cf._distributions.pop(physical_id, None)
+ dist = _cf._distributions.pop(physical_id, None)
_cf._invalidations.pop(physical_id, None)
+ if dist:
+ # The tagging API reads the store as it is, so a deleted
+ # distribution would keep answering GetResources.
+ _cf._tags.pop(dist["ARN"], None)
# ---------------------------------------------------------------------------
@@ -8588,20 +9115,57 @@ def _iot_ca_certificate_delete(physical_id, props):
_iot._handle_ca_certificate("DELETE", f"/cacertificate/{physical_id}", b"", {})
-def _cognito_identity_pool_role_attachment_create(logical_id, props, stack_name):
+def _cognito_identity_pool_role_attachment_apply(props):
+ """Push Roles and RoleMappings onto the identity pool through
+ SetIdentityPoolRoles, which takes the whole configuration: a property the
+ template drops is cleared, its create default."""
iid = props.get("IdentityPoolId")
if not iid:
raise ValueError("AWS::Cognito::IdentityPoolRoleAttachment requires IdentityPoolId")
- resp = _cognito._set_identity_pool_roles({"IdentityPoolId": iid, "Roles": props.get("Roles", {})})
+ resp = _cognito._set_identity_pool_roles({
+ "IdentityPoolId": iid,
+ "Roles": props.get("Roles", {}),
+ "RoleMappings": props.get("RoleMappings", {}),
+ })
if resp[0] >= 400:
- raise ValueError(f"AWS::Cognito::IdentityPoolRoleAttachment create failed: {resp[2]!r}")
+ raise ValueError(
+ f"AWS::Cognito::IdentityPoolRoleAttachment: SetIdentityPoolRoles failed: {resp[2]!r}")
+ # Ref returns the IdentityPoolId (resource reference); Fn::GetAtt Id is
+ # documented as "the resource ID" only, and here that is the same value,
+ # because the pool id is the physical id of the attachment.
return iid, {"Id": iid}
+def _cognito_identity_pool_role_attachment_create(logical_id, props, stack_name):
+ return _cognito_identity_pool_role_attachment_apply(props)
+
+
+def _cognito_identity_pool_role_attachment_update(physical_id, old_props, new_props,
+ stack_name):
+ """Roles and RoleMappings are "Update requires: No interruption" on the
+ resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-identitypoolroleattachment.html),
+ so both are re-applied to the pool the attachment already sits on.
+ IdentityPoolId requires replacement: the new pool is configured first and
+ the old pool's configuration cleared afterwards, CloudFormation's
+ replacement order, which without this handler happened only because the
+ physical id of this type is the pool id itself."""
+ replacement = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, None,
+ new_props.get("IdentityPoolId"), physical_id,
+ _cognito_identity_pool_role_attachment_create,
+ _cognito_identity_pool_role_attachment_delete,
+ )
+ if replacement is not None:
+ return replacement
+ return _cognito_identity_pool_role_attachment_apply(new_props)
+
+
def _cognito_identity_pool_role_attachment_delete(physical_id, props):
pool = _cognito._identity_pools.get(physical_id)
if pool is not None:
pool["_roles"] = {}
+ pool["_role_mappings"] = {}
def _cognito_identity_pool_principal_tag_apply(props):
@@ -8894,7 +9458,12 @@ _RESOURCE_HANDLERS = {
"update_with_logical_id": True,
"delete": _sns_delete,
},
- "AWS::SNS::Subscription": {"create": _sns_sub_create, "delete": _sns_sub_delete},
+ "AWS::SNS::Subscription": {
+ "create": _sns_sub_create,
+ "update": _sns_sub_update,
+ "update_with_logical_id": True,
+ "delete": _sns_sub_delete,
+ },
"AWS::DynamoDB::Table": {
"create": _ddb_create,
"update": _ddb_update,
@@ -8930,7 +9499,12 @@ _RESOURCE_HANDLERS = {
"update_with_logical_id": True,
"delete": _iam_policy_delete,
},
- "AWS::IAM::InstanceProfile": {"create": _iam_ip_create, "delete": _iam_ip_delete},
+ "AWS::IAM::InstanceProfile": {
+ "create": _iam_ip_create,
+ "update": _iam_ip_update,
+ "update_with_logical_id": True,
+ "delete": _iam_ip_delete,
+ },
"AWS::SSM::Parameter": {"create": _ssm_create, "update": _ssm_update, "delete": _ssm_delete},
"AWS::AppConfig::Application": {
"create": _appconfig_application_create,
@@ -8967,7 +9541,12 @@ _RESOURCE_HANDLERS = {
"update": _cwlogs_resource_policy_update,
"delete": _cwlogs_resource_policy_delete,
},
- "AWS::Logs::SubscriptionFilter": {"create": _cwlogs_subfilter_create, "delete": _cwlogs_subfilter_delete},
+ "AWS::Logs::SubscriptionFilter": {
+ "create": _cwlogs_subfilter_create,
+ "update": _cwlogs_subfilter_update,
+ "update_with_logical_id": True,
+ "delete": _cwlogs_subfilter_delete,
+ },
"AWS::Events::EventBus": {"create": _eb_event_bus_create, "update": _eb_event_bus_update, "delete": _eb_event_bus_delete},
"AWS::Kinesis::Stream": {"create": _kinesis_stream_create, "update": _kinesis_stream_update, "delete": _kinesis_stream_delete},
"AWS::Events::Rule": {
@@ -9090,9 +9669,22 @@ _RESOURCE_HANDLERS = {
"delete": _lambda_event_invoke_config_delete,
},
"AWS::Pipes::Pipe": {"create": _pipes_pipe_create, "delete": _pipes_pipe_delete},
- "AWS::Lambda::Alias": {"create": _lambda_alias_create, "delete": _lambda_alias_delete},
- "AWS::SQS::QueuePolicy": {"create": _sqs_queue_policy_create, "delete": _sqs_queue_policy_delete},
- "AWS::SNS::TopicPolicy": {"create": _sns_topic_policy_create, "delete": _sns_topic_policy_delete},
+ "AWS::Lambda::Alias": {
+ "create": _lambda_alias_create,
+ "update": _lambda_alias_update,
+ "update_with_logical_id": True,
+ "delete": _lambda_alias_delete,
+ },
+ "AWS::SQS::QueuePolicy": {
+ "create": _sqs_queue_policy_create,
+ "update": _sqs_queue_policy_update,
+ "delete": _sqs_queue_policy_delete,
+ },
+ "AWS::SNS::TopicPolicy": {
+ "create": _sns_topic_policy_create,
+ "update": _sns_topic_policy_update,
+ "delete": _sns_topic_policy_delete,
+ },
"AWS::AppSync::GraphQLApi": {"create": _appsync_api_create, "delete": _appsync_api_delete},
"AWS::AppSync::DataSource": {"create": _appsync_ds_create, "delete": _appsync_ds_delete},
"AWS::AppSync::FunctionConfiguration": {
@@ -9121,7 +9713,12 @@ _RESOURCE_HANDLERS = {
"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::UserPoolResourceServer": {
+ "create": _cognito_user_pool_resource_server_create,
+ "update": _cognito_user_pool_resource_server_update,
+ "update_with_logical_id": True,
+ "delete": _cognito_user_pool_resource_server_delete,
+ },
"AWS::Cognito::UserPoolGroup": {
"create": _cognito_user_pool_group_create,
"update": _cognito_user_pool_group_update,
@@ -9189,10 +9786,30 @@ _RESOURCE_HANDLERS = {
},
"AWS::Route53::HostedZone": {"create": _r53_hosted_zone_create, "delete": _r53_hosted_zone_delete},
"AWS::Route53::RecordSet": {"create": _r53_record_set_create, "update": _r53_record_set_update, "delete": _r53_record_set_delete},
- "AWS::ApiGatewayV2::Api": {"create": _apigw_v2_api_create, "delete": _apigw_v2_api_delete},
- "AWS::ApiGatewayV2::Stage": {"create": _apigw_v2_stage_create, "delete": _apigw_v2_stage_delete},
- "AWS::ApiGatewayV2::Integration": {"create": _apigw_v2_integration_create, "delete": _apigw_v2_integration_delete},
- "AWS::ApiGatewayV2::Route": {"create": _apigw_v2_route_create, "delete": _apigw_v2_route_delete},
+ "AWS::ApiGatewayV2::Api": {
+ "create": _apigw_v2_api_create,
+ "update": _apigw_v2_api_update,
+ "update_with_logical_id": True,
+ "delete": _apigw_v2_api_delete,
+ },
+ "AWS::ApiGatewayV2::Stage": {
+ "create": _apigw_v2_stage_create,
+ "update": _apigw_v2_stage_update,
+ "update_with_logical_id": True,
+ "delete": _apigw_v2_stage_delete,
+ },
+ "AWS::ApiGatewayV2::Integration": {
+ "create": _apigw_v2_integration_create,
+ "update": _apigw_v2_integration_update,
+ "update_with_logical_id": True,
+ "delete": _apigw_v2_integration_delete,
+ },
+ "AWS::ApiGatewayV2::Route": {
+ "create": _apigw_v2_route_create,
+ "update": _apigw_v2_route_update,
+ "update_with_logical_id": True,
+ "delete": _apigw_v2_route_delete,
+ },
"AWS::ApiGatewayV2::Authorizer": {"create": _apigw_v2_authorizer_create, "update": _apigw_v2_authorizer_update, "delete": _apigw_v2_authorizer_delete},
"AWS::SES::EmailIdentity": {"create": _ses_email_identity_create, "delete": _ses_email_identity_delete},
"AWS::SES::ConfigurationSet": {"create": _ses_configuration_set_create, "delete": _ses_configuration_set_delete},
@@ -9203,7 +9820,12 @@ _RESOURCE_HANDLERS = {
"update": _cf_oai_update,
"delete": _cf_oai_delete,
},
- "AWS::CloudFront::Distribution": {"create": _cf_distribution_create, "delete": _cf_distribution_delete},
+ "AWS::CloudFront::Distribution": {
+ "create": _cf_distribution_create,
+ "update": _cf_distribution_update,
+ "update_with_logical_id": True,
+ "delete": _cf_distribution_delete,
+ },
"AWS::CloudFront::KeyValueStore": {"create": _cf_kvs_create, "update": _cf_kvs_update, "delete": _cf_kvs_delete},
"AWS::CloudFront::CachePolicy": {
"create": _cf_cache_policy_create,
@@ -9280,6 +9902,7 @@ _RESOURCE_HANDLERS = {
},
"AWS::Cognito::IdentityPoolRoleAttachment": {
"create": _cognito_identity_pool_role_attachment_create,
+ "update": _cognito_identity_pool_role_attachment_update,
"delete": _cognito_identity_pool_role_attachment_delete,
},
"AWS::Cognito::IdentityPoolPrincipalTag": {
diff --git a/ministack/services/cloudfront.py b/ministack/services/cloudfront.py
index 16cf0fd8..9b04e85d 100644
--- a/ministack/services/cloudfront.py
+++ b/ministack/services/cloudfront.py
@@ -417,6 +417,101 @@ def _ensure_distribution_config_sdk_compat(config_el):
SubElement(og, "Quantity").text = "0"
+# CloudFormation's DistributionConfig is the API's, in JSON, with a few
+# differences: a {Quantity, Items} block is a plain list (Aliases, Origins,
+# CacheBehaviors, AllowedMethods, ...; OriginGroups and GeoRestriction keep
+# the block), CachedMethods sits next to AllowedMethods instead of inside it,
+# and these member names are spelled differently. Keyed by the API structure
+# the member sits in.
+_CFN_DISTRIBUTION_CONFIG_RENAMES = {
+ ("DistributionConfig", "IPV6Enabled"): "IsIPV6Enabled",
+ ("Origin", "OriginCustomHeaders"): "CustomHeaders",
+ ("CustomOriginConfig", "OriginSSLProtocols"): "OriginSslProtocols",
+ ("ViewerCertificate", "AcmCertificateArn"): "ACMCertificateArn",
+ ("ViewerCertificate", "IamCertificateId"): "IAMCertificateId",
+ ("ViewerCertificate", "SslSupportMethod"): "SSLSupportMethod",
+ ("GeoRestriction", "Locations"): "Items",
+}
+
+_api_model = None
+
+
+def _api_shape(name):
+ """A shape of the CloudFront API model botocore ships, loaded once."""
+ global _api_model
+ if _api_model is None:
+ import botocore.session
+
+ _api_model = botocore.session.get_session().get_service_model("cloudfront")
+ return _api_model.shape_for(name)
+
+
+def _distribution_config_xml(config: dict):
+ """The ``DistributionConfig`` element for a configuration given in
+ CloudFormation's JSON shape: what ``CreateDistribution`` would have
+ stored had the same configuration arrived on the wire, so every read
+ path parses a CloudFormation-provisioned distribution like any other.
+ Walks the API model, so a member the API defines renders and one it
+ does not (the legacy ``CNAMEs``, ``CustomOrigin``, ``S3Origin``) is
+ dropped; an element that would come out empty is omitted, as the API
+ omits ``Items`` at ``Quantity`` 0."""
+ root = Element("DistributionConfig")
+ _render_config_member(root, _api_shape("DistributionConfig"), config)
+ return root
+
+
+def _render_config_member(el, shape, value):
+ if shape.type_name == "structure":
+ if not isinstance(value, dict):
+ return
+ members = shape.members
+ value = {_CFN_DISTRIBUTION_CONFIG_RENAMES.get((shape.name, k), k): v
+ for k, v in value.items()}
+ if "AllowedMethods" in members and (
+ isinstance(value.get("AllowedMethods"), list) or "CachedMethods" in value):
+ # The API nests CachedMethods inside AllowedMethods, so a
+ # CachedMethods on its own needs one: GET and HEAD, the first of
+ # the three choices the reference lists (it states no default).
+ value["AllowedMethods"] = {"Items": value.get("AllowedMethods") or ["GET", "HEAD"],
+ "CachedMethods": value.pop("CachedMethods", None)}
+ if "Quantity" in members and "Items" in members:
+ value.setdefault("Quantity", len(value.get("Items") or []))
+ if "Enabled" in members and "Enabled" not in value:
+ # Six structures carry an Enabled the template may omit:
+ # TrustedSigners and TrustedKeyGroups are on when they list
+ # anything; Logging, OriginShield and GrpcConfig are on when the
+ # block is present; DistributionConfig defaults to on, as
+ # _get_enabled reads it.
+ value["Enabled"] = bool(value.get("Items")) if "Items" in members else True
+ for name, member in members.items():
+ item = value.get(name)
+ if item is None:
+ continue
+ if member.type_name == "structure" and "Items" in member.members and isinstance(item, list):
+ item = {"Items": item}
+ _append_config_member(el, member.serialization.get("name", name), member, item)
+ elif shape.type_name == "list":
+ if not isinstance(value, list):
+ return
+ tag = shape.member.serialization.get("name", "member")
+ for item in value:
+ _append_config_member(el, tag, shape.member, item)
+ elif isinstance(value, bool):
+ el.text = "true" if value else "false"
+ elif not isinstance(value, (dict, list)):
+ el.text = str(value)
+
+
+def _append_config_member(parent, tag, shape, value):
+ """Render ``value`` under ``tag`` and attach it only when something came
+ out: an empty list, or a structure none of whose keys the API knows,
+ leaves no element behind."""
+ child = Element(tag)
+ _render_config_member(child, shape, value)
+ if len(child) or child.text is not None:
+ parent.append(child)
+
+
def _build_distribution_xml(parent, dist):
"""Append Distribution child elements to parent."""
SubElement(parent, "Id").text = dist["Id"]
@@ -2076,8 +2171,9 @@ def _get_distribution_config(dist_id):
def _dist_config_el(dist):
"""Parsed DistributionConfig element for a stored distribution.
- CloudFormation-provisioned records carry an empty ``config_xml``; parse
- defensively so account-wide scans never fail on them."""
+ A CloudFormation-provisioned record persisted before the provisioner
+ rendered its configuration carries an empty ``config_xml``; parse
+ defensively so account-wide scans never fail on one."""
xml = dist.get("config_xml")
if xml:
try:
diff --git a/ministack/services/cognito.py b/ministack/services/cognito.py
index b5880de6..4ab8391f 100644
--- a/ministack/services/cognito.py
+++ b/ministack/services/cognito.py
@@ -6609,7 +6609,12 @@ def _set_identity_pool_roles(data):
pool = _identity_pools.get(iid)
if not pool:
return error_response_json("ResourceNotFoundException", f"Identity pool {iid} not found.", 400)
+ # The call sets the whole configuration: RoleMappings is optional on the
+ # API reference and no call removes a mapping on its own, so an omitted
+ # member clears what was there. Reasoned from the API surface, not
+ # measured against a live account.
pool["_roles"] = data.get("Roles", {})
+ pool["_role_mappings"] = data.get("RoleMappings", {})
return json_response({})
@@ -6621,7 +6626,9 @@ def _get_identity_pool_roles(data):
return json_response({
"IdentityPoolId": iid,
"Roles": pool.get("_roles", {}),
- "RoleMappings": {},
+ # .get, not indexing: pools created before this field existed (and the
+ # ones the CloudFormation provisioner builds itself) carry no entry.
+ "RoleMappings": pool.get("_role_mappings", {}),
})
diff --git a/ministack/services/iam.py b/ministack/services/iam.py
index 5a1553d6..4d007be4 100644
--- a/ministack/services/iam.py
+++ b/ministack/services/iam.py
@@ -1279,6 +1279,13 @@ def _lookup_instance_profile(name="", arn=""):
return None
+def instance_profile_arn(name, path="/"):
+ """The ARN CreateInstanceProfile mints. The path is part of it and
+ already carries its slashes ("/" for the default, "/team/" for a nested
+ one), so it needs no separator of its own."""
+ return f"arn:aws:iam::{get_account_id()}:instance-profile{path or '/'}{name}"
+
+
def _create_instance_profile(p):
name = _p(p, "InstanceProfileName")
if name in _instance_profiles:
@@ -1286,9 +1293,7 @@ def _create_instance_profile(p):
f"Instance profile {name} already exists.", ns="iam")
path = _p(p, "Path") or "/"
ip_id = _gen_id("AIPA")
- arn = (f"arn:aws:iam::{get_account_id()}:instance-profile{path}{name}"
- if path != "/" else
- f"arn:aws:iam::{get_account_id()}:instance-profile/{name}")
+ arn = instance_profile_arn(name, path)
_instance_profiles[name] = {
"InstanceProfileName": name,
"InstanceProfileId": ip_id,
diff --git a/ministack/services/sns.py b/ministack/services/sns.py
index 1b855d8e..572dc9d2 100644
--- a/ministack/services/sns.py
+++ b/ministack/services/sns.py
@@ -408,7 +408,7 @@ def _subscribe(params):
}
allowed_attrs = {"DeliveryPolicy", "FilterPolicy", "FilterPolicyScope",
- "RawMessageDelivery", "RedrivePolicy"}
+ "RawMessageDelivery", "RedrivePolicy", "SubscriptionRoleArn"}
i = 1
while _p(params, f"Attributes.entry.{i}.key"):
key = _p(params, f"Attributes.entry.{i}.key")
@@ -549,7 +549,7 @@ def _set_subscription_attributes(params):
attr_val = _p(params, "AttributeValue")
allowed = {"DeliveryPolicy", "FilterPolicy", "FilterPolicyScope",
- "RawMessageDelivery", "RedrivePolicy"}
+ "RawMessageDelivery", "RedrivePolicy", "SubscriptionRoleArn"}
if attr_name not in allowed:
return _error("InvalidParameterException",
f"Invalid attribute name: {attr_name}", 400)
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 16f33e41..97cd993c 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -4518,6 +4518,119 @@ def test_cfn_lambda_alias_and_esm_keep_function_name(cfn, lam):
pass
+def _cfn_alias_test_function(lam, fn):
+ """A function with two published versions, for the alias update tests."""
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", "def handler(e,c): return {}")
+ lam.create_function(
+ FunctionName=fn, Runtime="python3.11", Role="arn:aws:iam::000000000000:role/r",
+ Handler="index.handler", Code={"ZipFile": buf.getvalue()},
+ )
+ v1 = lam.publish_version(FunctionName=fn)["Version"]
+ lam.update_function_configuration(FunctionName=fn, Description="second")
+ v2 = lam.publish_version(FunctionName=fn)["Version"]
+ assert v1 != v2
+ return v1, v2
+
+
+def _cfn_alias_template(fn, properties):
+ return json.dumps({
+ "Resources": {"Alias": {"Type": "AWS::Lambda::Alias",
+ "Properties": {"FunctionName": fn, **properties}}},
+ "Outputs": {"AliasArn": {"Value": {"Ref": "Alias"}}},
+ })
+
+
+def test_cfn_lambda_alias_updates_in_place(cfn, lam):
+ """FunctionVersion, Description, RoutingConfig and
+ ProvisionedConcurrencyConfig are No interruption on the resource
+ reference: the alias keeps its ARN and GetAlias reads the new values,
+ the routing weights in the API's map shape and the provisioned
+ concurrency on the alias qualifier. A dropped Description empties, a
+ dropped RoutingConfig or ProvisionedConcurrencyConfig is removed."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ fn = f"cfn-alias-upd-{suffix}"
+ stack_name = f"cfn-alias-upd-{suffix}"
+ v1, v2 = _cfn_alias_test_function(lam, fn)
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_alias_template(fn, {
+ "Name": "live", "FunctionVersion": v1, "Description": "first",
+ "ProvisionedConcurrencyConfig": {"ProvisionedConcurrentExecutions": 2},
+ }))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ alias_arn = _output(stack, "AliasArn")
+ assert alias_arn.endswith(f":function:{fn}:live")
+ pc = lam.get_provisioned_concurrency_config(FunctionName=fn, Qualifier="live")
+ assert pc["RequestedProvisionedConcurrentExecutions"] == 2
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_alias_template(fn, {
+ "Name": "live", "FunctionVersion": v2, "Description": "second",
+ "RoutingConfig": {"AdditionalVersionWeights": [
+ {"FunctionVersion": v1, "FunctionWeight": 0.3}]},
+ "ProvisionedConcurrencyConfig": {"ProvisionedConcurrentExecutions": 3},
+ }))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "AliasArn") == alias_arn
+ alias = lam.get_alias(FunctionName=fn, Name="live")
+ assert alias["FunctionVersion"] == v2
+ assert alias["Description"] == "second"
+ assert alias["RoutingConfig"] == {"AdditionalVersionWeights": {v1: 0.3}}
+ pc = lam.get_provisioned_concurrency_config(FunctionName=fn, Qualifier="live")
+ assert pc["RequestedProvisionedConcurrentExecutions"] == 3
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_alias_template(fn, {
+ "Name": "live", "FunctionVersion": v2,
+ }))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "AliasArn") == alias_arn
+ alias = lam.get_alias(FunctionName=fn, Name="live")
+ assert alias["FunctionVersion"] == v2
+ assert alias.get("Description", "") == ""
+ assert "RoutingConfig" not in alias
+ with pytest.raises(ClientError) as exc_info:
+ lam.get_provisioned_concurrency_config(FunctionName=fn, Qualifier="live")
+ assert exc_info.value.response["Error"]["Code"] == "ProvisionedConcurrencyConfigNotFoundException"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ lam.delete_function(FunctionName=fn)
+
+
+def test_cfn_lambda_alias_rename_replaces_it(cfn, lam):
+ """Name requires replacement: the alias under the new name is created
+ and the old one removed, so the ARN changes and the function carries
+ exactly one alias."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ fn = f"cfn-alias-ren-{suffix}"
+ stack_name = f"cfn-alias-ren-{suffix}"
+ v1, _v2 = _cfn_alias_test_function(lam, fn)
+ try:
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_alias_template(fn, {
+ "Name": "live", "FunctionVersion": v1,
+ }))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ old_arn = _output(stack, "AliasArn")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_alias_template(fn, {
+ "Name": "blue", "FunctionVersion": v1,
+ }))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ new_arn = _output(stack, "AliasArn")
+ assert new_arn != old_arn
+ assert new_arn.endswith(f":function:{fn}:blue")
+ aliases = lam.list_aliases(FunctionName=fn)["Aliases"]
+ assert [a["Name"] for a in aliases] == ["blue"]
+ assert aliases[0]["FunctionVersion"] == v1
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ lam.delete_function(FunctionName=fn)
+
+
def test_cfn_lambda_esm_preserves_qualified_function_ref(cfn, lam):
suffix = _uuid_mod.uuid4().hex[:8]
fn = f"cfn-esm-qualified-{suffix}"
@@ -6535,6 +6648,248 @@ def test_cfn_sns_subscription_raw_message_delivery(cfn, sns, sqs):
_wait_stack(cfn, stack_name)
+def _sns_subscription_stack_template(uid, subscription):
+ return json.dumps({
+ "Resources": {
+ "Topic": {"Type": "AWS::SNS::Topic",
+ "Properties": {"TopicName": f"cfn-sub-upd-topic-{uid}"}},
+ "QueueA": {"Type": "AWS::SQS::Queue",
+ "Properties": {"QueueName": f"cfn-sub-upd-a-{uid}"}},
+ "QueueB": {"Type": "AWS::SQS::Queue",
+ "Properties": {"QueueName": f"cfn-sub-upd-b-{uid}"}},
+ "Sub": {"Type": "AWS::SNS::Subscription", "Properties": subscription},
+ },
+ "Outputs": {"TopicArn": {"Value": {"Ref": "Topic"}},
+ "SubscriptionArn": {"Value": {"Ref": "Sub"}}},
+ })
+
+
+def test_cfn_sns_subscription_updates_attributes_in_place(cfn, sns):
+ """FilterPolicy, FilterPolicyScope, RawMessageDelivery, DeliveryPolicy,
+ RedrivePolicy and SubscriptionRoleArn are No interruption on the resource reference: the
+ subscription keeps its ARN and GetSubscriptionAttributes reads the new
+ values. A property the template drops reverts to what the create
+ stores without it (no filter policy, MessageAttributes scope, raw
+ delivery off). Without an update handler every change re-subscribed
+ under a fresh ARN."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-sns-sub-upd-{uid}"
+ base = {"TopicArn": {"Ref": "Topic"}, "Protocol": "sqs",
+ "Endpoint": {"Fn::GetAtt": ["QueueA", "Arn"]}}
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=_sns_subscription_stack_template(uid, {
+ **base, "FilterPolicy": {"color": ["blue"]}, "RawMessageDelivery": True,
+ }))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ sub_arn = _output(stack, "SubscriptionArn")
+ attrs = sns.get_subscription_attributes(SubscriptionArn=sub_arn)["Attributes"]
+ assert json.loads(attrs["FilterPolicy"]) == {"color": ["blue"]}
+ assert attrs["RawMessageDelivery"] == "true"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_sns_subscription_stack_template(uid, {
+ **base,
+ "FilterPolicy": {"color": ["red"]},
+ "FilterPolicyScope": "MessageBody",
+ "RawMessageDelivery": True,
+ "DeliveryPolicy": {"healthyRetryPolicy": {"numRetries": 5}},
+ "RedrivePolicy": {"deadLetterTargetArn": {"Fn::GetAtt": ["QueueB", "Arn"]}},
+ "SubscriptionRoleArn": "arn:aws:iam::000000000000:role/cfn-sub-upd-role",
+ }))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "SubscriptionArn") == sub_arn
+ attrs = sns.get_subscription_attributes(SubscriptionArn=sub_arn)["Attributes"]
+ assert json.loads(attrs["FilterPolicy"]) == {"color": ["red"]}
+ assert attrs["FilterPolicyScope"] == "MessageBody"
+ assert attrs["RawMessageDelivery"] == "true"
+ assert json.loads(attrs["DeliveryPolicy"]) == {"healthyRetryPolicy": {"numRetries": 5}}
+ assert json.loads(attrs["RedrivePolicy"])["deadLetterTargetArn"].endswith(f":cfn-sub-upd-b-{uid}")
+ assert attrs["SubscriptionRoleArn"] == "arn:aws:iam::000000000000:role/cfn-sub-upd-role"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_sns_subscription_stack_template(uid, base))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "SubscriptionArn") == sub_arn
+ attrs = sns.get_subscription_attributes(SubscriptionArn=sub_arn)["Attributes"]
+ assert attrs.get("FilterPolicy", "") == ""
+ assert attrs["FilterPolicyScope"] == "MessageAttributes"
+ assert attrs["RawMessageDelivery"] == "false"
+ assert attrs.get("DeliveryPolicy", "") == ""
+ assert attrs.get("RedrivePolicy", "") == ""
+ assert attrs.get("SubscriptionRoleArn", "") == ""
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_sns_subscription_endpoint_change_replaces_it(cfn, sns):
+ """Endpoint requires replacement: the subscription to the new endpoint
+ is created and the old one removed, so the ARN changes and the topic
+ ends up with exactly one subscription."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-sns-sub-rep-{uid}"
+
+ def subscription(queue):
+ return {"TopicArn": {"Ref": "Topic"}, "Protocol": "sqs",
+ "Endpoint": {"Fn::GetAtt": [queue, "Arn"]}}
+
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_sns_subscription_stack_template(uid, subscription("QueueA")))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ topic_arn = _output(stack, "TopicArn")
+ old_arn = _output(stack, "SubscriptionArn")
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_sns_subscription_stack_template(uid, subscription("QueueB")))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ new_arn = _output(stack, "SubscriptionArn")
+ assert new_arn != old_arn
+ subs = sns.list_subscriptions_by_topic(TopicArn=topic_arn)["Subscriptions"]
+ assert [s["SubscriptionArn"] for s in subs] == [new_arn]
+ assert subs[0]["Endpoint"].endswith(f":cfn-sub-upd-b-{uid}")
+ with pytest.raises(ClientError):
+ sns.get_subscription_attributes(SubscriptionArn=old_arn)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _sqs_policy_sids(sqs, queue_url):
+ """The statement ids of the queue's Policy attribute, [] when it has none."""
+ policy = sqs.get_queue_attributes(
+ QueueUrl=queue_url, AttributeNames=["Policy"],
+ )["Attributes"].get("Policy")
+ if not policy:
+ return []
+ return [st.get("Sid") for st in json.loads(policy)["Statement"]]
+
+
+def _sqs_policy_document(sid, queue_arns):
+ return {
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Sid": sid,
+ "Effect": "Allow",
+ "Principal": {"Service": "sns.amazonaws.com"},
+ "Action": "sqs:SendMessage",
+ "Resource": queue_arns,
+ }],
+ }
+
+
+def test_cfn_sqs_queue_policy_updates_in_place(cfn, sqs):
+ """PolicyDocument and Queues are both No interruption on the resource
+ reference: the policy resource keeps its physical id, the queues it
+ still names carry the new document, and a queue dropped from Queues
+ loses its policy. Without an update handler the resource was replaced
+ and the replacement's cleanup delete stripped the policy off the very
+ queues the new document had just been written to."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-sqs-qpol-{uid}"
+
+ def template(sid, queues):
+ return json.dumps({
+ "Resources": {
+ "QueueA": {"Type": "AWS::SQS::Queue",
+ "Properties": {"QueueName": f"cfn-qpol-a-{uid}"}},
+ "QueueB": {"Type": "AWS::SQS::Queue",
+ "Properties": {"QueueName": f"cfn-qpol-b-{uid}"}},
+ "Policy": {"Type": "AWS::SQS::QueuePolicy", "Properties": {
+ "Queues": [{"Ref": q} for q in queues],
+ "PolicyDocument": _sqs_policy_document(
+ sid, [{"Fn::GetAtt": [q, "Arn"]} for q in queues]),
+ }},
+ },
+ "Outputs": {"QueueA": {"Value": {"Ref": "QueueA"}},
+ "QueueB": {"Value": {"Ref": "QueueB"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("AllowSns", ["QueueA", "QueueB"]))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ queue_a = _output(stack, "QueueA")
+ queue_b = _output(stack, "QueueB")
+ assert _sqs_policy_sids(sqs, queue_a) == ["AllowSns"]
+ assert _sqs_policy_sids(sqs, queue_b) == ["AllowSns"]
+ physical_id = _stack_physical_id(cfn, stack_name, "Policy")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("AllowSnsV2", ["QueueA"]))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _sqs_policy_sids(sqs, queue_a) == ["AllowSnsV2"]
+ assert _sqs_policy_sids(sqs, queue_b) == []
+ assert _stack_physical_id(cfn, stack_name, "Policy") == physical_id
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _sns_policy_sids(sns, topic_arn):
+ """The statement ids of the topic's Policy attribute, [] when it has none."""
+ policy = sns.get_topic_attributes(TopicArn=topic_arn)["Attributes"].get("Policy")
+ if not policy:
+ return []
+ return [st.get("Sid") for st in json.loads(policy)["Statement"]]
+
+
+def test_cfn_sns_topic_policy_updates_in_place(cfn, sns):
+ """PolicyDocument and Topics are both No interruption on the resource
+ reference: the policy resource keeps its physical id, the topics it
+ still names carry the new document, and a topic dropped from Topics
+ loses its policy. Without an update handler the resource was replaced
+ and the replacement's cleanup delete stripped the policy off the very
+ topics the new document had just been written to."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-sns-tpol-{uid}"
+
+ def template(sid, topics):
+ return json.dumps({
+ "Resources": {
+ "TopicA": {"Type": "AWS::SNS::Topic",
+ "Properties": {"TopicName": f"cfn-tpol-a-{uid}"}},
+ "TopicB": {"Type": "AWS::SNS::Topic",
+ "Properties": {"TopicName": f"cfn-tpol-b-{uid}"}},
+ "Policy": {"Type": "AWS::SNS::TopicPolicy", "Properties": {
+ "Topics": [{"Ref": t} for t in topics],
+ "PolicyDocument": {
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Sid": sid,
+ "Effect": "Allow",
+ "Principal": {"Service": "events.amazonaws.com"},
+ "Action": "sns:Publish",
+ "Resource": [{"Ref": t} for t in topics],
+ }],
+ },
+ }},
+ },
+ "Outputs": {"TopicA": {"Value": {"Ref": "TopicA"}},
+ "TopicB": {"Value": {"Ref": "TopicB"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("AllowEvents", ["TopicA", "TopicB"]))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ topic_a = _output(stack, "TopicA")
+ topic_b = _output(stack, "TopicB")
+ assert _sns_policy_sids(sns, topic_a) == ["AllowEvents"]
+ assert _sns_policy_sids(sns, topic_b) == ["AllowEvents"]
+ physical_id = _stack_physical_id(cfn, stack_name, "Policy")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("AllowEventsV2", ["TopicA"]))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _sns_policy_sids(sns, topic_a) == ["AllowEventsV2"]
+ assert _sns_policy_sids(sns, topic_b) == []
+ assert _stack_physical_id(cfn, stack_name, "Policy") == physical_id
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
# ===========================================================================
# CodeBuild Project Tests
# ===========================================================================
@@ -8423,6 +8778,76 @@ def test_cfn_apigwv2_integration_basic(cfn, apigw):
_assert_apigwv2_api_not_found(lambda: apigw.get_integrations(ApiId=api_id))
+def _apigwv2_integration_update_template(uid, description="first", timeout=5000,
+ request_parameters=True, on_second_api=False):
+ props = {
+ "ApiId": {"Ref": "SecondApi" if on_second_api else "HttpApi"},
+ "IntegrationType": "HTTP_PROXY",
+ "IntegrationMethod": "ANY",
+ "IntegrationUri": "https://backend.example",
+ "PayloadFormatVersion": "1.0",
+ "Description": description,
+ "TimeoutInMillis": timeout,
+ }
+ if request_parameters:
+ props["RequestParameters"] = {"append:header.x-trace": "$context.requestId"}
+ return json.dumps({
+ "Resources": {
+ "HttpApi": {"Type": "AWS::ApiGatewayV2::Api",
+ "Properties": {"Name": f"api-{uid}", "ProtocolType": "HTTP"}},
+ "SecondApi": {"Type": "AWS::ApiGatewayV2::Api",
+ "Properties": {"Name": f"api-{uid}-2", "ProtocolType": "HTTP"}},
+ "Integration": {"Type": "AWS::ApiGatewayV2::Integration", "Properties": props},
+ },
+ "Outputs": {"ApiId": {"Value": {"Ref": "HttpApi"}},
+ "SecondApiId": {"Value": {"Ref": "SecondApi"}},
+ "IntegrationId": {"Value": {"Ref": "Integration"}}},
+ })
+
+
+def test_cfn_apigwv2_integration_updates_in_place(cfn, apigw):
+ """Every property but ApiId is No interruption on the
+ AWS::ApiGatewayV2::Integration reference: an update keeps the
+ integrationId (what every Route's Target names) and GetIntegration reads
+ the new values. The create fallback minted a new id on every change and
+ left the old integration on the API. A dropped RequestParameters reverts
+ to the create default (none); an ApiId change replaces the integration
+ on the new API and removes it from the old one."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-apigwv2-integration-update-{uid}"
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_apigwv2_integration_update_template(uid))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ api_id, int_id = _output(stack, "ApiId"), _output(stack, "IntegrationId")
+ before = apigw.get_integration(ApiId=api_id, IntegrationId=int_id)
+ assert before["RequestParameters"] == {"append:header.x-trace": "$context.requestId"}
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_apigwv2_integration_update_template(
+ uid, description="second", timeout=9000, request_parameters=False))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "IntegrationId") == int_id
+ after = apigw.get_integration(ApiId=api_id, IntegrationId=int_id)
+ assert after["Description"] == "second"
+ assert after["TimeoutInMillis"] == 9000
+ assert not after.get("RequestParameters")
+ assert len(apigw.get_integrations(ApiId=api_id)["Items"]) == 1
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_apigwv2_integration_update_template(
+ uid, description="second", timeout=9000, request_parameters=False,
+ on_second_api=True))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ second_api_id, new_int_id = _output(stack, "SecondApiId"), _output(stack, "IntegrationId")
+ assert new_int_id != int_id
+ assert apigw.get_integration(ApiId=second_api_id, IntegrationId=new_int_id)["Description"] == "second"
+ assert apigw.get_integrations(ApiId=api_id)["Items"] == []
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
def test_cfn_apigwv2_ms_custom_id(cfn, apigw):
"""CloudFormation ms-custom-id tag pins the ApiGatewayV2 API id (issue #400)."""
template = {
@@ -8455,6 +8880,108 @@ def test_cfn_apigwv2_ms_custom_id(cfn, apigw):
_wait_stack(cfn, stack_name)
+def _apigwv2_api_update_template(name, protocol="HTTP", cors=True, description="first",
+ route_selection=None):
+ props = {"Name": name, "ProtocolType": protocol, "Description": description,
+ "Version": "v1", "Tags": {"env": "a"}}
+ if cors:
+ props["CorsConfiguration"] = {"AllowOrigins": ["https://a.example"],
+ "AllowMethods": ["GET"]}
+ if route_selection:
+ props["RouteSelectionExpression"] = route_selection
+ return json.dumps({
+ "Resources": {"HttpApi": {"Type": "AWS::ApiGatewayV2::Api", "Properties": props}},
+ "Outputs": {"ApiId": {"Value": {"Ref": "HttpApi"}},
+ "Endpoint": {"Value": {"Fn::GetAtt": ["HttpApi", "ApiEndpoint"]}}},
+ })
+
+
+def test_cfn_apigwv2_api_updates_in_place(cfn, apigw):
+ """Every property but ProtocolType is No interruption on the
+ AWS::ApiGatewayV2::Api reference: an update keeps the apiId and the
+ ApiEndpoint and the service reads the new values through GetApi. The
+ create fallback minted a new id and endpoint on every change. A dropped
+ property reverts to the create default (no CorsConfiguration, the
+ protocol's route selection expression); a ProtocolType change replaces
+ the API and removes the old one."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-apigwv2-api-update-{uid}"
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_apigwv2_api_update_template(f"api-{uid}"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ api_id, endpoint = _output(stack, "ApiId"), _output(stack, "Endpoint")
+ assert "CorsConfiguration" in apigw.get_api(ApiId=api_id)
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_apigwv2_api_update_template(
+ f"api-{uid}-renamed", cors=False, description="second"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "ApiId") == api_id
+ assert _output(stack, "Endpoint") == endpoint
+ api = apigw.get_api(ApiId=api_id)
+ assert api["Name"] == f"api-{uid}-renamed"
+ assert api["Description"] == "second"
+ assert "CorsConfiguration" not in api
+ assert _template_tags(api["Tags"]) == {"env": "a"}
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_apigwv2_api_update_template(
+ f"api-{uid}-ws", protocol="WEBSOCKET"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ new_id = _output(stack, "ApiId")
+ assert new_id != api_id
+ api = apigw.get_api(ApiId=new_id)
+ assert api["ProtocolType"] == "WEBSOCKET"
+ assert api["RouteSelectionExpression"] == "$request.body.action"
+ _assert_apigwv2_api_not_found(lambda: apigw.get_api(ApiId=api_id))
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_apigwv2_api_update_template(
+ f"api-{uid}-ws", protocol="WEBSOCKET", route_selection="$request.body.op"))
+ _wait_stack(cfn, stack_name)
+ assert apigw.get_api(ApiId=new_id)["RouteSelectionExpression"] == "$request.body.op"
+ cfn.update_stack(StackName=stack_name, TemplateBody=_apigwv2_api_update_template(
+ f"api-{uid}-ws", protocol="WEBSOCKET"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "ApiId") == new_id
+ assert apigw.get_api(ApiId=new_id)["RouteSelectionExpression"] == "$request.body.action"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_apigwv2_api_update_keeps_pinned_id(cfn, apigw):
+ """With an ms-custom-id tag the create fallback resolved the pinned id a
+ second time, which refused it as already in use and rolled the stack
+ back; the update now keeps the pinned id and applies the change."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-apigwv2-api-pinned-{uid}"
+ pinned = f"pinned-{uid}"
+
+ def template(description):
+ return json.dumps({"Resources": {"HttpApi": {
+ "Type": "AWS::ApiGatewayV2::Api",
+ "Properties": {"Name": f"api-{uid}", "ProtocolType": "HTTP",
+ "Description": description,
+ "Tags": {"ms-custom-id": pinned}},
+ }}, "Outputs": {"ApiId": {"Value": {"Ref": "HttpApi"}}}})
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("first"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ assert _output(stack, "ApiId") == pinned
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("second"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "ApiId") == pinned
+ assert apigw.get_api(ApiId=pinned)["Description"] == "second"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
def test_cfn_apigwv2_route_basic(cfn, apigw):
"""CFN stack with ApiGatewayV2 Api + Integration + Route deploys successfully."""
template = {
@@ -8507,6 +9034,71 @@ def test_cfn_apigwv2_route_basic(cfn, apigw):
_assert_apigwv2_api_not_found(lambda: apigw.get_routes(ApiId=api_id))
+def _apigwv2_route_update_template(uid, operation_name="first", scopes=True,
+ on_second_api=False):
+ props = {
+ "ApiId": {"Ref": "SecondApi" if on_second_api else "HttpApi"},
+ "RouteKey": "GET /items",
+ "AuthorizationType": "JWT" if scopes else "NONE",
+ "OperationName": operation_name,
+ }
+ if scopes:
+ props["AuthorizationScopes"] = ["items:read"]
+ return json.dumps({
+ "Resources": {
+ "HttpApi": {"Type": "AWS::ApiGatewayV2::Api",
+ "Properties": {"Name": f"api-{uid}", "ProtocolType": "HTTP"}},
+ "SecondApi": {"Type": "AWS::ApiGatewayV2::Api",
+ "Properties": {"Name": f"api-{uid}-2", "ProtocolType": "HTTP"}},
+ "Route": {"Type": "AWS::ApiGatewayV2::Route", "Properties": props},
+ },
+ "Outputs": {"ApiId": {"Value": {"Ref": "HttpApi"}},
+ "SecondApiId": {"Value": {"Ref": "SecondApi"}},
+ "RouteId": {"Value": {"Fn::GetAtt": ["Route", "RouteId"]}}},
+ })
+
+
+def test_cfn_apigwv2_route_updates_in_place(cfn, apigw):
+ """Every property but ApiId is No interruption on the
+ AWS::ApiGatewayV2::Route reference: an update keeps the routeId and
+ GetRoute reads the new values. The create fallback minted a new id on
+ every change and left the old route on the API. A dropped
+ AuthorizationScopes reverts to the create default (none); an ApiId
+ change replaces the route on the new API and removes it from the old
+ one."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-apigwv2-route-update-{uid}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=_apigwv2_route_update_template(uid))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ api_id, route_id = _output(stack, "ApiId"), _output(stack, "RouteId")
+ before = apigw.get_route(ApiId=api_id, RouteId=route_id)
+ assert before["AuthorizationScopes"] == ["items:read"]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_apigwv2_route_update_template(
+ uid, operation_name="second", scopes=False))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "RouteId") == route_id
+ after = apigw.get_route(ApiId=api_id, RouteId=route_id)
+ assert after["OperationName"] == "second"
+ assert after["AuthorizationType"] == "NONE"
+ assert not after.get("AuthorizationScopes")
+ assert len(apigw.get_routes(ApiId=api_id)["Items"]) == 1
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_apigwv2_route_update_template(
+ uid, operation_name="second", scopes=False, on_second_api=True))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ second_api_id, new_route_id = _output(stack, "SecondApiId"), _output(stack, "RouteId")
+ assert new_route_id != route_id
+ assert apigw.get_route(ApiId=second_api_id, RouteId=new_route_id)["RouteKey"] == "GET /items"
+ assert apigw.get_routes(ApiId=api_id)["Items"] == []
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
def test_cfn_apigwv2_authorizer_jwt(cfn, apigw):
"""CFN stack with an AWS::ApiGatewayV2::Authorizer deploys successfully and
a Route referencing it via AuthorizerId is enforced at request time.
@@ -8756,6 +9348,72 @@ def test_cfn_apigwv2_integration_idempotent_delete(cfn):
cfn.delete_stack(StackName=stack_name)
+def _apigwv2_stage_update_template(uid, stage_name="dev", description="first",
+ variables=None, auto_deploy=True):
+ props = {
+ "ApiId": {"Ref": "HttpApi"},
+ "StageName": stage_name,
+ "Description": description,
+ "StageVariables": variables or {"tier": "1"},
+ "Tags": {"env": "a"},
+ }
+ if auto_deploy:
+ props["AutoDeploy"] = True
+ return json.dumps({
+ "Resources": {
+ "HttpApi": {"Type": "AWS::ApiGatewayV2::Api",
+ "Properties": {"Name": f"api-{uid}", "ProtocolType": "HTTP"}},
+ "Stage": {"Type": "AWS::ApiGatewayV2::Stage", "Properties": props},
+ },
+ "Outputs": {"ApiId": {"Value": {"Ref": "HttpApi"}},
+ "StageRef": {"Value": {"Ref": "Stage"}}},
+ })
+
+
+def test_cfn_apigwv2_stage_updates_in_place(cfn, apigw):
+ """Every property but ApiId and StageName is No interruption on the
+ AWS::ApiGatewayV2::Stage reference: an update keeps the stage (its
+ CreatedDate and Ref) and GetStage reads the new values. The create
+ fallback rebuilt the record under the same name, resetting CreatedDate.
+ A dropped AutoDeploy reverts to the create default (false); a StageName
+ change replaces the stage and removes the old one."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-apigwv2-stage-update-{uid}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=_apigwv2_stage_update_template(uid))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ api_id, stage_ref = _output(stack, "ApiId"), _output(stack, "StageRef")
+ before = apigw.get_stage(ApiId=api_id, StageName="dev")
+ assert before["AutoDeploy"] is True
+ time.sleep(1.1)
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_apigwv2_stage_update_template(
+ uid, description="second", variables={"tier": "2"}, auto_deploy=False))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "StageRef") == stage_ref
+ after = apigw.get_stage(ApiId=api_id, StageName="dev")
+ assert after["Description"] == "second"
+ assert after["StageVariables"] == {"tier": "2"}
+ assert after["AutoDeploy"] is False
+ assert after["CreatedDate"] == before["CreatedDate"]
+ assert after["LastUpdatedDate"] > before["LastUpdatedDate"]
+ assert _template_tags(after["Tags"]) == {"env": "a"}
+ assert len(apigw.get_stages(ApiId=api_id)["Items"]) == 1
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_apigwv2_stage_update_template(
+ uid, stage_name="prod", description="second", variables={"tier": "2"},
+ auto_deploy=False))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "StageRef") != stage_ref
+ assert apigw.get_stage(ApiId=api_id, StageName="prod")["Description"] == "second"
+ assert [s["StageName"] for s in apigw.get_stages(ApiId=api_id)["Items"]] == ["prod"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
def test_cfn_apigwv2_full_http_api_stack(cfn, apigw):
"""Full HTTP API stack with Api + Stage + Integration + Route deploys and cleans up."""
template = {
@@ -9935,7 +10593,8 @@ def test_cfn_cloudfront_distribution_consumes_provisioned_policies(cfn, cloudfro
"""The payoff: a distribution in the same stack references the policies and
the function by Ref/GetAtt. This is what a CDK app emits, and it only works
if Ref yields the value the distribution's own parser expects."""
- template = json.loads(_cloudfront_template("prov2"))
+ uid = _uuid_mod.uuid4().hex[:8]
+ template = json.loads(_cloudfront_template(f"prov2{uid}"))
template["Resources"]["Dist"] = {
"Type": "AWS::CloudFront::Distribution",
"Properties": {"DistributionConfig": {
@@ -9958,34 +10617,216 @@ def test_cfn_cloudfront_distribution_consumes_provisioned_policies(cfn, cloudfro
}
template["Outputs"]["DistId"] = {"Value": {"Ref": "Dist"}}
- cfn.create_stack(StackName="cfn-cf-dist-policies", TemplateBody=json.dumps(template))
- stack = _wait_stack(cfn, "cfn-cf-dist-policies")
- assert stack["StackStatus"] == "CREATE_COMPLETE"
- out = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}
+ stack_name = f"cfn-cf-dist-policies-{uid}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ out = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}
+
+ # The distribution provisioner accepted every Ref without rolling back,
+ # and each one addresses a real object; the stored DefaultCacheBehavior
+ # names the same ids the policies were created under.
+ assert cloudfront.get_cache_policy(Id=out["CachePolicyRef"])["CachePolicy"]["Id"]
+ assert cloudfront.get_origin_request_policy(
+ Id=out["OrpRef"])["OriginRequestPolicy"]["Id"]
+ assert cloudfront.get_response_headers_policy(
+ Id=out["RhpRef"])["ResponseHeadersPolicy"]["Id"]
+ assert out["FunctionArn"].endswith(f":function/cfn-fn-prov2{uid}")
+ behavior = cloudfront.get_distribution_config(
+ Id=out["DistId"])["DistributionConfig"]["DefaultCacheBehavior"]
+ assert behavior["CachePolicyId"] == out["CachePolicyRef"]
+ assert behavior["OriginRequestPolicyId"] == out["OrpRef"]
+ assert behavior["ResponseHeadersPolicyId"] == out["RhpRef"]
+ assert behavior["FunctionAssociations"]["Items"][0]["FunctionARN"] == out["FunctionArn"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def _cf_distribution_update_template(comment="first", aliases=("a.example",),
+ origins=("origin1",), enabled=True, tags=None):
+ return json.dumps({
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Resources": {"Dist": {
+ "Type": "AWS::CloudFront::Distribution",
+ "Properties": {
+ "DistributionConfig": {
+ "Enabled": enabled,
+ "Comment": comment,
+ "Aliases": list(aliases),
+ "DefaultRootObject": "index.html",
+ "IPV6Enabled": True,
+ "Origins": [{"Id": o, "DomainName": f"{o}.example.test",
+ "OriginCustomHeaders": [{"HeaderName": "X-Origin",
+ "HeaderValue": o}],
+ "CustomOriginConfig": {"OriginProtocolPolicy": "https-only",
+ "OriginSSLProtocols": ["TLSv1.2"]}}
+ for o in origins],
+ "DefaultCacheBehavior": {
+ "TargetOriginId": origins[0],
+ "ViewerProtocolPolicy": "redirect-to-https",
+ "AllowedMethods": ["GET", "HEAD", "OPTIONS"],
+ "CachedMethods": ["GET", "HEAD"],
+ "Compress": True,
+ "ForwardedValues": {"QueryString": False,
+ "Cookies": {"Forward": "none"}},
+ },
+ "CustomErrorResponses": [{"ErrorCode": 404, "ResponseCode": 200,
+ "ResponsePagePath": "/index.html"}],
+ "Restrictions": {"GeoRestriction": {"RestrictionType": "whitelist",
+ "Locations": ["DE", "AT"]}},
+ "ViewerCertificate": {
+ "AcmCertificateArn": "arn:aws:acm:us-east-1:000000000000:certificate/cfn",
+ "SslSupportMethod": "sni-only",
+ "MinimumProtocolVersion": "TLSv1.2_2021",
+ },
+ },
+ "Tags": [{"Key": k, "Value": v} for k, v in (tags or {"env": "a"}).items()],
+ },
+ }},
+ "Outputs": {"DistId": {"Value": {"Ref": "Dist"}},
+ "DomainName": {"Value": {"Fn::GetAtt": ["Dist", "DomainName"]}}},
+ })
+
+
+def test_cfn_cloudfront_distribution_readable_through_the_api(cfn, cloudfront):
+ """A CloudFormation-provisioned distribution stored an empty config, so
+ GetDistribution and GetDistributionConfig failed with a 500 on it and
+ ListDistributions showed empty blocks. The create now stores the
+ DistributionConfig rendered the way CreateDistribution stores it, in the
+ API's shape: plain lists become Quantity/Items blocks, CachedMethods
+ nests under AllowedMethods, IPV6Enabled is IsIPV6Enabled, the
+ ViewerCertificate members take the API's capitalisation."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cf-dist-read-{uid}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cf_distribution_update_template())
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ dist_id = _output(stack, "DistId")
+
+ response = cloudfront.get_distribution(Id=dist_id)
+ dist, dist_etag = response["Distribution"], response["ETag"]
+ assert dist["Id"] == dist_id
+ assert dist["DomainName"] == _output(stack, "DomainName")
+ cfg = dist["DistributionConfig"]
+ assert cfg["CallerReference"]
+ assert cfg["Comment"] == "first"
+ assert cfg["Aliases"] == {"Quantity": 1, "Items": ["a.example"]}
+ assert cfg["IsIPV6Enabled"] is True
+ origin = cfg["Origins"]["Items"][0]
+ assert origin["DomainName"] == "origin1.example.test"
+ assert origin["CustomHeaders"]["Items"] == [{"HeaderName": "X-Origin", "HeaderValue": "origin1"}]
+ assert origin["CustomOriginConfig"]["OriginSslProtocols"]["Items"] == ["TLSv1.2"]
+ behavior = cfg["DefaultCacheBehavior"]
+ assert behavior["AllowedMethods"]["Items"] == ["GET", "HEAD", "OPTIONS"]
+ assert behavior["AllowedMethods"]["CachedMethods"]["Items"] == ["GET", "HEAD"]
+ assert cfg["CustomErrorResponses"]["Items"][0]["ResponsePagePath"] == "/index.html"
+ assert cfg["Restrictions"]["GeoRestriction"] == {
+ "RestrictionType": "whitelist", "Quantity": 2, "Items": ["DE", "AT"]}
+ assert cfg["ViewerCertificate"] == {
+ "ACMCertificateArn": "arn:aws:acm:us-east-1:000000000000:certificate/cfn",
+ "SSLSupportMethod": "sni-only", "MinimumProtocolVersion": "TLSv1.2_2021"}
+
+ config = cloudfront.get_distribution_config(Id=dist_id)
+ assert config["DistributionConfig"]["Origins"] == cfg["Origins"]
+ assert config["ETag"] == dist_etag
+ summary = next(d for d in cloudfront.list_distributions()["DistributionList"]["Items"]
+ if d["Id"] == dist_id)
+ assert summary["Aliases"]["Items"] == ["a.example"]
+ assert summary["Origins"]["Quantity"] == 1
+ # The distribution is in _STACK_TAG_PROPERTY, so the three
+ # aws:cloudformation: tags reach it alongside the template's own,
+ # the way every other tag-storing type receives them.
+ tags = {t["Key"]: t["Value"]
+ for t in cloudfront.list_tags_for_resource(Resource=dist["ARN"])["Tags"]["Items"]}
+ assert tags["env"] == "a"
+ assert tags["aws:cloudformation:stack-name"] == stack_name
+ assert tags["aws:cloudformation:logical-id"] == "Dist"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_cloudfront_distribution_updates_in_place(cfn, cloudfront, tagging):
+ """DistributionConfig and Tags are both No interruption on the
+ AWS::CloudFront::Distribution reference, so an update never replaces:
+ Id, ARN and DomainName stay, the ETag rolls, GetDistributionConfig reads
+ the new configuration, a dropped alias is gone, Enabled: false reaches
+ the summary, tags are reconciled and the invalidation history survives.
+ The create fallback minted a new Id and DomainName on every change and
+ the engine deleted the old distribution. Deleting the stack removes the
+ tags with the distribution, so the tagging API stops listing it."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cf-dist-update-{uid}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cf_distribution_update_template())
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ dist_id, domain = _output(stack, "DistId"), _output(stack, "DomainName")
+ before = cloudfront.get_distribution(Id=dist_id)
+ cloudfront.create_invalidation(
+ DistributionId=dist_id,
+ InvalidationBatch={"Paths": {"Quantity": 1, "Items": ["/*"]},
+ "CallerReference": f"inv-{uid}"})
- # The distribution provisioner accepted every Ref without rolling back, and
- # each one addresses a real object. Asserting the stored DefaultCacheBehavior
- # would be the stronger check, but GetDistribution and GetDistributionConfig
- # both 500 on any CloudFormation-provisioned distribution (the record carries
- # an empty config_xml) — that is a separate, pre-existing bug.
- assert cloudfront.get_cache_policy(Id=out["CachePolicyRef"])["CachePolicy"]["Id"]
- assert cloudfront.get_origin_request_policy(
- Id=out["OrpRef"])["OriginRequestPolicy"]["Id"]
- assert cloudfront.get_response_headers_policy(
- Id=out["RhpRef"])["ResponseHeadersPolicy"]["Id"]
- assert out["FunctionArn"].endswith(":function/cfn-fn-prov2")
- assert out["DistId"]
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cf_distribution_update_template(
+ comment="second", aliases=("b.example",), origins=("origin1", "origin2"),
+ enabled=False, tags={"env": "b", "team": "web"}))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "DistId") == dist_id
+ assert _output(stack, "DomainName") == domain
+
+ after = cloudfront.get_distribution(Id=dist_id)
+ assert after["ETag"] != before["ETag"]
+ dist = after["Distribution"]
+ assert dist["ARN"] == before["Distribution"]["ARN"]
+ assert dist["LastModifiedTime"] >= before["Distribution"]["LastModifiedTime"]
+ cfg = cloudfront.get_distribution_config(Id=dist_id)["DistributionConfig"]
+ assert cfg["Comment"] == "second"
+ assert cfg["Enabled"] is False
+ assert cfg["Aliases"] == {"Quantity": 1, "Items": ["b.example"]}
+ assert [o["Id"] for o in cfg["Origins"]["Items"]] == ["origin1", "origin2"]
+ assert cfg["CallerReference"] == before["Distribution"]["DistributionConfig"]["CallerReference"]
+ summary = next(d for d in cloudfront.list_distributions()["DistributionList"]["Items"]
+ if d["Id"] == dist_id)
+ assert summary["Enabled"] is False
+ # The template's own tags are reconciled (env moved from a to b,
+ # team added); the stack tags the type now receives alongside them
+ # survive the update rather than being reconciled away.
+ tags = {t["Key"]: t["Value"]
+ for t in cloudfront.list_tags_for_resource(Resource=dist["ARN"])["Tags"]["Items"]}
+ assert tags["env"] == "b"
+ assert tags["team"] == "web"
+ assert tags["aws:cloudformation:stack-name"] == stack_name
+ assert tags["aws:cloudformation:logical-id"] == "Dist"
+ invalidations = cloudfront.list_invalidations(DistributionId=dist_id)["InvalidationList"]
+ assert invalidations["Quantity"] == 1
+
+ # A dropped property reverts to the create default: no aliases.
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cf_distribution_update_template(
+ comment="second", aliases=(), origins=("origin1", "origin2"), enabled=False,
+ tags={"env": "b", "team": "web"}))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "DistId") == dist_id
+ cfg = cloudfront.get_distribution_config(Id=dist_id)["DistributionConfig"]
+ assert cfg["Aliases"]["Quantity"] == 0
+ assert "Items" not in cfg["Aliases"]
- cfn.delete_stack(StackName="cfn-cf-dist-policies")
- _wait_stack(cfn, "cfn-cf-dist-policies")
+ _delete_cfn_test_stack(cfn, stack_name)
+ listed = [r["ResourceARN"] for r in tagging.get_resources(
+ ResourceTypeFilters=["cloudfront"])["ResourceTagMappingList"]]
+ assert dist["ARN"] not in listed
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
def test_cfn_cloudfront_distribution_keeps_its_policy_ref_across_a_rename(cfn, cloudfront):
"""The payoff of updating in place: a distribution that took the cache
policy's Ref keeps pointing at the same policy after the policy is renamed
- through the stack. Only the Ref and the policy itself can be asserted here;
- GetDistributionConfig on a CloudFormation-provisioned distribution is the
- separate, pre-existing 500."""
+ through the stack. The Ref and the policy itself are what the rename is
+ about, so they are what this asserts."""
uid = _uuid_mod.uuid4().hex[:8]
stack_name = f"cfn-cf-dist-rename-{uid}"
template = json.loads(_cloudfront_template(f"ren{uid}"))
@@ -11649,6 +12490,104 @@ def test_cfn_logs_subscription_filter_provisions(cfn, logs):
logs.describe_subscription_filters(logGroupName="/cfn/subfilter-test")
+def _cfn_subfilter_template(uid, filter_props):
+ return json.dumps({
+ "Resources": {
+ "GroupA": {"Type": "AWS::Logs::LogGroup",
+ "Properties": {"LogGroupName": f"/cfn/subfilter-upd-a-{uid}"}},
+ "GroupB": {"Type": "AWS::Logs::LogGroup",
+ "Properties": {"LogGroupName": f"/cfn/subfilter-upd-b-{uid}"}},
+ "Filter": {"Type": "AWS::Logs::SubscriptionFilter", "Properties": filter_props},
+ },
+ "Outputs": {"FilterRef": {"Value": {"Ref": "Filter"}}},
+ })
+
+
+def test_cfn_logs_subscription_filter_updates_in_place(cfn, logs):
+ """FilterPattern, DestinationArn, RoleArn and Distribution are No
+ interruption on the resource reference: the filter keeps its name (what
+ Ref returns) and DescribeSubscriptionFilters reads the new values. A
+ dropped RoleArn empties and a dropped Distribution reverts to
+ ByLogStream, what the create stores without them."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-subfilter-upd-{uid}"
+ group = f"/cfn/subfilter-upd-a-{uid}"
+ base = {"LogGroupName": {"Ref": "GroupA"}}
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_subfilter_template(uid, {
+ **base, "FilterPattern": "[Producer]",
+ "DestinationArn": "arn:aws:lambda:us-east-1:000000000000:function:consumer",
+ }))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ filter_name = _output(stack, "FilterRef")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_subfilter_template(uid, {
+ **base, "FilterPattern": "ERROR",
+ "DestinationArn": "arn:aws:kinesis:us-east-1:000000000000:stream/errors",
+ "RoleArn": "arn:aws:iam::000000000000:role/logs-to-kinesis",
+ "Distribution": "Random",
+ }))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "FilterRef") == filter_name
+ filters = logs.describe_subscription_filters(logGroupName=group)["subscriptionFilters"]
+ assert [f["filterName"] for f in filters] == [filter_name]
+ assert filters[0]["filterPattern"] == "ERROR"
+ assert filters[0]["destinationArn"].endswith(":stream/errors")
+ assert filters[0]["roleArn"].endswith(":role/logs-to-kinesis")
+ assert filters[0]["distribution"] == "Random"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_subfilter_template(uid, {
+ **base, "FilterPattern": "ERROR",
+ "DestinationArn": "arn:aws:kinesis:us-east-1:000000000000:stream/errors",
+ }))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "FilterRef") == filter_name
+ filters = logs.describe_subscription_filters(logGroupName=group)["subscriptionFilters"]
+ assert [f["filterName"] for f in filters] == [filter_name]
+ assert filters[0].get("roleArn", "") == ""
+ assert filters[0]["distribution"] == "ByLogStream"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_logs_subscription_filter_group_change_moves_it(cfn, logs):
+ """LogGroupName requires replacement: the filter is created on the new
+ group and removed from the old one. The filter keeps its explicit
+ FilterName, so the physical id does not change; without an update
+ handler the create wrote the new filter and the old group kept its
+ copy, since the engine saw no replacement to clean up."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-subfilter-move-{uid}"
+ group_a = f"/cfn/subfilter-upd-a-{uid}"
+ group_b = f"/cfn/subfilter-upd-b-{uid}"
+
+ def filter_props(group):
+ return {"LogGroupName": {"Ref": group}, "FilterName": f"cfn-move-{uid}",
+ "FilterPattern": "[Producer]",
+ "DestinationArn": "arn:aws:lambda:us-east-1:000000000000:function:consumer"}
+
+ cfn.create_stack(StackName=stack_name,
+ TemplateBody=_cfn_subfilter_template(uid, filter_props("GroupA")))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=_cfn_subfilter_template(uid, filter_props("GroupB")))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "FilterRef") == f"cfn-move-{uid}"
+ assert logs.describe_subscription_filters(logGroupName=group_a)["subscriptionFilters"] == []
+ moved = logs.describe_subscription_filters(logGroupName=group_b)["subscriptionFilters"]
+ assert [f["filterName"] for f in moved] == [f"cfn-move-{uid}"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
def test_cfn_logs_resource_policy_identity_and_lifecycle(cfn):
"""Logs resource policies expose their policy name without enforcing it."""
suffix = _uuid_mod.uuid4().hex[:8]
@@ -16373,6 +17312,339 @@ def test_cfn_cognito_user_pool_enabled_mfas_update(cfn, cognito_idp):
_delete_cfn_test_stack(cfn, stack_name)
+def _role_mapping(role_arn, resolution="Deny"):
+ """A RoleMappings entry in the shape the resource reference's own example
+ uses (a Rules mapping with one claim rule)."""
+ return {
+ "Type": "Rules",
+ "AmbiguousRoleResolution": resolution,
+ "RulesConfiguration": {"Rules": [{
+ "Claim": "sub", "MatchType": "Equals", "Value": "goodvalue",
+ "RoleARN": role_arn,
+ }]},
+ }
+
+
+def test_cfn_cognito_role_attachment_update_applies_roles_and_mappings(
+ cfn, cognito_identity
+):
+ """Roles and RoleMappings are both "Update requires: No interruption" on
+ AWS::Cognito::IdentityPoolRoleAttachment: a changed role ARN and an added
+ role mapping reach GetIdentityPoolRoles on the pool the attachment
+ already sits on, with Ref and Fn::GetAtt Id still the identity pool id."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-attach-upd-{uid}"
+ pool_id = cognito_identity.create_identity_pool(
+ IdentityPoolName=f"cfn_attach_upd_{uid}", AllowUnauthenticatedIdentities=True,
+ )["IdentityPoolId"]
+ auth_v1 = "arn:aws:iam::000000000000:role/attach-auth-v1"
+ auth_v2 = "arn:aws:iam::000000000000:role/attach-auth-v2"
+
+ def template(role_arn, mappings):
+ props = {"IdentityPoolId": pool_id, "Roles": {"authenticated": role_arn}}
+ if mappings is not None:
+ props["RoleMappings"] = mappings
+ return json.dumps({
+ "Resources": {"Attach": {
+ "Type": "AWS::Cognito::IdentityPoolRoleAttachment", "Properties": props}},
+ "Outputs": {"AttachRef": {"Value": {"Ref": "Attach"}},
+ "AttachId": {"Value": {"Fn::GetAtt": ["Attach", "Id"]}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(auth_v1, None))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "AttachRef") == pool_id
+ assert _output(stack, "AttachId") == pool_id
+ attached = cognito_identity.get_identity_pool_roles(IdentityPoolId=pool_id)
+ assert attached["Roles"] == {"authenticated": auth_v1}
+ assert attached["RoleMappings"] == {}
+
+ mappings = {"graph.facebook.com": _role_mapping(auth_v2)}
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(auth_v2, mappings))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "AttachRef") == pool_id
+ assert _output(stack, "AttachId") == pool_id
+ attached = cognito_identity.get_identity_pool_roles(IdentityPoolId=pool_id)
+ assert attached["Roles"] == {"authenticated": auth_v2}
+ assert attached["RoleMappings"] == mappings
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ cognito_identity.delete_identity_pool(IdentityPoolId=pool_id)
+
+
+def test_cfn_cognito_role_attachment_dropped_mappings_revert(cfn, cognito_identity):
+ """A role attachment property the new template drops reverts to its
+ create default, because SetIdentityPoolRoles takes the whole
+ configuration: the mappings go away and the roles stay."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-attach-drop-{uid}"
+ pool_id = cognito_identity.create_identity_pool(
+ IdentityPoolName=f"cfn_attach_drop_{uid}", AllowUnauthenticatedIdentities=True,
+ )["IdentityPoolId"]
+ role_arn = "arn:aws:iam::000000000000:role/attach-drop"
+ mappings = {"graph.facebook.com": _role_mapping(role_arn)}
+
+ def template(declared):
+ props = {"IdentityPoolId": pool_id, "Roles": {"authenticated": role_arn}}
+ if declared:
+ props["RoleMappings"] = mappings
+ return json.dumps({
+ "Resources": {"Attach": {
+ "Type": "AWS::Cognito::IdentityPoolRoleAttachment", "Properties": props}},
+ "Outputs": {"AttachRef": {"Value": {"Ref": "Attach"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(True))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert cognito_identity.get_identity_pool_roles(
+ IdentityPoolId=pool_id)["RoleMappings"] == mappings
+
+ 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, "AttachRef") == pool_id
+ attached = cognito_identity.get_identity_pool_roles(IdentityPoolId=pool_id)
+ assert attached["RoleMappings"] == {}
+ assert attached["Roles"] == {"authenticated": role_arn}
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ cognito_identity.delete_identity_pool(IdentityPoolId=pool_id)
+
+
+def test_cfn_cognito_role_attachment_pool_move_replaces_the_attachment(
+ cfn, cognito_identity
+):
+ """IdentityPoolId is the one property of the type that requires
+ replacement: the attachment moves to the new pool, Ref follows it, and
+ the pool it left keeps neither the roles nor the mappings. The pools live
+ outside the stack, so nothing else moves with it."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-attach-move-{uid}"
+ pool_a, pool_b = (
+ cognito_identity.create_identity_pool(
+ IdentityPoolName=f"cfn_attach_move_{side}_{uid}",
+ AllowUnauthenticatedIdentities=True)["IdentityPoolId"]
+ for side in ("a", "b")
+ )
+ role_arn = "arn:aws:iam::000000000000:role/attach-move"
+ mappings = {"graph.facebook.com": _role_mapping(role_arn)}
+
+ def template(pool_id):
+ return json.dumps({
+ "Resources": {"Attach": {
+ "Type": "AWS::Cognito::IdentityPoolRoleAttachment", "Properties": {
+ "IdentityPoolId": pool_id,
+ "Roles": {"authenticated": role_arn},
+ "RoleMappings": mappings}}},
+ "Outputs": {"AttachRef": {"Value": {"Ref": "Attach"}}},
+ })
+
+ 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")
+ assert _output(stack, "AttachRef") == pool_a
+
+ 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, "AttachRef") == pool_b
+
+ left = cognito_identity.get_identity_pool_roles(IdentityPoolId=pool_a)
+ assert left["Roles"] == {}
+ assert left["RoleMappings"] == {}
+ moved = cognito_identity.get_identity_pool_roles(IdentityPoolId=pool_b)
+ assert moved["Roles"] == {"authenticated": role_arn}
+ assert moved["RoleMappings"] == mappings
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ for pool_id in (pool_a, pool_b):
+ cognito_identity.delete_identity_pool(IdentityPoolId=pool_id)
+
+
+def test_cfn_cognito_resource_server_update_keeps_the_identifier(cfn, cognito_idp):
+ """Name and Scopes are "Update requires: No interruption" on
+ AWS::Cognito::UserPoolResourceServer: both change through
+ UpdateResourceServer on the resource server DescribeResourceServer
+ already knows, with Ref still the Identifier. Dropping Scopes reverts it
+ to the empty list CreateResourceServer defaults to."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-rs-upd-{uid}"
+ pool_id = cognito_idp.create_user_pool(PoolName=f"cfn-rs-upd-{uid}")["UserPool"]["Id"]
+ read = {"ScopeName": "read", "ScopeDescription": "Read access"}
+ write = {"ScopeName": "write", "ScopeDescription": "Write access"}
+
+ def template(name, scopes):
+ props = {"UserPoolId": pool_id, "Identifier": "solar-system-data", "Name": name}
+ if scopes is not None:
+ props["Scopes"] = scopes
+ return json.dumps({
+ "Resources": {"Server": {
+ "Type": "AWS::Cognito::UserPoolResourceServer", "Properties": props}},
+ "Outputs": {"ServerRef": {"Value": {"Ref": "Server"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("Solar data", [read]))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "ServerRef") == "solar-system-data"
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=template("Solar system data", [read, write]))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "ServerRef") == "solar-system-data"
+ server = cognito_idp.describe_resource_server(
+ UserPoolId=pool_id, Identifier="solar-system-data")["ResourceServer"]
+ assert server["Name"] == "Solar system data"
+ assert server["Scopes"] == [read, write]
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=template("Solar system data", None))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ server = cognito_idp.describe_resource_server(
+ UserPoolId=pool_id, Identifier="solar-system-data")["ResourceServer"]
+ assert server["Scopes"] == []
+ assert server["Name"] == "Solar system data"
+ assert [s["Identifier"] for s in cognito_idp.list_resource_servers(
+ UserPoolId=pool_id, MaxResults=50)["ResourceServers"]] == ["solar-system-data"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ cognito_idp.delete_user_pool(UserPoolId=pool_id)
+
+
+def test_cfn_cognito_resource_server_rename_replaces_the_server(cfn, cognito_idp):
+ """Identifier requires replacement, and it is the physical id, so a
+ changed Identifier is the rename CloudFormation allows: the new resource
+ server is created and the one under the old identifier is gone."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-rs-rename-{uid}"
+ pool_id = cognito_idp.create_user_pool(PoolName=f"cfn-rs-rename-{uid}")["UserPool"]["Id"]
+ scope = {"ScopeName": "read", "ScopeDescription": "Read access"}
+
+ def template(identifier):
+ return json.dumps({
+ "Resources": {"Server": {
+ "Type": "AWS::Cognito::UserPoolResourceServer", "Properties": {
+ "UserPoolId": pool_id, "Identifier": identifier,
+ "Name": "Solar data", "Scopes": [scope]}}},
+ "Outputs": {"ServerRef": {"Value": {"Ref": "Server"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("solar-v1"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "ServerRef") == "solar-v1"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("solar-v2"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "ServerRef") == "solar-v2"
+
+ renamed = cognito_idp.describe_resource_server(
+ UserPoolId=pool_id, Identifier="solar-v2")["ResourceServer"]
+ assert renamed["Scopes"] == [scope]
+ assert [s["Identifier"] for s in cognito_idp.list_resource_servers(
+ UserPoolId=pool_id, MaxResults=50)["ResourceServers"]] == ["solar-v2"]
+ with pytest.raises(ClientError) as exc:
+ cognito_idp.describe_resource_server(UserPoolId=pool_id, Identifier="solar-v1")
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ cognito_idp.delete_user_pool(UserPoolId=pool_id)
+
+
+def test_cfn_cognito_resource_server_rename_under_retain_keeps_both(cfn, cognito_idp):
+ """UpdateReplacePolicy Retain on a resource server whose Identifier
+ changes: the replacement is created and the resource server under the
+ old identifier is kept, scopes and all, instead of being deleted."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-cog-rs-retain-{uid}"
+ pool_id = cognito_idp.create_user_pool(PoolName=f"cfn-rs-retain-{uid}")["UserPool"]["Id"]
+ scope = {"ScopeName": "read", "ScopeDescription": "Read access"}
+
+ def template(identifier):
+ return json.dumps({
+ "Resources": {"Server": {
+ "Type": "AWS::Cognito::UserPoolResourceServer",
+ "UpdateReplacePolicy": "Retain",
+ "Properties": {
+ "UserPoolId": pool_id, "Identifier": identifier,
+ "Name": "Solar data", "Scopes": [scope]}}},
+ "Outputs": {"ServerRef": {"Value": {"Ref": "Server"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("solar-v1"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("solar-v2"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "ServerRef") == "solar-v2"
+
+ retained = cognito_idp.describe_resource_server(
+ UserPoolId=pool_id, Identifier="solar-v1")["ResourceServer"]
+ assert retained["Scopes"] == [scope]
+ assert sorted(s["Identifier"] for s in cognito_idp.list_resource_servers(
+ UserPoolId=pool_id, MaxResults=50)["ResourceServers"]) == ["solar-v1", "solar-v2"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ cognito_idp.delete_user_pool(UserPoolId=pool_id)
+
+
+def test_cfn_cognito_resource_server_move_under_custom_name_fails_loudly(cfn, cognito_idp):
+ """UserPoolId requires replacement, which CloudFormation refuses for a
+ resource server, whose Identifier is always a custom name: the stack
+ rolls back, the resource server stays in the pool it was created in with
+ its scopes, and the pool the template pointed at gets nothing. 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-rs-move-{uid}"
+ pool_a = cognito_idp.create_user_pool(PoolName=f"cfn-rs-move-a-{uid}")["UserPool"]["Id"]
+ pool_b = cognito_idp.create_user_pool(PoolName=f"cfn-rs-move-b-{uid}")["UserPool"]["Id"]
+ scope = {"ScopeName": "read", "ScopeDescription": "Read access"}
+
+ def template(pool_id):
+ return json.dumps({
+ "Resources": {"Server": {
+ "Type": "AWS::Cognito::UserPoolResourceServer", "Properties": {
+ "UserPoolId": pool_id, "Identifier": "solar-system-data",
+ "Name": "Solar data", "Scopes": [scope]}}},
+ "Outputs": {"ServerRef": {"Value": {"Ref": "Server"}}},
+ })
+
+ 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")
+
+ 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, "ServerRef") == "solar-system-data"
+
+ stayed = cognito_idp.describe_resource_server(
+ UserPoolId=pool_a, Identifier="solar-system-data")["ResourceServer"]
+ assert stayed["Scopes"] == [scope]
+ assert cognito_idp.list_resource_servers(
+ UserPoolId=pool_b, MaxResults=50)["ResourceServers"] == []
+ 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_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
@@ -18171,6 +19443,125 @@ def test_cfn_iam_managed_policy_delete_detaches_entities(cfn, iam):
_cfn_policy_test_roles_cleanup(iam, [role])
+def _cfn_instance_profile_template(uid, profile_props):
+ def role(name):
+ return {"Type": "AWS::IAM::Role", "Properties": {
+ "RoleName": f"cfn-ip-{name}-{uid}",
+ "AssumeRolePolicyDocument": {"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": {"Service": "ec2.amazonaws.com"},
+ "Action": "sts:AssumeRole"}]},
+ }}
+ return json.dumps({
+ "Resources": {"RoleA": role("a"), "RoleB": role("b"),
+ "Profile": {"Type": "AWS::IAM::InstanceProfile", "Properties": profile_props}},
+ "Outputs": {"ProfileRef": {"Value": {"Ref": "Profile"}},
+ "ProfileArn": {"Value": {"Fn::GetAtt": ["Profile", "Arn"]}}},
+ })
+
+
+def test_cfn_iam_instance_profile_roles_update_in_place(cfn, iam):
+ """Roles is No interruption on the resource reference: the profile keeps
+ its ARN and id, GetInstanceProfile reads the new role, and a tag set
+ through TagInstanceProfile survives the update (the create rebuilt the
+ record without tags)."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-iam-ip-upd-{uid}"
+ name = f"cfn-ip-upd-{uid}"
+
+ def props(role):
+ return {"InstanceProfileName": name, "Roles": [{"Ref": role}]}
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_instance_profile_template(
+ uid, props("RoleA")), Capabilities=["CAPABILITY_NAMED_IAM"])
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ ref = _output(stack, "ProfileRef")
+ arn = _output(stack, "ProfileArn")
+ profile = iam.get_instance_profile(InstanceProfileName=name)["InstanceProfile"]
+ assert profile["Arn"] == arn
+ assert [r["RoleName"] for r in profile["Roles"]] == [f"cfn-ip-a-{uid}"]
+ profile_id = profile["InstanceProfileId"]
+ iam.tag_instance_profile(InstanceProfileName=name, Tags=[{"Key": "team", "Value": "ops"}])
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_instance_profile_template(
+ uid, props("RoleB")), Capabilities=["CAPABILITY_NAMED_IAM"])
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "ProfileRef") == ref
+ assert _output(stack, "ProfileArn") == arn
+ profile = iam.get_instance_profile(InstanceProfileName=name)["InstanceProfile"]
+ assert [r["RoleName"] for r in profile["Roles"]] == [f"cfn-ip-b-{uid}"]
+ assert profile["InstanceProfileId"] == profile_id
+ assert profile.get("Tags") == [{"Key": "team", "Value": "ops"}]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_iam_instance_profile_path_change_under_custom_name_fails_loudly(cfn, iam):
+ """Path requires replacement, which CloudFormation refuses for a
+ custom-named profile: the stack rolls back and the profile keeps its
+ path and role. Without an update handler the create silently rebuilt
+ the profile under the new path."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-iam-ip-path-{uid}"
+ name = f"cfn-ip-named-{uid}"
+
+ def props(path):
+ return {"InstanceProfileName": name, "Path": path, "Roles": [{"Ref": "RoleA"}]}
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_instance_profile_template(
+ uid, props("/")), Capabilities=["CAPABILITY_NAMED_IAM"])
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_instance_profile_template(
+ uid, props("/moved/")), Capabilities=["CAPABILITY_NAMED_IAM"])
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert "custom-named resource requires replacing" in _stack_event_reasons(cfn, stack_name)
+ profile = iam.get_instance_profile(InstanceProfileName=name)["InstanceProfile"]
+ assert profile["Path"] == "/"
+ assert profile["Arn"].endswith(f":instance-profile/{name}")
+ assert [r["RoleName"] for r in profile["Roles"]] == [f"cfn-ip-a-{uid}"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_iam_instance_profile_path_change_under_generated_name_replaces_it(cfn, iam):
+ """Under a generated name a Path change is a replacement: the profile
+ is re-created under the new path, so its ARN changes and its role
+ comes along."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-iam-ip-gen-{uid}"
+
+ def props(path):
+ return {"Path": path, "Roles": [{"Ref": "RoleA"}]}
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_instance_profile_template(
+ uid, props("/")), Capabilities=["CAPABILITY_NAMED_IAM"])
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ old_arn = _output(stack, "ProfileArn")
+ # Ref returns the ARN here; the generated name is its last segment.
+ name = old_arn.rsplit("/", 1)[1]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_instance_profile_template(
+ uid, props("/moved/")), Capabilities=["CAPABILITY_NAMED_IAM"])
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ new_arn = _output(stack, "ProfileArn")
+ assert new_arn != old_arn
+ assert new_arn.endswith(f":instance-profile/moved/{name}")
+ profile = iam.get_instance_profile(InstanceProfileName=name)["InstanceProfile"]
+ assert profile["Arn"] == new_arn
+ assert profile["Path"] == "/moved/"
+ assert [r["RoleName"] for r in profile["Roles"]] == [f"cfn-ip-a-{uid}"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
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
diff --git a/tests/test_cognito.py b/tests/test_cognito.py
index c3bf50b9..665fbf7e 100644
--- a/tests/test_cognito.py
+++ b/tests/test_cognito.py
@@ -926,6 +926,35 @@ def test_cognito_identity_pool_roles(cognito_identity):
assert roles["Roles"]["authenticated"] == "arn:aws:iam::000000000000:role/AuthRole"
assert roles["Roles"]["unauthenticated"] == "arn:aws:iam::000000000000:role/UnauthRole"
+def test_cognito_identity_pool_role_mappings_round_trip(cognito_identity):
+ """SetIdentityPoolRoles keeps the RoleMappings it is given and
+ GetIdentityPoolRoles serves them back; a later call without RoleMappings
+ clears them, since the call sets the whole configuration."""
+ iid = cognito_identity.create_identity_pool(
+ IdentityPoolName="RoleMappingsPool",
+ AllowUnauthenticatedIdentities=True,
+ )["IdentityPoolId"]
+ provider = "cognito-idp.us-east-1.amazonaws.com/us-east-1_example:client"
+ mapping = {"Type": "Token", "AmbiguousRoleResolution": "AuthenticatedRole"}
+
+ cognito_identity.set_identity_pool_roles(
+ IdentityPoolId=iid,
+ Roles={"authenticated": "arn:aws:iam::000000000000:role/AuthRole"},
+ RoleMappings={provider: mapping},
+ )
+ roles = cognito_identity.get_identity_pool_roles(IdentityPoolId=iid)
+ assert roles["Roles"] == {"authenticated": "arn:aws:iam::000000000000:role/AuthRole"}
+ assert roles["RoleMappings"] == {provider: mapping}
+
+ cognito_identity.set_identity_pool_roles(
+ IdentityPoolId=iid,
+ Roles={"authenticated": "arn:aws:iam::000000000000:role/AuthRole"},
+ )
+ roles = cognito_identity.get_identity_pool_roles(IdentityPoolId=iid)
+ assert roles["Roles"] == {"authenticated": "arn:aws:iam::000000000000:role/AuthRole"}
+ assert roles.get("RoleMappings", {}) == {}
+
+
def test_cognito_identity_pool_principal_tags(cognito_identity):
"""SetPrincipalTagAttributeMap stores a provider's attribute mapping and
GetPrincipalTagAttributeMap reports it back."""
diff --git a/tests/test_sns.py b/tests/test_sns.py
index 9188aaff..00d9ae66 100644
--- a/tests/test_sns.py
+++ b/tests/test_sns.py
@@ -378,6 +378,24 @@ def test_sns_subscribe_with_raw_message_delivery(sns):
attrs = sns.get_subscription_attributes(SubscriptionArn=sub_arn)["Attributes"]
assert attrs["RawMessageDelivery"] == "true"
+
+def test_sns_subscribe_with_subscription_role_arn(sns):
+ """SubscriptionRoleArn is a Subscribe and SetSubscriptionAttributes
+ attribute (the role Firehose subscriptions write with); both calls keep it."""
+ arn = sns.create_topic(Name="intg-sns-sub-role")["TopicArn"]
+ sub_arn = sns.subscribe(
+ TopicArn=arn, Protocol="email", Endpoint="[email protected]",
+ Attributes={"SubscriptionRoleArn": "arn:aws:iam::000000000000:role/sub-role-a"},
+ )["SubscriptionArn"]
+ attrs = sns.get_subscription_attributes(SubscriptionArn=sub_arn)["Attributes"]
+ assert attrs["SubscriptionRoleArn"] == "arn:aws:iam::000000000000:role/sub-role-a"
+ sns.set_subscription_attributes(
+ SubscriptionArn=sub_arn, AttributeName="SubscriptionRoleArn",
+ AttributeValue="arn:aws:iam::000000000000:role/sub-role-b")
+ attrs = sns.get_subscription_attributes(SubscriptionArn=sub_arn)["Attributes"]
+ assert attrs["SubscriptionRoleArn"] == "arn:aws:iam::000000000000:role/sub-role-b"
+
+
def test_sns_subscribe_with_filter_policy(sns):
arn = sns.create_topic(Name="intg-sns-sub-filter")["TopicArn"]
filter_policy = json.dumps({"event": ["MyEvent"]})