Skip to content

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

prerelease (#1878)

Nahuel Nucera45d80ce169fb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 085de01e..0aab1f49 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,36 +7,19 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
-### Fixed
-
-- **RDS — instances become `available` under `MINISTACK_RDS_PUBLIC_ENDPOINT=1` in a container** — with the setting on, database containers were left off MiniStack's network and readiness dialled `127.0.0.1:<host port>`, which inside MiniStack's own container is not the database, so a new instance or cluster stayed `creating` forever. A containerised MiniStack now keeps its database containers on its network for readiness and internal wiring, and still reports `{MINISTACK_HOST, host_port}` for writer and reader endpoints; DSQL, which shares the network lookup, gets the same reachable backend. A MiniStack running on the host is unchanged. Fixes #1884.
-- **IoT — `RegisterCACertificate` checks the verification certificate** — in `DEFAULT` mode a CA now registers only with a `verificationCertificate` that the CA signed and whose CN is the account's registration code, `SNI_ONLY` refuses one, and each failure returns the error AWS returns, so an `AWS::IoT::CACertificate` in `DEFAULT` mode without `VerificationCertificatePem` fails as well.
-- **CloudFormation — `OnFailure` and `OnStackFailure` are honoured** — CreateStack `OnFailure=DO_NOTHING` leaves a failed create in `CREATE_FAILED`, as `DisableRollback=true` does, and `DELETE` rolls the create back and then deletes the stack, which ends `DELETE_COMPLETE` (or `DELETE_FAILED` when a resource does not delete). `OnFailure` together with `DisableRollback` is a `ValidationError`. CreateChangeSet `OnStackFailure` makes the same choice when the change set executes; `DELETE` is refused unless `ChangeSetType` is `CREATE`, DescribeChangeSet reports the value, and ExecuteChangeSet refuses `DisableRollback` for such a change set. ExecuteChangeSet ignored `DisableRollback=true` and rolled back anyway; it now leaves the failed operation in `CREATE_FAILED` or `UPDATE_FAILED`.
-- **CloudFormation — `DeleteStack` takes `DeletionMode=FORCE_DELETE_STACK`** — on a `DELETE_FAILED` stack, the resources that failed to delete and the resources they depend on are retained with a `DELETE_SKIPPED` event, and the stack reaches `DELETE_COMPLETE`. On any other status the call is a `ValidationError`, and DescribeStacks reports the stack's `DeletionMode`.
-- **CloudFormation — `GetTemplate` reads `TemplateStage` and `ChangeSetName`** — `Processed` returns the template after its SAM, `AWS::LanguageExtensions` and `AWS::Include` transforms as JSON; a template without a transform is the same at both stages. `Original` stays the default. The response lists `StagesAvailable` (`Original`, `Processed`), and `ChangeSetName` returns a change set's template, answering `ChangeSetNotFound` (404) for an unknown one.
-- **CloudFormation — stack events carry `ClientRequestToken`** — every event recorded by CreateStack, UpdateStack, DeleteStack, ExecuteChangeSet and ContinueUpdateRollback carries the token of that call, and the rollback events of a CancelUpdateStack carry the cancel's token. A token outside `[a-zA-Z0-9][-a-zA-Z0-9]*` or longer than 128 characters is a `ValidationError`.
-
-- **Bedrock AgentCore — `InvokeAgentRuntime` enforces IAM policies** — with `AUTH=true`, runtime invocations now resolve to `bedrock-agentcore:InvokeAgentRuntime` and authorize against the ARN in the request path, so a policy can allow one runtime and deny another. Previously, the action was not extracted and the request bypassed identity-policy evaluation.
-- **IAM — a negated condition operator is true when its key is absent** — the evaluator treated an absent key as a failed condition for every operator, so a `Deny` guarded by `StringNotEquals`, `StringNotLike`, `ArnNotLike`, `NotIpAddress` or another negated operator never applied to a request without that key. AWS evaluates such a condition as true and denies. The single-valued negated operators now do the same, while `ForAnyValue` and the affirmative operators still fail on an absent key. Contributed by @iot-rocket.
-- **KMS — `GenerateDataKey` returns `KeyMaterialId`** — requests without `Recipient` now include the identifier of the wrapping key material. The identifier remains stable across requests and persistence reloads, and changes when the wrapping material changes. Fixes #1853.
-- **Secrets Manager — `BatchGetSecretValue` returns only the secrets the caller may read** — under `AUTH=true` a grant on `secretsmanager:BatchGetSecretValue` alone returned every secret in the request, and `Filters` were ignored, so a filtered call returned the whole store. Each secret now needs `secretsmanager:GetSecretValue` and lands in `Errors` as `AccessDeniedException` without it, a call by `Filters` also needs `secretsmanager:ListSecrets`, and the filters select the secrets as in `ListSecrets`. Contributed by @iot-rocket.
-- **CloudFormation — change set members follow the action** — `Add` and `Remove` changes carried `Replacement: False`, a `Remove` had no physical id, `PolicyAction` was never sent and a `Metadata` or policy detail had no `RequiresRecreation`. `Remove` and `Modify` now name the physical resource, a `Remove` answers `PolicyAction: Delete` and a replacing `Modify` `ReplaceAndDelete` unless the resource retains or snapshots, and attribute details answer `Never`. Contributed by @iot-rocket.
-- **CloudFormation — `AWS::SQS::Queue` applies every queue property** — `RedrivePolicy`, `RedriveAllowPolicy`, `KmsMasterKeyId`, `KmsDataKeyReusePeriodSeconds`, `SqsManagedSseEnabled`, `DeduplicationScope` and `FifoThroughputLimit` were dropped on create and update, so a dead-letter queue declared in a template never received messages, and a value SQS refuses now fails the resource instead of being stored. Contributed by @iot-rocket.
-- **Lambda — Docker executor honors timeouts above 300 seconds** — pass the configured `Timeout` to AWS RIE through `AWS_LAMBDA_FUNCTION_TIMEOUT`, preventing its default 300-second limit from ending longer invocations early. Timeout updates recycle warm containers so the RIE deadline follows the new configuration (#1844).
-- **KMS — `GenerateDataKey` returns `KeyMaterialId`** — requests without `Recipient` now include the identifier of the wrapping key material. The identifier remains stable across requests and persistence reloads, and changes when the wrapping material changes. Fixes #1853.
-- **CloudFormation — a nested stack's update deletes the resources its template drops** — a resource removed from the child template, or created by a failed child update that was rolled back, stayed in its service and in the nested stack's resource list. Contributed by @iot-rocket.
### Added
-- **CloudFormation — `RollbackStack`** — a stack left `CREATE_FAILED` or `UPDATE_FAILED` by `DisableRollback` is rolled back to its last stable state, as `cdk rollback` expects. A failed create deletes what it made and ends `ROLLBACK_COMPLETE`; a failed update reverts in-place changes, deletes what it added and ends `UPDATE_ROLLBACK_COMPLETE` with the previous template, parameters, tags and outputs. `RetainExceptOnCreate` also deletes new resources marked `Retain`. Any other status answers `ValidationError`.
-- **CloudFormation — stack drift detection** — `DetectStackDrift` (with `LogicalResourceIds`), `DescribeStackDriftDetectionStatus`, `DetectStackResourceDrift` and `DescribeStackResourceDrifts` (status filters, `MaxResults`, `NextToken`) compare the properties a template sets, plus stack-level tags, with the owning service's current record. A deleted record is `DELETED`; a changed one is `MODIFIED` with `PropertyDifferences` (`ADD`, `REMOVE`, `NOT_EQUAL`) and expected and actual properties. Property-level drift covers SQS queues, SSM parameters, SNS topics, Lambda functions, IAM roles, DynamoDB tables, S3 buckets (name and versioning), log groups and Secrets Manager secrets; Kinesis streams, ECR repositories, state machines, EventBridge rules and SNS subscriptions get an existence check; other types stay `NOT_CHECKED`. `DescribeStacks`, `ListStacks`, `DescribeStackResource(s)` and `ListStackResources` report `DriftInformation`, and results persist with the stack. Detection runs on `CREATE_COMPLETE`, `UPDATE_COMPLETE`, `UPDATE_ROLLBACK_COMPLETE` and `UPDATE_ROLLBACK_FAILED` stacks only.
-- **CloudWatch Logs — resource policy** — `PutResourcePolicy`, `DescribeResourcePolicies` and `DeleteResourcePolicy`, the account/log-group-level policy Crossplane's `provider-aws-cloudwatchlogs` manages for cross-service log delivery — distinct from the per-destination `PutDestinationPolicy` and the delivery-scoped `PutDeliveryDestinationPolicy`. `PutResourcePolicy` supports `expectedRevisionId` for optimistic concurrency (`OperationAbortedException` on mismatch). Contributed by @fabio-andre-rodrigues.
+- **CloudWatch Logs — resource policies** — `PutResourcePolicy`, `DescribeResourcePolicies` and `DeleteResourcePolicy`, account-scoped (up to 10) or scoped to one log group through `resourceArn`, with `expectedRevisionId` checks. `AWS::Logs::ResourcePolicy` stacks now create real policies. Contributed by @fabio-andre-rodrigues.
+- **CloudFormation — `RollbackStack`** — rolls a stack left `CREATE_FAILED` or `UPDATE_FAILED` with rollback disabled back to its last stable state: a failed create ends `ROLLBACK_COMPLETE`, a failed update reverts its changes, deletes what it added and ends `UPDATE_ROLLBACK_COMPLETE`. `RetainExceptOnCreate` is honoured. Contributed by @fabio-andre-rodrigues.
+- **CloudFormation — stack drift detection** — `DetectStackDrift`, `DescribeStackDriftDetectionStatus`, `DetectStackResourceDrift` and `DescribeStackResourceDrifts` compare the properties a template sets, plus stack-level tags, with the service's current record (`IN_SYNC`, `MODIFIED` with `PropertyDifferences`, `DELETED`); stacks and resources report `DriftInformation`. Contributed by @fabio-andre-rodrigues.
- **Bedrock AgentCore — resource-based policies** — `PutResourcePolicy`, `GetResourcePolicy` and `DeleteResourcePolicy` persist policies for runtimes and endpoints. With `AUTH=true`, runtime invocation evaluates caller principals, explicit denies and the runtime-plus-endpoint policy requirement for cross-account calls. This emulates the documented AgentCore policy contract locally; it does not validate behavior against AWS.
-- **KMS — grants** — `CreateGrant`, `RevokeGrant` and `RetireGrant`, and `ListGrants` returns the grants they create instead of always an empty list. `CreateGrant` returns a `GrantId` and a `GrantToken`, follows the key state (`DisabledException` for a disabled key, `KMSInvalidStateException` pending deletion, replica deletion or import), rejects operations the key cannot perform (`Sign` / `Verify` / `GenerateMac` / `VerifyMac` on a symmetric encryption key, data key operations on an asymmetric key, anything but `GenerateMac` / `VerifyMac` / `DescribeKey` / `CreateGrant` / `RetireGrant` on an HMAC key) with `ValidationException`, and with a `Name` a retry with identical parameters returns the original `GrantId` with a new token. `ListGrants` filters by `GrantId` and `GranteePrincipal` and pages with `Limit` (1 to 100, default 50) and `Marker`. `RetireGrant` takes a `GrantToken`, or a `KeyId` and `GrantId`. All three honour `DryRun`, and grants persist with the key. Grants are recorded but not evaluated when authorizing other calls, as with key policies. Contributed by @DaviReisVieira.
-- **RDS — IAM database authentication for MySQL and Aurora MySQL** — users created `IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS'` log in with an SDK-generated token over `mysql_clear_password`, as on AWS. The instance or cluster must have `IAMDatabaseAuthenticationEnabled`; with `AUTH=true` the token and the `rds-db:connect` policy are verified too. `ModifyDBInstance` accepts `EnableIAMDatabaseAuthentication`. Contributed by @Areson.
- **KMS — grants** — `CreateGrant`, `RevokeGrant` and `RetireGrant`; `ListGrants` now returns the grants they create, filtered by `GrantId` / `GranteePrincipal` and paged with `Limit` / `Marker`. `CreateGrant` follows the key state, rejects operations the key type cannot perform, and is idempotent for a named grant. Grants persist with the key and are not evaluated for authorization. Contributed by @DaviReisVieira.
+- **RDS — IAM database authentication for MySQL and Aurora MySQL** — users created `IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS'` log in with an SDK-generated token over `mysql_clear_password`, as on AWS. The instance or cluster must have `IAMDatabaseAuthenticationEnabled`; with `AUTH=true` the token and the `rds-db:connect` policy are verified too. `ModifyDBInstance` accepts `EnableIAMDatabaseAuthentication`. Contributed by @Areson.
### Fixed
+- **Bedrock AgentCore — runtime and endpoint ARNs match AWS** — `CreateAgentRuntime` returned `…:agent/{uuid}:{version}` and endpoints `…:agentEndpoint/{uuid}`, so identity and resource policies written for AWS never matched and every update changed the runtime ARN. Runtimes are now `…:runtime/{agentRuntimeId}`, stable across updates, endpoints are `…:runtime/{agentRuntimeId}/runtime-endpoint/{name}`, and the `DEFAULT` endpoint is created with the runtime and follows its latest version. Saved state moves to the new ARNs on restore.
+- **Bedrock AgentCore — `InvokeAgentRuntime` enforces IAM policies** — with `AUTH=true`, a runtime invocation resolves to `bedrock-agentcore:InvokeAgentRuntime` and is authorized against both the runtime ARN and its runtime-endpoint ARN (the `qualifier`, or `DEFAULT`), as AWS requires, so a policy can allow one runtime and deny another. Before, the action was not extracted and the invocation skipped policy evaluation. Contributed by @pingedbrain.
- **IAM — a negated condition operator is true when its key is absent** — the evaluator treated an absent key as a failed condition for every operator, so a `Deny` guarded by `StringNotEquals`, `StringNotLike`, `ArnNotLike`, `NotIpAddress` or another negated operator never applied to a request without that key. AWS evaluates such a condition as true and denies. The single-valued negated operators now do the same, while `ForAnyValue` and the affirmative operators still fail on an absent key. Contributed by @iot-rocket.
- **Secrets Manager — `BatchGetSecretValue` returns only the secrets the caller may read** — under `AUTH=true` a grant on `secretsmanager:BatchGetSecretValue` alone returned every secret in the request, and `Filters` were ignored, so a filtered call returned the whole store. Each secret now needs `secretsmanager:GetSecretValue` and lands in `Errors` as `AccessDeniedException` without it, a call by `Filters` also needs `secretsmanager:ListSecrets`, and the filters select the secrets as in `ListSecrets`. Contributed by @iot-rocket.
- **CloudFormation — change set members follow the action** — `Add` and `Remove` changes carried `Replacement: False`, a `Remove` had no physical id, `PolicyAction` was never sent and a `Metadata` or policy detail had no `RequiresRecreation`. `Remove` and `Modify` now name the physical resource, a `Remove` answers `PolicyAction: Delete` and a replacing `Modify` `ReplaceAndDelete` unless the resource retains or snapshots, and attribute details answer `Never`. `PolicyAction` also reports `Retain`, `Snapshot` and their `ReplaceAnd` forms from the resource's policy. Contributed by @iot-rocket.
@@ -48,6 +31,12 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **Lambda — a Docker invocation that reaches its timeout fails** — the emulator's plain-text `Task timed out` reply was returned as a successful payload, so Step Functions recorded `TaskSucceeded` and skipped `Catch`. Contributed by @drakeo338.
- **RDS — a persisted instance stays reachable after a restart** — when its saved host port was taken, the instance moved to a new port but `Endpoint.Port` kept the old one.
- **RDS — pending boolean modifications read as `true`** — `PendingModifiedValues` wrote Python `True`/`False`, which the SDKs parse as `false`.
+- **CloudFormation — `OnFailure` and `OnStackFailure` are honoured** — CreateStack `OnFailure` and CreateChangeSet `OnStackFailure` take `DO_NOTHING`, `ROLLBACK` or `DELETE` (roll back, then delete the stack). `OnFailure` with `DisableRollback`, or `OnStackFailure=DELETE` on a non-`CREATE` change set, is a `ValidationError`. ExecuteChangeSet now honours `DisableRollback=true`. Contributed by @fabio-andre-rodrigues.
+- **CloudFormation — `DeleteStack` `DeletionMode=FORCE_DELETE_STACK`** — on a `DELETE_FAILED` stack, resources that fail to delete and their dependencies are retained as `DELETE_SKIPPED` and the stack reaches `DELETE_COMPLETE`; on any other status it is a `ValidationError`. Contributed by @fabio-andre-rodrigues.
+- **CloudFormation — `GetTemplate` `TemplateStage` and `ChangeSetName`** — `Processed`, now the default, returns the template after its transforms; `Original` returns it as sent. `StagesAvailable` is reported, and `ChangeSetName` returns a change set's template (`ChangeSetNotFound` when unknown). Contributed by @fabio-andre-rodrigues.
+- **CloudFormation — stack events carry `ClientRequestToken`** — every event of CreateStack, UpdateStack, DeleteStack, ExecuteChangeSet, ContinueUpdateRollback, CancelUpdateStack and RollbackStack carries that call's token. Contributed by @fabio-andre-rodrigues.
+- **RDS — instances become `available` under `MINISTACK_RDS_PUBLIC_ENDPOINT=1` in a container** — database containers were left off MiniStack's network, so readiness never connected and the instance stayed `creating`. They now join the network for readiness and internal wiring, and `DescribeDBInstances` / `DescribeDBClusters` still report `{MINISTACK_HOST, host_port}`. Contributed by @skialpine.
+- **IoT — `RegisterCACertificate` checks the verification certificate** — `DEFAULT` mode requires a `verificationCertificate` signed by the CA with the registration code as its CN, and `SNI_ONLY` refuses one, each with its own error; `AWS::IoT::CACertificate` fails the same way. Contributed by @iot-rocket.
## [1.5.18] — 2026-09-28
diff --git a/README.md b/README.md
index 38a02694..1c093b63 100644
--- a/README.md
+++ b/README.md
@@ -470,7 +470,10 @@ subnet = ec2.create_subnet(
| **Conditions** | Fn::Equals, Fn::And, Fn::Or, Fn::Not — conditional resource creation |
| **Rules** | The `Rules` section runs after the parameters resolve and before any resource is touched (CreateStack, UpdateStack, CreateChangeSet): `RuleCondition`, `Assertions` with `AssertDescription`, Fn::And/Or/Not/Equals/If/Contains/EachMemberEquals/EachMemberIn and Ref; Fn::RefAll, Fn::ValueOf and Fn::ValueOfAll read the EC2 store for VPC, subnet and security-group ids |
| **Transforms** | `AWS::Serverless-2016-10-31` (SAM, in the `full` image), `AWS::LanguageExtensions` (`Fn::ForEach` over a literal list, a `CommaDelimitedList` parameter, `Fn::FindInMap` or `Fn::Split`, nested and inside `Properties`; `${Id}` / `&{Id}` in the fragment keys, `${Id}` in `Fn::Sub` and a `Ref` to the identifier; `Fn::Length`, `Fn::ToJsonString`) and the embedded `AWS::Include` transform (`Fn::Transform` with an `s3://` `Location`, JSON or YAML snippets) |
-| **Rollback** | Configurable via `DisableRollback` — on failure, previously created resources are cleaned up in reverse dependency order; a stack left `CREATE_FAILED` or `UPDATE_FAILED` by `DisableRollback` is rolled back later with RollbackStack (`ROLLBACK_COMPLETE` or `UPDATE_ROLLBACK_COMPLETE`, `RetainExceptOnCreate` honoured) |
+| **Rollback** | Configurable via `DisableRollback`, CreateStack `OnFailure` (`ROLLBACK`, `DO_NOTHING`, `DELETE`) and CreateChangeSet `OnStackFailure` (`DELETE` for CREATE change sets only); ExecuteChangeSet honours `DisableRollback`. On failure, previously created resources are cleaned up in reverse dependency order; `DELETE` then deletes the stack; a stack left `CREATE_FAILED` or `UPDATE_FAILED` with rollback disabled is rolled back later with RollbackStack (`ROLLBACK_COMPLETE` or `UPDATE_ROLLBACK_COMPLETE`, `RetainExceptOnCreate` honoured) |
+| **Stack Deletion** | `RetainResources` and `DeletionMode=FORCE_DELETE_STACK` on a `DELETE_FAILED` stack: the resources that failed to delete, and what they depend on, are retained (`DELETE_SKIPPED`) and the stack reaches `DELETE_COMPLETE` |
+| **Templates** | GetTemplate `TemplateStage` (`Processed`, the default, the template after SAM, `AWS::LanguageExtensions` and `AWS::Include`), `StagesAvailable`, and a change set's template through `ChangeSetName` |
+| **Client Request Tokens** | The `ClientRequestToken` of CreateStack, UpdateStack, DeleteStack, ExecuteChangeSet, ContinueUpdateRollback, CancelUpdateStack and RollbackStack is reported on every stack event the operation records |
| **Drift Detection** | DetectStackDrift, DescribeStackDriftDetectionStatus, DetectStackResourceDrift, DescribeStackResourceDrifts (status filters, `MaxResults`/`NextToken`), and `DriftInformation` on DescribeStacks, ListStacks and the stack resource calls. Detection completes synchronously and compares the properties the template sets with the service's current record. Property-level drift (`PropertyDifferences`, expected and actual properties) for AWS::SQS::Queue, AWS::SSM::Parameter, AWS::SNS::Topic, AWS::Lambda::Function, AWS::IAM::Role, AWS::DynamoDB::Table, AWS::S3::Bucket (name, versioning), AWS::Logs::LogGroup and AWS::SecretsManager::Secret; stack-level tags count toward `Tags`. Existence only (`IN_SYNC` or `DELETED`) for AWS::Kinesis::Stream, AWS::ECR::Repository, AWS::StepFunctions::StateMachine, AWS::Events::Rule and AWS::SNS::Subscription. Every other type is `NOT_CHECKED` |
| **Async Status** | Stacks deploy asynchronously (`CREATE_IN_PROGRESS` → `CREATE_COMPLETE`) — poll with DescribeStacks |
| **Quotas** | The template and stack quotas of the CloudFormation quotas page are enforced before a stack exists: 51,200 bytes of `TemplateBody`, 1,000,000 bytes behind `TemplateURL`, 500 resources, 200 parameters / outputs / mappings, 200 attributes per mapping, 255-character names, a 1,024-byte description, 4,096-byte parameter values, and a stack name of up to 128 alphanumeric characters and hyphens starting with a letter |
diff --git a/ministack/app.py b/ministack/app.py
index 7b3d7696..42f45b38 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -2406,6 +2406,7 @@ async def _dispatch_service_request(
if AUTH:
from ministack.core.iam_actions import (
access_denied_response,
+ agentcore_endpoint_arn,
dynamodb_resource_arns,
dynamodb_service_context,
eventbridge_resource_arns,
@@ -2454,6 +2455,10 @@ async def _dispatch_service_request(
break
# PutEvents carries one entry per event, and entries may name
# different buses: AWS authorizes each against its own bus.
+ if service == "bedrock-agentcore" and method == "POST" and not denied:
+ endpoint_arn = agentcore_endpoint_arn(path, routing_params)
+ if endpoint_arn:
+ denied = enforce(access_key, iam_action, service, region, resource_arn=endpoint_arn)
if service == "events" and not denied:
for extra_arn in eventbridge_resource_arns(
body, region, get_account_id())[1:]:
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index ec025456..45b75613 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -456,11 +456,7 @@ _BOTOCORE_SERVICE_MAP: dict[str, list[str]] = {
"bedrock-runtime": ["bedrock-runtime"],
"bedrock-agent": ["bedrock-agent"],
"bedrock-agent-runtime": ["bedrock-agent-runtime"],
- # Both the control and data-plane clients sign with the same
- # ``bedrock-agentcore`` name. The control model supplies the REST routes
- # for resource-policy CRUD; InvokeAgentRuntime remains explicit below so
- # older Botocore installations still authorize it.
- "bedrock-agentcore": ["bedrock-agentcore-control"],
+ "bedrock-agentcore": [], # InvokeAgentRuntime is mapped in extract_iam_action
"cloudfront": ["cloudfront"],
"cloudfront-keyvaluestore": ["cloudfront-keyvaluestore"],
"dsql": ["dsql"],
@@ -666,6 +662,14 @@ def _agentcore_runtime_arn(path: str) -> str | None:
return match.group(1) if match else None
+def agentcore_endpoint_arn(path: str, query_params: dict) -> str | None:
+ """The runtime-endpoint ARN InvokeAgentRuntime also authorizes: the qualifier, else DEFAULT."""
+ runtime_arn = _agentcore_runtime_arn(path)
+ if not runtime_arn:
+ return None
+ return f"{runtime_arn}/runtime-endpoint/{_query_param(query_params, 'qualifier') or 'DEFAULT'}"
+
+
def extract_iam_action(service: str, method: str, path: str,
headers: dict, body: bytes,
query_params: dict) -> str | None:
diff --git a/ministack/services/bedrock_agentcore.py b/ministack/services/bedrock_agentcore.py
index 50172fcf..eb7a457c 100644
--- a/ministack/services/bedrock_agentcore.py
+++ b/ministack/services/bedrock_agentcore.py
@@ -87,6 +87,27 @@ def _restore_state(data):
_runtimes.update(data.get("runtimes", {}))
_endpoints.update(data.get("endpoints", {}))
_resource_policies.update(data.get("resourcePolicies", {}))
+ _migrate_legacy_arns()
+
+
+def _migrate_legacy_arns():
+ """State saved before runtimes had AWS-shaped ARNs (``agent/{uuid}:{version}``)."""
+ for key, runtime in list(_runtimes._data.items()):
+ old = runtime.get("agentRuntimeArn", "")
+ if ":agent/" not in old:
+ continue
+ account_id, region = key[0], key[1]
+ new = f"arn:aws:bedrock-agentcore:{region}:{account_id}:runtime/{runtime['agentRuntimeId']}"
+ runtime["agentRuntimeArn"] = new
+ runtime.pop("_uuid", None)
+ endpoints = _endpoints.get_scoped(account_id, region, runtime["agentRuntimeId"]) or {}
+ for name, endpoint in endpoints.items():
+ endpoint["agentRuntimeArn"] = new
+ endpoint["agentRuntimeEndpointArn"] = _endpoint_arn(new, name)
+ if "DEFAULT" not in endpoints:
+ with request_scope(account_id, region):
+ endpoints["DEFAULT"] = _endpoint_record(runtime, "DEFAULT", runtime["agentRuntimeVersion"])
+ _endpoints.set_scoped(account_id, region, runtime["agentRuntimeId"], endpoints)
@@ -115,14 +136,28 @@ def _resource_id(name: str) -> str:
return f"{name}-{_rand_suffix()}"
-def _runtime_arn(runtime_uuid: str, version: str) -> str:
- return (f"arn:aws:bedrock-agentcore:{get_region()}:{get_account_id()}:"
- f"agent/{runtime_uuid}:{version}")
+def _runtime_arn(runtime_id: str) -> str:
+ return f"arn:aws:bedrock-agentcore:{get_region()}:{get_account_id()}:runtime/{runtime_id}"
-def _endpoint_arn(endpoint_uuid: str) -> str:
- return (f"arn:aws:bedrock-agentcore:{get_region()}:{get_account_id()}:"
- f"agentEndpoint/{endpoint_uuid}")
+def _endpoint_arn(runtime_arn: str, name: str) -> str:
+ return f"{runtime_arn}/runtime-endpoint/{name}"
+
+
+def _endpoint_record(runtime, name, version, description=""):
+ now = now_iso()
+ return {
+ "name": name,
+ "id": _resource_id(name),
+ "agentRuntimeEndpointArn": _endpoint_arn(runtime["agentRuntimeArn"], name),
+ "agentRuntimeArn": runtime["agentRuntimeArn"],
+ "targetVersion": version,
+ "liveVersion": version,
+ "status": "READY",
+ "description": description,
+ "createdAt": now,
+ "lastUpdatedAt": now,
+ }
def _arn_owner(resource_arn: str) -> tuple[str, str] | None:
@@ -271,11 +306,10 @@ def _create_agent_runtime(body):
if any(r.get("agentRuntimeName") == name for r in _runtimes.values()):
return _conflict(f"Agent runtime with name {name} already exists")
- runtime_uuid = new_uuid()
runtime_id = _resource_id(name)
version = "1"
now = now_iso()
- arn = _runtime_arn(runtime_uuid, version)
+ arn = _runtime_arn(runtime_id)
workload = {"workloadIdentityArn": _workload_identity_arn(name)}
record = {
"agentRuntimeArn": arn,
@@ -289,7 +323,6 @@ def _create_agent_runtime(body):
"status": "READY",
"agentRuntimeArtifact": data["agentRuntimeArtifact"],
"workloadIdentityDetails": workload,
- "_uuid": runtime_uuid,
}
for opt in ("description", "protocolConfiguration", "environmentVariables",
"authorizerConfiguration", "requestHeaderConfiguration",
@@ -298,7 +331,8 @@ def _create_agent_runtime(body):
if opt in data:
record[opt] = data[opt]
_runtimes[runtime_id] = record
- _endpoints[runtime_id] = {}
+ # AWS creates the DEFAULT endpoint with the runtime, pointing at the latest version.
+ _endpoints[runtime_id] = {"DEFAULT": _endpoint_record(record, "DEFAULT", version)}
# AWS returns CREATING at create time; the runtime settles to READY.
return json_response({
@@ -359,12 +393,12 @@ def _update_agent_runtime(runtime_id, body):
if not data.get(field):
return _validation(f"{field} is required")
_stop_container(runtime_id)
- old_arn = record["agentRuntimeArn"]
now = now_iso()
new_version = str(int(record["agentRuntimeVersion"]) + 1)
record["agentRuntimeVersion"] = new_version
- record["agentRuntimeArn"] = _runtime_arn(record["_uuid"], new_version)
- _resource_policies.pop(old_arn, None)
+ default = (_endpoints.get(runtime_id) or {}).get("DEFAULT")
+ if default:
+ default.update(targetVersion=new_version, liveVersion=new_version, lastUpdatedAt=now)
record["lastUpdatedAt"] = now
record["status"] = "READY"
for field in ("agentRuntimeArtifact", "roleArn", "networkConfiguration"):
@@ -415,20 +449,8 @@ def _create_agent_runtime_endpoint(runtime_id, body):
if name in endpoints:
return _conflict(f"Endpoint {name} already exists")
target_version = data.get("agentRuntimeVersion") or runtime["agentRuntimeVersion"]
- endpoint_uuid = new_uuid()
- now = now_iso()
- record = {
- "name": name,
- "id": _resource_id(name),
- "agentRuntimeEndpointArn": _endpoint_arn(endpoint_uuid),
- "agentRuntimeArn": runtime["agentRuntimeArn"],
- "targetVersion": target_version,
- "liveVersion": target_version,
- "status": "READY",
- "description": data.get("description", ""),
- "createdAt": now,
- "lastUpdatedAt": now,
- }
+ record = _endpoint_record(runtime, name, target_version, data.get("description", ""))
+ now = record["createdAt"]
endpoints[name] = record
return json_response({
"targetVersion": target_version,
@@ -536,8 +558,6 @@ def _find_runtime(runtime_arn):
record
for record in _runtimes.values_scoped(account_id, region)
if record["agentRuntimeArn"] == runtime_arn
- or record["agentRuntimeArn"].rsplit(":", 1)[0]
- == runtime_arn.rsplit(":", 1)[0]
),
None,
)
@@ -545,8 +565,9 @@ def _find_runtime(runtime_arn):
def _endpoint_for_qualifier(runtime, account_id, region, qualifier):
- if not qualifier:
+ if runtime is None:
return None
+ qualifier = qualifier or "DEFAULT"
endpoints = _endpoints.get_scoped(account_id, region, runtime["agentRuntimeId"], {})
return endpoints.get(qualifier)
@@ -680,14 +701,14 @@ def _invoke_agent_runtime(runtime_arn, headers, body, query_params=None):
return _not_found(f"Agent runtime endpoint {qualifier} not found")
from ministack.app import AUTH
- from ministack.core.iam_evaluator import pin_request_caller
+ from ministack.core.iam_evaluator import caller_arn, pin_request_caller
pin_request_caller(headers, query_params or {})
if AUTH and not _resource_policy_allows_invocation(
runtime, owner_account, owner_region, qualifier, headers, query_params
):
return error_response_json(
"AccessDeniedException",
- f"User: {get_account_id()} is not authorized to perform: "
+ f"User: {caller_arn()} is not authorized to perform: "
f"bedrock-agentcore:InvokeAgentRuntime on resource: {runtime_arn}",
403,
)
diff --git a/ministack/services/cloudformation/__init__.py b/ministack/services/cloudformation/__init__.py
index e535e9e4..befe2733 100644
--- a/ministack/services/cloudformation/__init__.py
+++ b/ministack/services/cloudformation/__init__.py
@@ -82,7 +82,7 @@ async def handle_request(method: str, path: str, headers: dict,
# The stack operations that take a ClientRequestToken and record stack events.
_TOKEN_ACTIONS = frozenset({
"CreateStack", "UpdateStack", "DeleteStack", "ExecuteChangeSet",
- "ContinueUpdateRollback", "CancelUpdateStack",
+ "ContinueUpdateRollback", "CancelUpdateStack", "RollbackStack",
})
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index bf3a9f8e..68f0d2ba 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -787,11 +787,7 @@ def _get_template(params):
return _error("ValidationError",
f"Stack [{stack_name}] does not exist")
- # The API reference defaults TemplateStage to Processed; Original stays the
- # default here, which is what GetTemplate has always answered and what the
- # tests of transform templates expect. For a template without a transform
- # the two stages are the same.
- if _p(params, "TemplateStage") == "Processed":
+ if _p(params, "TemplateStage", "Processed") == "Processed":
template_body = _processed_template_body(record)
else:
template_body = record.get("_template_body") or "{}"
@@ -1389,9 +1385,8 @@ def _rollback_stack(params):
to its last known stable state. ``CREATE_FAILED`` has none, so what the
create made is deleted and the stack ends ``ROLLBACK_COMPLETE``;
``UPDATE_FAILED`` goes back to the stack as it was before the update and
- ends ``UPDATE_ROLLBACK_COMPLETE`` (API_RollbackStack). ``RoleARN`` and
- ``ClientRequestToken`` are accepted and not used: the emulator assumes no
- role, and a repeated token is not refused."""
+ ends ``UPDATE_ROLLBACK_COMPLETE`` (API_RollbackStack). ``RoleARN`` is
+ accepted and not used."""
stack_name = _p(params, "StackName")
if not stack_name:
return _error("ValidationError", "StackName is required")
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index f29087c0..136ea51c 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -3087,8 +3087,12 @@ def _cwlogs_resource_policy_create(logical_id, props, stack_name):
policy_name = props.get("PolicyName")
if not policy_name:
raise ValueError("AWS::Logs::ResourcePolicy requires PolicyName")
- # Local log delivery is intentionally permissive, so the policy only needs
- # its CloudFormation identity rather than a data-plane enforcement store.
+ document = props.get("PolicyDocument")
+ if not isinstance(document, str):
+ document = json.dumps(document)
+ resp = _cw_logs._put_resource_policy({"policyName": policy_name, "policyDocument": document})
+ if resp[0] >= 400:
+ raise ValueError(f"AWS::Logs::ResourcePolicy create failed: {resp[2]!r}")
return policy_name, {}
@@ -3097,7 +3101,7 @@ def _cwlogs_resource_policy_update(physical_id, old_props, new_props, stack_name
def _cwlogs_resource_policy_delete(physical_id, props):
- pass
+ _cw_logs._delete_resource_policy({"policyName": physical_id})
# --- CloudWatch Logs SubscriptionFilter (#896) ---
diff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.py
index 7ece44ef..28289b6e 100644
--- a/ministack/services/cloudwatch_logs.py
+++ b/ministack/services/cloudwatch_logs.py
@@ -68,8 +68,10 @@ _destinations = AccountRegionScopedDict()
# dest_name -> {destinationName, targetArn, roleArn, accessPolicy, arn, creationTime}
_resource_policies = AccountRegionScopedDict()
-# policy_name -> {policyName, policyDocument, resourceArn, policyScope,
-# lastUpdatedTime, revisionId}
+# policy_name -> {policyName, policyDocument, policyScope, lastUpdatedTime, revisionId}
+_log_group_policies = AccountRegionScopedDict()
+# log_group_name -> the one RESOURCE-scoped policy a log group can have
+_MAX_ACCOUNT_RESOURCE_POLICIES = 10
_metric_filters = AccountRegionScopedDict()
# (log_group_name, filter_name) -> {filterName, logGroupName, filterPattern, metricTransformations, creationTime}
@@ -115,6 +117,7 @@ def get_state():
"log_groups": copy.deepcopy(_log_groups),
"destinations": copy.deepcopy(_destinations),
"resource_policies": copy.deepcopy(_resource_policies),
+ "log_group_policies": copy.deepcopy(_log_group_policies),
"metric_filters": copy.deepcopy(_metric_filters),
"queries": copy.deepcopy(_queries),
"log_records": copy.deepcopy(_log_records),
@@ -206,6 +209,7 @@ def _restore_state(data):
_log_groups.update(data.get("log_groups", {}))
_destinations.update(data.get("destinations", {}))
_resource_policies.update(data.get("resource_policies", {}))
+ _log_group_policies.update(data.get("log_group_policies", {}))
_restore_metric_filters(data.get("metric_filters", {}))
_restore_queries(data.get("queries", {}))
_log_records.update(data.get("log_records", {}))
@@ -396,6 +400,7 @@ def _delete_log_group(data):
)
_forget_log_records_for_group(name)
del _log_groups[name]
+ _log_group_policies.pop(name, None)
return json_response({})
@@ -1594,6 +1599,13 @@ def _format_resource_policy(policy):
}
+def _revision_mismatch():
+ return error_response_json(
+ "OperationAbortedException",
+ "The revision id does not match the latest revision id.", 400,
+ )
+
+
def _put_resource_policy(data):
name = data.get("policyName")
document = data.get("policyDocument")
@@ -1602,37 +1614,71 @@ def _put_resource_policy(data):
"InvalidParameterException",
"policyName and policyDocument are required.", 400,
)
+ resource_arn = data.get("resourceArn")
expected_revision = data.get("expectedRevisionId")
- existing = _resource_policies.get(name)
- if expected_revision is not None and (not existing or existing["revisionId"] != expected_revision):
- return error_response_json(
- "OperationAbortedException",
- "The revision id does not match the latest revision id.", 400,
- )
policy = {
"policyName": name,
"policyDocument": document,
- "resourceArn": data.get("resourceArn"),
- "policyScope": data.get("policyScope", "ACCOUNT"),
"lastUpdatedTime": int(time.time() * 1000),
"revisionId": new_uuid(),
}
- _resource_policies[name] = policy
- formatted = _format_resource_policy(policy)
- return json_response({"resourcePolicy": formatted, "revisionId": policy["revisionId"]})
+ if resource_arn:
+ # RESOURCE scope: one policy per existing log group, guarded by its revision.
+ group = _resolve_group_by_arn(resource_arn)
+ if group is None:
+ return error_response_json(
+ "ResourceNotFoundException", "The specified log group does not exist.", 400)
+ existing = _log_group_policies.get(group)
+ if (existing["revisionId"] if existing else None) != expected_revision:
+ return _revision_mismatch()
+ policy.update(policyScope="RESOURCE", resourceArn=resource_arn)
+ _log_group_policies[group] = policy
+ else:
+ existing = _resource_policies.get(name)
+ if expected_revision is not None and (not existing or existing["revisionId"] != expected_revision):
+ return _revision_mismatch()
+ if existing is None and len(_resource_policies) >= _MAX_ACCOUNT_RESOURCE_POLICIES:
+ return error_response_json(
+ "LimitExceededException",
+ f"Resource limit exceeded. An account can have at most "
+ f"{_MAX_ACCOUNT_RESOURCE_POLICIES} resource policies.", 400)
+ policy["policyScope"] = "ACCOUNT"
+ _resource_policies[name] = policy
+ return json_response({"resourcePolicy": _format_resource_policy(policy),
+ "revisionId": policy["revisionId"]})
def _describe_resource_policies(data):
resource_arn = data.get("resourceArn")
- policies = [
- _format_resource_policy(p) for p in _resource_policies.values()
- if not resource_arn or p.get("resourceArn") == resource_arn
- ]
- return json_response({"resourcePolicies": policies})
+ scope = data.get("policyScope") or "ACCOUNT"
+ if scope not in ("ACCOUNT", "RESOURCE"):
+ return error_response_json(
+ "InvalidParameterException", f"Invalid policyScope: {scope}", 400)
+ if resource_arn:
+ group = _resolve_group_by_arn(resource_arn)
+ found = _log_group_policies.get(group) if group else None
+ policies = [found] if found else []
+ elif scope == "RESOURCE":
+ policies = list(_log_group_policies.values())
+ else:
+ policies = list(_resource_policies.values())
+ return json_response({"resourcePolicies": [_format_resource_policy(p) for p in policies]})
def _delete_resource_policy(data):
name = data.get("policyName")
+ resource_arn = data.get("resourceArn")
+ if resource_arn:
+ group = _resolve_group_by_arn(resource_arn)
+ existing = _log_group_policies.get(group) if group else None
+ if existing is None:
+ return error_response_json(
+ "ResourceNotFoundException",
+ f"The specified resource policy does not exist: {name}", 400)
+ if data.get("expectedRevisionId") != existing["revisionId"]:
+ return _revision_mismatch()
+ del _log_group_policies[group]
+ return json_response({})
if not name or name not in _resource_policies:
return error_response_json(
"ResourceNotFoundException",
@@ -2093,6 +2139,7 @@ def reset():
_log_groups.clear()
_destinations.clear()
_resource_policies.clear()
+ _log_group_policies.clear()
_metric_filters.clear()
_queries.clear()
_log_records.clear()
diff --git a/tests/test_bedrock_agentcore.py b/tests/test_bedrock_agentcore.py
index 38a5fae3..22c59069 100644
--- a/tests/test_bedrock_agentcore.py
+++ b/tests/test_bedrock_agentcore.py
@@ -60,8 +60,7 @@ def test_agentcore_runtime_lifecycle():
rid = created["agentRuntimeId"]
assert created["status"] == "CREATING"
assert created["agentRuntimeVersion"] == "1"
- assert created["agentRuntimeArn"].startswith(
- "arn:aws:bedrock-agentcore:us-east-1:000000000000:agent/")
+ assert created["agentRuntimeArn"] == f"arn:aws:bedrock-agentcore:us-east-1:000000000000:runtime/{rid}"
assert created["workloadIdentityDetails"]["workloadIdentityArn"]
try:
got = ctl.get_agent_runtime(agentRuntimeId=rid)
@@ -78,6 +77,9 @@ def test_agentcore_runtime_lifecycle():
)
assert updated["agentRuntimeVersion"] == "2"
assert updated["status"] == "UPDATING"
+ assert updated["agentRuntimeArn"] == created["agentRuntimeArn"]
+ default = ctl.get_agent_runtime_endpoint(agentRuntimeId=rid, endpointName="DEFAULT")
+ assert (default["liveVersion"], default["targetVersion"]) == ("2", "2")
assert ctl.get_agent_runtime(agentRuntimeId=rid)["agentRuntimeVersion"] == "2"
versions = ctl.list_agent_runtime_versions(agentRuntimeId=rid)["agentRuntimes"]
@@ -99,8 +101,8 @@ def test_agentcore_endpoint_lifecycle():
ep = ctl.create_agent_runtime_endpoint(agentRuntimeId=rid, name="prod")
assert ep["endpointName"] == "prod"
assert ep["status"] == "CREATING"
- assert ep["agentRuntimeEndpointArn"].startswith(
- "arn:aws:bedrock-agentcore:us-east-1:000000000000:agentEndpoint/")
+ assert ep["agentRuntimeEndpointArn"] == (
+ f"arn:aws:bedrock-agentcore:us-east-1:000000000000:runtime/{rid}/runtime-endpoint/prod")
got = ctl.get_agent_runtime_endpoint(agentRuntimeId=rid, endpointName="prod")
assert got["status"] == "READY"
@@ -108,7 +110,7 @@ def test_agentcore_endpoint_lifecycle():
names = [e["name"] for e in
ctl.list_agent_runtime_endpoints(agentRuntimeId=rid)["runtimeEndpoints"]]
- assert names == ["prod"]
+ assert sorted(names) == ["DEFAULT", "prod"]
upd = ctl.update_agent_runtime_endpoint(
agentRuntimeId=rid, endpointName="prod", description="live")
@@ -751,3 +753,53 @@ def test_without_docker_the_invocation_echoes(monkeypatch):
assert json.loads(body)["input"] == {"prompt": "hi"}
finally:
agentcore._delete_agent_runtime(runtime["agentRuntimeId"])
+
+
+def test_agentcore_resource_policy_survives_update_and_default_endpoint_takes_one():
+ ctl = _client("bedrock-agentcore-control")
+ created = _create(ctl, f"rt_{_uuid_mod.uuid4().hex[:8]}")
+ rid, arn = created["agentRuntimeId"], created["agentRuntimeArn"]
+ default_arn = f"{arn}/runtime-endpoint/DEFAULT"
+
+ def policy(resource):
+ return json.dumps({"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::111111111111:root"},
+ "Action": "bedrock-agentcore:InvokeAgentRuntime", "Resource": resource}]})
+
+ try:
+ ctl.put_resource_policy(resourceArn=arn, policy=policy(arn))
+ ctl.put_resource_policy(resourceArn=default_arn, policy=policy(default_arn))
+ ctl.update_agent_runtime(agentRuntimeId=rid, agentRuntimeArtifact=_ARTIFACT,
+ roleArn=_ROLE, networkConfiguration=_NET)
+ assert ctl.get_resource_policy(resourceArn=arn)["policy"] == policy(arn)
+ assert ctl.get_resource_policy(resourceArn=default_arn)["policy"] == policy(default_arn)
+ finally:
+ ctl.delete_agent_runtime(agentRuntimeId=rid)
+
+
+def test_agentcore_state_with_legacy_arns_moves_to_aws_arns():
+ from ministack.core.responses import AccountRegionScopedDict
+ from ministack.services import bedrock_agentcore as svc
+
+ runtimes, endpoints = AccountRegionScopedDict(), AccountRegionScopedDict()
+ runtimes.set_scoped("000000000000", "us-east-1", "old-AbCdEfGhIj", {
+ "agentRuntimeId": "old-AbCdEfGhIj", "agentRuntimeVersion": "3",
+ "agentRuntimeArn": "arn:aws:bedrock-agentcore:us-east-1:000000000000:agent/1234:3",
+ "_uuid": "1234",
+ })
+ endpoints.set_scoped("000000000000", "us-east-1", "old-AbCdEfGhIj", {"prod": {
+ "name": "prod", "agentRuntimeArn": "x",
+ "agentRuntimeEndpointArn": "arn:aws:bedrock-agentcore:us-east-1:000000000000:agentEndpoint/5678",
+ }})
+ saved = svc.get_state()
+ try:
+ svc.load_persisted_state({"runtimes": runtimes, "endpoints": endpoints})
+ runtime_arn = "arn:aws:bedrock-agentcore:us-east-1:000000000000:runtime/old-AbCdEfGhIj"
+ record = svc._runtimes.get_scoped("000000000000", "us-east-1", "old-AbCdEfGhIj")
+ assert record["agentRuntimeArn"] == runtime_arn and "_uuid" not in record
+ eps = svc._endpoints.get_scoped("000000000000", "us-east-1", "old-AbCdEfGhIj")
+ assert eps["prod"]["agentRuntimeEndpointArn"] == f"{runtime_arn}/runtime-endpoint/prod"
+ assert eps["DEFAULT"]["agentRuntimeEndpointArn"] == f"{runtime_arn}/runtime-endpoint/DEFAULT"
+ assert eps["DEFAULT"]["liveVersion"] == "3"
+ finally:
+ svc.load_persisted_state(saved)
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index a533dc9a..2c098599 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -14412,8 +14412,8 @@ def test_cfn_logs_subscription_filter_group_change_moves_it(cfn, logs, rollback)
_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."""
+def test_cfn_logs_resource_policy_identity_and_lifecycle(cfn, logs):
+ """Logs resource policies provision through the CloudWatch Logs API."""
suffix = _uuid_mod.uuid4().hex[:8]
stack_name = f"cfn-logs-policy-{suffix}"
policy_name = f"logs-policy-{suffix}"
@@ -14451,6 +14451,8 @@ def test_cfn_logs_resource_policy_identity_and_lifecycle(cfn):
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
assert stack["Outputs"][0]["OutputValue"] == policy_name
+ created = {p["policyName"]: p for p in logs.describe_resource_policies()["resourcePolicies"]}
+ assert "InitialPolicy" in created[policy_name]["policyDocument"]
cfn.update_stack(
StackName=stack_name,
@@ -14468,10 +14470,14 @@ def test_cfn_logs_resource_policy_identity_and_lifecycle(cfn):
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
assert stack["Outputs"][0]["OutputValue"] == updated_name
+ names = [p["policyName"] for p in logs.describe_resource_policies()["resourcePolicies"]]
+ assert updated_name in names and policy_name not in names
cfn.delete_stack(StackName=stack_name)
stack = _wait_stack(cfn, stack_name)
assert stack["StackStatus"] == "DELETE_COMPLETE"
+ names = [p["policyName"] for p in logs.describe_resource_policies()["resourcePolicies"]]
+ assert updated_name not in names
def test_cfn_kinesisfirehose_delivery_stream_shares_firehose_state(cfn, fh):
@@ -24348,7 +24354,7 @@ def _include_transform(cfn, s3, ssm, uid, bucket, name):
assert _output(stack, "IncludedOutput") == handle_url
# The stored template is the one the caller sent: the include is not
# baked into it.
- stored = cfn.get_template(StackName=name)["TemplateBody"]
+ stored = cfn.get_template(StackName=name, TemplateStage="Original")["TemplateBody"]
assert "Fn::Transform" in stored["Resources"] and "Included" not in stored["Resources"]
# A snippet edited in S3 after the deploy is not picked up by an update
@@ -24535,7 +24541,7 @@ def _language_extensions(cfn, ssm, prefix, name):
assert _output(stack, "PairxName") == prefix + "/pair-x"
assert _output(stack, "PairxLiteral") == "&{Id}-${Id}"
- stored = cfn.get_template(StackName=name)["TemplateBody"]
+ stored = cfn.get_template(StackName=name, TemplateStage="Original")["TemplateBody"]
assert "Fn::ForEach::Addresses" in stored["Resources"]
parameters = [{"ParameterKey": "Addresses", "ParameterValue": "10.1,10.2,10.3"}]
@@ -28099,11 +28105,11 @@ def test_cfn_get_template_stages(cfn):
default = cfn.get_template(StackName=stack_name)
assert default["StagesAvailable"] == ["Original", "Processed"]
- assert "Fn::ForEach::Topics" in default["TemplateBody"]["Resources"]
+ assert sorted(default["TemplateBody"]["Resources"]) == ["TopicA", "TopicB"]
original = cfn.get_template(StackName=stack_name, TemplateStage="Original")
- assert original["TemplateBody"] == default["TemplateBody"]
+ assert "Fn::ForEach::Topics" in original["TemplateBody"]["Resources"]
processed = cfn.get_template(StackName=stack_name, TemplateStage="Processed")
- assert sorted(processed["TemplateBody"]["Resources"]) == ["TopicA", "TopicB"]
+ assert processed["TemplateBody"] == default["TemplateBody"]
assert processed["StagesAvailable"] == ["Original", "Processed"]
assert (cfn.get_template(StackName=plain_name, TemplateStage="Processed")["TemplateBody"]
@@ -28117,7 +28123,8 @@ def test_cfn_get_template_stages(cfn):
cs_id = cfn.create_change_set(StackName=stack_name, ChangeSetName="more",
TemplateBody=json.dumps(more))["Id"]
assert _wait_change_set(cfn, stack_name, "more")["Status"] == "CREATE_COMPLETE"
- cs_original = cfn.get_template(StackName=stack_name, ChangeSetName="more")
+ cs_original = cfn.get_template(StackName=stack_name, ChangeSetName="more",
+ TemplateStage="Original")
assert cs_original["TemplateBody"]["Resources"]["Fn::ForEach::Topics"][1] == [
"A", "B", "C"]
cs_processed = cfn.get_template(ChangeSetName=cs_id, TemplateStage="Processed")
@@ -28258,3 +28265,412 @@ def test_cfn_client_request_token_on_cancel_and_continue_rollback(cfn, lam):
lam.delete_function(FunctionName=fn)
except ClientError:
pass
+
+
+def _stack_event_statuses(cfn, name):
+ events = cfn.describe_stack_events(StackName=name)["StackEvents"]
+ return [(e["LogicalResourceId"], e["ResourceStatus"], e.get("ResourceStatusReason", ""))
+ for e in reversed(events)]
+
+
+def _detect(cfn, name, **kwargs):
+ detection_id = cfn.detect_stack_drift(StackName=name, **kwargs)["StackDriftDetectionId"]
+ for _ in range(50):
+ status = cfn.describe_stack_drift_detection_status(StackDriftDetectionId=detection_id)
+ if status["DetectionStatus"] != "DETECTION_IN_PROGRESS":
+ return status
+ time.sleep(0.2)
+ raise TimeoutError("drift detection did not finish")
+
+
+def _drifts(cfn, name, **kwargs):
+ return {d["LogicalResourceId"]: d for d in
+ cfn.describe_stack_resource_drifts(StackName=name, **kwargs)["StackResourceDrifts"]}
+
+# ---------------------------------------------------------------------------
+# RollbackStack
+# ---------------------------------------------------------------------------
+
+def test_rollback_stack_from_create_failed_deletes_what_the_create_made(cfn, sqs):
+ name = f"rb-create-{_uuid_mod.uuid4().hex[:8]}"
+ queue = f"{name}-q"
+ template = {"Resources": {
+ "Q": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": queue}},
+ "Bad": {**_FAILING_RESOURCE, "DependsOn": "Q"},
+ }}
+ try:
+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(template),
+ DisableRollback=True)
+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_FAILED"
+ assert _queue_exists(sqs, queue)
+
+ stack_id = cfn.rollback_stack(StackName=name, ClientRequestToken="rb-token")["StackId"]
+ assert stack_id.startswith("arn:aws:cloudformation:")
+ assert _wait_stack(cfn, name)["StackStatus"] == "ROLLBACK_COMPLETE"
+ rollback_events = [e for e in cfn.describe_stack_events(StackName=name)["StackEvents"]
+ if e["ResourceStatus"] in ("ROLLBACK_IN_PROGRESS", "ROLLBACK_COMPLETE")]
+ assert rollback_events and all(e.get("ClientRequestToken") == "rb-token"
+ for e in rollback_events)
+ assert not _queue_exists(sqs, queue)
+ events = _stack_event_statuses(cfn, name)
+ assert (name, "ROLLBACK_IN_PROGRESS", "User Initiated") in events
+ assert ("Q", "DELETE_COMPLETE", "") in events
+ assert events[-1][:2] == (name, "ROLLBACK_COMPLETE")
+ assert cfn.describe_stack_resources(StackName=name)["StackResources"] == []
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
+def test_rollback_stack_from_update_failed_restores_the_previous_stack(cfn, sqs, ssm):
+ name = f"rb-update-{_uuid_mod.uuid4().hex[:8]}"
+ queue = f"{name}-q"
+ added = f"{name}-added"
+ param = f"/{name}/p"
+
+ def template(visibility, value, extra):
+ resources = {
+ "Q": {"Type": "AWS::SQS::Queue",
+ "Properties": {"QueueName": queue, "VisibilityTimeout": visibility}},
+ "P": {"Type": "AWS::SSM::Parameter",
+ "Properties": {"Name": param, "Type": "String", "Value": value}},
+ }
+ if extra:
+ resources["Added"] = {"Type": "AWS::SQS::Queue",
+ "Properties": {"QueueName": added}}
+ resources["Bad"] = {**_FAILING_RESOURCE, "DependsOn": ["P", "Q", "Added"]}
+ return json.dumps({"Resources": resources})
+
+ try:
+ cfn.create_stack(StackName=name, TemplateBody=template(30, "v1", False))
+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ cfn.update_stack(StackName=name, TemplateBody=template(60, "v2", True),
+ DisableRollback=True)
+ failed = _wait_stack(cfn, name)
+ assert failed["StackStatus"] == "UPDATE_FAILED"
+ # DisableRollback kept the partial update in place.
+ assert ssm.get_parameter(Name=param)["Parameter"]["Value"] == "v2"
+ assert _queue_exists(sqs, added)
+
+ cfn.rollback_stack(StackName=name)
+ assert _wait_stack(cfn, name)["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ assert ssm.get_parameter(Name=param)["Parameter"]["Value"] == "v1"
+ url = sqs.get_queue_url(QueueName=queue)["QueueUrl"]
+ attrs = sqs.get_queue_attributes(QueueUrl=url, AttributeNames=["VisibilityTimeout"])
+ assert attrs["Attributes"]["VisibilityTimeout"] == "30"
+ assert not _queue_exists(sqs, added)
+ body = cfn.get_template(StackName=name)["TemplateBody"]
+ assert "Bad" not in json.dumps(body)
+ listed = {r["LogicalResourceId"] for r in
+ cfn.list_stack_resources(StackName=name)["StackResourceSummaries"]}
+ assert listed == {"Q", "P"}
+ statuses = [s for lid, s, _ in _stack_event_statuses(cfn, name) if lid == name]
+ assert statuses[-3:] == ["UPDATE_ROLLBACK_IN_PROGRESS",
+ "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS",
+ "UPDATE_ROLLBACK_COMPLETE"]
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
+def test_rollback_stack_retain_except_on_create_deletes_retained_new_resources(cfn, sqs):
+ name = f"rb-retain-{_uuid_mod.uuid4().hex[:8]}"
+ queue = f"{name}-q"
+ template = {"Resources": {
+ "Q": {"Type": "AWS::SQS::Queue", "DeletionPolicy": "Retain",
+ "Properties": {"QueueName": queue}},
+ "Bad": {**_FAILING_RESOURCE, "DependsOn": "Q"},
+ }}
+ try:
+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(template),
+ DisableRollback=True)
+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_FAILED"
+ cfn.rollback_stack(StackName=name, RetainExceptOnCreate=True)
+ assert _wait_stack(cfn, name)["StackStatus"] == "ROLLBACK_COMPLETE"
+ assert not _queue_exists(sqs, queue)
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
+def test_rollback_stack_wrong_state_and_missing_stack(cfn):
+ name = f"rb-wrong-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(
+ {"Resources": {"Q": {"Type": "AWS::SQS::Queue"}}}))
+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ with pytest.raises(ClientError) as exc:
+ cfn.rollback_stack(StackName=name)
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+ assert "cannot be called from current stack status" in exc.value.response["Error"]["Message"]
+ with pytest.raises(ClientError) as exc:
+ cfn.rollback_stack(StackName=f"rb-missing-{_uuid_mod.uuid4().hex[:8]}")
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+ assert "does not exist" in exc.value.response["Error"]["Message"]
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
+# ---------------------------------------------------------------------------
+# Drift detection
+# ---------------------------------------------------------------------------
+
+def _drift_template(name):
+ return json.dumps({"Resources": {
+ "Q": {"Type": "AWS::SQS::Queue", "Properties": {
+ "QueueName": f"{name}-q", "VisibilityTimeout": 45,
+ "Tags": [{"Key": "team", "Value": "a"}]}},
+ "P": {"Type": "AWS::SSM::Parameter", "Properties": {
+ "Name": f"/{name}/p", "Type": "String", "Value": "expected"}},
+ # No drift reader for queue policies: NOT_CHECKED.
+ "Policy": {"Type": "AWS::SQS::QueuePolicy", "Properties": {
+ "Queues": [{"Ref": "Q"}],
+ "PolicyDocument": {"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": "*", "Action": "sqs:SendMessage",
+ "Resource": "*"}]}}},
+ }})
+
+
+def drift_stack(cfn):
+ name = f"drift-{_uuid_mod.uuid4().hex[:8]}"
+ cfn.create_stack(StackName=name, TemplateBody=_drift_template(name),
+ Tags=[{"Key": "env", "Value": "test"}])
+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ yield name
+ _delete_cfn_test_stack(cfn, name)
+
+
+def test_drift_in_sync_after_create(cfn, drift_stack):
+ name = drift_stack
+ stack = cfn.describe_stacks(StackName=name)["Stacks"][0]
+ assert stack["DriftInformation"] == {"StackDriftStatus": "NOT_CHECKED"}
+ summary = next(s for s in _all_pages(cfn, "list_stacks", "StackSummaries")
+ if s["StackName"] == name)
+ assert summary["DriftInformation"]["StackDriftStatus"] == "NOT_CHECKED"
+
+ status = _detect(cfn, name)
+ assert status["DetectionStatus"] == "DETECTION_COMPLETE"
+ assert status["StackDriftStatus"] == "IN_SYNC"
+ assert status["DriftedStackResourceCount"] == 0
+ assert status["StackId"] == stack["StackId"]
+
+ drifts = _drifts(cfn, name)
+ # Only the checked resources are listed; the queue policy has no support.
+ assert set(drifts) == {"Q", "P"}
+ q = drifts["Q"]
+ assert q["StackResourceDriftStatus"] == "IN_SYNC"
+ assert json.loads(q["ExpectedProperties"]) == json.loads(q["ActualProperties"])
+ # The stack-level tag is part of the expected tags; aws: tags are not.
+ assert json.loads(q["ExpectedProperties"])["Tags"] == [
+ {"Key": "team", "Value": "a"}, {"Key": "env", "Value": "test"}]
+ assert "PropertyDifferences" not in q or q["PropertyDifferences"] == []
+
+ after = cfn.describe_stacks(StackName=name)["Stacks"][0]["DriftInformation"]
+ assert after["StackDriftStatus"] == "IN_SYNC"
+ assert "LastCheckTimestamp" in after
+ resources = {r["LogicalResourceId"]: r["DriftInformation"]
+ for r in cfn.describe_stack_resources(StackName=name)["StackResources"]}
+ assert resources["Q"]["StackResourceDriftStatus"] == "IN_SYNC"
+ assert "LastCheckTimestamp" in resources["Q"]
+ assert resources["Policy"] == {"StackResourceDriftStatus": "NOT_CHECKED"}
+ summaries = {r["LogicalResourceId"]: r["DriftInformation"]
+ for r in cfn.list_stack_resources(StackName=name)["StackResourceSummaries"]}
+ assert summaries["P"]["StackResourceDriftStatus"] == "IN_SYNC"
+ detail = cfn.describe_stack_resource(StackName=name, LogicalResourceId="Policy")
+ assert detail["StackResourceDetail"]["DriftInformation"]["StackResourceDriftStatus"] == "NOT_CHECKED"
+
+
+def test_drift_modified_after_out_of_band_changes(cfn, sqs, ssm, drift_stack):
+ name = drift_stack
+ url = sqs.get_queue_url(QueueName=f"{name}-q")["QueueUrl"]
+ sqs.set_queue_attributes(QueueUrl=url, Attributes={"VisibilityTimeout": "99"})
+ sqs.tag_queue(QueueUrl=url, Tags={"added": "x"})
+ ssm.put_parameter(Name=f"/{name}/p", Value="changed", Type="String", Overwrite=True)
+
+ status = _detect(cfn, name)
+ assert status["StackDriftStatus"] == "DRIFTED"
+ assert status["DriftedStackResourceCount"] == 2
+
+ drifts = _drifts(cfn, name)
+ q = drifts["Q"]
+ assert q["StackResourceDriftStatus"] == "MODIFIED"
+ diffs = {d["PropertyPath"]: d for d in q["PropertyDifferences"]}
+ assert diffs["/VisibilityTimeout"] == {
+ "PropertyPath": "/VisibilityTimeout", "ExpectedValue": "45",
+ "ActualValue": "99", "DifferenceType": "NOT_EQUAL"}
+ added = [d for d in q["PropertyDifferences"] if d["DifferenceType"] == "ADD"]
+ assert len(added) == 1 and added[0]["PropertyPath"].startswith("/Tags/")
+ assert json.loads(added[0]["ActualValue"]) == {"Key": "added", "Value": "x"}
+ assert json.loads(q["ActualProperties"])["VisibilityTimeout"] == 99
+ assert json.loads(q["ExpectedProperties"])["VisibilityTimeout"] == 45
+
+ p = drifts["P"]
+ assert p["StackResourceDriftStatus"] == "MODIFIED"
+ assert p["PropertyDifferences"] == [{
+ "PropertyPath": "/Value", "ExpectedValue": "expected",
+ "ActualValue": "changed", "DifferenceType": "NOT_EQUAL"}]
+
+ assert cfn.describe_stacks(StackName=name)["Stacks"][0]["DriftInformation"][
+ "StackDriftStatus"] == "DRIFTED"
+ modified = _drifts(cfn, name, StackResourceDriftStatusFilters=["MODIFIED"])
+ assert set(modified) == {"Q", "P"}
+ assert _drifts(cfn, name, StackResourceDriftStatusFilters=["IN_SYNC", "DELETED"]) == {}
+ assert _drifts(cfn, name, StackResourceDriftStatusFilters=["NOT_CHECKED"]) == {}
+
+
+def test_drift_removed_tag_is_reported_as_remove(cfn, sqs, drift_stack):
+ name = drift_stack
+ url = sqs.get_queue_url(QueueName=f"{name}-q")["QueueUrl"]
+ sqs.untag_queue(QueueUrl=url, TagKeys=["team"])
+ drift = cfn.detect_stack_resource_drift(StackName=name, LogicalResourceId="Q")[
+ "StackResourceDrift"]
+ assert drift["StackResourceDriftStatus"] == "MODIFIED"
+ assert drift["PropertyDifferences"] == [{
+ "PropertyPath": "/Tags/0", "ExpectedValue": json.dumps(
+ {"Key": "team", "Value": "a"}, sort_keys=True),
+ "ActualValue": "null", "DifferenceType": "REMOVE"}]
+
+
+def test_drift_deleted_after_out_of_band_delete(cfn, sqs, drift_stack):
+ name = drift_stack
+ url = sqs.get_queue_url(QueueName=f"{name}-q")["QueueUrl"]
+ sqs.delete_queue(QueueUrl=url)
+
+ drift = cfn.detect_stack_resource_drift(StackName=name, LogicalResourceId="Q")[
+ "StackResourceDrift"]
+ assert drift["StackResourceDriftStatus"] == "DELETED"
+ assert "ExpectedProperties" not in drift and "ActualProperties" not in drift
+ assert drift["PhysicalResourceId"] == url
+ # A single-resource check moves the stack's LastCheckTimestamp only.
+ info = cfn.describe_stacks(StackName=name)["Stacks"][0]["DriftInformation"]
+ assert info["StackDriftStatus"] == "NOT_CHECKED" and "LastCheckTimestamp" in info
+ assert set(_drifts(cfn, name, StackResourceDriftStatusFilters=["DELETED"])) == {"Q"}
+
+ status = _detect(cfn, name)
+ assert status["StackDriftStatus"] == "DRIFTED"
+ assert status["DriftedStackResourceCount"] == 1
+
+
+def test_drift_logical_resource_ids_filter(cfn, ssm, drift_stack):
+ name = drift_stack
+ ssm.put_parameter(Name=f"/{name}/p", Value="changed", Type="String", Overwrite=True)
+ status = _detect(cfn, name, LogicalResourceIds=["Q"])
+ assert status["StackDriftStatus"] == "IN_SYNC"
+ assert set(_drifts(cfn, name)) == {"Q"}
+ with pytest.raises(ClientError) as exc:
+ cfn.detect_stack_drift(StackName=name, LogicalResourceIds=["Nope"])
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+
+
+def test_drift_unsupported_type_and_missing_resource(cfn, drift_stack):
+ name = drift_stack
+ with pytest.raises(ClientError) as exc:
+ cfn.detect_stack_resource_drift(StackName=name, LogicalResourceId="Policy")
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+ assert "AWS::SQS::QueuePolicy" in exc.value.response["Error"]["Message"]
+ with pytest.raises(ClientError) as exc:
+ cfn.detect_stack_resource_drift(StackName=name, LogicalResourceId="Nope")
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+ with pytest.raises(ClientError) as exc:
+ cfn.describe_stack_drift_detection_status(StackDriftDetectionId=str(_uuid_mod.uuid4()))
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+
+
+def test_drift_refused_on_unstable_stack(cfn):
+ name = f"drift-failed-{_uuid_mod.uuid4().hex[:8]}"
+ template = {"Resources": {"Q": {"Type": "AWS::SQS::Queue"}, "Bad": _FAILING_RESOURCE}}
+ try:
+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(template),
+ DisableRollback=True)
+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_FAILED"
+ with pytest.raises(ClientError) as exc:
+ cfn.detect_stack_drift(StackName=name)
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+ assert "CREATE_FAILED" in exc.value.response["Error"]["Message"]
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
+def test_drift_property_readers_for_more_types(cfn, iam, lam, ddb, sns, s3):
+ name = f"drift-types-{_uuid_mod.uuid4().hex[:8]}"
+ template = {"Resources": {
+ "Role": {"Type": "AWS::IAM::Role", "Properties": {
+ "RoleName": f"{name}-role", "MaxSessionDuration": 3600,
+ "AssumeRolePolicyDocument": {"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"},
+ "Action": "sts:AssumeRole"}]}}},
+ "Fn": {"Type": "AWS::Lambda::Function", "Properties": {
+ "FunctionName": f"{name}-fn", "Runtime": "python3.12", "Handler": "index.handler",
+ "Role": {"Fn::GetAtt": ["Role", "Arn"]}, "Timeout": 10,
+ "Code": {"ZipFile": "def handler(e, c):\n return 1\n"},
+ "Environment": {"Variables": {"A": "1"}}}},
+ "Table": {"Type": "AWS::DynamoDB::Table", "Properties": {
+ "TableName": f"{name}-t", "BillingMode": "PROVISIONED",
+ "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
+ "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}}},
+ "Topic": {"Type": "AWS::SNS::Topic", "Properties": {
+ "TopicName": f"{name}-topic", "DisplayName": "before"}},
+ "Bucket": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": f"{name}-b"}},
+ }}
+ try:
+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(template),
+ Capabilities=["CAPABILITY_NAMED_IAM"])
+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ assert _detect(cfn, name)["StackDriftStatus"] == "IN_SYNC"
+ assert {d["StackResourceDriftStatus"] for d in _drifts(cfn, name).values()} == {"IN_SYNC"}
+
+ iam.update_role(RoleName=f"{name}-role", MaxSessionDuration=7200)
+ lam.update_function_configuration(FunctionName=f"{name}-fn", Timeout=20,
+ Environment={"Variables": {"A": "2"}})
+ ddb.update_table(TableName=f"{name}-t", ProvisionedThroughput={
+ "ReadCapacityUnits": 7, "WriteCapacityUnits": 5})
+ topic_arn = cfn.describe_stack_resource(StackName=name, LogicalResourceId="Topic")[
+ "StackResourceDetail"]["PhysicalResourceId"]
+ sns.set_topic_attributes(TopicArn=topic_arn, AttributeName="DisplayName",
+ AttributeValue="after")
+ s3.delete_bucket(Bucket=f"{name}-b")
+
+ status = _detect(cfn, name)
+ assert status["DriftedStackResourceCount"] == 5
+ drifts = _drifts(cfn, name)
+ paths = {lid: {(d["PropertyPath"], d["ExpectedValue"], d["ActualValue"])
+ for d in d_.get("PropertyDifferences", [])}
+ for lid, d_ in drifts.items()}
+ assert paths["Role"] == {("/MaxSessionDuration", "3600", "7200")}
+ assert paths["Fn"] == {("/Timeout", "10", "20"), ("/Environment/Variables/A", "1", "2")}
+ assert paths["Table"] == {("/ProvisionedThroughput/ReadCapacityUnits", "5", "7")}
+ assert paths["Topic"] == {("/DisplayName", "before", "after")}
+ assert drifts["Bucket"]["StackResourceDriftStatus"] == "DELETED"
+ finally:
+ try:
+ s3.create_bucket(Bucket=f"{name}-b")
+ except ClientError:
+ pass
+ _delete_cfn_test_stack(cfn, name)
+
+
+def test_describe_stack_resource_drifts_pagination(cfn):
+ name = f"drift-page-{_uuid_mod.uuid4().hex[:8]}"
+ resources = {
+ f"P{i}": {"Type": "AWS::SSM::Parameter", "Properties": {
+ "Name": f"/{name}/p{i}", "Type": "String", "Value": str(i)}}
+ for i in range(3)
+ }
+ try:
+ cfn.create_stack(StackName=name, TemplateBody=json.dumps({"Resources": resources}))
+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ _detect(cfn, name)
+ first = cfn.describe_stack_resource_drifts(StackName=name, MaxResults=2)
+ assert len(first["StackResourceDrifts"]) == 2
+ assert first.get("NextToken")
+ second = cfn.describe_stack_resource_drifts(StackName=name, MaxResults=2,
+ NextToken=first["NextToken"])
+ assert len(second["StackResourceDrifts"]) == 1
+ assert "NextToken" not in second
+ ids = {d["LogicalResourceId"] for d in
+ first["StackResourceDrifts"] + second["StackResourceDrifts"]}
+ assert ids == {"P0", "P1", "P2"}
+ with pytest.raises(ClientError) as exc:
+ cfn.describe_stack_resource_drifts(StackName=name, NextToken="ListStacks:1")
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+ finally:
+ _delete_cfn_test_stack(cfn, name)
diff --git a/tests/test_cfn_drift.py b/tests/test_cfn_drift.py
deleted file mode 100644
index aea4c5be..00000000
--- a/tests/test_cfn_drift.py
+++ /dev/null
@@ -1,459 +0,0 @@
-"""RollbackStack and stack drift detection (DetectStackDrift,
-DescribeStackDriftDetectionStatus, DetectStackResourceDrift,
-DescribeStackResourceDrifts, DriftInformation)."""
-
-import json
-import time
-import uuid
-
-import pytest
-from botocore.exceptions import ClientError
-
-_FAILING = {
- "Type": "AWS::CloudFormation::CustomResource",
- "Properties": {
- "ServiceToken": "arn:aws:lambda:us-east-1:000000000000:function:cfn-drift-does-not-exist",
- },
-}
-
-
-def _name(prefix):
- return f"{prefix}-{uuid.uuid4().hex[:8]}"
-
-
-def _wait(cfn, name, timeout=30):
- deadline = time.time() + timeout
- status = "UNKNOWN"
- while time.time() < deadline:
- try:
- stack = cfn.describe_stacks(StackName=name)["Stacks"][0]
- except ClientError as exc:
- if "does not exist" in str(exc):
- return {"StackStatus": "DELETE_COMPLETE"}
- raise
- status = stack["StackStatus"]
- if not status.endswith("_IN_PROGRESS"):
- return stack
- time.sleep(0.3)
- raise TimeoutError(f"{name} stuck at {status}")
-
-
-def _cleanup(cfn, name):
- try:
- cfn.delete_stack(StackName=name)
- _wait(cfn, name)
- except ClientError:
- pass
-
-
-def _statuses(cfn, name):
- events = cfn.describe_stack_events(StackName=name)["StackEvents"]
- return [(e["LogicalResourceId"], e["ResourceStatus"], e.get("ResourceStatusReason", ""))
- for e in reversed(events)]
-
-
-def _queue_exists(sqs, name):
- try:
- sqs.get_queue_url(QueueName=name)
- return True
- except ClientError:
- return False
-
-
-def _detect(cfn, name, **kwargs):
- detection_id = cfn.detect_stack_drift(StackName=name, **kwargs)["StackDriftDetectionId"]
- for _ in range(50):
- status = cfn.describe_stack_drift_detection_status(StackDriftDetectionId=detection_id)
- if status["DetectionStatus"] != "DETECTION_IN_PROGRESS":
- return status
- time.sleep(0.2)
- raise TimeoutError("drift detection did not finish")
-
-
-def _drifts(cfn, name, **kwargs):
- return {d["LogicalResourceId"]: d for d in
- cfn.describe_stack_resource_drifts(StackName=name, **kwargs)["StackResourceDrifts"]}
-
-
-# ---------------------------------------------------------------------------
-# RollbackStack
-# ---------------------------------------------------------------------------
-
-def test_rollback_stack_from_create_failed_deletes_what_the_create_made(cfn, sqs):
- name = _name("rb-create")
- queue = f"{name}-q"
- template = {"Resources": {
- "Q": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": queue}},
- "Bad": {**_FAILING, "DependsOn": "Q"},
- }}
- try:
- cfn.create_stack(StackName=name, TemplateBody=json.dumps(template),
- DisableRollback=True)
- assert _wait(cfn, name)["StackStatus"] == "CREATE_FAILED"
- assert _queue_exists(sqs, queue)
-
- stack_id = cfn.rollback_stack(StackName=name)["StackId"]
- assert stack_id.startswith("arn:aws:cloudformation:")
- assert _wait(cfn, name)["StackStatus"] == "ROLLBACK_COMPLETE"
- assert not _queue_exists(sqs, queue)
- events = _statuses(cfn, name)
- assert (name, "ROLLBACK_IN_PROGRESS", "User Initiated") in events
- assert ("Q", "DELETE_COMPLETE", "") in events
- assert events[-1][:2] == (name, "ROLLBACK_COMPLETE")
- assert cfn.describe_stack_resources(StackName=name)["StackResources"] == []
- finally:
- _cleanup(cfn, name)
-
-
-def test_rollback_stack_from_update_failed_restores_the_previous_stack(cfn, sqs, ssm):
- name = _name("rb-update")
- queue = f"{name}-q"
- added = f"{name}-added"
- param = f"/{name}/p"
-
- def template(visibility, value, extra):
- resources = {
- "Q": {"Type": "AWS::SQS::Queue",
- "Properties": {"QueueName": queue, "VisibilityTimeout": visibility}},
- "P": {"Type": "AWS::SSM::Parameter",
- "Properties": {"Name": param, "Type": "String", "Value": value}},
- }
- if extra:
- resources["Added"] = {"Type": "AWS::SQS::Queue",
- "Properties": {"QueueName": added}}
- resources["Bad"] = {**_FAILING, "DependsOn": ["P", "Q", "Added"]}
- return json.dumps({"Resources": resources})
-
- try:
- cfn.create_stack(StackName=name, TemplateBody=template(30, "v1", False))
- assert _wait(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
- cfn.update_stack(StackName=name, TemplateBody=template(60, "v2", True),
- DisableRollback=True)
- failed = _wait(cfn, name)
- assert failed["StackStatus"] == "UPDATE_FAILED"
- # DisableRollback kept the partial update in place.
- assert ssm.get_parameter(Name=param)["Parameter"]["Value"] == "v2"
- assert _queue_exists(sqs, added)
-
- cfn.rollback_stack(StackName=name)
- assert _wait(cfn, name)["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
- assert ssm.get_parameter(Name=param)["Parameter"]["Value"] == "v1"
- url = sqs.get_queue_url(QueueName=queue)["QueueUrl"]
- attrs = sqs.get_queue_attributes(QueueUrl=url, AttributeNames=["VisibilityTimeout"])
- assert attrs["Attributes"]["VisibilityTimeout"] == "30"
- assert not _queue_exists(sqs, added)
- body = cfn.get_template(StackName=name)["TemplateBody"]
- assert "Bad" not in json.dumps(body)
- listed = {r["LogicalResourceId"] for r in
- cfn.list_stack_resources(StackName=name)["StackResourceSummaries"]}
- assert listed == {"Q", "P"}
- statuses = [s for lid, s, _ in _statuses(cfn, name) if lid == name]
- assert statuses[-3:] == ["UPDATE_ROLLBACK_IN_PROGRESS",
- "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS",
- "UPDATE_ROLLBACK_COMPLETE"]
- finally:
- _cleanup(cfn, name)
-
-
-def test_rollback_stack_retain_except_on_create_deletes_retained_new_resources(cfn, sqs):
- name = _name("rb-retain")
- queue = f"{name}-q"
- template = {"Resources": {
- "Q": {"Type": "AWS::SQS::Queue", "DeletionPolicy": "Retain",
- "Properties": {"QueueName": queue}},
- "Bad": {**_FAILING, "DependsOn": "Q"},
- }}
- try:
- cfn.create_stack(StackName=name, TemplateBody=json.dumps(template),
- DisableRollback=True)
- assert _wait(cfn, name)["StackStatus"] == "CREATE_FAILED"
- cfn.rollback_stack(StackName=name, RetainExceptOnCreate=True)
- assert _wait(cfn, name)["StackStatus"] == "ROLLBACK_COMPLETE"
- assert not _queue_exists(sqs, queue)
- finally:
- _cleanup(cfn, name)
-
-
-def test_rollback_stack_wrong_state_and_missing_stack(cfn):
- name = _name("rb-wrong")
- try:
- cfn.create_stack(StackName=name, TemplateBody=json.dumps(
- {"Resources": {"Q": {"Type": "AWS::SQS::Queue"}}}))
- assert _wait(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
- with pytest.raises(ClientError) as exc:
- cfn.rollback_stack(StackName=name)
- assert exc.value.response["Error"]["Code"] == "ValidationError"
- assert "cannot be called from current stack status" in exc.value.response["Error"]["Message"]
- with pytest.raises(ClientError) as exc:
- cfn.rollback_stack(StackName=_name("rb-missing"))
- assert exc.value.response["Error"]["Code"] == "ValidationError"
- assert "does not exist" in exc.value.response["Error"]["Message"]
- finally:
- _cleanup(cfn, name)
-
-
-# ---------------------------------------------------------------------------
-# Drift detection
-# ---------------------------------------------------------------------------
-
-def _drift_template(name):
- return json.dumps({"Resources": {
- "Q": {"Type": "AWS::SQS::Queue", "Properties": {
- "QueueName": f"{name}-q", "VisibilityTimeout": 45,
- "Tags": [{"Key": "team", "Value": "a"}]}},
- "P": {"Type": "AWS::SSM::Parameter", "Properties": {
- "Name": f"/{name}/p", "Type": "String", "Value": "expected"}},
- # No drift reader for queue policies: NOT_CHECKED.
- "Policy": {"Type": "AWS::SQS::QueuePolicy", "Properties": {
- "Queues": [{"Ref": "Q"}],
- "PolicyDocument": {"Version": "2012-10-17", "Statement": [{
- "Effect": "Allow", "Principal": "*", "Action": "sqs:SendMessage",
- "Resource": "*"}]}}},
- }})
-
-
-def drift_stack(cfn):
- name = _name("drift")
- cfn.create_stack(StackName=name, TemplateBody=_drift_template(name),
- Tags=[{"Key": "env", "Value": "test"}])
- assert _wait(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
- yield name
- _cleanup(cfn, name)
-
-
-def test_drift_in_sync_after_create(cfn, drift_stack):
- name = drift_stack
- stack = cfn.describe_stacks(StackName=name)["Stacks"][0]
- assert stack["DriftInformation"] == {"StackDriftStatus": "NOT_CHECKED"}
- summary = next(s for s in cfn.list_stacks()["StackSummaries"] if s["StackName"] == name)
- assert summary["DriftInformation"]["StackDriftStatus"] == "NOT_CHECKED"
-
- status = _detect(cfn, name)
- assert status["DetectionStatus"] == "DETECTION_COMPLETE"
- assert status["StackDriftStatus"] == "IN_SYNC"
- assert status["DriftedStackResourceCount"] == 0
- assert status["StackId"] == stack["StackId"]
-
- drifts = _drifts(cfn, name)
- # Only the checked resources are listed; the queue policy has no support.
- assert set(drifts) == {"Q", "P"}
- q = drifts["Q"]
- assert q["StackResourceDriftStatus"] == "IN_SYNC"
- assert json.loads(q["ExpectedProperties"]) == json.loads(q["ActualProperties"])
- # The stack-level tag is part of the expected tags; aws: tags are not.
- assert json.loads(q["ExpectedProperties"])["Tags"] == [
- {"Key": "team", "Value": "a"}, {"Key": "env", "Value": "test"}]
- assert "PropertyDifferences" not in q or q["PropertyDifferences"] == []
-
- after = cfn.describe_stacks(StackName=name)["Stacks"][0]["DriftInformation"]
- assert after["StackDriftStatus"] == "IN_SYNC"
- assert "LastCheckTimestamp" in after
- resources = {r["LogicalResourceId"]: r["DriftInformation"]
- for r in cfn.describe_stack_resources(StackName=name)["StackResources"]}
- assert resources["Q"]["StackResourceDriftStatus"] == "IN_SYNC"
- assert "LastCheckTimestamp" in resources["Q"]
- assert resources["Policy"] == {"StackResourceDriftStatus": "NOT_CHECKED"}
- summaries = {r["LogicalResourceId"]: r["DriftInformation"]
- for r in cfn.list_stack_resources(StackName=name)["StackResourceSummaries"]}
- assert summaries["P"]["StackResourceDriftStatus"] == "IN_SYNC"
- detail = cfn.describe_stack_resource(StackName=name, LogicalResourceId="Policy")
- assert detail["StackResourceDetail"]["DriftInformation"]["StackResourceDriftStatus"] == "NOT_CHECKED"
-
-
-def test_drift_modified_after_out_of_band_changes(cfn, sqs, ssm, drift_stack):
- name = drift_stack
- url = sqs.get_queue_url(QueueName=f"{name}-q")["QueueUrl"]
- sqs.set_queue_attributes(QueueUrl=url, Attributes={"VisibilityTimeout": "99"})
- sqs.tag_queue(QueueUrl=url, Tags={"added": "x"})
- ssm.put_parameter(Name=f"/{name}/p", Value="changed", Type="String", Overwrite=True)
-
- status = _detect(cfn, name)
- assert status["StackDriftStatus"] == "DRIFTED"
- assert status["DriftedStackResourceCount"] == 2
-
- drifts = _drifts(cfn, name)
- q = drifts["Q"]
- assert q["StackResourceDriftStatus"] == "MODIFIED"
- diffs = {d["PropertyPath"]: d for d in q["PropertyDifferences"]}
- assert diffs["/VisibilityTimeout"] == {
- "PropertyPath": "/VisibilityTimeout", "ExpectedValue": "45",
- "ActualValue": "99", "DifferenceType": "NOT_EQUAL"}
- added = [d for d in q["PropertyDifferences"] if d["DifferenceType"] == "ADD"]
- assert len(added) == 1 and added[0]["PropertyPath"].startswith("/Tags/")
- assert json.loads(added[0]["ActualValue"]) == {"Key": "added", "Value": "x"}
- assert json.loads(q["ActualProperties"])["VisibilityTimeout"] == 99
- assert json.loads(q["ExpectedProperties"])["VisibilityTimeout"] == 45
-
- p = drifts["P"]
- assert p["StackResourceDriftStatus"] == "MODIFIED"
- assert p["PropertyDifferences"] == [{
- "PropertyPath": "/Value", "ExpectedValue": "expected",
- "ActualValue": "changed", "DifferenceType": "NOT_EQUAL"}]
-
- assert cfn.describe_stacks(StackName=name)["Stacks"][0]["DriftInformation"][
- "StackDriftStatus"] == "DRIFTED"
- modified = _drifts(cfn, name, StackResourceDriftStatusFilters=["MODIFIED"])
- assert set(modified) == {"Q", "P"}
- assert _drifts(cfn, name, StackResourceDriftStatusFilters=["IN_SYNC", "DELETED"]) == {}
- assert _drifts(cfn, name, StackResourceDriftStatusFilters=["NOT_CHECKED"]) == {}
-
-
-def test_drift_removed_tag_is_reported_as_remove(cfn, sqs, drift_stack):
- name = drift_stack
- url = sqs.get_queue_url(QueueName=f"{name}-q")["QueueUrl"]
- sqs.untag_queue(QueueUrl=url, TagKeys=["team"])
- drift = cfn.detect_stack_resource_drift(StackName=name, LogicalResourceId="Q")[
- "StackResourceDrift"]
- assert drift["StackResourceDriftStatus"] == "MODIFIED"
- assert drift["PropertyDifferences"] == [{
- "PropertyPath": "/Tags/0", "ExpectedValue": json.dumps(
- {"Key": "team", "Value": "a"}, sort_keys=True),
- "ActualValue": "null", "DifferenceType": "REMOVE"}]
-
-
-def test_drift_deleted_after_out_of_band_delete(cfn, sqs, drift_stack):
- name = drift_stack
- url = sqs.get_queue_url(QueueName=f"{name}-q")["QueueUrl"]
- sqs.delete_queue(QueueUrl=url)
-
- drift = cfn.detect_stack_resource_drift(StackName=name, LogicalResourceId="Q")[
- "StackResourceDrift"]
- assert drift["StackResourceDriftStatus"] == "DELETED"
- assert "ExpectedProperties" not in drift and "ActualProperties" not in drift
- assert drift["PhysicalResourceId"] == url
- # A single-resource check moves the stack's LastCheckTimestamp only.
- info = cfn.describe_stacks(StackName=name)["Stacks"][0]["DriftInformation"]
- assert info["StackDriftStatus"] == "NOT_CHECKED" and "LastCheckTimestamp" in info
- assert set(_drifts(cfn, name, StackResourceDriftStatusFilters=["DELETED"])) == {"Q"}
-
- status = _detect(cfn, name)
- assert status["StackDriftStatus"] == "DRIFTED"
- assert status["DriftedStackResourceCount"] == 1
-
-
-def test_drift_logical_resource_ids_filter(cfn, ssm, drift_stack):
- name = drift_stack
- ssm.put_parameter(Name=f"/{name}/p", Value="changed", Type="String", Overwrite=True)
- status = _detect(cfn, name, LogicalResourceIds=["Q"])
- assert status["StackDriftStatus"] == "IN_SYNC"
- assert set(_drifts(cfn, name)) == {"Q"}
- with pytest.raises(ClientError) as exc:
- cfn.detect_stack_drift(StackName=name, LogicalResourceIds=["Nope"])
- assert exc.value.response["Error"]["Code"] == "ValidationError"
-
-
-def test_drift_unsupported_type_and_missing_resource(cfn, drift_stack):
- name = drift_stack
- with pytest.raises(ClientError) as exc:
- cfn.detect_stack_resource_drift(StackName=name, LogicalResourceId="Policy")
- assert exc.value.response["Error"]["Code"] == "ValidationError"
- assert "AWS::SQS::QueuePolicy" in exc.value.response["Error"]["Message"]
- with pytest.raises(ClientError) as exc:
- cfn.detect_stack_resource_drift(StackName=name, LogicalResourceId="Nope")
- assert exc.value.response["Error"]["Code"] == "ValidationError"
- with pytest.raises(ClientError) as exc:
- cfn.describe_stack_drift_detection_status(StackDriftDetectionId=str(uuid.uuid4()))
- assert exc.value.response["Error"]["Code"] == "ValidationError"
-
-
-def test_drift_refused_on_unstable_stack(cfn):
- name = _name("drift-failed")
- template = {"Resources": {"Q": {"Type": "AWS::SQS::Queue"}, "Bad": _FAILING}}
- try:
- cfn.create_stack(StackName=name, TemplateBody=json.dumps(template),
- DisableRollback=True)
- assert _wait(cfn, name)["StackStatus"] == "CREATE_FAILED"
- with pytest.raises(ClientError) as exc:
- cfn.detect_stack_drift(StackName=name)
- assert exc.value.response["Error"]["Code"] == "ValidationError"
- assert "CREATE_FAILED" in exc.value.response["Error"]["Message"]
- finally:
- _cleanup(cfn, name)
-
-
-def test_drift_property_readers_for_more_types(cfn, iam, lam, ddb, sns, s3):
- name = _name("drift-types")
- template = {"Resources": {
- "Role": {"Type": "AWS::IAM::Role", "Properties": {
- "RoleName": f"{name}-role", "MaxSessionDuration": 3600,
- "AssumeRolePolicyDocument": {"Version": "2012-10-17", "Statement": [{
- "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"},
- "Action": "sts:AssumeRole"}]}}},
- "Fn": {"Type": "AWS::Lambda::Function", "Properties": {
- "FunctionName": f"{name}-fn", "Runtime": "python3.12", "Handler": "index.handler",
- "Role": {"Fn::GetAtt": ["Role", "Arn"]}, "Timeout": 10,
- "Code": {"ZipFile": "def handler(e, c):\n return 1\n"},
- "Environment": {"Variables": {"A": "1"}}}},
- "Table": {"Type": "AWS::DynamoDB::Table", "Properties": {
- "TableName": f"{name}-t", "BillingMode": "PROVISIONED",
- "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
- "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
- "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}}},
- "Topic": {"Type": "AWS::SNS::Topic", "Properties": {
- "TopicName": f"{name}-topic", "DisplayName": "before"}},
- "Bucket": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": f"{name}-b"}},
- }}
- try:
- cfn.create_stack(StackName=name, TemplateBody=json.dumps(template),
- Capabilities=["CAPABILITY_NAMED_IAM"])
- assert _wait(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
- assert _detect(cfn, name)["StackDriftStatus"] == "IN_SYNC"
- assert {d["StackResourceDriftStatus"] for d in _drifts(cfn, name).values()} == {"IN_SYNC"}
-
- iam.update_role(RoleName=f"{name}-role", MaxSessionDuration=7200)
- lam.update_function_configuration(FunctionName=f"{name}-fn", Timeout=20,
- Environment={"Variables": {"A": "2"}})
- ddb.update_table(TableName=f"{name}-t", ProvisionedThroughput={
- "ReadCapacityUnits": 7, "WriteCapacityUnits": 5})
- topic_arn = cfn.describe_stack_resource(StackName=name, LogicalResourceId="Topic")[
- "StackResourceDetail"]["PhysicalResourceId"]
- sns.set_topic_attributes(TopicArn=topic_arn, AttributeName="DisplayName",
- AttributeValue="after")
- s3.delete_bucket(Bucket=f"{name}-b")
-
- status = _detect(cfn, name)
- assert status["DriftedStackResourceCount"] == 5
- drifts = _drifts(cfn, name)
- paths = {lid: {(d["PropertyPath"], d["ExpectedValue"], d["ActualValue"])
- for d in d_.get("PropertyDifferences", [])}
- for lid, d_ in drifts.items()}
- assert paths["Role"] == {("/MaxSessionDuration", "3600", "7200")}
- assert paths["Fn"] == {("/Timeout", "10", "20"), ("/Environment/Variables/A", "1", "2")}
- assert paths["Table"] == {("/ProvisionedThroughput/ReadCapacityUnits", "5", "7")}
- assert paths["Topic"] == {("/DisplayName", "before", "after")}
- assert drifts["Bucket"]["StackResourceDriftStatus"] == "DELETED"
- finally:
- try:
- s3.create_bucket(Bucket=f"{name}-b")
- except ClientError:
- pass
- _cleanup(cfn, name)
-
-
-def test_describe_stack_resource_drifts_pagination(cfn):
- name = _name("drift-page")
- resources = {
- f"P{i}": {"Type": "AWS::SSM::Parameter", "Properties": {
- "Name": f"/{name}/p{i}", "Type": "String", "Value": str(i)}}
- for i in range(3)
- }
- try:
- cfn.create_stack(StackName=name, TemplateBody=json.dumps({"Resources": resources}))
- assert _wait(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
- _detect(cfn, name)
- first = cfn.describe_stack_resource_drifts(StackName=name, MaxResults=2)
- assert len(first["StackResourceDrifts"]) == 2
- assert first.get("NextToken")
- second = cfn.describe_stack_resource_drifts(StackName=name, MaxResults=2,
- NextToken=first["NextToken"])
- assert len(second["StackResourceDrifts"]) == 1
- assert "NextToken" not in second
- ids = {d["LogicalResourceId"] for d in
- first["StackResourceDrifts"] + second["StackResourceDrifts"]}
- assert ids == {"P0", "P1", "P2"}
- with pytest.raises(ClientError) as exc:
- cfn.describe_stack_resource_drifts(StackName=name, NextToken="ListStacks:1")
- assert exc.value.response["Error"]["Code"] == "ValidationError"
- finally:
- _cleanup(cfn, name)
diff --git a/tests/test_cloudwatch_logs.py b/tests/test_cloudwatch_logs.py
index 0a170466..6e5228be 100644
--- a/tests/test_cloudwatch_logs.py
+++ b/tests/test_cloudwatch_logs.py
@@ -1042,6 +1042,55 @@ def test_logs_put_resource_policy_rejects_stale_revision(logs):
logs.delete_resource_policy(policyName=name)
+def test_logs_resource_scoped_policy_lives_on_its_log_group(logs):
+ uid = _uuid_mod.uuid4().hex[:8]
+ group = f"/intg/resource-policy/{uid}"
+ logs.create_log_group(logGroupName=group)
+ arn = logs.describe_log_groups(logGroupNamePrefix=group)["logGroups"][0]["arn"]
+ try:
+ with pytest.raises(ClientError) as exc:
+ logs.put_resource_policy(policyName="p", policyDocument="{}",
+ resourceArn=arn.replace(uid, "missing"))
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+ first = logs.put_resource_policy(policyName="p", policyDocument="{}", resourceArn=arn)
+ assert first["resourcePolicy"]["policyScope"] == "RESOURCE"
+ with pytest.raises(ClientError) as exc: # a second write needs the current revision
+ logs.put_resource_policy(policyName="p", policyDocument="{}", resourceArn=arn)
+ assert exc.value.response["Error"]["Code"] == "OperationAbortedException"
+ second = logs.put_resource_policy(policyName="p", policyDocument="{}", resourceArn=arn,
+ expectedRevisionId=first["revisionId"])
+
+ assert all(p["policyScope"] == "ACCOUNT"
+ for p in logs.describe_resource_policies()["resourcePolicies"])
+ listed = logs.describe_resource_policies(resourceArn=arn)["resourcePolicies"]
+ assert [p["revisionId"] for p in listed] == [second["revisionId"]]
+ scoped = logs.describe_resource_policies(policyScope="RESOURCE")["resourcePolicies"]
+ assert any(p.get("resourceArn") == arn for p in scoped)
+
+ logs.delete_resource_policy(policyName="p", resourceArn=arn,
+ expectedRevisionId=second["revisionId"])
+ assert logs.describe_resource_policies(resourceArn=arn)["resourcePolicies"] == []
+ finally:
+ logs.delete_log_group(logGroupName=group)
+
+
+def test_logs_account_resource_policies_are_limited_to_ten(logs):
+ existing = len(logs.describe_resource_policies()["resourcePolicies"])
+ uid = _uuid_mod.uuid4().hex[:8]
+ created = [f"intg-limit-{uid}-{i}" for i in range(10 - existing)]
+ try:
+ for name in created:
+ logs.put_resource_policy(policyName=name, policyDocument="{}")
+ with pytest.raises(ClientError) as exc:
+ logs.put_resource_policy(policyName=f"intg-limit-{uid}-over", policyDocument="{}")
+ assert exc.value.response["Error"]["Code"] == "LimitExceededException"
+ finally:
+ for name in created:
+ logs.delete_resource_policy(policyName=name)
+
+
# ---------------------------------------------------------------------------
# ARN-based tagging operations (TagResource / UntagResource)
# ---------------------------------------------------------------------------
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index bf66a9ea..dedc4b1e 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -2215,7 +2215,7 @@ class TestBedrockAgentCoreAuthorization:
_OTHER_RUNTIME_ARN = "arn:aws:bedrock-agentcore:us-east-1:000000000000:runtime/rt-other"
@staticmethod
- def _invoke(path, monkeypatch, policy):
+ def _invoke(path, monkeypatch, policy, query=None):
import asyncio
import ministack.app as app_mod
@@ -2249,29 +2249,43 @@ class TestBedrockAgentCoreAuthorization:
"20260101/eu-central-1/", "20260101/us-east-1/"
)
response = asyncio.run(
- app_mod._dispatch_service_request("POST", path, headers, b"{}", {}, "req-agentcore")
+ app_mod._dispatch_service_request("POST", path, headers, b"{}", query or {}, "req-agentcore")
)
return response, seen
def test_invoke_allows_the_exact_runtime_resource(self, monkeypatch):
path = "/runtimes/" + self._RUNTIME_ARN.replace(":", "%3A").replace("/", "%2F") + "/invocations"
+ endpoint = self._RUNTIME_ARN + "/runtime-endpoint/DEFAULT"
response, seen = self._invoke(
path,
monkeypatch,
{"Statement": [{
"Effect": "Allow",
"Action": "bedrock-agentcore:InvokeAgentRuntime",
- "Resource": self._RUNTIME_ARN,
+ "Resource": [self._RUNTIME_ARN, endpoint],
}]},
)
assert response[0] == 200
- assert seen == [(
- "bedrock-agentcore:InvokeAgentRuntime",
- "bedrock-agentcore",
- "us-east-1",
- self._RUNTIME_ARN,
- )]
+ assert [arn for *_, arn in seen] == [self._RUNTIME_ARN, endpoint]
+
+ @pytest.mark.parametrize("query,endpoint_name", [({}, "DEFAULT"), ({"qualifier": ["prod"]}, "prod")])
+ def test_invoke_also_needs_the_runtime_endpoint(self, monkeypatch, query, endpoint_name):
+ """runtime and runtime-endpoint are both required resources of InvokeAgentRuntime."""
+ path = "/runtimes/" + self._RUNTIME_ARN.replace(":", "%3A").replace("/", "%2F") + "/invocations"
+ response, seen = self._invoke(
+ path,
+ monkeypatch,
+ {"Statement": [{
+ "Effect": "Allow",
+ "Action": "bedrock-agentcore:InvokeAgentRuntime",
+ "Resource": self._RUNTIME_ARN,
+ }]},
+ query,
+ )
+
+ assert response[0] == 403
+ assert seen[-1][3] == f"{self._RUNTIME_ARN}/runtime-endpoint/{endpoint_name}"
def test_invoke_denies_a_different_runtime_resource(self, monkeypatch):
path = "/runtimes/" + self._OTHER_RUNTIME_ARN.replace(":", "%3A").replace("/", "%2F") + "/invocations"