Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
prerelease v1.5.22 (#2016)
Nahuel Nucera64315af312b9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 82a5d305..27b0c496 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,18 +9,19 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added-- **Bedrock AgentCore — Memory data plane** — the `bedrock-agentcore` data-plane endpoint now serves the short-term Memory event log (`CreateEvent` with generated session ids and `clientToken` replay, `GetEvent`, `ListEvents` with branch, parent-branch and metadata filters and `includePayloads`, `DeleteEvent`) plus `ListActors` and `ListSessions`, the long-term record store (`BatchCreateMemoryRecords`, `BatchUpdateMemoryRecords`, `BatchDeleteMemoryRecords` with per-record success/failure results, `GetMemoryRecord`, `ListMemoryRecords` with namespace, strategy and metadata filters, `DeleteMemoryRecord`), `RetrieveMemoryRecords`, and the extraction-job registry (`StartMemoryExtractionJob`, `ListMemoryExtractionJobs`). Extraction behind memory strategies still does not run, and with no embeddings `RetrieveMemoryRecords` scores records by the share of query word tokens present in the record text. Shapes, paths and id patterns verified against botocore `bedrock-agentcore`; not validated against AWS. Contributed by @pingedbrain.+- **Bedrock AgentCore — Memory data plane** — the `bedrock-agentcore` data-plane endpoint now serves the short-term Memory event log (`CreateEvent` with generated session ids and `clientToken` replay, `GetEvent`, `ListEvents` with branch, parent-branch and metadata filters and `includePayloads`, `DeleteEvent`) plus `ListActors` and `ListSessions`, the long-term record store (`BatchCreateMemoryRecords`, `BatchUpdateMemoryRecords`, `BatchDeleteMemoryRecords` with per-record success/failure results, `GetMemoryRecord`, `ListMemoryRecords` with namespace, strategy and metadata filters, `DeleteMemoryRecord`), `RetrieveMemoryRecords`, `StartMemoryExtractionJob` and `ListMemoryExtractionJobs`. Extraction behind memory strategies still does not run, so no extraction job ever fails: `ListMemoryExtractionJobs` is empty and `StartMemoryExtractionJob` answers `ResourceNotFoundException`. A memory ARN from another account is refused with `AccessDeniedException` under `AUTH=true`, since Memory takes no resource policy. With no embeddings, `RetrieveMemoryRecords` scores records by the share of query word tokens present in the record text. Shapes, paths and id patterns verified against botocore `bedrock-agentcore`; not validated against AWS. Contributed by @pingedbrain.- **AWS Budgets** — `CreateBudget` (inline `NotificationsWithSubscribers` and `ResourceTags`), `DescribeBudget`, `DescribeBudgets`, `UpdateBudget`, `DeleteBudget`, `CreateNotification`, `UpdateNotification`, `DeleteNotification`, `DescribeNotificationsForBudget`, `CreateSubscriber`, `UpdateSubscriber`, `DeleteSubscriber`, `DescribeSubscribersForNotification`, `TagResource`, `UntagResource`, `ListTagsForResource`. Global (account-scoped, no region) JSON 1.1 service; a new or updated budget reports zero `CalculatedSpend.ActualSpend` and no `ForecastedSpend` rather than an invented number; an omitted `TimePeriod.Start` defaults to the start of the budget's `TimeUnit` period and an omitted `End` to `06/15/87 00:00 UTC`, and an omitted notification `ThresholdType` defaults to `PERCENTAGE`, as AWS does; the 10-notification/budget and 11-subscriber/notification quotas are enforced (`CreationLimitExceededException`); deleting a notification's last subscriber deletes the notification, matching AWS. Budget Actions (RI/Savings Plans auto-remediation) and `DescribeBudgetPerformanceHistory` are out of scope.### Fixed+- **Cognito — app client secret hashes** — clients created with `GenerateSecret=true` require a valid `SecretHash` on signup, confirmation and password recovery, and `SECRET_HASH` on authentication and challenge responses. Missing or incorrect hashes return `NotAuthorizedException` before user changes, email delivery or Lambda triggers. Clients without a secret reject a supplied hash on self-service and initial authentication calls, while refresh and challenge responses ignore it, as on AWS. Refresh authentication verifies the token owner's username, or `sub` when the pool uses `UsernameAttributes`, and custom challenge sessions cannot be answered through a different client. The checks apply under `AUTH=true`.- **Bedrock — foundation model agreement offers** — `ListFoundationModelAgreementOffers` always returned an empty `offers` list, so there was no `offerToken` to pass to `CreateFoundationModelAgreement`. It now returns one offer for third-party models (Amazon models have none), and `CreateFoundationModelAgreement` requires `offerToken` and answers `ResourceNotFoundException` for an unknown model. `GetFoundationModelAvailability` reports a third-party model's `agreementAvailability` as `AVAILABLE` only while an agreement exists, so the Terraform/OpenTofu `aws_bedrock_foundation_model_agreement` resource can be destroyed. Reported by @wparad.- **RDS — MySQL instances apply their DB parameter group** — a group's parameters were stored but never reached the server. A MySQL or MariaDB instance now starts with its group's set parameters as server options; `ModifyDBParameterGroup` with `ApplyMethod=immediate` applies dynamic parameters to running instances (`SET GLOBAL`), and `ResetDBParameterGroup` returns them to the engine default; an `immediate` change to a static parameter is refused with `InvalidParameterCombination`, as AWS refuses it, when a running instance uses the group (MiniStack has no parameter list, so with none it is stored); a `pending-reboot` change reports `ParameterApplyStatus: pending-reboot` until the instance next starts. Names and values are not validated against the engine's parameter list, and formula values (`{DBInstanceClassMemory*3/4}`) are not evaluated. Contributed by @skialpine.- **API Gateway — `GetApiKeys` filters by `nameQuery`** — `GetApiKeys` ignored `nameQuery` and returned all the API keys, so a lookup by name could get the wrong key. It now returns only the keys whose names start with `nameQuery`.- **RDS — creating an existing parameter group is refused** — `CreateDBParameterGroup` and `CreateDBClusterParameterGroup` with a name already in use replaced the group with an empty one, dropping its parameters; they now return `DBParameterGroupAlreadyExists`, as AWS does. Contributed by @skialpine.- **RDS — a backup retention period of 0 turns binary logging off** — on RDS for MySQL, `BackupRetentionPeriod=0` turns binary logging off; MiniStack's MySQL 8.0/8.4 instances kept the image default, binary logging on. Such an instance now starts with binary logging off. Contributed by @skialpine.- **IoT — `CreateThingGroup` on an existing name returns the group when nothing differs** — a repeated `CreateThingGroup` always failed with `ResourceAlreadyExistsException`. It now returns the existing group's name, ARN and id when the description, attributes (in any order), parent and tags match, and answers 409 with AWS's message otherwise, leaving the group unchanged, as AWS does. An `AWS::IoT::ThingGroup` that names an existing group still fails its stack, with or without matching properties, now with AWS's name-conflict message. Contributed by @iot-rocket.-- **IoT — just-in-time registration under a CA in `SNI_ONLY` mode** — a device certificate signed by a CA registered with `certificateMode` `SNI_ONLY` and auto-registration enabled was refused on its first mTLS connect, so only `DEFAULT` CAs auto-registered. Such a CA now registers the certificate `PENDING_ACTIVATION` and publishes the registered event when the device's TLS ClientHello names the account's endpoint (its DescribeEndpoint prefix in any region) or a host the gateway serves (`localhost`, a compose service name, `MINISTACK_HOST`), and does nothing without a server name. Under a `DEFAULT` CA, a server name with another account's endpoint prefix or a name the gateway does not serve (`mqtt.example.com`) no longer auto-registers, as on AWS. Contributed by @iot-rocket.+- **IoT — just-in-time registration under a CA in `SNI_ONLY` mode** — a device certificate signed by a CA registered with `certificateMode` `SNI_ONLY` and auto-registration enabled was refused on its first mTLS connect, so only `DEFAULT` CAs auto-registered. Such a CA now registers the certificate `PENDING_ACTIVATION` and publishes the registered event when the device's TLS ClientHello carries a server name, and does nothing without one. Under either mode, an endpoint name with another account's prefix auto-registers nothing. Contributed by @iot-rocket.- **IoT — `RegisterCertificate` links the CA that signed the certificate** — a certificate registered without `caCertificatePem` carried no `caCertificateId`, even when a registered ACTIVE CA had signed it, so `DescribeCertificate` named no CA and `ListCertificatesByCA` left it out. It is now linked to that CA, as AWS does; when several registered CAs share a subject, the signature decides. Contributed by @iot-rocket.- **IoT — a CONTINUOUS job runs again for a thing that rejoins its target group** — executions were kept one per thing and job, so a thing that finished the job, left the group and was added back never got another execution. Joining a target group now queues the next execution number when the thing's newest execution is finished, leaving the group moves a QUEUED execution to `REMOVED`, both publish `jobs/notify(-next)`, the `notify-next` execution leaves out `thingName` and an empty `statusDetails`, and `ListJobExecutionsForThing`, `DescribeJobExecution` with `executionNumber` and `jobProcessDetails` include the earlier executions, as AWS does. Contributed by @iot-rocket.@@ -35,6 +36,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **RDS — `ModifyDBInstance` settings that are not pending modifications apply immediately** — without `ApplyImmediately`, `DeletionProtection`, `CopyTagsToSnapshot`, `PreferredBackupWindow`, `PreferredMaintenanceWindow`, `PubliclyAccessible`, `MaxAllocatedStorage`, `MonitoringInterval` and `MonitoringRoleArn` were queued in `PendingModifiedValues`, which has no such members, and never applied. They now apply at once on every instance. Contributed by @AdrianAcala.- **ALB — repeated HTTP target response headers** — forwards every `Set-Cookie` as a separate header, preserving cookie attributes and repeated fields even when their names use different casing; previously only the first value survived.- **Aurora DSQL — the 8-key index limit comes first** — measured live, DSQL reports `54011` before the mode, key-expression and `INCLUDE` rules; the proxy reported those first, so a plain `CREATE INDEX` on nine columns drew "unsupported mode". `sys.jobs.details` is now NULL for a job that succeeded, where it was an empty string. Contributed by @vivedo.- **Aurora DSQL — `CALL sys.wait_for_job($1)` with a bound job id** — a job id bound as a parameter over the extended protocol went through to the backing Postgres and failed `3F000` schema "sys" does not exist, after the index had been built. Bound job ids now work for `sys.wait_for_job` and for `sys.jobs ... WHERE job_id = $1`, and `CALL` answers the procedure's `succeeded` column with the `CALL` tag, as measured on the live service (eu-central-1, 2026-10-04); a malformed id is refused `22P02`. `CREATE INDEX ASYNC` and `ALTER TABLE ASYNC` answer the `CREATE INDEX` / `ALTER TABLE` tags, `sys.jobs` declares its `oid` and `timestamptz` columns, a constraint validation job carries `class_id` 2606, and a unique index that fails on duplicates reports the service's `details`. Contributed by @vivedo.@@ -45,7 +47,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **API Gateway v2 — JWT claims reach a Lambda as strings** — `requestContext.authorizer.jwt.claims` holds every claim as a string, as on AWS: numbers as digits, booleans as `true`/`false` and arrays as their items in brackets, e.g. `[admin dev]`. Typed event models (for example `aws_lambda_events` in Rust, or Go's `map[string]string`) parse the event.- **Lambda — throttle `retryAfterSeconds` is a string** — a `TooManyRequestsException` returns `retryAfterSeconds` as a string, as the Lambda API model declares, so SDK clients such as the AWS SDK for Rust parse the response as a throttle.- **Step Functions — `States.TaskFailed` no longer matches `States.Timeout`** — a `Retry` or `Catch` on `States.TaskFailed` also matched a timeout, so a state machine retried or caught a timeout where AWS does not. `States.TaskFailed` now matches every error except `States.Timeout`, as the Step Functions error handling guide describes.-- **Cognito — `/oauth2/token` refreshes tokens issued by the API** — the `refresh_token` grant answered `invalid_grant` for a refresh token from `InitiateAuth`, `AdminInitiateAuth`, `RespondToAuthChallenge` or a federated sign-in, because it only knew the ones its own Hosted UI code flow issues. It now validates such a token as `REFRESH_TOKEN_AUTH` does, so a revoked or signed-out token, or one issued to another app client, is still refused with `invalid_grant`, and returns a new ID token and access token. A wrong client secret answers `invalid_client`. Contributed by @Pintouch.+- **Cognito — `/oauth2/token` refreshes tokens issued by the API** — the `refresh_token` grant answered `invalid_grant` for a refresh token from `InitiateAuth`, `AdminInitiateAuth`, `RespondToAuthChallenge` or a federated sign-in, because it only knew the ones its own Hosted UI code flow issues. It now validates such a token as `REFRESH_TOKEN_AUTH` does, so a revoked or signed-out token, or one issued to another app client, is still refused with `invalid_grant`, and returns a new ID token and access token. A missing or wrong client secret, or an unknown client, answers `invalid_client`. Contributed by @Pintouch.- **AppConfig — predefined deployment strategies** — `AppConfig.AllAtOnce`, `AppConfig.Linear50PercentEvery30Seconds`, `AppConfig.Canary10Percent20Minutes` and `AppConfig.Linear20PercentEvery6Minutes` now exist in every account and region and cannot be updated or deleted, as on AWS. A deployment records its strategy's parameters, and `StartDeployment` and `AWS::AppConfig::Deployment` fail with `ResourceNotFoundException` for a strategy that does not exist, where they used to accept any id. Contributed by @koh-sh.- **RDS — standalone deletion protection and snapshot-tag settings apply immediately** — `ModifyDBInstance` now applies `DeletionProtection` and `CopyTagsToSnapshot` regardless of `ApplyImmediately`, returning the active values without adding these fields to `PendingModifiedValues`. Omitted settings keep their existing values.- **OpenSearch — data-plane containers are named per account** — a domain's container was named `ministack-opensearch-<region>-<domain>`, so a second account creating a domain of the same name (including an account on another MiniStack sharing the Docker daemon) failed with a Docker name conflict, and the failed create's cleanup removed containers by that name. The names now carry an account and region hash, as RDS's do. Contributed by @skialpine.@@ -58,13 +60,14 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **OpenSearch Serverless — collections, security and access policies, and a proxied data plane** — `CreateCollection`, `BatchGetCollection`, `ListCollections`, `UpdateCollection`, `DeleteCollection`, `Create`/`Get`/`Update`/`Delete`/`ListSecurityPolicy` (`encryption`, `network`), `Create`/`Get`/`Update`/`Delete`/`ListAccessPolicy` (`data`), `GetPoliciesStats` and `TagResource` / `UntagResource` / `ListTagsForResource`, enough for Terraform's `aws_opensearchserverless_collection`, `_security_policy` and `_access_policy` to apply, plan clean and destroy. A collection needs a matching encryption policy (exact name or `prefix*`, most specific wins) unless `encryptionConfig` is given, and answers `kmsKeyArn: auto` for an AWS-owned key; policy documents are validated, a resource pattern may sit in only one encryption policy, a data policy refuses empty or wildcard principals, and an update must name the current `policyVersion` (`base64("<lastModifiedDate>_<n>")`). Its `collectionEndpoint`, `http://<id>.<region>.aoss.<host>:<port>`, is served through the gateway and requests must be SigV4-signed for `aoss` and carry `x-amz-content-sha256` (403 otherwise); with `OPENSEARCH_DATAPLANE=1` it is backed by its own `opensearchproject/opensearch` container, persisted on a named Docker volume across a restart under `PERSIST_STATE` and removed on `DeleteCollection`, otherwise it answers 503. APIs AOSS does not support answer 404, as `_refresh`, `_cluster/*` and scroll do on AWS, and `TIMESERIES` collections refuse custom document ids and updates. Data access and network policies are stored, not enforced. Checked against the botocore model and the OpenSearch Serverless developer guide and API reference.### Fixed++- **RDS — the MySQL master user gets the privileges AWS gives it** — the master user was granted `ALL PRIVILEGES`, including `SUPER` and `SYSTEM_VARIABLES_ADMIN`, so `SET GLOBAL` and `SET PERSIST` worked where RDS denies them, and an instance started in the background (engine image not cached yet, or respawned on restore) got no global grant at all. Every start path now grants the privileges in the RDS and Aurora master user tables for the engine and version, `WITH GRANT OPTION`. Contributed by @skialpine.+- **Lambda — a timed-out invocation reports `Sandbox.Timedout`** — a function that ran past its `Timeout` returned `errorType` `Runtime.ExitError`, so a Step Functions `Retry` or `Catch` on `Sandbox.Timedout` never matched, and the execution failed where it recovers on AWS. All executors now return `Sandbox.Timedout` with the message `Task timed out after N.00 seconds`, as the Lambda and Step Functions error-handling docs describe. A runtime that exits before it responds still reports `Runtime.ExitError`.- **Step Functions — `TimeoutSeconds` applies to Lambda and service integration tasks** — only `.waitForTaskToken` tasks used `TimeoutSeconds`; a Lambda or service integration task ran to the end, so a `Retry` or `Catch` on `States.Timeout` never ran. Such a task now fails with `States.Timeout` when it runs longer than `TimeoutSeconds`, as the Step Functions Task state reference describes. Activity tasks and `TimeoutSecondsPath` do not change.- **Step Functions — `States.TaskFailed` no longer matches `States.Timeout`** — a `Retry` or `Catch` on `States.TaskFailed` also matched a timeout, so a state machine retried or caught a timeout where AWS does not. `States.TaskFailed` now matches every error except `States.Timeout`, as the Step Functions error handling guide describes.-- **ElastiCache — serverless caches run in cluster mode** — AWS serves a serverless cache as a cluster-mode cache, so a multi-key command whose keys hash to different slots fails with `CROSSSLOT`; MiniStack's container ran without cluster mode and accepted it, so such code passed locally and failed on AWS. The container now runs as one cluster-mode shard holding every slot, and `CLUSTER SLOTS` reports the cache's endpoint, as AWS's single virtual shard does. Contributed by @skialpine.- **CloudTrail — `PutEventSelectors` stores `AdvancedEventSelectors` and sets `HasCustomEventSelectors`** — advanced selectors are now stored and returned in place of `EventSelectors` instead of being dropped, a request with both kinds, neither, or an empty or oversized list fails with `InvalidEventSelectorsException`, basic selectors read back with their omitted members filled in, and `GetTrail` and `DescribeTrails` report `HasCustomEventSelectors: true` while a trail has selectors other than the default one. Contributed by @iot-rocket.- **CloudTrail — `GetEventSelectors` returns the default selector of a new trail** — a trail that never had `PutEventSelectors` answered an empty `EventSelectors` list instead of the default selector that logs all read and write management events. Contributed by @iot-rocket.-- **CloudTrail — `GetEventSelectors` returns the default selector of a new trail** — a trail that never had `PutEventSelectors` answered an empty `EventSelectors` list instead of the default selector that logs all read and write management events. Contributed by @iot-rocket.- **STS — `GetAccessKeyInfo` answers the account that owns the key** — it returned the caller's account whatever `AccessKeyId` said; it now returns the owning account for keys the emulator knows (its root key, IAM access keys and STS sessions), the account encoded in any other `AKIA` or `ASIA` key id as AWS does, and a `ValidationError` for an id that encodes no account or breaks the parameter's length and pattern constraints. Contributed by @iot-rocket.- **STS — `GetAccessKeyInfo` is authorized like other actions** — under `AUTH=true` it was allowed like `GetCallerIdentity` and `GetSessionToken`, whatever the caller's policies said. It now needs an identity policy that allows it and no deny, and otherwise answers `AccessDenied`, as AWS does; the other two stay allowed. Contributed by @iot-rocket.- **API Gateway v2 (WebSocket API) — `$connect` with `AWS_IAM`** — an unsigned handshake is refused with 403 `Missing Authentication Token`, and under `AUTH=true` the caller needs `execute-api:Invoke` on `arn:aws:execute-api:<region>:<account>:<api-id>/<stage>/$connect`. Contributed by @iot-rocket.@@ -117,10 +120,6 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **CloudFormation — `Fn::Select` in a condition** — a condition such as `!Not [!Equals [!Select [2, !Ref KeySpec], ""]]` was always true; conditions now resolve `Fn::Select`, and an index outside the list fails with `Template error: Fn::Select cannot select nonexistent value at index N`, in conditions and in properties. Contributed by @mishukdutta-cz.- **CloudFormation — `Ref` to a list parameter** — a `Ref` to a `CommaDelimitedList` or `List<...>` parameter gave the raw string, so a list property got one item per character; it now gives the space-trimmed list. A list in a nested stack's `Parameters` or in an `AWS::SSM::Parameter` `Value` fails the resource. Contributed by @mishukdutta-cz.-### Fixed--- **Lambda — a timed-out invocation reports `Sandbox.Timedout`** — a function that ran past its `Timeout` returned `errorType` `Runtime.ExitError`, so a Step Functions `Retry` or `Catch` on `Sandbox.Timedout` never matched, and the execution failed where it recovers on AWS. All executors now return `Sandbox.Timedout` with the message `Task timed out after N.00 seconds`, as the Lambda and Step Functions error-handling docs describe. A runtime that exits before it responds still reports `Runtime.ExitError`.-## [1.5.20] — 2026-10-01### Addeddiff --git a/ministack/app.py b/ministack/app.pyindex 4a2a77d9..826b32ca 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -2125,7 +2125,8 @@ def _enforce_data_plane(return access_denied_response(service, iam_action, "", request_id, error_code=denied.code, message=denied.message, headers=headers)- return access_denied_response(service, iam_action, denied.principal_arn, request_id, headers=headers)+ return access_denied_response(service, iam_action, denied.principal_arn, request_id, headers=headers,+ explicit_deny=denied.decision == "Deny")return Nonediff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex 46a1f19f..ed449932 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -1767,10 +1767,11 @@ def access_denied_response(service: str, action: str, principal_arn: str,json.dumps({"__type": "AccessDeniedException", "Message": message}).encode(),)if not message:- message = (- f"User: {principal_arn} is not authorized to perform: {action} "- f"because no identity-based policy allows the {action} action"+ reason = (+ "with an explicit deny in an identity-based policy" if explicit_deny+ else f"because no identity-based policy allows the {action} action")+ message = f"User: {principal_arn} is not authorized to perform: {action} {reason}"code = error_code or "AccessDenied"protocol = _SERVICE_PROTOCOL.get(service, "json")if service in _CBOR_CAPABLE:diff --git a/ministack/core/pgproxy.py b/ministack/core/pgproxy.pyindex 6f9270fa..66ea64ef 100644--- a/ministack/core/pgproxy.py+++ b/ministack/core/pgproxy.py@@ -2317,7 +2317,8 @@ async def _ext_describe(conn, payload, b_writer, c_writer):returnout = b""if target == b"S":- nparams = entry["synth"][1].get("nparams", 0)+ kind, result = entry["synth"]+ nparams = result.get("nparams", 0) if kind == "rows" else 0out += _frame( # ParameterDescription: every placeholder is textb"t", struct.pack("!H", nparams) + struct.pack("!I", 25) * nparams)diff --git a/ministack/services/alb.py b/ministack/services/alb.pyindex 13134612..804e4617 100644--- a/ministack/services/alb.py+++ b/ministack/services/alb.py@@ -1814,7 +1814,7 @@ async def _invoke_lambda_target(function_ref, tg_arn, method, path, headers, bodresp_code = int(result.get("statusCode", 200))out_headers = dict(result.get("headers") or {})for k, vals in (result.get("multiValueHeaders") or {}).items():- out_headers[k] = vals[-1]+ out_headers[k] = vals[0] if len(vals) == 1 else valsout_body = result.get("body", "")if result.get("isBase64Encoded"):diff --git a/ministack/services/bedrock_agentcore.py b/ministack/services/bedrock_agentcore.pyindex 93539171..d14250e6 100644--- a/ministack/services/bedrock_agentcore.py+++ b/ministack/services/bedrock_agentcore.py@@ -76,7 +76,6 @@ _resource_policies = AccountRegionScopedDict() # resource ARN -> policy string_memories = AccountRegionScopedDict() # memoryId -> memory record_memory_events = AccountRegionScopedDict() # memoryId -> {actorId -> {sessionId -> session}}_memory_records = AccountRegionScopedDict() # memoryId -> {memoryRecordId -> record}-_extraction_jobs = AccountRegionScopedDict() # memoryId -> [job metadata]_containers = {} # (account, region, runtime id, version) -> Docker container_container_lock = threading.RLock()@@ -93,7 +92,6 @@ def get_state():"memories": _memories,"memoryEvents": _memory_events,"memoryRecords": _memory_records,- "extractionJobs": _extraction_jobs,})@@ -110,14 +108,12 @@ def _restore_state(data):_memories.clear()_memory_events.clear()_memory_records.clear()- _extraction_jobs.clear()_runtimes.update(data.get("runtimes", {}))_endpoints.update(data.get("endpoints", {}))_resource_policies.update(data.get("resourcePolicies", {}))_memories.update(data.get("memories", {}))_memory_events.update(data.get("memoryEvents", {}))_memory_records.update(data.get("memoryRecords", {}))- _extraction_jobs.update(data.get("extractionJobs", {}))_migrate_legacy_arns()# Backfill one snapshot for state written before version history existed.for runtime in _runtimes._data.values():@@ -160,7 +156,6 @@ def reset():_memories.clear()_memory_events.clear()_memory_records.clear()- _extraction_jobs.clear()# ---------------------------------------------------------------------------@@ -566,7 +561,6 @@ def _delete_memory(memory_id):return _not_found(f"Memory '{memory_id}' not found")_memory_events.pop(memory_id, None)_memory_records.pop(memory_id, None)- _extraction_jobs.pop(memory_id, None)return json_response({"memoryId": memory_id, "status": "DELETING"}, 202)@@ -606,6 +600,12 @@ def _resolve_memory(raw_id):scope = Noneif ":memory/" in memory_id:scope = _arn_owner(memory_id)+ from ministack.app import AUTH+ if AUTH and scope and scope[0] != get_account_id():+ # Memory takes no resource policy, so no other account is granted.+ return None, None, error_response_json(+ "AccessDeniedException",+ f"User is not authorized to access memory {memory_id}", 403)memory_id = memory_id.rsplit(":memory/", 1)[1]if not _MEMORY_ID_RE.fullmatch(memory_id):return None, None, _validation(@@ -667,11 +667,11 @@ def _create_event(raw_memory_id, body):for session in sessions.values():for existing in session["events"]:if existing.get("_clientToken") == token:- return json_response({"event": _public_event(existing)})+ return json_response({"event": _public_event(existing)}, 201)session = bucket.setdefault(actor_id, {}).get(session_id)if session is None:- session = {"createdAt": time.time(), "nextSeq": 0, "events": []}+ session = {"createdAt": int(time.time()), "nextSeq": 0, "events": []}bucket[actor_id][session_id] = sessionsession["nextSeq"] += 1event = {@@ -691,7 +691,7 @@ def _create_event(raw_memory_id, body):event["_clientToken"] = tokensession["events"].append(event)_mem_set(_memory_events, memory_id, scope, bucket)- return json_response({"event": _public_event(event)})+ return json_response({"event": _public_event(event)}, 201)def _find_event(memory_id, scope, actor_id, session_id, event_id):@@ -1021,7 +1021,7 @@ def _batch_create_memory_records(raw_memory_id, body):succeeded.append(_batch_result(record_id, "SUCCEEDED", request_id))_mem_set(_memory_records, memory_id, scope, bucket)return json_response(- {"successfulRecords": succeeded, "failedRecords": failed})+ {"successfulRecords": succeeded, "failedRecords": failed}, 201)def _batch_update_memory_records(raw_memory_id, body):@@ -1094,34 +1094,23 @@ def _batch_delete_memory_records(raw_memory_id, body):{"successfulRecords": succeeded, "failedRecords": failed})-def _find_memory_record(memory_id, scope, record_id, namespace=None):- record = _records_bucket(memory_id, scope).get(record_id)- if record is None:- return None- if namespace and namespace not in (record.get("namespaces") or []):- return None- return record---def _get_memory_record(raw_memory_id, record_id, query_params):+def _get_memory_record(raw_memory_id, record_id):memory_id, scope, error = _resolve_memory(raw_memory_id)if error:return errorrecord_id = unquote(record_id)- namespace = _agentcore_query_value(query_params, "namespace")- record = _find_memory_record(memory_id, scope, record_id, namespace)+ record = _records_bucket(memory_id, scope).get(record_id)if record is None:return _not_found(f"Memory record '{record_id}' not found")return json_response({"memoryRecord": _record_summary(record)})-def _delete_memory_record(raw_memory_id, record_id, query_params):+def _delete_memory_record(raw_memory_id, record_id):memory_id, scope, error = _resolve_memory(raw_memory_id)if error:return errorrecord_id = unquote(record_id)- namespace = _agentcore_query_value(query_params, "namespace")- record = _find_memory_record(memory_id, scope, record_id, namespace)+ record = _records_bucket(memory_id, scope).get(record_id)if record is None:return _not_found(f"Memory record '{record_id}' not found")bucket = dict(_records_bucket(memory_id, scope))@@ -1199,58 +1188,30 @@ def _retrieve_memory_records(raw_memory_id, body):})-# --- extraction jobs (registry only; extraction itself does not run) ----------def _jobs_bucket(memory_id, scope):- return _mem_get(_extraction_jobs, memory_id, scope, [])-+# --- extraction jobs: extraction never runs, so no job is ever eligible ------def _start_extraction_job(raw_memory_id, body):- memory_id, scope, error = _resolve_memory(raw_memory_id)+ _memory_id, _scope, error = _resolve_memory(raw_memory_id)if error:return error- data = _parse_body(body)- job = data.get("extractionJob")- job_id = (job or {}).get("jobId") if isinstance(job, dict) else None+ job = _parse_body(body).get("extractionJob")+ job_id = job.get("jobId") if isinstance(job, dict) else Noneif not isinstance(job_id, str) or not job_id:return _validation("extractionJob.jobId is required")- jobs = list(_jobs_bucket(memory_id, scope))- if not any(existing["jobID"] == job_id for existing in jobs):- jobs.append({"jobID": job_id, "status": "COMPLETED",- "messages": {"messagesList": []}})- _mem_set(_extraction_jobs, memory_id, scope, jobs)- return json_response({"jobId": job_id})+ return _not_found(f"Extraction job '{job_id}' not found")def _list_extraction_jobs(raw_memory_id, body):- memory_id, scope, error = _resolve_memory(raw_memory_id)+ _memory_id, _scope, error = _resolve_memory(raw_memory_id)if error:return error- data = _parse_body(body)- filters = data.get("filter") or {}- items = []- for job in _jobs_bucket(memory_id, scope):- if filters.get("status") and job.get("status") != filters["status"]:- continue- if filters.get("strategyId") and \- job.get("strategyId") != filters["strategyId"]:- continue- if filters.get("sessionId") and \- job.get("sessionId") != filters["sessionId"]:- continue- if filters.get("actorId") and job.get("actorId") != filters["actorId"]:- continue- items.append(copy.deepcopy(job))- page, error = _memory_page(items, data)+ page, error = _memory_page([], _parse_body(body))if error:return error- return json_response({- "jobs": page["items"],- **({"nextToken": page["nextToken"]} if "nextToken" in page else {}),- })+ return json_response({"jobs": page["items"]})-def _memory_data_plane(method, rest, body, query_params):+def _memory_data_plane(method, rest, body):"""Dispatch ``/memories/...`` data-plane paths; None when not a match.``memoryId`` and ``actorId`` may carry literal ``/`` (an ARN and the@@ -1313,12 +1274,12 @@ def _memory_data_plane(method, rest, body, query_params):if "/memoryRecord/" in rest:memory_id, _, record_id = rest.partition("/memoryRecord/")if "/" not in record_id and method == "GET":- return _get_memory_record(memory_id, record_id, query_params)+ return _get_memory_record(memory_id, record_id)return Noneif "/memoryRecords/" in rest:memory_id, _, record_id = rest.partition("/memoryRecords/")if "/" not in record_id and method == "DELETE":- return _delete_memory_record(memory_id, record_id, query_params)+ return _delete_memory_record(memory_id, record_id)return Nonereturn None@@ -2054,7 +2015,7 @@ async def handle_request(method, path, headers, body, query_params):return _create_memory(body)if inner.startswith("memories/"):rest = inner[len("memories/"):]- response = _memory_data_plane(method, rest, body, query_params)+ response = _memory_data_plane(method, rest, body)if response is not None:return responsememory_id, _, op = unquote(rest).rpartition("/")diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex 8a448690..aceb5f60 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -2269,7 +2269,7 @@ _SECRET_HASH_PARAMETERS = {def _validate_client_secret_hash(action: str, data: dict):"""Authenticate confidential app clients before user changes or triggers.- This is Cognito's app-client contract, independent of IAM's AUTH flag.+ Enforced under AUTH=true.Refresh authentication uses the token owner's username (or sub for aUsernameAttributes pool), rather than the alias used at initial sign-in."""@@ -2340,7 +2340,8 @@ def _validate_client_secret_hash(action: str, data: dict):def _run_idp_handler(handler, action: str, data: dict):if action in _UNSIGNED_IDP_ACTIONS:_pin_unsigned_idp_scope(data)- error = _validate_client_secret_hash(action, data)+ from ministack.app import AUTH+ error = _validate_client_secret_hash(action, data) if AUTH else Noneif error:return errorreturn handler(data)@@ -2859,7 +2860,7 @@ def _get_ui_customization(data):if err:return errui = pool.get("_ui_customizations", {})- return json_response({"UICustomization": ui.get(cid) or ui.get("ALL") or {"UserPoolId": pool["Id"], "ClientId": cid}})+ return json_response({"UICustomization": ui.get(cid) or ui.get("ALL") or {}})# ---------------------------------------------------------------------------@@ -6457,7 +6458,7 @@ def _oauth2_refresh_api_issued_token(refresh_val: str, cid: str, csec: str):"""Refresh tokens minted by InitiateAuth / RespondToAuthChallenge never enter``_refresh_tokens`` (that registry only holds Hosted UI grants), yet AWS acceptsthem at /oauth2/token. Validate them with the REFRESH_TOKEN_AUTH core, and the- client secret as the registry branch does."""+ client as the authorization_code branch does."""try:claims = _decode_id_token_unverified(refresh_val)except ValueError:@@ -6470,7 +6471,7 @@ def _oauth2_refresh_api_issued_token(refresh_val: str, cid: str, csec: str):return _oauth2_error("invalid_grant", "Invalid refresh token.")client_id = cid or str(claims.get("client_id", ""))_, _, client = _find_pool_by_client_id(client_id)- if client and client.get("ClientSecret") and csec and csec != client["ClientSecret"]:+ if not client or (client.get("ClientSecret") and csec != client["ClientSecret"]):return _oauth2_error("invalid_client", "Invalid client credentials.")result, err = _refresh_auth_result(pool, pid, client_id, refresh_val)if err:diff --git a/ministack/services/eks.py b/ministack/services/eks.pyindex 08587694..7812562f 100644--- a/ministack/services/eks.py+++ b/ministack/services/eks.py@@ -430,6 +430,7 @@ def _k3s_run_kwargs(ms_network: str | None = None,oidc_args: list[str] | None = None,node_labels: list[str] | None = None,+ account_id: str | None = None,) -> dict:"""Build the docker run kwargs for a k3s server container.@@ -451,6 +452,7 @@ def _k3s_run_kwargs(command.extend(oidc_args)if node_labels:command.extend(node_labels)+ account_id = account_id or get_account_id()run_kwargs = dict(image=apply_image_prefix(EKS_K3S_IMAGE),@@ -468,8 +470,8 @@ def _k3s_run_kwargs(security_opt=["seccomp=unconfined", "apparmor=unconfined"],devices=["/dev/fuse"],ports={"6443/tcp": port},- name=f"ministack-eks-{region}-{name}",- labels=container_reaper.own_labels("eks", cluster_name=name, region=region),+ name=f"ministack-eks-{account_id}-{region}-{name}",+ labels=container_reaper.own_labels("eks", cluster_name=name, region=region, account_id=account_id),environment={"K3S_KUBECONFIG_MODE": "644"},volumes={"/lib/modules": {"bind": "/lib/modules", "mode": "ro"}},tmpfs={"/run": "", "/var/run": "", "/tmp": ""},@@ -755,6 +757,7 @@ def _create_cluster(body, creator_arn=None):ms_network=ms_network,oidc_args=oidc_args,node_labels=node_labels,+ account_id=account_id,)registries_yaml = _k3s_registries_yaml(client, ms_network, _ecr_registry_hosts(cluster))@@ -1804,6 +1807,7 @@ def _restart_k3s(cluster_name, oidc_args=None, idp_cfg_refs=None):cluster["_docker_id"] = Nonems_network = _get_ministack_network(client)+ cluster_spec = parse_arn(cluster.get("arn", ""))run_kwargs = _k3s_run_kwargs(name=cluster_name,region=region,@@ -1811,10 +1815,10 @@ def _restart_k3s(cluster_name, oidc_args=None, idp_cfg_refs=None):ms_network=ms_network,oidc_args=oidc_args,node_labels=node_labels,+ account_id=cluster_spec.account_id,)registries_yaml = _k3s_registries_yaml(client, ms_network, _ecr_registry_hosts(cluster))- cluster_spec = parse_arn(cluster.get("arn", ""))# A restart reuses the cluster's token; one minted here would not# match the URL k3s was given, and the restored record carries it.cluster.setdefault("_auth_token", secrets.token_urlsafe(32))diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex f1ec016a..95e7e84b 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -85,7 +85,6 @@ from ministack.core.responses import (new_uuid,request_scope,)-from ministack.core.router import _host_served_by_stackfrom ministack.core.x509_utils import (certificate_is_signed_by,generate_ca,@@ -1747,7 +1746,7 @@ def _list_certificates_by_ca(path: str, qp: dict) -> tuple:page_size = int(page_size)except ValueError:return error_response_json(- "InvalidRequestException", "pageSize must be an integer", 400+ "InvalidRequestException", "The request is not valid.", 400)if page_size < 1:errors.append(@@ -8636,30 +8635,18 @@ def _mtls_resolve_identity(der: bytes | None) -> tuple[str, str] | None:def _mtls_server_name_reaches(server_name: str, account_id: str) -> bool:- """Whether a device that sent ``server_name`` as its SNI dialled ``account_id``'s endpoint.-- On AWS the endpoint prefix names the account: ``<prefix>-ats.iot.<region>...``- reaches it whichever region the name carries, while another account's- prefix, or any name that is not an IoT endpoint (``example.com``,- ``ministack``), auto-registers nothing, whatever the CA mode. Here a name- of a shape DescribeEndpoint hands out (``<prefix>-ats.iot.`` or- ``<prefix>.credentials.iot.``, under any suffix) counts only with this- account's prefix, and any other name counts when the gateway serves it- (``_host_served_by_stack``: ``localhost``, a compose service name,- ``MINISTACK_HOST``, any two-label alias, so ``example.com`` too), since- those are the names devices dial an emulator by.+ """Whether a device that sent ``server_name`` as its SNI may reach ``account_id``.++ An endpoint-shaped name (``<prefix>-ats.iot.`` or ``<prefix>.credentials.iot.``)+ counts only with this account's prefix; any other name counts."""name = server_name.lower().rstrip(".")first, _, rest = name.partition(".")if first.endswith("-ats") and rest.startswith("iot."):- prefix = first[: -len("-ats")]- elif rest.startswith("credentials.iot."):- prefix = first- else:- prefix = None- if prefix is not None and prefix != _endpoint_prefix(account_id):- return False- return _host_served_by_stack(name)+ return first[: -len("-ats")] == _endpoint_prefix(account_id)+ if rest.startswith("credentials.iot."):+ return first == _endpoint_prefix(account_id)+ return Truedef _mtls_auto_registering_ca(diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 162d2c5f..ac91c6e8 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -5278,7 +5278,7 @@ def _execute_function_warm(func: dict, event: dict) -> dict:else:error_msg = result.get("error", "Unknown error")error_type = "Runtime.HandlerError"- if "timed out" in error_msg.lower():+ if _RIE_TIMEOUT_TEXT_RE.fullmatch(error_msg):error_type = "Sandbox.Timedout"return {"body": {@@ -5370,7 +5370,7 @@ def _execute_function_provided_warm(func: dict, event: dict,if isinstance(payload, dict):return {"body": payload, "error": True, "log": result.get("log", "")}error_msg = result.get("error", "Unknown error")- error_type = ("Sandbox.Timedout" if "timed out" in error_msg.lower()+ error_type = ("Sandbox.Timedout" if _RIE_TIMEOUT_TEXT_RE.fullmatch(error_msg)else "Runtime.HandlerError")return {"body": {"errorMessage": error_msg, "errorType": error_type},diff --git a/ministack/services/mwaa.py b/ministack/services/mwaa.pyindex b02ff988..6f9dc2c3 100644--- a/ministack/services/mwaa.py+++ b/ministack/services/mwaa.py@@ -344,13 +344,13 @@ def _start_airflow_container_in_scope(account_id, region, env_name, env):container_env[f"AIRFLOW__{env_key}"] = valuetry:- container_name = f"ministack-mwaa-{region}-{env_name}"- legacy_container_name = f"ministack-mwaa-{env_name}"+ container_name = f"ministack-mwaa-{account_id}-{region}-{env_name}"+ legacy_container_names = (f"ministack-mwaa-{region}-{env_name}", f"ministack-mwaa-{env_name}")- # Remove stale current and pre-regional containers before binding the- # environment's host port. A container left by the previous naming- # scheme can otherwise survive an upgrade and block the regional one.- for stale_name in (container_name, legacy_container_name):+ # Remove stale current and earlier-scheme containers before binding the+ # environment's host port. A container left by a previous naming+ # scheme can otherwise survive an upgrade and block the current one.+ for stale_name in (container_name, *legacy_container_names):try:existing = docker_client.containers.get(stale_name)existing.remove(force=True, v=True)@@ -364,7 +364,7 @@ def _start_airflow_container_in_scope(account_id, region, env_name, env):environment=container_env,ports={f"{container_port}/tcp": host_port},name=container_name,- labels=container_reaper.own_labels("mwaa", region=region, env_name=env_name),+ labels=container_reaper.own_labels("mwaa", region=region, env_name=env_name, account_id=account_id),)if ms_network:diff --git a/ministack/services/rds.py b/ministack/services/rds.pyindex b3790b4e..117a5b07 100644--- a/ministack/services/rds.py+++ b/ministack/services/rds.py@@ -895,6 +895,7 @@ def _restore_state(data, *, resume_runtime=False):cluster.get("MasterUsername", "admin"),cluster.get("_MasterUserPassword", "password"),cluster_id,+ cluster.get("Engine", ""),)cluster["_shared_container_ready"] = authenticated_readyif authenticated_ready and _aurora_mysql_8_replication_enabled(@@ -2544,7 +2545,7 @@ def _start_rds_container_for_instance(db_id, instance):return_grant_mysql_master_user_privileges(internal_host or "127.0.0.1", internal_port or host_port,- master_user, master_pass, db_id,+ master_user, master_pass, db_id, engine,)_instance_available_unless_stopped(instance)logger.info("RDS: respawned container %s for instance %s",@@ -2626,17 +2627,12 @@ def _is_mysql_engine(engine):return any(e in engine for e in ("mysql", "aurora-mysql", "mariadb"))-# A DB parameter group name that is also a server variable (RDS-only names such-# as `rds.force_ssl` are not).+# Excludes RDS-only names such as `rds.force_ssl`._MYSQL_SERVER_PARAMETER = re.compile(r"[A-Za-z0-9_]+")def _mysql_server_options(backup_retention_period, param_group_name=None):- """Server options for a standalone MySQL/MariaDB instance, as RDS starts one:- a backup retention period of 0 turns binary logging off, and the instance's- DB parameter group's set values are server options. `--loose-` keeps a name- the server does not know as a startup option (such as `time_zone`) from- stopping it; formula values (`{DBInstanceClassMemory*3/4}`) are not evaluated."""+ """Startup options: retention 0 disables the binlog; group values go as `--loose-` options."""options = [] if int(backup_retention_period) > 0 else ["--skip-log-bin"]group = _param_groups.get(param_group_name) if param_group_name else Nonefor name, param in ((group or {}).get("Parameters") or {}).items():@@ -2657,15 +2653,7 @@ def _mysql_parameter_value(value):def _apply_parameter_group_changes(group_name, changes, refuse_static=True):- """Apply `(name, value, apply_method)` changes to the running MySQL instances- in a DB parameter group, as RDS does: an `immediate` change to a dynamic- parameter takes effect now (a `None` value resets it to the engine default);- a `pending-reboot` change leaves the instance `pending-reboot` until the next- start, which applies the whole group (`_mysql_server_options`). An `immediate`- change to a static parameter, which the server reports as a read-only- variable, is refused as AWS refuses it, before anything is applied; with- `refuse_static=False` (a reset) it is left pending-reboot instead. Returns- the refusal, or None."""+ """Apply `(name, value, apply_method)` changes to the group's running MySQL instances; returns a refusal or None."""for instance in list(_instances.values()):groups = instance.get("DBParameterGroups") or []if not (@@ -3867,8 +3855,39 @@ def _configure_or_defer_mysql_replication(cluster_id, cluster):_schedule_mysql_replication_retry(cluster_id, cluster)-def _grant_mysql_master_user_privileges(host, port, master_user, master_pass, db_id):- """Grant the emulated MySQL master user AWS/RDS-like admin privileges."""+_MYSQL_MASTER_PRIVILEGES = (+ "SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, PROCESS, REFERENCES, "+ "INDEX, ALTER, SHOW DATABASES, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, "+ "REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, "+ "ALTER ROUTINE, CREATE USER, EVENT, TRIGGER"+)+_AURORA_MYSQL_3_MASTER_PRIVILEGES = (+ "CREATE ROLE", "DROP ROLE", "APPLICATION_PASSWORD_ADMIN", "CONNECTION_ADMIN",+ "ROLE_ADMIN", "XA_RECOVER_ADMIN", "SHOW_ROUTINE", "FLUSH_OPTIMIZER_COSTS",+ "FLUSH_STATUS", "FLUSH_TABLES", "FLUSH_USER_RESOURCES",+)+++def _mysql_master_extra_privileges(engine, server_version):+ """Master-user privileges beyond _MYSQL_MASTER_PRIVILEGES, per the RDS and Aurora master user tables."""+ version = tuple(int(n) for n in re.findall(r"\d+", server_version)[:3])+ if "mariadb" in server_version.lower():+ return ("SHOW CREATE ROUTINE",) if version >= (11, 4) else ()+ if engine.startswith("aurora"):+ if version < (8,):+ return ("LOAD FROM S3", "SELECT INTO S3")+ if version >= (8, 4):+ return _AURORA_MYSQL_3_MASTER_PRIVILEGES + (+ "ALLOW_NONEXISTENT_DEFINER", "FLUSH_PRIVILEGES", "OPTIMIZE_LOCAL_TABLE", "SET_ANY_DEFINER")+ return _AURORA_MYSQL_3_MASTER_PRIVILEGES + ("SET_USER_ID",)+ if version >= (8, 0, 36):+ return ("CREATE ROLE", "DROP ROLE", "APPLICATION_PASSWORD_ADMIN", "ROLE_ADMIN",+ "SET_USER_ID", "XA_RECOVER_ADMIN")+ return ()+++def _grant_mysql_master_user_privileges(host, port, master_user, master_pass, db_id, engine=""):+ """Grant the emulated MySQL master user the privileges AWS gives it, and no others."""try:import pymysqlconn = pymysql.connect(@@ -3879,13 +3898,17 @@ def _grant_mysql_master_user_privileges(host, port, master_user, master_pass, db"CREATE USER IF NOT EXISTS %s@'%%' IDENTIFIED BY %s",(master_user, master_pass),)+ if master_user != "root":+ cur.execute("REVOKE ALL PRIVILEGES, GRANT OPTION FROM %s@'%%'", (master_user,))cur.execute(- "GRANT ALL PRIVILEGES ON *.* TO %s@'%%' WITH GRANT OPTION",+ f"GRANT {_MYSQL_MASTER_PRIVILEGES} ON *.* TO %s@'%%' WITH GRANT OPTION",(master_user,),)- for privilege in ("APPLICATION_PASSWORD_ADMIN",):+ cur.execute("SELECT VERSION()")+ server_version = cur.fetchone()[0]+ for privilege in _mysql_master_extra_privileges(engine or "", server_version):try:- cur.execute(f"GRANT {privilege} ON *.* TO %s@'%%'", (master_user,))+ cur.execute(f"GRANT {privilege} ON *.* TO %s@'%%' WITH GRANT OPTION", (master_user,))except Exception as e:logger.debug("RDS: MySQL privilege %s unsupported for %s: %s",@@ -5187,7 +5210,7 @@ def _create_db_instance_impl(p):_grant_mysql_master_user_privileges(ready_host, ready_port, master_user,cluster.get("_MasterUserPassword", master_pass),- cluster_id,+ cluster_id, engine,)cluster["_shared_container_ready"] = Trueif _aurora_mysql_8_replication_enabled(cluster):@@ -5228,7 +5251,7 @@ def _create_db_instance_impl(p):if _is_mysql_engine(engine):_grant_mysql_master_user_privileges(ready_host, ready_port, master_user, master_pass,- cluster_id or db_id,+ cluster_id or db_id, engine,)inst = _instances.get(db_id)if inst is not None:@@ -5446,6 +5469,12 @@ def _rotate_instance_password(instance, old_pass, new_pass):db_id, e)+_IMMEDIATE_INSTANCE_SETTINGS = frozenset({+ "DeletionProtection", "CopyTagsToSnapshot", "PreferredBackupWindow", "PreferredMaintenanceWindow",+ "PubliclyAccessible", "MaxAllocatedStorage", "MonitoringInterval", "MonitoringRoleArn",+})++def _modify_db_instance(p):db_id = _p(p, "DBInstanceIdentifier")instance = _resolve_instance(db_id)@@ -5477,11 +5506,6 @@ def _modify_db_instance(p):return engine_version_errorapply_immediately = _p(p, "ApplyImmediately") == "true"- standalone = not (- instance.get("DBClusterIdentifier")- or instance.get("_shared_cluster_id")- or instance.get("Engine", "").startswith("aurora")- )field_map = {"DBInstanceClass": "DBInstanceClass",@@ -5522,11 +5546,8 @@ def _modify_db_instance(p):"CopyTagsToSnapshot", "EnableIAMDatabaseAuthentication"):val = val == "true"- # These standalone settings take effect immediately and never enter- # PendingModifiedValues, regardless of ApplyImmediately (RDS settings).- if apply_immediately or (- standalone and param_key in ("DeletionProtection", "CopyTagsToSnapshot")- ):+ # Not PendingModifiedValues members: AWS applies these whatever ApplyImmediately says.+ if apply_immediately or param_key in _IMMEDIATE_INSTANCE_SETTINGS:instance[instance_key] = valelse:pending[instance_key] = val@@ -7274,7 +7295,7 @@ def _start_db_cluster(p):_grant_mysql_master_user_privileges(ready_host, ready_port, master_user,cluster.get("_MasterUserPassword", master_pass),- cluster_id,+ cluster_id, engine,)cluster["_shared_container_ready"] = Trueif _aurora_mysql_8_replication_enabled(cluster):diff --git a/ministack/services/secretsmanager.py b/ministack/services/secretsmanager.pyindex 6ff02885..c3a72fcb 100644--- a/ministack/services/secretsmanager.py+++ b/ministack/services/secretsmanager.py@@ -630,7 +630,8 @@ def _batch_get_secret_value(data, access_key=None):denied = authorize("secretsmanager:ListSecrets", "*")if denied:return access_denied_response("secretsmanager", "secretsmanager:ListSecrets",- getattr(denied, "principal_arn", ""), new_uuid())+ getattr(denied, "principal_arn", ""), new_uuid(),+ explicit_deny=getattr(denied, "decision", "") == "Deny")names = sorted(n for n, s in _secrets.items() if not s.get("DeletedDate"))targets = [_secrets[n]["ARN"] for n in _filter_secret_names(names, data.get("Filters", []))]@@ -647,8 +648,10 @@ def _batch_get_secret_value(data, access_key=None):"ErrorCode": "AccessDeniedException","Message": (f"User: {principal} is not authorized to perform: "- f"secretsmanager:GetSecretValue on resource: {sid} because no "- "identity-based policy allows the secretsmanager:GetSecretValue action"+ f"secretsmanager:GetSecretValue on resource: {sid} "+ + ("with an explicit deny in an identity-based policy"+ if getattr(denied, "decision", "") == "Deny" else+ "because no identity-based policy allows the secretsmanager:GetSecretValue action")),})continuediff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.pyindex 10e2acdb..a88187f4 100644--- a/ministack/services/stepfunctions.py+++ b/ministack/services/stepfunctions.py@@ -2190,7 +2190,36 @@ def _sleep_until(iso_ts):# Parallel state# ---------------------------------------------------------------------------+def _with_retry_and_catch(state_def, raw_input, ctx, attempt):+ """Run a Parallel or Map attempt under the state's Retry and Catch fields."""+ retry_counts: dict = {}+ while True:+ try:+ return attempt()+ except _ExecutionError as err:+ retrier, retrier_idx = _find_matching_retrier(+ state_def.get("Retry", []), err.error, retry_counts)+ if retrier is not None:+ count = retry_counts.get(retrier_idx, 0)+ interval = retrier.get("IntervalSeconds", 1)+ _scaled_sleep(min(interval * (retrier.get("BackoffRate", 2.0) ** count), 60))+ retry_counts[retrier_idx] = count + 1+ continue+ catcher = _find_matching_catcher(state_def.get("Catch", []), err.error)+ if catcher is None:+ raise+ error_output = {"Error": err.error, "Cause": err.cause}+ output = _apply_result_path_raw(catcher.get("ResultPath", "$"), raw_input, error_output)+ return output, catcher["Next"]++def _execute_parallel(state_def, raw_input, execution, ctx):+ return _with_retry_and_catch(+ state_def, raw_input, ctx,+ lambda: _run_parallel_branches(state_def, raw_input, execution, ctx))+++def _run_parallel_branches(state_def, raw_input, execution, ctx):effective = _apply_input_path(state_def, raw_input, ctx)effective = _apply_parameters(state_def, effective, ctx)@@ -2241,6 +2270,12 @@ def _execute_parallel(state_def, raw_input, execution, ctx):# ---------------------------------------------------------------------------def _execute_map(state_def, raw_input, execution, ctx):+ return _with_retry_and_catch(+ state_def, raw_input, ctx,+ lambda: _run_map_items(state_def, raw_input, execution, ctx))+++def _run_map_items(state_def, raw_input, execution, ctx):# No _apply_parameters here: on a Map, Parameters is the deprecated ItemSelector spelling and# is applied per item below -- and ItemsPath must resolve against the untransformed inputeffective = _apply_input_path(state_def, raw_input, ctx)diff --git a/tests/test_alb.py b/tests/test_alb.pyindex c961c660..2987d4bd 100644--- a/tests/test_alb.py+++ b/tests/test_alb.py@@ -531,6 +531,23 @@ def test_elbv2_dataplane_lambda_target_emits_metrics(elbv2, lam, cw):_alb_teardown(elbv2, lam, lb_arn, tg_arn, l_arn, fn_name)+def test_elbv2_dataplane_lambda_multi_value_set_cookie(elbv2, lam):+ import urllib.request as _req++ fn_code = (+ "def handler(event, context):\n"+ " return {'statusCode': 200, 'body': 'ok',\n"+ " 'multiValueHeaders': {'Set-Cookie': ['a=1', 'b=2'], 'Content-Type': ['text/plain']}}\n"+ )+ lb_arn, tg_arn, l_arn, _fn_arn = _alb_setup(elbv2, lam, "dp-alb-mvh", "dp-alb-mvh-fn", fn_code)+ try:+ resp = _req.urlopen(f"{_endpoint}/_alb/dp-alb-mvh/")+ assert resp.headers.get_all("Set-Cookie") == ["a=1", "b=2"]+ assert resp.headers.get("Content-Type") == "text/plain"+ finally:+ _alb_teardown(elbv2, lam, lb_arn, tg_arn, l_arn, "dp-alb-mvh-fn")++def test_elbv2_dataplane_event_shape(elbv2, lam):"""ALB event passed to Lambda contains all required fields."""import urllib.request as _reqdiff --git a/tests/test_bedrock_agentcore.py b/tests/test_bedrock_agentcore.pyindex fc7844a2..6ab59138 100644--- a/tests/test_bedrock_agentcore.py+++ b/tests/test_bedrock_agentcore.py@@ -1149,11 +1149,13 @@ def test_agentcore_memory_events_data_plane():actorId="user-1", eventTimestamp=_TS, payload=[_convo("USER", "hi")])assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"- event = dp.create_event(+ resp = dp.create_event(memoryId=memory_id, actorId="user-1", sessionId="s1",eventTimestamp=_TS, payload=[_convo("USER", "hello")],metadata={"source": {"stringValue": "test"}},- )["event"]+ )+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 201+ event = resp["event"]assert re.fullmatch(r"[0-9]+#[a-fA-F0-9]+", event["eventId"])assert event["sessionId"] == "s1" and event["actorId"] == "user-1"assert event["metadata"] == {"source": {"stringValue": "test"}}@@ -1266,6 +1268,7 @@ def test_agentcore_memory_records_data_plane():ids = {r["requestIdentifier"]: r["memoryRecordId"]for r in created["successfulRecords"]}assert all(re.fullmatch(r"mem-.{40}", rid) for rid in ids.values())+ assert created["ResponseMetadata"]["HTTPStatusCode"] == 201got = dp.get_memory_record(memoryId=memory_id, memoryRecordId=ids["r1"])["memoryRecord"]@@ -1331,14 +1334,12 @@ def test_agentcore_memory_extraction_jobs_and_region_scope():memory = _memory(control)memory_id = memory["id"]try:- started = dp.start_memory_extraction_job(- memoryId=memory_id, extractionJob={"jobId": "job-1"})- assert started["jobId"] == "job-1"- jobs = dp.list_memory_extraction_jobs(memoryId=memory_id)["jobs"]- assert [j["jobID"] for j in jobs] == ["job-1"]- assert jobs[0]["status"] == "COMPLETED"- assert dp.list_memory_extraction_jobs(- memoryId=memory_id, filter={"status": "FAILED"})["jobs"] == []+ # Only FAILED extractions are listed and restartable; none ever run here.+ with pytest.raises(ClientError) as exc:+ dp.start_memory_extraction_job(+ memoryId=memory_id, extractionJob={"jobId": "job-1"})+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+ assert dp.list_memory_extraction_jobs(memoryId=memory_id)["jobs"] == []west = _client("bedrock-agentcore", "us-west-2")with pytest.raises(ClientError) as exc:@@ -1360,3 +1361,22 @@ def test_agentcore_memory_delete_purges_data_plane_state():with pytest.raises(ClientError) as exc:dp.list_events(memoryId=memory_id, actorId="user-1", sessionId="s1")assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++ not _AUTH_ENABLED,+ reason="cross-account authorization requires a MiniStack server with AUTH=true",+)+def test_agentcore_memory_arn_from_another_account_is_denied():+ """Memory takes no resource policy, so another account's ARN is refused."""+ control = _client("bedrock-agentcore-control", access_key="111111111111")+ memory = _memory(control)+ try:+ other = _client("bedrock-agentcore", access_key="222222222222")+ with pytest.raises(ClientError) as exc:+ other.list_actors(memoryId=memory["arn"])+ assert exc.value.response["Error"]["Code"] == "AccessDeniedException"+ owner = _client("bedrock-agentcore", access_key="111111111111")+ assert owner.list_actors(memoryId=memory["arn"])["actorSummaries"] == []+ finally:+ control.delete_memory(memoryId=memory["id"])diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex dffff661..4e19763b 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -2,6 +2,7 @@import asyncioimport base64+import contextlibimport datetimeimport hashlibimport hmac@@ -115,6 +116,8 @@ def test_cognito_ui_customization(cognito_idp):assert exc.value.response["Error"]["Code"] == "InvalidParameterException"cognito_idp.create_user_pool_domain(UserPoolId=pid, Domain=f"ui-{pid.split('_')[1].lower()}")+ assert cognito_idp.get_ui_customization(UserPoolId=pid)["UICustomization"] == {}+ assert cognito_idp.get_ui_customization(UserPoolId=pid, ClientId=cid)["UICustomization"] == {}pool_ui = cognito_idp.set_ui_customization(UserPoolId=pid, CSS=".banner-customizable {}")["UICustomization"]assert pool_ui["ClientId"] == "ALL" and pool_ui["CSS"] == ".banner-customizable {}" and pool_ui["CSSVersion"]assert cognito_idp.get_ui_customization(UserPoolId=pid, ClientId=cid)["UICustomization"]["CSS"] == pool_ui["CSS"]@@ -9220,6 +9223,9 @@ def test_cognito_federation_access_token_pretoken_event_has_user_attributes(cognassert access["seen_groups"] == "admins"+# Secret-hash checks run under AUTH=true; server tests need a MiniStack started with it.+_requires_auth = pytest.mark.skipif(os.environ.get("AUTH", "").lower() != "true",+ reason="secret-hash checks need a MiniStack server with AUTH=true")def _api_issued_tokens(cognito_idp, pool_name):"""A pool with a confidential client and a user signed in through InitiateAuth.@@ -9241,7 +9247,8 @@ def _api_issued_tokens(cognito_idp, pool_name):UserPoolId=pid, Username="apirefresh", Password="Refresh-Pass1", Permanent=True)tokens = cognito_idp.initiate_auth(ClientId=client["ClientId"], AuthFlow="USER_PASSWORD_AUTH",- AuthParameters={"USERNAME": "apirefresh", "PASSWORD": "Refresh-Pass1"},+ AuthParameters={"USERNAME": "apirefresh", "PASSWORD": "Refresh-Pass1",+ "SECRET_HASH": _cognito_secret_hash(client, "apirefresh")},)["AuthenticationResult"]return pid, client, tokens@@ -9306,6 +9313,19 @@ def test_cognito_oauth2_token_rejects_api_issued_refresh_token_with_wrong_secretassert body["error"] == "invalid_client"+def test_cognito_oauth2_token_rejects_api_issued_refresh_token_without_secret(cognito_idp):+ _, client, tokens = _api_issued_tokens(cognito_idp, "OAuthApiRefreshNoSecretPool")++ status, _, body = _post_form(+ f"{ENDPOINT}/oauth2/token",+ {"grant_type": "refresh_token", "client_id": client["ClientId"],+ "refresh_token": tokens["RefreshToken"]},+ )++ assert status == 400+ assert json.loads(body)["error"] == "invalid_client"++@pytest.mark.parametrize("case", ["garbage", "access_token", "deleted_pool"])def test_cognito_oauth2_token_rejects_invalid_refresh_token(cognito_idp, case):"""A string that is not a refresh token of an existing pool mints no tokens."""@@ -9347,9 +9367,11 @@ _SECRET_HASH_OPERATIONS = (])def test_cognito_secret_hash_dispatch_prevents_side_effects(monkeypatch, action, hash_kind):"""Refusal precedes user/token changes, code delivery, and Lambda callbacks."""+ import ministack.app as app_modfrom ministack.core.responses import AccountRegionScopedDictmod = _cognito_module()+ monkeypatch.setattr(app_mod, "AUTH", True)# These stores belong to the test process, never the running server.monkeypatch.setattr(mod, "_user_pools", AccountRegionScopedDict())monkeypatch.setattr(mod, "_refresh_tokens", {})@@ -9433,6 +9455,28 @@ def test_cognito_secret_hash_dispatch_prevents_side_effects(monkeypatch, action,)+def test_cognito_secret_hash_not_checked_without_auth(monkeypatch):+ import ministack.app as app_mod+ from ministack.core.responses import AccountRegionScopedDict++ mod = _cognito_module()+ monkeypatch.setattr(app_mod, "AUTH", False)+ monkeypatch.setattr(mod, "_user_pools", AccountRegionScopedDict())+ pid = json.loads(mod._create_user_pool({"PoolName": "NoAuthSecret"})[2])["UserPool"]["Id"]+ cid = json.loads(mod._create_user_pool_client({+ "UserPoolId": pid, "ClientName": "app", "GenerateSecret": True,+ "ExplicitAuthFlows": ["ALLOW_USER_PASSWORD_AUTH"],+ })[2])["UserPoolClient"]["ClientId"]+ mod._admin_create_user({"UserPoolId": pid, "Username": "u", "TemporaryPassword": "Correct1!",+ "MessageAction": "SUPPRESS"})+ mod._admin_set_user_password({"UserPoolId": pid, "Username": "u", "Password": "Correct1!", "Permanent": True})+ status, _, body = asyncio.run(mod._dispatch_idp("InitiateAuth", {+ "ClientId": cid, "AuthFlow": "USER_PASSWORD_AUTH",+ "AuthParameters": {"USERNAME": "u", "PASSWORD": "Correct1!"},+ }))+ assert status == 200, body++def _secret_hash_pool(cognito_idp, **pool_options):pid = cognito_idp.create_user_pool(PoolName="SecretHashPool", **pool_options)["UserPool"]["Id"]client = cognito_idp.create_user_pool_client(@@ -9456,6 +9500,7 @@ def _secret_hash_user(cognito_idp, pid, username="canonical-user", permanent=Trureturn user+@_requires_authdef test_cognito_secret_hash_self_service(cognito_idp):pid, client = _secret_hash_pool(cognito_idp)params = {"ClientId": client["ClientId"], "Username": "signup-user",@@ -9477,6 +9522,7 @@ def test_cognito_secret_hash_self_service(cognito_idp):assert cognito_idp.get_user(AccessToken=auth["AuthenticationResult"]["AccessToken"])["Username"] == "signup-user"+@_requires_auth@pytest.mark.parametrize("admin", [False, True])@pytest.mark.parametrize("login", ["canonical-user", "[email protected]"])def test_cognito_secret_hash_password_uses_submitted_alias(cognito_idp, admin, login):@@ -9501,6 +9547,7 @@ def test_cognito_secret_hash_password_uses_submitted_alias(cognito_idp, admin, lassert exc.value.response["Error"]["Message"] == f"Unable to verify secret hash for client {client['ClientId']}"+@_requires_auth@pytest.mark.parametrize("admin", [False, True])def test_cognito_secret_hash_new_password_challenge(cognito_idp, admin):pid, client = _secret_hash_pool(cognito_idp)@@ -9532,6 +9579,7 @@ def test_cognito_secret_hash_new_password_challenge(cognito_idp, admin):assert cognito_idp.get_user(AccessToken=result["AccessToken"])["Username"] == "canonical-user"+@_requires_auth@pytest.mark.parametrize("admin", [False, True])@pytest.mark.parametrize("username_attributes", [False, True], ids=["username-sign-in", "email-sign-in"])@pytest.mark.parametrize("flow", ["REFRESH_TOKEN_AUTH", "REFRESH_TOKEN"])@@ -9566,6 +9614,7 @@ def test_cognito_secret_hash_refresh_uses_token_owner(cognito_idp, admin, usernaassert cognito_idp.get_user(AccessToken=refreshed["AccessToken"])["Username"] == user["Username"]+@_requires_auth@pytest.mark.parametrize("admin", [False, True])def test_cognito_secret_hash_srp_proof(cognito_idp, admin):pid, client = _secret_hash_pool(cognito_idp, AliasAttributes=["email"])@@ -9594,8 +9643,11 @@ def test_cognito_secret_hash_srp_proof(cognito_idp, admin):assert cognito_idp.get_user(AccessToken=result["AccessToken"])["Username"] == "canonical-user"+@_requires_auth@pytest.mark.parametrize("admin", [False, True])-def test_cognito_secret_hash_custom_challenge(cognito_idp, lam, admin):+def test_cognito_secret_hash_custom_challenge(cognito_idp, lam, iam, admin):+ with contextlib.suppress(iam.exceptions.EntityAlreadyExistsException):+ iam.create_role(RoleName="lambda-role", AssumeRolePolicyDocument="{}")pid, client = _secret_hash_pool(cognito_idp)_secret_hash_user(cognito_idp, pid)suffix = _uuid_mod.uuid4().hex[:8]@@ -9667,6 +9719,7 @@ def test_cognito_secret_hash_custom_challenge(cognito_idp, lam, admin):assert cognito_idp.get_user(AccessToken=result["AccessToken"])["Username"] == "canonical-user"+@_requires_authdef test_cognito_secret_hash_admin_sms_challenge(cognito_idp):"""Existing admin SMS handling must also require the app-client proof."""pid, client = _secret_hash_pool(cognito_idp)@@ -9685,6 +9738,7 @@ def test_cognito_secret_hash_admin_sms_challenge(cognito_idp):assert cognito_idp.get_user(AccessToken=result["AccessToken"])["Username"] == "canonical-user"+@_requires_auth@pytest.mark.parametrize("admin", [False, True])@pytest.mark.parametrize("include_hash", [False, True], ids=["missing-hash", "wrong-hash"])def test_cognito_secret_hash_invalid_refresh_preserves_token_error(cognito_idp, admin, include_hash):@@ -9705,6 +9759,7 @@ def test_cognito_secret_hash_invalid_refresh_preserves_token_error(cognito_idp,}+@_requires_auth@pytest.mark.parametrize("admin", [False, True])def test_cognito_secret_hash_no_secret_refresh_ignores_supplied_hash(cognito_idp, admin):pid = cognito_idp.create_user_pool(PoolName="PublicRefreshHashPool")["UserPool"]["Id"]diff --git a/tests/test_dsql.py b/tests/test_dsql.pyindex 0693fc32..36d9bffa 100644--- a/tests/test_dsql.py+++ b/tests/test_dsql.py@@ -2239,6 +2239,19 @@ class TestExtendedProtocol:# ... while FOR UPDATE reaches the backend whatever the predicate.assert c.extended("SELECT * FROM xp_lock WHERE v > 1 FOR UPDATE").ok+ def test_describe_statement_on_create_index_async(self, dsql_proxy):+ """Parse + Describe('S'), as asyncpg prepares: no parameters, a job_id column."""+ with _WireClient(dsql_proxy) as c:+ c.simple("CREATE TABLE xp_desc (id int, name text)")+ c.sock.sendall(+ c._frame(b"P", b"\0CREATE INDEX ASYNC xp_desc_i ON xp_desc (name)\0" + struct.pack("!H", 0))+ + c._frame(b"D", b"S\0") + c._frame(b"S", b"")+ )+ frames = c._until_ready()+ assert [t for t, _ in frames] == [b"1", b"t", b"T", b"Z"]+ assert dict(frames)[b"t"] == struct.pack("!H", 0)+ assert c.simple("SELECT 1").rows == [("1",)]+def test_create_index_async_returns_a_job_over_parse(self, dsql_proxy):"""DSQL-only syntax has to be rewritten on this path too, or thebackend answers with a bare syntax error."""diff --git a/tests/test_eks.py b/tests/test_eks.pyindex 009e890a..6a494d2a 100644--- a/tests/test_eks.py+++ b/tests/test_eks.py@@ -662,15 +662,18 @@ def test_eks_k3s_run_kwargs_network_optional():assert with_net["network"] == "ministack-net"-def test_eks_k3s_run_kwargs_container_name_and_labels_are_region_scoped():- """Same-name clusters in different regions need distinct containers."""+def test_eks_k3s_run_kwargs_container_name_and_labels_are_account_and_region_scoped():+ """Same-name clusters in different accounts or regions need distinct containers."""from ministack.services.eks import _k3s_run_kwargs- east = _k3s_run_kwargs(name="my-cluster", region="us-east-1", port=16443)- west = _k3s_run_kwargs(name="my-cluster", region="us-west-2", port=16444)+ east = _k3s_run_kwargs(name="my-cluster", region="us-east-1", port=16443, account_id="111111111111")+ west = _k3s_run_kwargs(name="my-cluster", region="us-west-2", port=16444, account_id="111111111111")+ other = _k3s_run_kwargs(name="my-cluster", region="us-east-1", port=16445, account_id="222222222222")- assert east["name"] == "ministack-eks-us-east-1-my-cluster"- assert west["name"] == "ministack-eks-us-west-2-my-cluster"+ assert east["name"] == "ministack-eks-111111111111-us-east-1-my-cluster"+ assert west["name"] == "ministack-eks-111111111111-us-west-2-my-cluster"+ assert other["name"] == "ministack-eks-222222222222-us-east-1-my-cluster"+ assert other["labels"]["account_id"] == "222222222222"# Subset, not equality: containers also carry the ownership labels# (`ministack.instance` / `ministack.boot`) that scope reaping to this# MiniStack. This test is about region scoping, so it asserts only that.diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex aed6d1cf..b684217d 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -4167,3 +4167,17 @@ def test_trust_denies_and_conditions_remain_permissive_without_auth(trust_api, mmonkeypatch.setattr(app_mod, "AUTH", False)_install_policy(trust_api, operation, policy)_assume(trust_api, 200, RoleSessionName="unrestricted")++[email protected]("service, action", [("iam", "iam:ListUsers"), ("sqs", "sqs:ListQueues"), ("sns", "sns:ListTopics")])[email protected]("explicit_deny, reason", [+ (True, "with an explicit deny in an identity-based policy"),+ (False, "because no identity-based policy allows the {action} action"),+])+def test_access_denied_message_names_an_explicit_deny(service, action, explicit_deny, reason):+ from ministack.core.iam_actions import access_denied_response++ _status, _headers, body = access_denied_response(+ service, action, "arn:aws:iam::000000000000:user/u", "req-1", explicit_deny=explicit_deny)+ expected = f"User: arn:aws:iam::000000000000:user/u is not authorized to perform: {action} "+ assert (expected + reason.format(action=action)) in body.decode()diff --git a/tests/test_iot.py b/tests/test_iot.pyindex ebb3a393..a9540aff 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -6020,13 +6020,11 @@ def test_iot_jitr_auto_registration_on_connect(monkeypatch):def test_iot_jitr_under_an_sni_only_ca_needs_sni():- """A CA in SNI_ONLY mode auto-registers only on a connect whose ClientHello- named the account's endpoint, as on AWS: the account's endpoint prefix- counts in any region (and so do the names the gateway serves), while no- server name, an unrelated one or another account's prefix creates- nothing. A certificate already PENDING_ACTIVATION gets a repeat event only- with SNI. A DEFAULT CA auto-registers nothing for an unrelated name- either, but still does for a compose service name."""+ """A CA in SNI_ONLY mode auto-registers only on a connect that sent SNI:+ the account's endpoint prefix counts in any region, no server name or+ another account's prefix creates nothing. A certificate already+ PENDING_ACTIVATION gets a repeat event only with SNI. A DEFAULT CA+ auto-registers for a non-endpoint name."""import sslfrom ministack.services import iot as iot_module@@ -6046,7 +6044,6 @@ def test_iot_jitr_under_an_sni_only_ca_needs_sni():await _jitr_scope_with_ca(iot_module, def_ca_pem, def_verification_pem, [])for server_name in (None,- "mqtt.example.com",f"{other_prefix}-ats.iot.{_TEST_REGION}.amazonaws.com",f"{other_prefix}-ats.iot.{_TEST_REGION}.localhost",f"{other_prefix}.credentials.iot.{_TEST_REGION}.localhost",@@ -6054,9 +6051,7 @@ def test_iot_jitr_under_an_sni_only_ca_needs_sni():assert not await iot_module._mtls_auto_register(der, peer, server_name)assert cert_id not in iot_module._certificatesdef_der = ssl.PEM_cert_to_DER_cert(def_leaf_pem)- assert not await iot_module._mtls_auto_register(def_der, peer, "mqtt.example.com")- assert iot_module.get_certificate_id(def_leaf_pem) not in iot_module._certificates- assert await iot_module._mtls_auto_register(def_der, peer, "ministack")+ assert await iot_module._mtls_auto_register(def_der, peer, "mqtt.example.com")other_region = f"{prefix.upper()}-ats.iot.us-east-1.amazonaws.com"assert await iot_module._mtls_auto_register(der, peer, other_region)diff --git a/tests/test_iot_data.py b/tests/test_iot_data.pyindex d201aa44..a8b2fff9 100644--- a/tests/test_iot_data.py+++ b/tests/test_iot_data.py@@ -3729,9 +3729,8 @@ def test_mtls_jitr_auto_registers_an_unknown_cert_without_connack(broker, tmp_padef test_mtls_jitr_under_an_sni_only_ca_needs_sni(broker, tmp_path):"""A CA in SNI_ONLY mode auto-registers a device only when its ClientHello- carries a server name that reaches the endpoint, as on AWS. Without one,- or with an unrelated one, the certificate stays unknown and is refused- like any other unknown certificate (CONNACK 5)."""+ carries a server name. Without one the certificate stays unknown and is+ refused like any other unknown certificate (CONNACK 5)."""from ministack.core.x509_utils import generate_ca, get_certificate_id, sign_leaf_certificateiot = broker.client("iot")@@ -3743,7 +3742,7 @@ def test_mtls_jitr_under_an_sni_only_ca_needs_sni(broker, tmp_path):leaf_pem, leaf_key, _public = sign_leaf_certificate(ca_pem, ca_key, common_name="jitr-sni-device")cert_id = get_certificate_id(leaf_pem)try:- for server_name in (None, "mqtt.example.com"):+ for server_name in (None,):peer = _Peer(_mtls_connect(broker, leaf_pem, leaf_key, tmp_path, server_name=server_name))try:_assert_connack(peer.connect(_unique("jitr-no-sni")), return_code=5)diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex bb9dbee6..4f5a1ec0 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -10970,6 +10970,23 @@ def test_lambda_docker_timeout_update_changes_rie_deadline(lam, old_timeout, newreason="requires LAMBDA_EXECUTOR=docker and Docker daemon",)@pytest.mark.data_plane+def test_lambda_handler_error_mentioning_timed_out_is_not_a_timeout(lam):+ fname = f"lam-read-timeout-{_uuid_mod.uuid4().hex[:8]}"+ code = "def handler(event, context):\n raise Exception('Read timed out. (read timeout=5)')\n"+ lam.create_function(+ FunctionName=fname, Runtime="python3.12", Handler="index.handler",+ Role=_LAMBDA_ROLE, Code={"ZipFile": _make_zip(code)}, Timeout=10,+ )+ try:+ resp = lam.invoke(FunctionName=fname, Payload=b"{}")+ payload = json.loads(resp["Payload"].read())+ assert resp.get("FunctionError") == "Unhandled"+ assert payload["errorMessage"] == "Read timed out. (read timeout=5)"+ assert payload["errorType"] != "Sandbox.Timedout"+ finally:+ lam.delete_function(FunctionName=fname)++def test_lambda_docker_timeout_returns_task_timed_out_promptly(lam):"""The real RIE end of the timeout story: one AWS-style error, promptly.diff --git a/tests/test_mwaa.py b/tests/test_mwaa.pyindex adfc799c..879c7bd9 100644--- a/tests/test_mwaa.py+++ b/tests/test_mwaa.py@@ -287,7 +287,8 @@ def test_airflow_runtime_identity_and_background_scope_include_region(account_id = "111111111111"region = "us-west-2"env_name = "regional-runtime"- expected_name = f"ministack-mwaa-{region}-{env_name}"+ expected_name = f"ministack-mwaa-{account_id}-{region}-{env_name}"+ regional_name = f"ministack-mwaa-{region}-{env_name}"legacy_name = f"ministack-mwaa-{env_name}"env = {"AirflowVersion": "3.0.6",@@ -318,7 +319,7 @@ def test_airflow_runtime_identity_and_background_scope_include_region(mod._start_airflow_container(account_id, region, env_name, env)assert dag_sync_complete.wait(timeout=2)- assert docker_client.containers.get_calls == [expected_name, legacy_name]+ assert docker_client.containers.get_calls == [expected_name, regional_name, legacy_name]# v=True reclaims the container's anonymous volume. Verified against# docker: named volumes (MWAA's dags/db persistence) are untouched# by remove(v=True), so this cannot lose persisted state.@@ -330,6 +331,7 @@ def test_airflow_runtime_identity_and_background_scope_include_region("ministack": "mwaa","region": region,"env_name": env_name,+ "account_id": account_id,}.items() <= docker_client.containers.run_kwargs["labels"].items()expected_volume_prefix = legacy_name if legacy_volumes else expected_nameassert set(docker_client.containers.run_kwargs["volumes"]) == {diff --git a/tests/test_opensearch.py b/tests/test_opensearch.pyindex 9032f659..d31620d6 100644--- a/tests/test_opensearch.py+++ b/tests/test_opensearch.py@@ -659,7 +659,10 @@ def test_opensearch_dataplane_names_include_account_and_region():their containers must not collide, and the data container's name stays oneDNS label (Dashboards reaches it by name) for the longest domain name."""from ministack.core.responses import (- get_account_id, get_region, set_request_account_id, set_request_region,+ get_account_id,+ get_region,+ set_request_account_id,+ set_request_region,)from ministack.services import opensearchdiff --git a/tests/test_opensearchserverless.py b/tests/test_opensearchserverless.pyindex 64a96c14..27a4d687 100644--- a/tests/test_opensearchserverless.py+++ b/tests/test_opensearchserverless.py@@ -23,11 +23,10 @@ from botocore.auth import SigV4Authfrom botocore.awsrequest import AWSRequestfrom botocore.credentials import Credentialsfrom botocore.exceptions import ClientError+from conftest import ENDPOINT, GATEWAY_PORTfrom ministack.services import opensearchserverless as aoss_module-from conftest import ENDPOINT, GATEWAY_PORT-REGION = "us-east-1"diff --git a/tests/test_rds.py b/tests/test_rds.pyindex 67313d9f..36a68461 100644--- a/tests/test_rds.py+++ b/tests/test_rds.py@@ -13,14 +13,21 @@ import timeimport typesimport uuidimport uuid as _uuid_mod+import xml.etree.ElementTree as _imm_ETimport zipfile+from urllib.parse import urlencode as _imm_urlencodeimport boto3import pytest+from botocore.awsrequest import AWSResponse as _ImmAWSResponsefrom botocore.config import Configfrom botocore.exceptions import ClientErrorfrom conftest import ENDPOINT+from ministack.core.responses import AccountRegionScopedDict as _ImmScopedDict+from ministack.core.responses import request_scope as _imm_request_scope+from ministack.services import rds as _imm_rds+DEFAULT_AURORA_MYSQL_ENGINE_VERSION = "8.0.mysql_aurora.3.10.3"UNSUPPORTED_AURORA_MYSQL_ENGINE_VERSION = "9.0.mysql_aurora.9.0.1"DEFAULT_AURORA_POSTGRESQL_ENGINE_VERSION = "17.7"@@ -4156,7 +4163,7 @@ def test_rds_empty_cluster_applies_pending_password_on_restart(rotations.append((old_password, new_password))return rotation_succeeds- def _grant(_host, _port, user, password, db_id):+ def _grant(_host, _port, user, password, db_id, _engine=""):grants.append((user, password, db_id))monkeypatch.setattr(m, "_get_docker", lambda: FakeDocker())@@ -4497,8 +4504,26 @@ def test_rds_delete_cluster_rejects_attached_members(monkeypatch):m._clusters.clear()-def test_rds_mysql_master_user_privilege_grants(monkeypatch):- """MySQL master users get admin grants, with dynamic grants best-effort."""+_AURORA_MYSQL_3_EXTRAS = (+ "CREATE ROLE", "DROP ROLE", "APPLICATION_PASSWORD_ADMIN", "CONNECTION_ADMIN", "ROLE_ADMIN",+ "XA_RECOVER_ADMIN", "SHOW_ROUTINE", "FLUSH_OPTIMIZER_COSTS", "FLUSH_STATUS", "FLUSH_TABLES",+ "FLUSH_USER_RESOURCES",+)++[email protected]("engine, server_version, extras", [+ ("mysql", "8.0.35", ()),+ ("mysql", "8.4.5", ("CREATE ROLE", "DROP ROLE", "APPLICATION_PASSWORD_ADMIN", "ROLE_ADMIN",+ "SET_USER_ID", "XA_RECOVER_ADMIN")),+ ("mariadb", "10.11.8-MariaDB", ()),+ ("mariadb", "11.4.2-MariaDB-ubu2404", ("SHOW CREATE ROUTINE",)),+ ("aurora-mysql", "5.7.44", ("LOAD FROM S3", "SELECT INTO S3")),+ ("aurora-mysql", "8.0.39", _AURORA_MYSQL_3_EXTRAS + ("SET_USER_ID",)),+ ("aurora-mysql", "8.4.5", _AURORA_MYSQL_3_EXTRAS + (+ "ALLOW_NONEXISTENT_DEFINER", "FLUSH_PRIVILEGES", "OPTIMIZE_LOCAL_TABLE", "SET_ANY_DEFINER")),+])+def test_rds_mysql_master_user_privilege_grants(monkeypatch, engine, server_version, extras):+ """The master user gets the privileges in AWS's master user table for its engine and version, and no others."""import sysimport types@@ -4512,6 +4537,9 @@ def test_rds_mysql_master_user_privilege_grants(monkeypatch):if "APPLICATION_PASSWORD_ADMIN" in sql:raise Exception("unsupported privilege")+ def fetchone(self):+ return (server_version,)+def close(self):calls.append(("cursor.close", None))@@ -4533,7 +4561,7 @@ def test_rds_mysql_master_user_privilege_grants(monkeypatch):)m._grant_mysql_master_user_privileges(- "10.0.0.12", 3306, "admin", "password123", "mysql-test")+ "10.0.0.12", 3306, "admin", "password123", "mysql-test", engine)assert calls[0] == ("connect",@@ -4549,10 +4577,11 @@ def test_rds_mysql_master_user_privilege_grants(monkeypatch):"CREATE USER IF NOT EXISTS %s@'%%' IDENTIFIED BY %s",("admin", "password123"),) in calls- assert (- "GRANT ALL PRIVILEGES ON *.* TO %s@'%%' WITH GRANT OPTION",- ("admin",),- ) in calls+ grants = [sql for sql, _params in calls if isinstance(sql, str) and sql.startswith("GRANT ")]+ assert grants == [f"GRANT {m._MYSQL_MASTER_PRIVILEGES} ON *.* TO %s@'%%' WITH GRANT OPTION"] + [+ f"GRANT {privilege} ON *.* TO %s@'%%' WITH GRANT OPTION" for privilege in extras]+ assert ("REVOKE ALL PRIVILEGES, GRANT OPTION FROM %s@'%%'", ("admin",)) in calls+ assert not any("ALL PRIVILEGES ON" in str(sql) for sql, _params in calls)assert ("FLUSH PRIVILEGES", None) in calls@@ -5324,7 +5353,7 @@ def test_rds_deferred_mysql_start_grants_master_privileges(monkeypatch):m._instances[db_id] = instancetry:m._start_rds_container_for_instance(db_id, instance)- assert grants == [("127.0.0.1", 15600, "admin", "password123", db_id)]+ assert grants == [("127.0.0.1", 15600, "admin", "password123", db_id, "mysql")]assert instance["DBInstanceStatus"] == "available"finally:m._instances.clear()@@ -5495,7 +5524,7 @@ def test_rds_restore_state_respawns_one_container_per_cluster(rotations.append((old_password, new_password))return True- def _grant(_host, _port, user, password, db_id):+ def _grant(_host, _port, user, password, db_id, _engine=""):grants.append((user, password, db_id))def _configure_replication(db_id, cluster):@@ -16554,3 +16583,225 @@ def test_rds_public_endpoint_cluster_reports_published_port(monkeypatch):finally:m._instances.clear()m._clusters.clear()+++# ---------------------------------------------------------------------------+# ModifyDBInstance settings that apply immediately (synthetic instances)+# ---------------------------------------------------------------------------++_IMM_FLAGS = ("DeletionProtection", "CopyTagsToSnapshot")+_IMM_ACCOUNT = "111111111111"+_IMM_REGION = "us-east-1"+++def imm_state(monkeypatch):+ monkeypatch.setattr(_imm_rds, "_instances", _ImmScopedDict())+ monkeypatch.setattr(_imm_rds, "_clusters", _ImmScopedDict())+ monkeypatch.setattr(_imm_rds, "_tags", _ImmScopedDict())+ with _imm_request_scope(_IMM_ACCOUNT, _IMM_REGION):+ yield+++def _imm_instance(**values):+ instance = {+ "DBInstanceIdentifier": "immediate-settings",+ "DBInstanceArn": f"arn:aws:rds:{_IMM_REGION}:{_IMM_ACCOUNT}:db:immediate-settings",+ "DBInstanceStatus": "available", "MasterUsername": "admin",+ "InstanceCreateTime": "2026-01-01T00:00:00Z",+ "Engine": "postgres", "EngineVersion": "16.3",+ "AllocatedStorage": 20, "DBInstanceClass": "db.t4g.small",+ "PendingModifiedValues": {},+ "DeletionProtection": False, "CopyTagsToSnapshot": False,+ }+ instance.update(values)+ _imm_rds._instances[instance["DBInstanceIdentifier"]] = instance+ return instance+++def _imm_query(action, **params):+ body = _imm_urlencode({"Action": action, "Version": "2014-10-31", **params}).encode()+ status, headers, body = asyncio.run(_imm_rds.handle_request(+ "POST", "/", {"content-type": "application/x-www-form-urlencoded"}, body, {},+ ))+ assert status == 200, body+ return status, headers, body.encode() if isinstance(body, str) else body+++class _ImmRawResponse(io.BytesIO):+ def stream(self, amt=None, decode_content=False):+ yield self.read()+++def _imm_sdk():+ # The before-send transport uses production Query dispatch and XML. An+ # accidentally unhandled request goes to a refusal endpoint, never AWS.+ client = boto3.client(+ "rds", endpoint_url="http://127.0.0.1:9", region_name=_IMM_REGION,+ aws_access_key_id=_IMM_ACCOUNT, aws_secret_access_key="test",+ config=Config(retries={"max_attempts": 0}),+ )++ def send(request, **kwargs):+ status, headers, body = asyncio.run(_imm_rds.handle_request(+ "POST", "/", {"content-type": "application/x-www-form-urlencoded"},+ request.body, {},+ ))+ body = body.encode() if isinstance(body, str) else body+ return _ImmAWSResponse(request.url, status, headers, _ImmRawResponse(body))++ client.meta.events.register("before-send.rds", send)+ return client+++def _imm_modify_readback(mode, **params):+ if mode == "sdk":+ client = _imm_sdk()+ changed = client.modify_db_instance(+ DBInstanceIdentifier="immediate-settings", **params,+ )["DBInstance"]+ described = client.describe_db_instances(+ DBInstanceIdentifier="immediate-settings",+ )["DBInstances"][0]+ return changed, described++ query_params = {key: str(value).lower() if isinstance(value, bool) else value+ for key, value in params.items()}+ outputs = []+ for action in ("ModifyDBInstance", "DescribeDBInstances"):+ _, _, body = _imm_query(+ action, DBInstanceIdentifier="immediate-settings",+ **(query_params if action == "ModifyDBInstance" else {}),+ )+ instance = _imm_ET.fromstring(body).find(".//{*}DBInstance")+ outputs.append({+ **{flag: instance.findtext(f"{{*}}{flag}") == "true" for flag in _IMM_FLAGS},+ "PendingModifiedValues": {+ child.tag.split("}")[-1]: child.text+ for child in instance.find("{*}PendingModifiedValues")+ },+ })+ return outputs++[email protected]("mode", ["sdk", "query"])[email protected]("apply", [None, False, True])[email protected]("desired", [False, True])[email protected]("flag", _IMM_FLAGS)+def test_rds_standalone_flags_apply_immediately(imm_state, mode, apply, desired, flag):+ instance = _imm_instance(**{flag: not desired})+ params = {flag: desired}+ if apply is not None:+ params["ApplyImmediately"] = apply+ for output in _imm_modify_readback(mode, **params):+ assert output[flag] is desired+ assert not set(_IMM_FLAGS).intersection(output["PendingModifiedValues"])+ assert instance[flag] is desired+ assert instance["PendingModifiedValues"] == {}++[email protected]("mode", ["sdk", "query"])[email protected]("apply", [None, False, True])+def test_rds_both_flags_repeated_updates_preserve_omitted_values(imm_state, mode, apply):+ _imm_instance()+ params = {} if apply is None else {"ApplyImmediately": apply}+ for desired in (True, False, True):+ for output in _imm_modify_readback(mode, **params, **dict.fromkeys(_IMM_FLAGS, desired)):+ assert all(output[flag] is desired for flag in _IMM_FLAGS)+ assert output["PendingModifiedValues"] == {}+ for output in _imm_modify_readback(mode, **params, DeletionProtection=False):+ assert output["DeletionProtection"] is False+ assert output["CopyTagsToSnapshot"] is True+ for output in _imm_modify_readback(mode, **params, CopyTagsToSnapshot=False):+ assert all(output[flag] is False for flag in _IMM_FLAGS)++[email protected]("flag", _IMM_FLAGS)+def test_rds_flag_only_request_preserves_unrelated_pending_changes(imm_state, flag):+ pending = {"DBInstanceClass": "db.t4g.medium", "AllocatedStorage": 30}+ instance = _imm_instance(PendingModifiedValues=pending.copy())+ for output in _imm_modify_readback("sdk", ApplyImmediately=False, **{flag: True}):+ assert output[flag] is True+ assert output["PendingModifiedValues"] == pending+ assert instance["PendingModifiedValues"] == pending++[email protected]("apply", [None, False, True])+def test_rds_immediate_protection_blocks_delete_and_disabling_allows_it(imm_state, monkeypatch, apply):+ monkeypatch.setattr(_imm_rds, "_get_docker", lambda: None)+ _imm_instance()+ client = _imm_sdk()+ params = {} if apply is None else {"ApplyImmediately": apply}+ client.modify_db_instance(+ DBInstanceIdentifier="immediate-settings", DeletionProtection=True, **params,+ )+ with pytest.raises(ClientError) as error:+ client.delete_db_instance(+ DBInstanceIdentifier="immediate-settings", SkipFinalSnapshot=True,+ )+ assert error.value.response["Error"]["Code"] == "InvalidParameterCombination"+ assert error.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+ assert client.describe_db_instances(+ DBInstanceIdentifier="immediate-settings",+ )["DBInstances"][0]["DeletionProtection"] is True+ client.modify_db_instance(+ DBInstanceIdentifier="immediate-settings", DeletionProtection=False, **params,+ )+ assert client.delete_db_instance(+ DBInstanceIdentifier="immediate-settings", SkipFinalSnapshot=True,+ )["DBInstance"]["DBInstanceStatus"] == "deleting"+ with pytest.raises(ClientError) as error:+ client.describe_db_instances(DBInstanceIdentifier="immediate-settings")+ assert error.value.response["Error"]["Code"] == "DBInstanceNotFound"+ assert error.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404+++def test_rds_flags_do_not_create_a_missing_instance(imm_state):+ with pytest.raises(ClientError) as error:+ _imm_sdk().modify_db_instance(+ DBInstanceIdentifier="missing-settings", DeletionProtection=True,+ CopyTagsToSnapshot=True,+ )+ assert error.value.response["Error"]["Code"] == "DBInstanceNotFound"+ assert error.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404+ assert not _imm_rds._instances+++def test_rds_immediate_flags_are_isolated_by_account_and_region(imm_state):+ tenants = [(_IMM_ACCOUNT, _IMM_REGION), ("222222222222", _IMM_REGION), (_IMM_ACCOUNT, "eu-west-1")]+ for account, region in tenants:+ with _imm_request_scope(account, region):+ _imm_instance()+ _imm_modify_readback("sdk", ApplyImmediately=False, **dict.fromkeys(_IMM_FLAGS, True))+ for account, region in tenants:+ with _imm_request_scope(account, region):+ output = _imm_sdk().describe_db_instances(+ DBInstanceIdentifier="immediate-settings",+ )["DBInstances"][0]+ assert all(output[flag] is ((account, region) == tenants[0]) for flag in _IMM_FLAGS)++[email protected]("membership", ["DBClusterIdentifier", "_shared_cluster_id", None])+def test_rds_cluster_member_settings_also_apply_immediately(imm_state, membership):+ instance = _imm_instance(Engine="aurora-postgresql", **({membership: "cluster"} if membership else {}))+ _imm_modify_readback("sdk", ApplyImmediately=False, **dict.fromkeys(_IMM_FLAGS, True))+ assert all(instance[flag] is True for flag in _IMM_FLAGS)+ assert instance["PendingModifiedValues"] == {}++[email protected]("param, value, stored", [+ ("PreferredBackupWindow", "03:00-04:00", "03:00-04:00"),+ ("PreferredMaintenanceWindow", "sun:05:00-sun:06:00", "sun:05:00-sun:06:00"),+ ("PubliclyAccessible", "true", True),+ ("MaxAllocatedStorage", "100", 100),+ ("MonitoringInterval", "60", 60),+ ("MonitoringRoleArn", "arn:aws:iam::111111111111:role/mon", "arn:aws:iam::111111111111:role/mon"),+])+def test_rds_settings_outside_pending_modified_values_apply_immediately(imm_state, param, value, stored):+ """botocore's PendingModifiedValues has no member for these, so they never queue."""+ instance = _imm_instance()+ status, _, _ = _imm_rds._modify_db_instance(+ {"DBInstanceIdentifier": ["immediate-settings"], param: [value], "ApplyImmediately": ["false"]})+ assert status == 200+ assert instance[param] == stored+ assert instance["PendingModifiedValues"] == {}diff --git a/tests/test_rds_immediate_settings.py b/tests/test_rds_immediate_settings.pydeleted file mode 100644index 15251519..00000000--- a/tests/test_rds_immediate_settings.py+++ /dev/null@@ -1,241 +0,0 @@-"""Configuration/readback regressions; synthetic instances, no DB or AWS calls."""--import asyncio-import io-import xml.etree.ElementTree as ET-from urllib.parse import urlencode--import boto3-import pytest-from botocore.awsrequest import AWSResponse-from botocore.config import Config-from botocore.exceptions import ClientError--from ministack.core.responses import AccountRegionScopedDict, request_scope-from ministack.services import rds--FLAGS = ("DeletionProtection", "CopyTagsToSnapshot")-ACCOUNT = "111111111111"-REGION = "us-east-1"--[email protected](autouse=True)-def isolated_state(monkeypatch):- monkeypatch.setattr(rds, "_instances", AccountRegionScopedDict())- monkeypatch.setattr(rds, "_clusters", AccountRegionScopedDict())- monkeypatch.setattr(rds, "_tags", AccountRegionScopedDict())- with request_scope(ACCOUNT, REGION):- yield---def _instance(**values):- instance = {- "DBInstanceIdentifier": "immediate-settings",- "DBInstanceArn": f"arn:aws:rds:{REGION}:{ACCOUNT}:db:immediate-settings",- "DBInstanceStatus": "available", "MasterUsername": "admin",- "InstanceCreateTime": "2026-01-01T00:00:00Z",- "Engine": "postgres", "EngineVersion": "16.3",- "AllocatedStorage": 20, "DBInstanceClass": "db.t4g.small",- "PendingModifiedValues": {},- "DeletionProtection": False, "CopyTagsToSnapshot": False,- }- instance.update(values)- rds._instances[instance["DBInstanceIdentifier"]] = instance- return instance---def _query(action, **params):- body = urlencode({"Action": action, "Version": "2014-10-31", **params}).encode()- status, headers, body = asyncio.run(rds.handle_request(- "POST", "/", {"content-type": "application/x-www-form-urlencoded"}, body, {},- ))- assert status == 200, body- return status, headers, body.encode() if isinstance(body, str) else body---class _RawResponse(io.BytesIO):- def stream(self, amt=None, decode_content=False):- yield self.read()---def _sdk():- # The before-send transport uses production Query dispatch and XML. An- # accidentally unhandled request goes to a refusal endpoint, never AWS.- client = boto3.client(- "rds", endpoint_url="http://127.0.0.1:9", region_name=REGION,- aws_access_key_id=ACCOUNT, aws_secret_access_key="test",- config=Config(retries={"max_attempts": 0}),- )-- def send(request, **kwargs):- status, headers, body = asyncio.run(rds.handle_request(- "POST", "/", {"content-type": "application/x-www-form-urlencoded"},- request.body, {},- ))- body = body.encode() if isinstance(body, str) else body- return AWSResponse(request.url, status, headers, _RawResponse(body))-- client.meta.events.register("before-send.rds", send)- return client---def _modify_readback(mode, **params):- if mode == "sdk":- client = _sdk()- changed = client.modify_db_instance(- DBInstanceIdentifier="immediate-settings", **params,- )["DBInstance"]- described = client.describe_db_instances(- DBInstanceIdentifier="immediate-settings",- )["DBInstances"][0]- return changed, described-- query_params = {key: str(value).lower() if isinstance(value, bool) else value- for key, value in params.items()}- outputs = []- for action in ("ModifyDBInstance", "DescribeDBInstances"):- _, _, body = _query(- action, DBInstanceIdentifier="immediate-settings",- **(query_params if action == "ModifyDBInstance" else {}),- )- instance = ET.fromstring(body).find(".//{*}DBInstance")- outputs.append({- **{flag: instance.findtext(f"{{*}}{flag}") == "true" for flag in FLAGS},- "PendingModifiedValues": {- child.tag.split("}")[-1]: child.text- for child in instance.find("{*}PendingModifiedValues")- },- })- return outputs--[email protected]("mode", ["sdk", "query"])[email protected]("apply", [None, False, True])[email protected]("desired", [False, True])[email protected]("flag", FLAGS)-def test_standalone_flags_apply_immediately(mode, apply, desired, flag):- instance = _instance(**{flag: not desired})- params = {flag: desired}- if apply is not None:- params["ApplyImmediately"] = apply- for output in _modify_readback(mode, **params):- assert output[flag] is desired- assert not set(FLAGS).intersection(output["PendingModifiedValues"])- assert instance[flag] is desired- assert instance["PendingModifiedValues"] == {}--[email protected]("mode", ["sdk", "query"])[email protected]("apply", [None, False, True])-def test_both_flags_repeated_updates_preserve_omitted_values(mode, apply):- _instance()- params = {} if apply is None else {"ApplyImmediately": apply}- for desired in (True, False, True):- for output in _modify_readback(mode, **params, **dict.fromkeys(FLAGS, desired)):- assert all(output[flag] is desired for flag in FLAGS)- assert output["PendingModifiedValues"] == {}- for output in _modify_readback(mode, **params, DeletionProtection=False):- assert output["DeletionProtection"] is False- assert output["CopyTagsToSnapshot"] is True- for output in _modify_readback(mode, **params, CopyTagsToSnapshot=False):- assert all(output[flag] is False for flag in FLAGS)--[email protected]("flag", FLAGS)-def test_flag_only_request_preserves_unrelated_pending_changes(flag):- pending = {"DBInstanceClass": "db.t4g.medium", "AllocatedStorage": 30}- instance = _instance(PendingModifiedValues=pending.copy())- for output in _modify_readback("sdk", ApplyImmediately=False, **{flag: True}):- assert output[flag] is True- assert output["PendingModifiedValues"] == pending- assert instance["PendingModifiedValues"] == pending--[email protected]("apply", [None, False, True])-def test_immediate_protection_blocks_delete_and_disabling_allows_it(monkeypatch, apply):- monkeypatch.setattr(rds, "_get_docker", lambda: None)- _instance()- client = _sdk()- params = {} if apply is None else {"ApplyImmediately": apply}- client.modify_db_instance(- DBInstanceIdentifier="immediate-settings", DeletionProtection=True, **params,- )- with pytest.raises(ClientError) as error:- client.delete_db_instance(- DBInstanceIdentifier="immediate-settings", SkipFinalSnapshot=True,- )- assert error.value.response["Error"]["Code"] == "InvalidParameterCombination"- assert error.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400- assert client.describe_db_instances(- DBInstanceIdentifier="immediate-settings",- )["DBInstances"][0]["DeletionProtection"] is True- client.modify_db_instance(- DBInstanceIdentifier="immediate-settings", DeletionProtection=False, **params,- )- assert client.delete_db_instance(- DBInstanceIdentifier="immediate-settings", SkipFinalSnapshot=True,- )["DBInstance"]["DBInstanceStatus"] == "deleting"- with pytest.raises(ClientError) as error:- client.describe_db_instances(DBInstanceIdentifier="immediate-settings")- assert error.value.response["Error"]["Code"] == "DBInstanceNotFound"- assert error.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404---def test_flags_do_not_create_a_missing_instance():- with pytest.raises(ClientError) as error:- _sdk().modify_db_instance(- DBInstanceIdentifier="missing-settings", DeletionProtection=True,- CopyTagsToSnapshot=True,- )- assert error.value.response["Error"]["Code"] == "DBInstanceNotFound"- assert error.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404- assert not rds._instances---def test_immediate_flags_are_isolated_by_account_and_region():- tenants = [(ACCOUNT, REGION), ("222222222222", REGION), (ACCOUNT, "eu-west-1")]- for account, region in tenants:- with request_scope(account, region):- _instance()- _modify_readback("sdk", ApplyImmediately=False, **dict.fromkeys(FLAGS, True))- for account, region in tenants:- with request_scope(account, region):- output = _sdk().describe_db_instances(- DBInstanceIdentifier="immediate-settings",- )["DBInstances"][0]- assert all(output[flag] is ((account, region) == tenants[0]) for flag in FLAGS)--[email protected]("engine,membership", [- ("aurora-postgresql", "DBClusterIdentifier"),- ("aurora-postgresql", "_shared_cluster_id"),- ("postgres", "DBClusterIdentifier"),- ("postgres", "_shared_cluster_id"),- ("aurora-postgresql", None),-])[email protected]("apply", [None, False, True])-def test_cluster_member_and_aurora_paths_are_unchanged(engine, membership, apply):- # These are existing behavior guards, not claims of cluster-member parity.- instance = _instance(Engine=engine, **({membership: "cluster"} if membership else {}))- cluster = {- "DBClusterIdentifier": "cluster", "DBClusterArn": f"arn:aws:rds:{REGION}:{ACCOUNT}:cluster:cluster",- "Engine": "aurora-postgresql", "EngineVersion": "17.7",- "Status": "available", "Port": 5432, **dict.fromkeys(FLAGS, False),- "ClusterCreateTime": "2026-01-01T00:00:00Z",- "EarliestRestorableTime": "2026-01-01T00:00:00Z",- "LatestRestorableTime": "2026-01-01T00:00:00Z",- }- rds._clusters["cluster"] = cluster- params = {} if apply is None else {"ApplyImmediately": apply}- _modify_readback("sdk", **params, **dict.fromkeys(FLAGS, True))- assert all(instance[flag] is (apply is True) for flag in FLAGS)- assert instance["PendingModifiedValues"] == (- {} if apply is True else dict.fromkeys(FLAGS, True)- )- assert all(cluster[flag] is False for flag in FLAGS)- client = _sdk()- changed = client.modify_db_cluster(- DBClusterIdentifier="cluster", **params, **dict.fromkeys(FLAGS, True),- )["DBCluster"]- described = client.describe_db_clusters(DBClusterIdentifier="cluster")["DBClusters"][0]- assert all(output[flag] is True for output in (changed, described) for flag in FLAGS)diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.pyindex 4de7133a..00348f3d 100644--- a/tests/test_stepfunctions.py+++ b/tests/test_stepfunctions.py@@ -3458,6 +3458,72 @@ def test_sfn_task_timeout_seconds_applies_to_lambda_invoke(sfn, lam):assert json.loads(desc["output"]) == "timed-out"+def test_sfn_task_failed_does_not_match_states_timeout(sfn, sqs):+ """States.TaskFailed matches every error except States.Timeout, in Retry and in Catch."""+ queue_url = sqs.create_queue(QueueName="sfn-taskfailed-timeout")["QueueUrl"]+ definition = json.dumps({+ "StartAt": "Wait",+ "States": {+ "Wait": {+ "Type": "Task",+ "Resource": "arn:aws:states:::sqs:sendMessage.waitForTaskToken",+ "Parameters": {"QueueUrl": queue_url, "MessageBody": {"token.$": "$$.Task.Token"}},+ "TimeoutSeconds": 1,+ "Retry": [{"ErrorEquals": ["States.TaskFailed"], "IntervalSeconds": 1, "MaxAttempts": 1}],+ "Catch": [+ {"ErrorEquals": ["States.TaskFailed"], "Next": "CaughtAsTaskFailed"},+ {"ErrorEquals": ["States.Timeout"], "Next": "CaughtAsTimeout"},+ ],+ "End": True,+ },+ "CaughtAsTaskFailed": {"Type": "Pass", "Result": "task-failed", "End": True},+ "CaughtAsTimeout": {"Type": "Pass", "Result": "timeout", "End": True},+ },+ })+ sm = sfn.create_state_machine(+ name="sfn-taskfailed-timeout", definition=definition, roleArn="arn:aws:iam::000000000000:role/R",+ )+ ex = sfn.start_execution(stateMachineArn=sm["stateMachineArn"], input="{}")++ desc = _wait_sfn(sfn, ex["executionArn"])+ assert desc["status"] == "SUCCEEDED"+ assert json.loads(desc["output"]) == "timeout"+ events = sfn.get_execution_history(executionArn=ex["executionArn"])["events"]+ assert [e["type"] for e in events].count("TaskScheduled") == 1+++_SFN_FAIL_BRANCH = {"StartAt": "F", "States": {"F": {"Type": "Fail", "Error": "MyErr", "Cause": "c"}}}++[email protected]("state", [+ {"Type": "Parallel", "Branches": [_SFN_FAIL_BRANCH]},+ {"Type": "Map", "ItemsPath": "$.xs", "ItemProcessor": _SFN_FAIL_BRANCH},+], ids=["parallel", "map"])+def test_sfn_parallel_and_map_apply_retry_and_catch(sfn, state):+ """A failed branch or iteration fails the state with its error, which the state's Retry and Catch handle."""+ definition = json.dumps({+ "StartAt": "S",+ "States": {+ "S": {+ **state,+ "Retry": [{"ErrorEquals": ["MyErr"], "IntervalSeconds": 1, "MaxAttempts": 1}],+ "Catch": [{"ErrorEquals": ["MyErr"], "ResultPath": "$.err", "Next": "Caught"}],+ "End": True,+ },+ "Caught": {"Type": "Pass", "End": True},+ },+ })+ sm = sfn.create_state_machine(+ name=f"sfn-{state['Type'].lower()}-catch-{_uuid_mod.uuid4().hex[:8]}", definition=definition,+ roleArn="arn:aws:iam::000000000000:role/R",+ )+ ex = sfn.start_execution(stateMachineArn=sm["stateMachineArn"], input='{"xs": [1]}')++ desc = _wait_sfn(sfn, ex["executionArn"])+ assert desc["status"] == "SUCCEEDED"+ assert json.loads(desc["output"]) == {"xs": [1], "err": {"Error": "MyErr", "Cause": "c"}}++def test_sfn_integration_lambda_invoke_wait_for_task_token(sfn, lam):"""lambda:invoke.waitForTaskToken must deliver the *unwrapped* Payload tothe handler, exactly like the synchronous lambda:invoke path.