Skip to content

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

feat(cloudformation): in-place update handlers, batch 2 of #1585 (#1637)

iot-rocketaafcb6cf962c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a53dcb81..44a3c1ec 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **CloudFormation — `AWS::StepFunctions::StateMachine` updates in place** — a stack update that changed a state machine's definition, substitutions, role, logging or tags fell through to the create handler, which overwrote the record wholesale: the executions and versions behind the ARN were gone, `Tags` were never applied, and nothing in the stack events said so. The machine now updates through `UpdateStateMachine` under the same ARN, keeping its executions; a dropped `LoggingConfiguration` reverts to `OFF`, tags reconcile through `TagResource` / `UntagResource`, and `Fn::GetAtt` serves `StateMachineRevisionId`. `StateMachineName` and `StateMachineType` require replacement and follow the conventions already in place: a renamed machine is created before the old one is deleted, a type change under an unchanged custom name gets CloudFormation's own refusal, and under a generated name the update fails with a message naming the property, since the deterministic name cannot yield a fresh identity. `TracingConfiguration` and `EncryptionConfiguration` are accepted without effect, the store has no field for them. Contributed by @iot-rocket.
- **CloudFormation — `AWS::CloudWatch::Alarm` updates in place** — a stack update that changed an alarm fell through to the create handler, which rewrote the record with a fresh `StateUpdatedTimestamp` on every update, so an alarm that had been in `ALARM` for an hour reported a state change that never happened. The alarm now updates as `PutMetricAlarm` does: the configuration is rewritten under the same name and ARN, a property left out of the template falls back to its default, and the state, its reason, its timestamp and the history stay, as CloudFormation documents. `Tags` are applied on create and update through the alarm's tag set (`PutMetricAlarm` ignores them on an existing alarm). `AlarmName` requires replacement and follows the convention already in place: the renamed alarm is created before the old one is deleted; an alarm deleted behind the stack's back is recreated the same way. `Metrics` (metric math) stays unsupported, as on create. Contributed by @iot-rocket.
- **CloudFormation — `AWS::IAM::Policy` updates in place** — a stack update that changed an inline policy's document, its name or its `Roles` / `Users` / `Groups` fell through to the create handler, which rebuilt the record under a fresh policy id and attached it again, so `GetAtt Id` changed on every edit and `AttachmentCount` drifted from the attachments the entities actually held. Every property of the resource updates with no interruption on AWS, and now it does here: a new `PolicyDocument` becomes the default version through the IAM module's own `CreatePolicyVersion` (pruning at the five-version cap), the entity lists reconcile through attach and detach — the two steps the `AWS::IAM::ManagedPolicy` handler runs, now shared — and a new `PolicyName` re-keys the record under the ARN derived from it, keeping the policy id, the version history and every entity's attachment, with `Ref` following the new name. Deleting either policy type now detaches it from its entities before the record goes, so a role no longer keeps a dangling ARN in its attached list. Contributed by @iot-rocket.
+- **CloudFormation — `AWS::ApiGateway::Authorizer` updates in place** — a stack update that changed an authorizer fell through to the create handler: a second authorizer under a new id, `Ref` flipping to it, the old one left on the API. Every property but `RestApiId` is *No interruption* on the resource reference, so the authorizer now updates through `UpdateAuthorizer` under its id; a property the template drops reverts to the value the create fills in (a 300 s result TTL, the `Authorization` header as identity source), `AuthType` is kept as `GetAuthorizer` reports it, and a `RestApiId` change replaces the authorizer in CloudFormation's order. Contributed by @iot-rocket.
+- **CloudFormation — `AWS::ApiGateway::Deployment` updates in place** — a deployment whose `Description`, `StageName` or `StageDescription` changed fell through to the create handler: a second deployment under a new id, `Ref` flipping to it, the first left on the API. The three properties are *No interruption* on the resource reference, so the deployment keeps its id: the description patches it, a changed stage name or stage description deploys the same deployment to that stage (a stage the template stops naming stays, as on AWS), and only `RestApiId` and `DeploymentCanarySettings`, which require replacement, create a new one. `StageDescription` is read as the object the reference defines (`Description`, `Variables`), and a failed `CreateDeployment` fails the stack instead of recording an empty id. Contributed by @iot-rocket.
+- **CloudFormation — `AWS::KMS::Alias` updates in place** — a stack update that changed an alias fell through to the create handler, which overwrote the record under the same name, and a renamed alias left the old name behind. `TargetKeyId` is *No interruption* on the resource reference, so a changed target re-points the alias under its name as `UpdateAlias` does; `AliasName` requires replacement and the new alias is created before the engine removes the old one. The create now checks the two constraints the reference states — the `alias/` prefix and the reserved `alias/aws/` prefix — and requires `TargetKeyId`. Contributed by @iot-rocket.
### Fixed
- **CloudFormation — `AWS::Events::Rule` reports the rule ARN the EventBridge service reports** — `Fn::GetAtt` `Arn` on a rule was built with the bus name in every case, so a rule on the default bus answered `rule/default/<name>` while `DescribeRule` and `ListRules` for the same rule answered `rule/<name>`; a permission or a target keyed on the template's ARN never matched the service's. The provisioner now derives the ARN through the service's own helper: no bus segment on the default bus, `rule/<bus>/<name>` on a custom one. Contributed by @iot-rocket.
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.py
index 3bdbe765..c6092b25 100644
--- a/ministack/services/apigateway_v1.py
+++ b/ministack/services/apigateway_v1.py
@@ -2945,31 +2945,40 @@ def _create_deployment(api_id, data):
# If stageName is provided, create/update the stage automatically
stage_name = data.get("stageName")
if stage_name:
- existing_stage = _stages_v1.get(api_id, {}).get(stage_name)
- if existing_stage:
- existing_stage["deploymentId"] = deployment_id
- existing_stage["lastUpdatedDate"] = _now_unix()
- else:
- stage = {
- "stageName": stage_name,
- "deploymentId": deployment_id,
- "description": data.get("stageDescription", ""),
- "createdDate": _now_unix(),
- "lastUpdatedDate": _now_unix(),
- "variables": data.get("variables", {}),
- "methodSettings": {},
- "accessLogSettings": {},
- "cacheClusterEnabled": False,
- "cacheClusterSize": None,
- "tracingEnabled": False,
- "tags": {},
- "documentationVersion": None,
- }
- _stages_v1.setdefault(api_id, {})[stage_name] = stage
+ _deploy_to_stage(api_id, deployment_id, stage_name,
+ data.get("stageDescription", ""), data.get("variables", {}))
return _v1_response(deployment, 201)
+def _deploy_to_stage(api_id, deployment_id, stage_name, description="", variables=None):
+ """Point a stage at a deployment, creating the stage when it does not
+ exist — what CreateDeployment does for its stageName, and what an
+ AWS::ApiGateway::Deployment update does for a changed StageName."""
+ existing_stage = _stages_v1.get(api_id, {}).get(stage_name)
+ if existing_stage:
+ existing_stage["deploymentId"] = deployment_id
+ existing_stage["lastUpdatedDate"] = _now_unix()
+ return existing_stage
+ stage = {
+ "stageName": stage_name,
+ "deploymentId": deployment_id,
+ "description": description,
+ "createdDate": _now_unix(),
+ "lastUpdatedDate": _now_unix(),
+ "variables": variables or {},
+ "methodSettings": {},
+ "accessLogSettings": {},
+ "cacheClusterEnabled": False,
+ "cacheClusterSize": None,
+ "tracingEnabled": False,
+ "tags": {},
+ "documentationVersion": None,
+ }
+ _stages_v1.setdefault(api_id, {})[stage_name] = stage
+ return stage
+
+
def _get_deployments(api_id, query_params):
if api_id not in _rest_apis:
return _v1_error("NotFoundException", "Invalid API identifier specified", 404)
@@ -3075,6 +3084,10 @@ def _create_authorizer(api_id, data):
),
"providerARNs": data.get("providerARNs", []),
}
+ if "authType" in data:
+ # An informational field (OpenAPI import/export); reported when set,
+ # as GetAuthorizer does.
+ authorizer["authType"] = data["authType"]
_authorizers_v1.setdefault(api_id, {})[auth_id] = authorizer
return _v1_response(authorizer, 201)
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 8a125b2b..09f10e95 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -3399,36 +3399,77 @@ def _apigw_model_delete(physical_id, props):
# --- API Gateway Authorizer ---
+# (CFN property, authorizer field, value the create fills in when the template
+# omits the property — the defaults of the resource reference: a 300 s result
+# TTL and the Authorization header as identity source). Name is required on
+# AWS and defaults to the logical id here; RestApiId is the one property that
+# requires replacement.
+_APIGW_AUTHORIZER_PROPERTIES = (
+ ("Type", "type", "TOKEN"),
+ ("AuthorizerUri", "authorizerUri", ""),
+ ("AuthorizerCredentials", "authorizerCredentials", None),
+ ("IdentitySource", "identitySource", "method.request.header.Authorization"),
+ ("IdentityValidationExpression", "identityValidationExpression", ""),
+ ("AuthorizerResultTtlInSeconds", "authorizerResultTtlInSeconds", 300),
+ ("ProviderARNs", "providerARNs", []),
+ ("AuthType", "authType", None),
+)
+
+
def _apigw_authorizer_create(logical_id, props, stack_name):
- """Provision an AWS::ApiGateway::Authorizer.
-
- Maps CFN properties to the existing apigateway_v1 authorizer store:
- Name, Type (TOKEN / REQUEST / COGNITO_USER_POOLS), AuthorizerUri,
- AuthorizerCredentials, IdentitySource, IdentityValidationExpression,
- AuthorizerResultTtlInSeconds, ProviderARNs, RestApiId. ``AuthType`` is
- documented in the AWS CFN spec as informational only; the underlying
- apigateway_v1._create_authorizer record does not currently expose it,
- so the field is dropped here.
- """
+ """Provision an AWS::ApiGateway::Authorizer through the apigateway_v1
+ authorizer store: Name, Type (TOKEN / REQUEST / COGNITO_USER_POOLS),
+ AuthorizerUri, AuthorizerCredentials, IdentitySource,
+ IdentityValidationExpression, AuthorizerResultTtlInSeconds, ProviderARNs,
+ AuthType (informational, kept as GetAuthorizer reports it), RestApiId."""
api_id = props.get("RestApiId", "")
- data = {
- "name": props.get("Name", logical_id),
- "type": props.get("Type", "TOKEN"),
- "authorizerUri": props.get("AuthorizerUri", ""),
- "authorizerCredentials": props.get("AuthorizerCredentials"),
- "identitySource": props.get("IdentitySource", "method.request.header.Authorization"),
- "identityValidationExpression": props.get("IdentityValidationExpression", ""),
- "authorizerResultTtlInSeconds": props.get("AuthorizerResultTtlInSeconds", 300),
- "providerARNs": props.get("ProviderARNs", []),
- }
- status, headers, body = _apigw_v1._create_authorizer(api_id, data)
+ data = {"name": props.get("Name", logical_id)}
+ for prop, field, default in _APIGW_AUTHORIZER_PROPERTIES:
+ value = props.get(prop, default)
+ if prop == "AuthType" and value is None:
+ continue
+ data[field] = value
+ status, _headers, body = _apigw_v1._create_authorizer(api_id, data)
if status >= 400:
raise ValueError(f"AWS::ApiGateway::Authorizer create failed: {body!r}")
- authorizer = json.loads(body) if isinstance(body, (bytes, bytearray)) else json.loads(body)
- authorizer_id = authorizer.get("id", "")
+ authorizer_id = json.loads(body).get("id", "")
return authorizer_id, {"AuthorizerId": authorizer_id}
+def _apigw_authorizer_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update an authorizer in place through UpdateAuthorizer, keeping its id
+ (what Ref and AuthorizerId return): every property but RestApiId is No
+ interruption on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-authorizer.html).
+ A property the new template drops reverts to the value the create fills
+ in. A changed RestApiId, or an authorizer deleted behind the stack's back,
+ is a replacement: the new authorizer is created and the engine removes
+ the old one."""
+ api_id = new_props.get("RestApiId", "")
+ record = _apigw_v1._authorizers_v1.get(api_id, {}).get(physical_id)
+ if record is None or new_props.get("RestApiId") != old_props.get("RestApiId"):
+ return _apigw_authorizer_create(logical_id or physical_id, new_props, stack_name)
+ default_name = logical_id or physical_id
+ patch_ops = []
+ if new_props.get("Name", default_name) != old_props.get("Name", default_name):
+ patch_ops.append({"op": "replace", "path": "/name",
+ "value": new_props.get("Name", default_name)})
+ for prop, field, default in _APIGW_AUTHORIZER_PROPERTIES:
+ value = new_props.get(prop, default)
+ if value == old_props.get(prop, default):
+ continue
+ if prop == "AuthType" and value is None:
+ patch_ops.append({"op": "remove", "path": f"/{field}"})
+ else:
+ patch_ops.append({"op": "replace", "path": f"/{field}", "value": value})
+ if patch_ops:
+ status, _headers, body = _apigw_v1._update_authorizer(
+ api_id, physical_id, {"patchOperations": patch_ops})
+ if status >= 400:
+ raise ValueError(f"AWS::ApiGateway::Authorizer update failed: {body!r}")
+ return physical_id, {"AuthorizerId": physical_id}
+
+
def _apigw_authorizer_delete(physical_id, props):
api_id = props.get("RestApiId", "")
authorizers = _apigw_v1._authorizers_v1.get(api_id, {})
@@ -3437,19 +3478,68 @@ def _apigw_authorizer_delete(physical_id, props):
# --- API Gateway Deployment ---
+def _apigw_deployment_stage(props):
+ """The stage a deployment declares: StageName plus the StageDescription
+ object's Description and Variables (a plain string is taken as the
+ description, for templates written against earlier releases)."""
+ stage_description = props.get("StageDescription") or {}
+ if isinstance(stage_description, dict):
+ description = stage_description.get("Description", "")
+ variables = stage_description.get("Variables") or {}
+ else:
+ description, variables = str(stage_description), {}
+ return props.get("StageName"), description, variables
+
+
def _apigw_deployment_create(logical_id, props, stack_name):
api_id = props.get("RestApiId", "")
+ stage_name, stage_description, variables = _apigw_deployment_stage(props)
data = {
"description": props.get("Description", ""),
- "stageName": props.get("StageName"),
- "stageDescription": props.get("StageDescription", ""),
+ "stageName": stage_name,
+ "stageDescription": stage_description,
+ "variables": variables,
}
- status, headers, body = _apigw_v1._create_deployment(api_id, data)
- deployment = json.loads(body) if isinstance(body, bytes) else json.loads(body)
- deployment_id = deployment.get("id", "")
+ status, _headers, body = _apigw_v1._create_deployment(api_id, data)
+ if status >= 400:
+ raise ValueError(f"AWS::ApiGateway::Deployment create failed: {body!r}")
+ deployment_id = json.loads(body).get("id", "")
return deployment_id, {"DeploymentId": deployment_id}
+def _apigw_deployment_update(physical_id, old_props, new_props, stack_name):
+ """Update a deployment in place, keeping its id (what Ref and DeploymentId
+ return): Description, StageName and StageDescription are No interruption
+ on the resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-deployment.html),
+ so a changed description patches the deployment and a changed stage name
+ or stage description deploys the same deployment to that stage, as the
+ create does. RestApiId and DeploymentCanarySettings require replacement:
+ a new deployment is created and the engine removes the old one. A stage
+ the template stops naming is left standing, as on AWS.
+
+ Not modelled: DeploymentCanarySettings is accepted without effect (the
+ create does not store it; a change still replaces), and of the
+ StageDescription object only Description and Variables reach the stage."""
+ api_id = new_props.get("RestApiId", "")
+ record = _apigw_v1._deployments_v1.get(api_id, {}).get(physical_id)
+ if record is None or any(
+ new_props.get(key) != old_props.get(key)
+ for key in ("RestApiId", "DeploymentCanarySettings")
+ ):
+ return _apigw_deployment_create(physical_id, new_props, stack_name)
+ if new_props.get("Description", "") != old_props.get("Description", ""):
+ status, _headers, body = _apigw_v1._update_deployment(api_id, physical_id, {
+ "patchOperations": [{"op": "replace", "path": "/description",
+ "value": new_props.get("Description", "")}]})
+ if status >= 400:
+ raise ValueError(f"AWS::ApiGateway::Deployment update failed: {body!r}")
+ stage = _apigw_deployment_stage(new_props)
+ if stage[0] and stage != _apigw_deployment_stage(old_props):
+ _apigw_v1._deploy_to_stage(api_id, physical_id, *stage)
+ return physical_id, {"DeploymentId": physical_id}
+
+
def _apigw_deployment_delete(physical_id, props):
api_id = props.get("RestApiId", "")
_apigw_v1._delete_deployment(api_id, physical_id)
@@ -5244,15 +5334,57 @@ def _kms_key_delete(physical_id, props):
})
+_KMS_ALIAS_NAME = re.compile(r"^alias/[a-zA-Z0-9:/_-]{1,250}$")
+
+
+def _kms_alias_target(target_key):
+ rec = _kms._resolve_key(target_key)
+ return rec["KeyId"] if rec else target_key
+
+
+def _kms_alias_name(props, stack_name, logical_id):
+ return props.get("AliasName") or f"alias/{stack_name}-{logical_id}"
+
+
def _kms_alias_create(logical_id, props, stack_name):
- alias_name = props.get("AliasName", f"alias/{stack_name}-{logical_id}")
+ alias_name = _kms_alias_name(props, stack_name, logical_id)
+ if not _KMS_ALIAS_NAME.match(alias_name) or alias_name.startswith("alias/aws/"):
+ # The constraints the resource reference states: the alias/ prefix,
+ # alphanumerics plus :/_- up to 256 characters, and alias/aws/
+ # reserved for AWS managed keys.
+ raise ValueError(
+ f"AWS::KMS::Alias AliasName {alias_name!r} must begin with alias/, "
+ "contain only alphanumerics, :, /, _ and -, and must not begin "
+ "with the reserved alias/aws/ prefix")
target_key = props.get("TargetKeyId", "")
- rec = _kms._resolve_key(target_key)
- alias_arn = _kms._alias_arn(alias_name)
- _kms._aliases[alias_arn] = rec["KeyId"] if rec else target_key
+ if not target_key:
+ raise ValueError("AWS::KMS::Alias requires TargetKeyId")
+ _kms._aliases[_kms._alias_arn(alias_name)] = _kms_alias_target(target_key)
return alias_name, {}
+def _kms_alias_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update an alias in place: TargetKeyId is No interruption on the
+ resource reference
+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-alias.html),
+ so a changed target re-points the alias under its name (what Ref
+ returns), as UpdateAlias does. AliasName requires replacement: the new
+ alias is created before the old one is removed."""
+ current = physical_id if _kms._alias_arn(physical_id) in _kms._aliases else None
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ _kms_alias_name(new_props, stack_name, logical_id or physical_id), current,
+ _kms_alias_create, _kms_alias_delete,
+ )
+ if replaced is not None:
+ return replaced
+ target_key = new_props.get("TargetKeyId", "")
+ if not target_key:
+ raise ValueError("AWS::KMS::Alias requires TargetKeyId")
+ _kms._aliases[_kms._alias_arn(physical_id)] = _kms_alias_target(target_key)
+ return physical_id, {}
+
+
def _kms_alias_delete(physical_id, props):
_kms._aliases.pop(_kms._alias_arn(physical_id), None)
@@ -8221,10 +8353,17 @@ _RESOURCE_HANDLERS = {
"update": _apigw_model_update,
"delete": _apigw_model_delete,
},
- "AWS::ApiGateway::Authorizer": {"create": _apigw_authorizer_create, "delete": _apigw_authorizer_delete},
- # Deployment stays create-only: AWS treats a deployment as an immutable
- # snapshot — an update is a new deployment (CFN replaces the resource).
- "AWS::ApiGateway::Deployment": {"create": _apigw_deployment_create, "delete": _apigw_deployment_delete},
+ "AWS::ApiGateway::Authorizer": {
+ "create": _apigw_authorizer_create,
+ "update": _apigw_authorizer_update,
+ "update_with_logical_id": True,
+ "delete": _apigw_authorizer_delete,
+ },
+ "AWS::ApiGateway::Deployment": {
+ "create": _apigw_deployment_create,
+ "update": _apigw_deployment_update,
+ "delete": _apigw_deployment_delete,
+ },
"AWS::ApiGateway::Stage": {
"create": _apigw_stage_create,
"update": _apigw_stage_update,
@@ -8343,7 +8482,12 @@ _RESOURCE_HANDLERS = {
"update": _kms_key_update,
"delete": _kms_key_delete,
},
- "AWS::KMS::Alias": {"create": _kms_alias_create, "delete": _kms_alias_delete},
+ "AWS::KMS::Alias": {
+ "create": _kms_alias_create,
+ "update": _kms_alias_update,
+ "update_with_logical_id": True,
+ "delete": _kms_alias_delete,
+ },
"AWS::EC2::VPC": {"create": _ec2_vpc_create, "delete": _ec2_vpc_delete},
"AWS::EC2::VPCEndpoint": {
"create": _ec2_vpc_endpoint_create,
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 17d63cb9..12109bb5 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -14366,6 +14366,205 @@ def test_cfn_delete_change_set_missing_is_idempotent(cfn):
assert exc.value.response["Error"]["Code"] == "ValidationError"
+def test_cfn_apigateway_authorizer_update_in_place_and_replacement(cfn, apigw_v1):
+ """An authorizer property change updates the authorizer under the same id
+ (Ref and AuthorizerId keep their value), a property the template drops
+ reverts to the create default, and a RestApiId change replaces the
+ authorizer: it appears on the new API and is gone from the old one."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-authz-upd-{uid}"
+ uri = ("arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/"
+ "arn:aws:lambda:us-east-1:000000000000:function:noop/invocations")
+
+ def template(api, name, ttl, identity_source, auth_type, kind="TOKEN", providers=None):
+ properties = {"Name": name, "Type": kind, "RestApiId": {"Ref": api},
+ "AuthorizerUri": uri, "IdentitySource": identity_source}
+ if providers:
+ properties["ProviderARNs"] = providers
+ if ttl is not None:
+ properties["AuthorizerResultTtlInSeconds"] = ttl
+ if auth_type is not None:
+ properties["AuthType"] = auth_type
+ return json.dumps({
+ "Resources": {
+ "ApiA": {"Type": "AWS::ApiGateway::RestApi", "Properties": {"Name": f"cfn-authz-a-{uid}"}},
+ "ApiB": {"Type": "AWS::ApiGateway::RestApi", "Properties": {"Name": f"cfn-authz-b-{uid}"}},
+ "Auth": {"Type": "AWS::ApiGateway::Authorizer", "Properties": properties},
+ },
+ "Outputs": {"Id": {"Value": {"Ref": "Auth"}},
+ "AttId": {"Value": {"Fn::GetAtt": ["Auth", "AuthorizerId"]}},
+ "ApiA": {"Value": {"Ref": "ApiA"}}, "ApiB": {"Value": {"Ref": "ApiB"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(
+ "ApiA", "first", 60, "method.request.header.X-Token", "custom"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ api_a, api_b = _output(stack, "ApiA"), _output(stack, "ApiB")
+ auth_id = _output(stack, "Id")
+ assert _output(stack, "AttId") == auth_id
+ authorizer = apigw_v1.get_authorizer(restApiId=api_a, authorizerId=auth_id)
+ assert (authorizer["name"], authorizer["authorizerResultTtlInSeconds"],
+ authorizer["identitySource"], authorizer["authType"]) == (
+ "first", 60, "method.request.header.X-Token", "custom")
+
+ pool_arn = f"arn:aws:cognito-idp:us-east-1:000000000000:userpool/us-east-1_{uid}"
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(
+ "ApiA", "second", None, "method.request.header.Authorization", None,
+ kind="COGNITO_USER_POOLS", providers=[pool_arn]))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Id") == auth_id
+ authorizer = apigw_v1.get_authorizer(restApiId=api_a, authorizerId=auth_id)
+ assert (authorizer["name"], authorizer["authorizerResultTtlInSeconds"],
+ authorizer["identitySource"], authorizer["type"], authorizer["providerARNs"]) == (
+ "second", 300, "method.request.header.Authorization", "COGNITO_USER_POOLS", [pool_arn])
+ assert "authType" not in authorizer
+ assert len(apigw_v1.get_authorizers(restApiId=api_a)["items"]) == 1
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(
+ "ApiB", "second", None, "method.request.header.Authorization", None))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ new_id = _output(stack, "Id")
+ assert new_id != auth_id
+ assert apigw_v1.get_authorizers(restApiId=api_a)["items"] == []
+ assert [a["id"] for a in apigw_v1.get_authorizers(restApiId=api_b)["items"]] == [new_id]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_apigateway_deployment_update_in_place_and_replacement(cfn, apigw_v1):
+ """A deployment's Description, StageName and StageDescription update in
+ place under the same deployment id: the description patches the
+ deployment, a new stage name deploys the same deployment to that stage
+ and leaves the previous stage standing. A RestApiId change replaces the
+ deployment on the other API."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-deploy-upd-{uid}"
+
+ def template(api, description, stage_name, stage_description, canary=None):
+ properties = {"RestApiId": {"Ref": api}, "Description": description}
+ if canary is not None:
+ properties["DeploymentCanarySettings"] = {"PercentTraffic": canary}
+ if stage_name:
+ properties["StageName"] = stage_name
+ properties["StageDescription"] = {"Description": stage_description,
+ "Variables": {"stage": stage_name}}
+ return json.dumps({
+ "Resources": {
+ "ApiA": {"Type": "AWS::ApiGateway::RestApi", "Properties": {"Name": f"cfn-deploy-a-{uid}"}},
+ "ApiB": {"Type": "AWS::ApiGateway::RestApi", "Properties": {"Name": f"cfn-deploy-b-{uid}"}},
+ "Dep": {"Type": "AWS::ApiGateway::Deployment", "Properties": properties},
+ },
+ "Outputs": {"Id": {"Value": {"Ref": "Dep"}},
+ "AttId": {"Value": {"Fn::GetAtt": ["Dep", "DeploymentId"]}},
+ "ApiA": {"Value": {"Ref": "ApiA"}}, "ApiB": {"Value": {"Ref": "ApiB"}}},
+ })
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("ApiA", "one", "alpha", "stage one"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ api_a, api_b = _output(stack, "ApiA"), _output(stack, "ApiB")
+ dep_id = _output(stack, "Id")
+ assert _output(stack, "AttId") == dep_id
+ assert apigw_v1.get_deployment(restApiId=api_a, deploymentId=dep_id)["description"] == "one"
+ stage = apigw_v1.get_stage(restApiId=api_a, stageName="alpha")
+ assert (stage["deploymentId"], stage["description"], stage["variables"]) == (
+ dep_id, "stage one", {"stage": "alpha"})
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("ApiA", "two", "beta", "stage two"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Id") == dep_id
+ assert apigw_v1.get_deployment(restApiId=api_a, deploymentId=dep_id)["description"] == "two"
+ assert len(apigw_v1.get_deployments(restApiId=api_a)["items"]) == 1
+ beta = apigw_v1.get_stage(restApiId=api_a, stageName="beta")
+ assert (beta["deploymentId"], beta["description"], beta["variables"]) == (
+ dep_id, "stage two", {"stage": "beta"})
+ assert apigw_v1.get_stage(restApiId=api_a, stageName="alpha")["deploymentId"] == dep_id
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("ApiB", "two", "beta", "stage two"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ new_id = _output(stack, "Id")
+ assert new_id != dep_id
+ assert apigw_v1.get_deployments(restApiId=api_a)["items"] == []
+ assert [d["id"] for d in apigw_v1.get_deployments(restApiId=api_b)["items"]] == [new_id]
+ assert apigw_v1.get_stage(restApiId=api_b, stageName="beta")["deploymentId"] == new_id
+
+ # DeploymentCanarySettings requires replacement on the reference: a
+ # new deployment id, the previous one removed by the engine.
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(
+ "ApiB", "two", "beta", "stage two", canary=10.0))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ canary_id = _output(stack, "Id")
+ assert canary_id != new_id
+ assert [d["id"] for d in apigw_v1.get_deployments(restApiId=api_b)["items"]] == [canary_id]
+ assert apigw_v1.get_stage(restApiId=api_b, stageName="beta")["deploymentId"] == canary_id
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_kms_alias_target_change_in_place_and_rename_replaces(cfn, kms_client):
+ """A TargetKeyId change re-points the alias under its name (Ref keeps its
+ value), an AliasName change replaces the alias — the new name exists, the
+ old one is gone — and an alias name without the alias/ prefix fails the
+ stack as the resource reference requires."""
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-kms-alias-{uid}"
+
+ def template(alias_name, key):
+ return json.dumps({
+ "Resources": {
+ "KeyA": {"Type": "AWS::KMS::Key", "Properties": {"Description": f"a-{uid}"}},
+ "KeyB": {"Type": "AWS::KMS::Key", "Properties": {"Description": f"b-{uid}"}},
+ "Alias": {"Type": "AWS::KMS::Alias", "Properties": {
+ "AliasName": alias_name, "TargetKeyId": {"Ref": key}}},
+ },
+ "Outputs": {"Alias": {"Value": {"Ref": "Alias"}},
+ "KeyA": {"Value": {"Ref": "KeyA"}}, "KeyB": {"Value": {"Ref": "KeyB"}}},
+ })
+
+ def alias_targets():
+ return {a["AliasName"]: a.get("TargetKeyId")
+ for a in kms_client.list_aliases()["Aliases"]}
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(f"alias/cfn-a-{uid}", "KeyA"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ key_a, key_b = _output(stack, "KeyA"), _output(stack, "KeyB")
+ assert _output(stack, "Alias") == f"alias/cfn-a-{uid}"
+ assert alias_targets()[f"alias/cfn-a-{uid}"] == key_a
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(f"alias/cfn-a-{uid}", "KeyB"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Alias") == f"alias/cfn-a-{uid}"
+ assert alias_targets()[f"alias/cfn-a-{uid}"] == key_b
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(f"alias/cfn-b-{uid}", "KeyB"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Alias") == f"alias/cfn-b-{uid}"
+ targets = alias_targets()
+ assert targets[f"alias/cfn-b-{uid}"] == key_b
+ assert f"alias/cfn-a-{uid}" not in targets
+
+ for bad_name in (f"cfn-c-{uid}", f"alias/aws/cfn-c-{uid}", f"alias/cfn c {uid}"):
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(bad_name, "KeyB"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert "must begin with alias/" in _stack_event_reasons(cfn, stack_name)
+ assert alias_targets()[f"alias/cfn-b-{uid}"] == key_b
+ assert bad_name not in alias_targets()
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ assert f"alias/cfn-b-{uid}" not in alias_targets()
def test_cfn_update_rollback_reports_the_previous_template_parameters_and_tags(cfn, sqs):
"""After UPDATE_ROLLBACK_COMPLETE the stack describes what it ran before
the failed update: GetTemplate returns the previous template body,