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.27 (#2209)
Nahuel Nucera7e0f8bc75596
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex abf5eae3..e24b3a64 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,53 +12,40 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **Auth — the request time of a header-signed request is checked** — under `AUTH=true` a request signed with an IAM user or STS session key was served whatever its time; one signed more than 15 minutes (STS, IAM, SNS, SQS, DynamoDB, S3, ECR, RDS, ElastiCache) or 5 minutes (the default for other services) from the server clock answers `SignatureDoesNotMatch` / `InvalidSignatureException` with AWS's `Signature expired` or `Signature not yet current` message, `RequestTimeTooSkewed` from S3 and `AuthFailure` from EC2. Contributed by @iot-rocket.- **Auth — the session token of a header-signed request is checked** — under `AUTH=true` an STS session key sent without its token was accepted and now answers as an unknown key, and a wrong token, or a token with an IAM user key, answers `InvalidClientTokenId` (`UnrecognizedClientException` from JSON services, `InvalidToken` 400 from S3), as on AWS. Contributed by @iot-rocket.- **Auth — header signatures are verified for IAM user and STS session keys** — under `AUTH=true` a request signed with such a key and the wrong secret, or changed after signing, was served; it now answers `SignatureDoesNotMatch` (or the service's `InvalidSignatureException`), an `Authorization` header without its `Signature` or `SignedHeaders` answers `IncompleteSignature` (Lambda `MissingAuthenticationTokenException`, S3 `AuthorizationHeaderMalformed`) and a credential date other than the request date `SignatureDoesNotMatch` (S3 `AuthorizationHeaderMalformed`), S3 unsigned, streaming and signed-chunk payloads are checked the same way, and the root key still accepts any secret. Contributed by @iot-rocket.+- **IoT — MQTT publish, subscribe and receive evaluate IoT policies under `AUTH=true`** — after the CONNECT a certificate session could publish, subscribe and receive on any topic; it now needs `iot:Publish` on the topic (and `iot:RetainPublish` for a retained message or will), `iot:Subscribe` per topic filter and `iot:Receive` per delivered message. A refused PUBLISH or SUBSCRIBE closes an MQTT 3.1.1 connection (disconnect reason `CLIENT_ERROR`), MQTT 5 answers PUBACK 0x87, DISCONNECT 0x87 at QoS 0 (`AUTH_ERROR`) or 0x87 for the refused filter, which the `subscribed` event leaves out (no event when none is granted), a refused will refuses the CONNECT, and a message the subscriber may not receive is dropped. Contributed by @iot-rocket.+- **IoT — MQTT connections evaluate `iot:Connect` under `AUTH=true`** — a device certificate on the mTLS listener connected under any client id, with or without a policy; with `AUTH=true` the CONNECT now needs an attached policy that allows `iot:Connect` on `client/<client id>` and none that denies it, with `${iot:ClientId}`, `${iot:Connection.Thing.ThingName}`, `iot:Connection.Thing.IsAttached` and `${iot:Certificate.Subject.CommonName}` resolved. A refusal closes an MQTT 3.1.1 connection without a CONNACK, answers MQTT 5 with CONNACK 0x87 and publishes `$aws/events/presence/connect_failed/{clientId}`. Contributed by @iot-rocket.+- **IoT — `TagResource`, `UntagResource` and `ListTagsForResource`** — the three operations answered `Unsupported IoT path`, so the tags the Create calls accept could not be read back. They now work on thing types, thing groups, policies, topic rules, jobs, job templates, CA certificates, provisioning templates and domain configurations with AWS's limits and errors, Create calls and CloudFormation `Tags` write the same tags, and deleting a resource drops them. Contributed by @iot-rocket.+- **IoT — retained messages** — `GetRetainedMessage` and `ListRetainedMessages` answered 501 `not yet implemented`; they now return the broker's retained messages (newest first, paged by `maxResults` and `nextToken`, with the user properties of an MQTT 5 publish), and a `PERSIST_STATE=1` restart keeps each message's `lastModifiedTime` and user properties. Contributed by @iot-rocket.+- **IoT — `ListJobExecutionsForJob`** — `GET /jobs/{jobId}/things` answered 400 `Unsupported IoT path`; it now lists every execution of the job, earlier ones of a rejoined thing included, most recently updated first, with the `status` filter and `maxResults` / `nextToken` paging. Contributed by @iot-rocket.+- **IoT — `DeleteJobExecution`** — `DELETE /things/{thingName}/jobs/{jobId}/executionNumber/{executionNumber}` answered 400 `Unsupported IoT path`; it now deletes the execution (an `IN_PROGRESS` one only with `force`), drops it from the job's lists and counts, completes the job when only finished executions are left, and publishes the `deleted` job execution event and the thing's `jobs/notify` topics; a `CONTINUOUS` job's thing left with no execution gets none back until it leaves the group, which leaves a `REMOVED` execution 1. Contributed by @iot-rocket.+- **Cognito — `InboundFederation` trigger on SAML and OIDC sign-in** — `LambdaConfig.InboundFederation` was stored but never invoked; SAML and OIDC federated sign-in now call the Lambda with `InboundFederation_ExternalProvider`, the provider-prefixed `userName` and the IdP's `samlResponse` or `idToken`. A non-empty `userAttributesToMap` replaces the IdP attributes before `AttributeMapping`, `{}` keeps them, and a failing or missing function fails the sign-in with `UserLambdaValidationException`. Contributed by @kjdev.### Fixed-- **Step Functions — aws-sdk results for JSON-protocol services keep the SDK's shape at every depth** — only the result's top-level keys took the SDK's names, so nested members kept their wire casing (`Executions[].executionArn`, `SecretList[].ARN`), timestamps stayed epoch numbers and absent members came back as `null`; the result is now shaped by the service's output model as on AWS: structure members renamed at every depth (DynamoDB's `BOOL`, `NULL` and `SS` as `Bool`, `Nul` and `Ss`), map keys such as attribute names and tag keys kept as sent, timestamps as ISO 8601 with milliseconds, and absent members left out. Two-letter all-caps member names (`SS`, `NS`, `ID`) now take the SDK's casing in every aws-sdk result.-- **Step Functions — JSONata Fail and Wait fields are evaluated** — a JSONata Fail state raised its `Error` and `Cause` expressions as literal text, a JSONata Wait failed on a `Seconds` expression, ignored a `Timestamp` expression and dropped its `Output` and `Assign`, and JSONPath `ErrorPath`/`CausePath` were ignored; they are now evaluated, with AWS's `States.QueryEvaluationError` or `States.Runtime` for a result of the wrong type, a `Seconds` that is not a non-negative integer and an unparsable `Timestamp`.+- **Step Functions — aws-sdk Parameters for JSON-protocol services take the wire names** — `ecs` and `ecr` received an aws-sdk task's PascalCase `Parameters` as sent, so their handlers ignored them (`describeClusters` with `Clusters` described `default`, `describeRepositories` with `RepositoryNames` returned every repository), and `sfn` and `cloudwatchlogs` lowercased every key, map keys included, so `tagResource` stored `Team-Name` as `team-Name`; the parameters are now renamed by the operation's input model, with map keys such as tag keys kept as written. Reported by @lucasmfraser.+- **Step Functions — aws-sdk results for JSON-protocol services keep the SDK's shape at every depth** — only the result's top-level keys took the SDK's names, so nested members kept their wire casing (`Executions[].executionArn`, `SecretList[].ARN`), timestamps stayed epoch numbers and absent members came back as `null`; the result is now shaped by the service's output model: structure members renamed at every depth (DynamoDB's `BOOL`, `NULL` and `SS` as `Bool`, `Nul` and `Ss`), map keys such as attribute names and tag keys kept as sent, timestamps as ISO 8601 with milliseconds, and absent members left out. A leading acronym is now lowered in every aws-sdk result, including two-letter names and ones with digits (`ID` as `Id`, `EC2InstanceId` as `Ec2InstanceId`, `MD5OfMessageBody` as `Md5OfMessageBody`). Contributed by @lucasmfraser.+- **S3 — `s3:prefix`, `s3:delimiter` and `s3:max-keys` under `AUTH=true`** — `ListObjects`, `ListObjectsV2` and `ListObjectVersions` set none of the three condition keys, so a `ListBucket` or `ListBucketVersions` grant scoped by them, such as `StringLike` on `s3:prefix` for one user's home folder, never matched and the listing answered `AccessDenied`; they now carry the request's `prefix`, `delimiter` and `max-keys`, path-style and virtual-hosted. Reported by @bettiah.+- **Idle memory** — the IoT mTLS listener built its TLS context at boot, which imported `cryptography` and minted the broker certificate before any device connected. It now binds port 8883 without TLS and builds the context on the first connection, and `x509_utils` imports `cryptography` on first use: an idle container drops from about 36.7 to 32.8 MiB.+- **Cognito — token lifetimes follow the app client** — access and ID tokens, `ExpiresIn` and the `/oauth2/token` `expires_in` were always one hour; they now follow the client's `AccessTokenValidity`, `IdTokenValidity` and `TokenValidityUnits` (one hour when unset, as on AWS), a client created without the two validities no longer reports `60` for them, and an expired token is refused by API Gateway's Cognito and JWT authorizers and, with `AUTH=true`, an expired access token by Cognito with `Access Token has expired`. Contributed by @iot-rocket.+- **Cognito — access tokens are verified under `AUTH=true`** — `GetUser` and the other calls that take an `AccessToken` accepted any JWT carrying a user's `sub`, including an ID token, a token with an altered payload and a token revoked by `GlobalSignOut`, `AdminUserGlobalSignOut` or `RevokeToken`; with `AUTH=true` they now answer `NotAuthorizedException` with `Invalid Access Token`, `Could not verify signature for Access Token` or `Access Token has been revoked`, as AWS does. Contributed by @iot-rocket.+- **IAM — user and role tag keys are case-insensitive** — `TagUser` and `TagRole` with `department` added a second tag beside `Department`, and `UntagUser` and `UntagRole` missed a key spelled differently; user and role tag keys now compare without case and keep the spelling last written, and `CreateUser`, `CreateRole`, `TagUser` and `TagRole` refuse keys that repeat without case with `InvalidInput` `Duplicate tag keys found. Please note that Tag keys are case insensitive.`, as does an `AWS::IAM::User` or `AWS::IAM::Role` whose stack tag differs from one of its own tags only in case. Other IAM resources keep case-sensitive keys. Contributed by @gakuto-cw21.+- **Signer — signing material checks in `PutSigningProfile`** — `PutSigningProfile` accepted any certificate ARN, or no `signingMaterial` at all, on every platform; the Lambda and Notation platforms now refuse any `signingMaterial` (`InvalidProfileParameters`), and with `AUTH=true` the IoT and FreeRTOS platforms refuse a profile without `signingMaterial` and a certificate ARN that is malformed, in another region or account, unknown to ACM or not issued, with AWS's errors. Contributed by @iot-rocket.+- **Step Functions — JSONata Fail and Wait fields are evaluated** — a JSONata Fail state raised its `Error` and `Cause` expressions as literal text, a JSONata Wait failed on a `Seconds` expression, ignored a `Timestamp` expression and dropped its `Output` and `Assign`, and JSONPath `ErrorPath`/`CausePath` were ignored; they are now evaluated, with AWS's `States.QueryEvaluationError` or `States.Runtime` for a result of the wrong type, a `Seconds` that is not a non-negative integer and an unparsable `Timestamp`. Contributed by @lucasmfraser.- **S3 — presigned URLs keep AWS's time limits under `AUTH=true`** — an `X-Amz-Expires` over 604800 seconds or not a number, or a malformed `X-Amz-Date`, answers 400 `AuthorizationQueryParametersError`, and a URL dated more than 15 minutes ahead answers 403 `AccessDenied` `Request is not yet valid`, where they were served. Contributed by @iot-rocket.- **Auth — credential failures in the service's protocol** — under `AUTH=true` an unknown, inactive or expired access key answered `UnrecognizedClientException` 403 from every service; it now gets the code, status and `Content-Type` AWS sends for the service's protocol, for example `InvalidClientTokenId` 403 from IAM and SQS, `UnrecognizedClientException` 400 from DynamoDB, `InvalidAccessKeyId` 403 from S3 and `AuthFailure` 401 from EC2. Contributed by @iot-rocket.-### Fixed-- **Step Functions — `ListExecutions` order and pagination** — executions came back oldest first, so `maxResults=1` returned the oldest, and `nextToken` was an offset; they now come back most recent first (running executions by `startDate`, the rest by `stopDate`), the token resumes after the last execution returned so one started between pages is not repeated, an unreadable token answers `InvalidToken` and `maxResults=0` uses the default, as on AWS.+- **Step Functions — `ListExecutions` order and pagination** — executions came back oldest first, so `maxResults=1` returned the oldest, and `nextToken` was an offset; they now come back most recent first (running executions by `startDate`, the rest by `stopDate`), the token resumes after the last execution returned so one started between pages is not repeated, an unreadable token answers `InvalidToken` and `maxResults=0` uses the default, as on AWS. Contributed by @lucasmfraser.- **Cognito — confirmation codes are checked under `AUTH=true`** — `ConfirmSignUp` and `ConfirmForgotPassword` accepted any code, and `ConfirmForgotPassword` changed the password even when no reset was requested; with `AUTH=true` they take only the issued code (`123456` for sign-up and `654321` for a password reset, as before), answer a wrong one with `CodeMismatchException` and a code that was never issued with `ExpiredCodeException`, and `ConfirmSignUp` refuses a user who is not `UNCONFIRMED` with `NotAuthorizedException`, as AWS does. Contributed by @iot-rocket.- **Cognito — `ExplicitAuthFlows` is enforced for the password flows under `AUTH=true`** — with `AUTH=true` a client that lists its auth flows now refuses `USER_PASSWORD_AUTH`, `ADMIN_USER_PASSWORD_AUTH` and `ADMIN_NO_SRP_AUTH` unless the list enables them (the legacy `USER_PASSWORD_AUTH` and `ADMIN_NO_SRP_AUTH` names included), with the `InvalidParameterException` AWS returns. Contributed by @iot-rocket.- **Cognito — `CUSTOM_AUTH` on clients without `ALLOW_` flows** — a client created without `ExplicitAuthFlows`, or with only the legacy names, refused `CUSTOM_AUTH`; it is now enabled, as on AWS, and a client whose `ALLOW_` list leaves it out answers `CUSTOM_AUTH is not enabled for the client.` as AWS does. Contributed by @iot-rocket.-- **Cognito — token lifetimes follow the app client** — access and ID tokens, `ExpiresIn` and the `/oauth2/token` `expires_in` were always one hour; they now follow the client's `AccessTokenValidity`, `IdTokenValidity` and `TokenValidityUnits` (one hour when unset, as on AWS), a client created without the two validities no longer reports `60` for them, and an expired token is refused by API Gateway's Cognito and JWT authorizers and, with `AUTH=true`, an expired access token by Cognito with `Access Token has expired`. Contributed by @iot-rocket.-- **Cognito — access tokens are verified under `AUTH=true`** — `GetUser` and the other calls that take an `AccessToken` accepted any JWT carrying a user's `sub`, including an ID token, a token with an altered payload and a token revoked by `GlobalSignOut`, `AdminUserGlobalSignOut` or `RevokeToken`; with `AUTH=true` they now answer `NotAuthorizedException` with `Invalid Access Token`, `Could not verify signature for Access Token` or `Access Token has been revoked`, as AWS does. Contributed by @iot-rocket.--- **Cognito — token lifetimes follow the app client** — access and ID tokens, `ExpiresIn` and the `/oauth2/token` `expires_in` were always one hour; they now follow the client's `AccessTokenValidity`, `IdTokenValidity` and `TokenValidityUnits` (one hour when unset, as on AWS), a client created without the two validities no longer reports `60` for them, and an expired token is refused by API Gateway's Cognito and JWT authorizers and, with `AUTH=true`, an expired access token by Cognito with `Access Token has expired`. Contributed by @iot-rocket.-- **Cognito — access tokens are verified under `AUTH=true`** — `GetUser` and the other calls that take an `AccessToken` accepted any JWT carrying a user's `sub`, including an ID token, a token with an altered payload and a token revoked by `GlobalSignOut`, `AdminUserGlobalSignOut` or `RevokeToken`; with `AUTH=true` they now answer `NotAuthorizedException` with `Invalid Access Token`, `Could not verify signature for Access Token` or `Access Token has been revoked`, as AWS does. Contributed by @iot-rocket.--- **CloudFormation — API Gateway v2 stage `Ref`** — `Ref` returned `<apiId>/<stageName>`, causing an `AWS::ApiGatewayV2::ApiMapping` using the reference as its `Stage` to fail with `Invalid stage identifier specified`; new stages now return the stage name. Stage updates, replacement on `ApiId` or `StageName` changes, and deletion use the resolved resource properties, including for stacks with legacy physical IDs.-- **IAM / CloudFormation — user and role tag keys** — IAM user and role tag keys now compare without case while preserving their spelling. Create and tag operations reject duplicate keys, untag operations match keys regardless of case, and CloudFormation validates duplicate keys and merges stack tags accordingly. User tag updates also compare keys without case. Other resource types retain case-sensitive tag handling.-- **Signer — signing material checks in `PutSigningProfile` under `AUTH=true`** — `PutSigningProfile` accepted any certificate ARN, or no `signingMaterial` at all, on every platform; with `AUTH=true` the IoT and FreeRTOS platforms now refuse a profile without `signingMaterial` and a certificate ARN that is malformed, in another region or account, unknown to ACM or not issued, and the Lambda and Notation platforms refuse any `signingMaterial`, with AWS's errors. Contributed by @iot-rocket.--### Added--- **IoT — MQTT publish, subscribe and receive evaluate IoT policies under `AUTH=true`** — after the CONNECT a certificate session could publish, subscribe and receive on any topic; it now needs `iot:Publish` on the topic (and `iot:RetainPublish` for a retained message or will), `iot:Subscribe` per topic filter and `iot:Receive` per delivered message. A refused PUBLISH or SUBSCRIBE closes an MQTT 3.1.1 connection (disconnect reason `CLIENT_ERROR`), MQTT 5 answers PUBACK 0x87, DISCONNECT 0x87 at QoS 0 (`AUTH_ERROR`) or 0x87 for the refused filter, which the `subscribed` event leaves out (no event when none is granted), a refused will refuses the CONNECT, and a message the subscriber may not receive is dropped. Contributed by @iot-rocket.-- **IoT — MQTT connections evaluate `iot:Connect` under `AUTH=true`** — a device certificate on the mTLS listener connected under any client id, with or without a policy; with `AUTH=true` the CONNECT now needs an attached policy that allows `iot:Connect` on `client/<client id>` and none that denies it, with `${iot:ClientId}`, `${iot:Connection.Thing.ThingName}`, `iot:Connection.Thing.IsAttached` and `${iot:Certificate.Subject.CommonName}` resolved. A refusal closes an MQTT 3.1.1 connection without a CONNACK, answers MQTT 5 with CONNACK 0x87 and publishes `$aws/events/presence/connect_failed/{clientId}`. Contributed by @iot-rocket.-### Fixed-+- **CloudFormation — API Gateway v2 stage `Ref`** — `Ref` returned `<apiId>/<stageName>`, causing an `AWS::ApiGatewayV2::ApiMapping` using the reference as its `Stage` to fail with `Invalid stage identifier specified`; new stages now return the stage name. Stage updates, replacement on `ApiId` or `StageName` changes, and deletion use the resolved resource properties, including for stacks with legacy physical IDs. Contributed by @matuscongrady.- **IoT — republish inside the rule's own topic filter** — `CreateTopicRule` and `ReplaceTopicRule` accepted a `republish` action whose topic the rule's `FROM` filter matches, so the rule fed on its own output; they now refuse it with AWS's `InvalidRequestException`, and an `AWS::IoT::TopicRule` with such an action fails its stack. Contributed by @iot-rocket.-### Added--- **IoT — `TagResource`, `UntagResource` and `ListTagsForResource`** — the three operations answered `Unsupported IoT path`, so the tags the Create calls accept could not be read back. They now work on thing types, thing groups, policies, topic rules, jobs, job templates, CA certificates, provisioning templates and domain configurations with AWS's limits and errors, Create calls and CloudFormation `Tags` write the same tags, and deleting a resource drops them. Contributed by @iot-rocket.-### Fixed-- **IoT — deleting things, certificates, policies and thing types still in use** — `DeleteThing` detached a thing's certificates and deleted it, and `DeleteCertificate` refused only an `ACTIVE` certificate. Now `DeleteThing` refuses a thing with a certificate attached, `DeleteCertificate` refuses a certificate with things attached and, without `forceDelete`, one with policies attached (`forceDelete` detaches them), `DeletePolicy` refuses a policy with non-default versions and `DeleteThingType` one that things still use, all with AWS's messages. Contributed by @iot-rocket.- **IoT — `RegisterCertificate` under an inactive CA** — a certificate issued by a CA that is not `ACTIVE` registered anyway; it is now refused with `CertificateStateException`, with or without `caCertificatePem`. An unregistered CA and a CA that did not issue the certificate are refused with AWS's codes and messages. Contributed by @iot-rocket.- **IoT — rule SQL `principal()` and `traceid()`** — both resolved to Undefined; `principal()` now returns the client certificate id for mTLS, the caller's `GetCallerIdentity` `UserId` for HTTP Publish and SigV4 WebSocket sessions (also their lifecycle events' `principalIdentifier`) and the rule role's session for a republish, and `traceid()` returns a per-message id that the errorAction document carries as `cloudwatchTraceId`. Contributed by @iot-rocket.-### Added--- **IoT — retained messages** — `GetRetainedMessage` and `ListRetainedMessages` answered 501 `not yet implemented`; they now return the broker's retained messages (newest first, paged by `maxResults` and `nextToken`, with the user properties of an MQTT 5 publish), and a `PERSIST_STATE=1` restart keeps each message's `lastModifiedTime` and user properties. Contributed by @iot-rocket.-- **IoT — `ListJobExecutionsForJob`** — `GET /jobs/{jobId}/things` answered 400 `Unsupported IoT path`; it now lists every execution of the job, earlier ones of a rejoined thing included, most recently updated first, with the `status` filter and `maxResults` / `nextToken` paging. Contributed by @iot-rocket.-- **IoT — `DeleteJobExecution`** — `DELETE /things/{thingName}/jobs/{jobId}/executionNumber/{executionNumber}` answered 400 `Unsupported IoT path`; it now deletes the execution (an `IN_PROGRESS` one only with `force`), drops it from the job's lists and counts, completes the job when only finished executions are left, and publishes the `deleted` job execution event and the thing's `jobs/notify` topics; a `CONTINUOUS` job's thing left with no execution gets none back until it leaves the group, which leaves a `REMOVED` execution 1. Contributed by @iot-rocket.-### Fixed-- **CloudFormation — `AWS::Logs::LogGroup` delete** — a stack delete or a `LogGroupName` replacement removed only the group record, so a metric filter or resource policy added through the Logs API stayed and came back with a new group of the same name; the group is now deleted through `DeleteLogGroup`. Contributed by @iot-rocket.- **Cognito Identity — `GetOpenIdToken` claims** — the token was a user-pool ID token with an empty audience; it is now issued by `https://cognito-identity.amazonaws.com` with the identity pool id as `aud`, the identity id as `sub`, an `amr` list naming the login providers and the user-pool sign-in, the pool ARN in `https://cognito-identity.amazonaws.com/identity-pool-arn` and a 10-minute lifetime. An identity id that no pool knows gets `ResourceNotFoundException` instead of a token. Contributed by @iot-rocket.- **CloudTrail — new trails start with logging off** — `CreateTrail` left a new trail logging, and `GetTrailStatus` reported a `StartLoggingTime` an hour back and a `LatestDeliveryTime` of now. A new trail now reports `IsLogging` false until `StartLogging`, and `GetTrailStatus` returns only the `StartLoggingTime` and `StopLoggingTime` of calls made (a restart keeps the last stop time), without `LatestDeliveryTime` or empty error strings. Contributed by @iot-rocket.-- **CloudFormation — EventBridge rules accept a bus ARN** — `AWS::Events::Rule` stored an ARN-valued `EventBusName` as the bus name, so `PutEvents` succeeded without delivering to its targets. Create, update, delete and drift detection now resolve the ARN through the existing EventBridge parser and use the bus name internally.+- **CloudFormation — EventBridge rules accept a bus ARN** — `AWS::Events::Rule` stored an ARN-valued `EventBusName` as the bus name, so `PutEvents` succeeded without delivering to its targets. Create, update, delete and drift detection now resolve the ARN through the existing EventBridge parser and use the bus name internally. Contributed by @matuscongrady.+- **Cognito — SAML `/oauth2/authorize` with `MetadataFile`** — a SAML provider created with only `MetadataFile` was refused with `InvalidParameterException`; the IdP sign-in URL now comes from `IDPSSOEndpoint`, then the metadata's HTTP-Redirect `SingleSignOnService`, then `MetadataURL`. Contributed by @kjdev.## [1.5.26] — 2026-10-11diff --git a/README.md b/README.mdindex 61917450..3979be3f 100644--- a/README.md+++ b/README.md@@ -646,8 +646,8 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i| **CodeBuild** | CreateProject, BatchGetProjects, ListProjects, UpdateProject, DeleteProject, StartBuild, BatchGetBuilds, StopBuild, ListBuilds, ListBuildsForProject, BatchDeleteBuilds | 11 actions; project and build metadata stored in-memory; builds complete immediately with SUCCEEDED status by default. Set `MINISTACK_CODEBUILD_EXECUTE=1` and mount the Docker socket to **really run them**: the project's inline buildspec goes to the official AWS CodeBuild local agent, which runs the phases in `environment.image`, and `BatchGetBuilds` reports live `phases` with a real `SUCCEEDED`/`FAILED` outcome. Execution needs the workspace shared with the host at the **same path** (`-v /tmp/ministack-codebuild:/tmp/ministack-codebuild`), because the agent bind-mounts it into the build container; a build gets `AWS_ENDPOINT_URL` pointing back at MiniStack, honours `timeoutInMinutes`, and is stopped by `StopBuild`. An executed build streams the agent output into its `logs.groupName` / `logs.streamName`, so `aws logs tail` reads the build log back || **AppConfig** | CreateApplication, GetApplication, ListApplications, UpdateApplication, DeleteApplication, CreateEnvironment, GetEnvironment, ListEnvironments, UpdateEnvironment, DeleteEnvironment, CreateConfigurationProfile, GetConfigurationProfile, ListConfigurationProfiles, UpdateConfigurationProfile, DeleteConfigurationProfile, CreateHostedConfigurationVersion, GetHostedConfigurationVersion, ListHostedConfigurationVersions, DeleteHostedConfigurationVersion, CreateDeploymentStrategy, GetDeploymentStrategy, ListDeploymentStrategies, UpdateDeploymentStrategy, DeleteDeploymentStrategy, StartDeployment, GetDeployment, ListDeployments, StopDeployment, TagResource, UntagResource, ListTagsForResource, StartConfigurationSession, GetLatestConfiguration | 33 operations; control plane + data plane; hosted configuration versions; the AWS-predefined deployment strategies (4) are listed and immutable; deployments move through `DEPLOYING`, `BAKING` and `COMPLETE` on the strategy's schedule (`LINEAR` or `EXPONENTIAL` steps, then the bake time), with `PercentageComplete`, the event log and the environment `State` reported along the way; a `Monitors` alarm that goes to `ALARM` before the bake ends rolls the deployment back; one deployment per environment at a time (`ConflictException`, also for a stale `LatestDeploymentNumber`); `StopDeployment` rolls back a `DEPLOYING` deployment, and with `AllowRevert` also a `BAKING` one, or reverts a completed one within 72 hours; during a rollout a session gets the new version once the rollout reaches its fixed slot (MiniStack's choice, since AWS does not document how it picks targets); `GetLatestConfiguration` returns an empty body when the session already has the latest version, plus `Version-Label`, and uses `RequiredMinimumPollIntervalInSeconds` as the poll interval || **Transfer Family** | CreateServer, DescribeServer, DeleteServer, ListServers, StartServer, StopServer, CreateUser, DescribeUser, DeleteUser, ListUsers, ImportSshPublicKey, DeleteSshPublicKey | 12 operations; **real SFTP listener** on `:2222` (override with `SFTP_PORT`) backed by S3 — `ls`, `put`, `get`, `mkdir`, `rename` work end-to-end against the local S3 emulator; `SFTP_PORT_PER_SERVER=1` allocates one port per `CreateServer` from `SFTP_BASE_PORT` (default 2300); SSH key auth scans every user across every server and account; `LOGICAL` and `PATH` home-directory mappings; host key persists across restarts when `PERSIST_STATE=1` |-| **IoT Jobs** | Control plane (`iot`): CreateJob, UpdateJob, DescribeJob, ListJobs, GetJobDocument, CancelJob, DeleteJob, ListJobExecutionsForThing, DescribeJobExecution, CancelJobExecution, CreateJobTemplate, DescribeJobTemplate, ListJobTemplates, DeleteJobTemplate; data plane (`iot-jobs-data`): GetPendingJobExecutions, StartNextPendingJobExecution, DescribeJobExecution (incl. the `$next` sentinel), UpdateJobExecution | 14 control-plane + 4 device data-plane operations sharing one store. A job created with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a request member replaces the template's. Executions walk `QUEUED → IN_PROGRESS → {SUCCEEDED, FAILED, REJECTED, CANCELED, TIMED_OUT}`; an execution past its `timeoutConfig.inProgressTimeoutInMinutes`, or past the `stepTimeoutInMinutes` the device reported, becomes `TIMED_OUT`, and the device plane reports `approximateSecondsBeforeTimedOut` while it runs. `REMOVED` is modeled and counted in `jobProcessDetails` but nothing sets it: deleting a thing DELETES its executions (freeing a job that was only waiting on that thing) rather than marking them `REMOVED`. `versionNumber` gives optimistic concurrency: every transition bumps it and a stale `expectedVersion` is rejected with a 409 whose message carries the current version — coded `VersionConflictException` on the control plane and `InvalidStateTransitionException` on the device plane, each as its own service model declares. `executionNumber` is write-once (always 1: an execution is never re-queued). Devices may only report `IN_PROGRESS` / `SUCCEEDED` / `FAILED` / `REJECTED` via `UpdateJobExecution`; targets are thing or thing-group ARNs — `SNAPSHOT` jobs resolve group membership once at creation, `CONTINUOUS` jobs also pick up things added to a target group later, and a target must name a thing or thing group in the caller's own account and region (anything else is `ResourceNotFoundException`, since it would resolve to no devices at all); a non-continuous job auto-`COMPLETED`s (with `jobProcessDetails` counts) once every execution is terminal. **`documentSource` is not fetched**: a job created with an S3 `documentSource` serves a `{"documentSource": "<url>"}` placeholder as its document rather than the object's content, so the lifecycle still runs — pass `document` when the content matters; a job template with a `documentSource` stores the same placeholder. **Timestamps are epoch seconds on every plane, as AWS documents**: control-plane responses use `timestamp` shapes (boto3 parses them to datetimes) while `iot-jobs-data` responses carry whole-second integer `long`s. **Jobs over MQTT**: the reserved `$aws/things/<thing>/jobs/#` request topics (`get`, `start-next`, `<jobId>/get` incl. `$next`, `<jobId>/update`) answer on their `accepted`/`rejected` topics from the same store as the HTTP plane (`jobDocument` as a JSON object over MQTT, a string over HTTP, as on AWS; rejections carry the string `ErrorCode` values and the execution's state on version and state-transition conflicts); `notify` fires when the pending set changes and `notify-next` when the queue front changes; `stepTimeoutInMinutes` and `executionNumber` are accepted but ignored. Job state persists with the IoT store when `PERSIST_STATE=1` |-| **IoT Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, ListThingGroupsForThing, CreateKeysAndCertificate, RegisterCertificate, RegisterCertificateWithoutCA, CreateCertificateFromCsr, UpdateCertificate, DeleteCertificate, GetRegistrationCode, DeleteRegistrationCode, RegisterCACertificate, DescribeCACertificate, UpdateCACertificate, ListCACertificates, DeleteCACertificate, ListCertificatesByCA, CreateProvisioningTemplate, DescribeProvisioningTemplate, ListProvisioningTemplates, UpdateProvisioningTemplate, DeleteProvisioningTemplate, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, AttachPrincipalPolicy, DetachPrincipalPolicy, ListPrincipalPolicies, ListPolicyPrincipals, CreateTopicRule, GetTopicRule, ReplaceTopicRule, DeleteTopicRule, ListTopicRules, UpdateIndexingConfiguration, GetIndexingConfiguration, DescribeIndex, ListIndices, SearchIndex, DescribeEndpoint, Publish (HTTP), MQTT-over-WebSocket pub/sub, DescribeEventConfigurations, UpdateEventConfigurations, CreateDomainConfiguration, DescribeDomainConfiguration, ListDomainConfigurations, UpdateDomainConfiguration, DeleteDomainConfiguration | 63 operations + **MQTT 3.1.1 and 5.0 over WebSocket** (negotiated per connection) on the gateway port — clients use the address returned by `DescribeEndpoint`; local CA signs `CreateKeysAndCertificate` certificates (CA persists across restarts when `PERSIST_STATE=1`); multi-tenancy via transparent topic prefixing (same pattern as Transfer Family's shared SFTP listener); no plain TCP 1883 (real AWS IoT requires TLS or SigV4 on every connection), but a **native mTLS MQTT listener on 8883** serves device SDK binaries by default — the client certificate is optional (no certificate means the default account, like an unsigned WebSocket upgrade) and, when presented, must be registered `ACTIVE` in exactly one account, which then serves the session; unknown, inactive or doubly-registered certificates get a "not authorized" CONNACK (see `IOT_MTLS_PORT` in the environment table); local CA cert available at `GET /_ministack/iot/ca.pem` for SDK trust configuration; IoT policies are stored but **not enforced** on the data plane, except on mTLS MQTT connections with `AUTH=true`; **fleet indexing** works the way it does on AWS — `UpdateIndexingConfiguration` turns the `AWS_Things` index on (Terraform `aws_iot_indexing_configuration`), and searching while `thingIndexingMode` is `OFF` answers `ResourceNotFoundException`; `SearchIndex` then queries the live registry + classic shadows with `AND`-separated `thingName` / `thingTypeName` / `thingGroupNames` / `attributes.*` / `shadow.reported.*` / `shadow.desired.*` terms (`*` / `?` wildcards, `maxResults` / `nextToken` paging) — there is no projection to build, so hits are always current; the deprecated principal-policy family (`AttachPrincipalPolicy` / `DetachPrincipalPolicy` / `ListPrincipalPolicies` / `ListPolicyPrincipals`) maps 1:1 onto the modern policy-target store; **topic rules fire on matching publishes** (incl. Basic Ingest `$aws/rules/<name>`) with SQL SELECT projection (`topic()`, `timestamp()`, `encode()`, `newuuid()`, `replace()`, `clientid()`, `isUndefined()`), **WHERE-clause evaluation** (comparisons, `IN`, `LIKE`, `BETWEEN`, `IS NULL`, `regexp_matches`, bare boolean attributes, composed with `AND` / `OR` and parenthesised grouping; missing attributes fail closed as on AWS; unparseable SQL → `SqlParseException`), and `lambda` / `republish` / `dynamoDBv2` / `sns` / `sqs` actions dispatched in-process with the rule's `errorAction` on failure; **device shadows over MQTT** — the `$aws/things/<thing>/shadow[/name/<name>]/{get,update,delete}` reserved topics drive the shadow store and reply on `accepted` / `rejected` (with `delta` and `documents` on update); a **CA-certificate registry** (`RegisterCACertificate` and friends) with the just-in-time-registration `registered` event on `$aws/events/certificates/registered/{caCertificateId}`; a **provisioning-template registry** (`CreateProvisioningTemplate` and friends) — storage + CRUD only, so `provisioningRoleArn` is presence-checked but not resolved and the fleet-provisioning MQTT workflow (`$aws/provisioning-templates/...`) is not implemented; and `SearchIndex` answers `connectivity.connected` / `connectivity.timestamp` / `connectivity.disconnectReason` when `thingConnectivityIndexingMode` is `STATUS`, deriving `connected` from the live session registry; the broker publishes the presence and subscription lifecycle events (`$aws/events/presence/connected\|disconnected/{clientId}`, `$aws/events/subscriptions/subscribed\|unsubscribed/{clientId}`) |+| **IoT Jobs** | Control plane (`iot`): CreateJob, UpdateJob, DescribeJob, ListJobs, GetJobDocument, CancelJob, DeleteJob, ListJobExecutionsForThing, ListJobExecutionsForJob, DescribeJobExecution, CancelJobExecution, DeleteJobExecution, CreateJobTemplate, DescribeJobTemplate, ListJobTemplates, DeleteJobTemplate; data plane (`iot-jobs-data`): GetPendingJobExecutions, StartNextPendingJobExecution, DescribeJobExecution (incl. the `$next` sentinel), UpdateJobExecution | 16 control-plane + 4 device data-plane operations sharing one store. A job created with a `jobTemplateArn` takes the template's document, configuration and maintenance windows, and a request member replaces the template's. Executions walk `QUEUED → IN_PROGRESS → {SUCCEEDED, FAILED, REJECTED, CANCELED, TIMED_OUT}`; an execution past its `timeoutConfig.inProgressTimeoutInMinutes`, or past the `stepTimeoutInMinutes` the device reported, becomes `TIMED_OUT`, and the device plane reports `approximateSecondsBeforeTimedOut` while it runs. `REMOVED` is counted in `jobProcessDetails`; a thing that leaves every target group of a `CONTINUOUS` job turns its `QUEUED` execution `REMOVED`, or gets a `REMOVED` execution 1 (without an event) if all its executions were deleted; deleting a thing DELETES its executions (freeing a job that was only waiting on that thing) rather than marking them `REMOVED`. `versionNumber` gives optimistic concurrency: every transition bumps it and a stale `expectedVersion` is rejected with a 409 whose message carries the current version — coded `VersionConflictException` on the control plane and `InvalidStateTransitionException` on the device plane, each as its own service model declares. `executionNumber` is 1 for a thing's first execution of a job and one more each time the thing rejoins a `CONTINUOUS` job's target group after its execution finished. Devices may only report `IN_PROGRESS` / `SUCCEEDED` / `FAILED` / `REJECTED` via `UpdateJobExecution`; targets are thing or thing-group ARNs — `SNAPSHOT` jobs resolve group membership once at creation, `CONTINUOUS` jobs also pick up things added to a target group later, and a target must name a thing or thing group in the caller's own account and region (anything else is `ResourceNotFoundException`, since it would resolve to no devices at all); a non-continuous job auto-`COMPLETED`s (with `jobProcessDetails` counts) once every execution is terminal. **`documentSource` is not fetched**: a job created with an S3 `documentSource` serves a `{"documentSource": "<url>"}` placeholder as its document rather than the object's content, so the lifecycle still runs — pass `document` when the content matters; a job template with a `documentSource` stores the same placeholder. **Timestamps are epoch seconds on every plane, as AWS documents**: control-plane responses use `timestamp` shapes (boto3 parses them to datetimes) while `iot-jobs-data` responses carry whole-second integer `long`s. **Jobs over MQTT**: the reserved `$aws/things/<thing>/jobs/#` request topics (`get`, `start-next`, `<jobId>/get` incl. `$next`, `<jobId>/update`) answer on their `accepted`/`rejected` topics from the same store as the HTTP plane (`jobDocument` as a JSON object over MQTT, a string over HTTP, as on AWS; rejections carry the string `ErrorCode` values and the execution's state on version and state-transition conflicts); `notify` fires when the pending set changes and `notify-next` when the queue front changes; `stepTimeoutInMinutes` and `executionNumber` are accepted but ignored. Job state persists with the IoT store when `PERSIST_STATE=1` |+| **IoT Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, ListThingGroupsForThing, CreateKeysAndCertificate, RegisterCertificate, RegisterCertificateWithoutCA, CreateCertificateFromCsr, UpdateCertificate, DeleteCertificate, GetRegistrationCode, DeleteRegistrationCode, RegisterCACertificate, DescribeCACertificate, UpdateCACertificate, ListCACertificates, DeleteCACertificate, ListCertificatesByCA, CreateProvisioningTemplate, DescribeProvisioningTemplate, ListProvisioningTemplates, UpdateProvisioningTemplate, DeleteProvisioningTemplate, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, AttachPrincipalPolicy, DetachPrincipalPolicy, ListPrincipalPolicies, ListPolicyPrincipals, CreateTopicRule, GetTopicRule, ReplaceTopicRule, DeleteTopicRule, ListTopicRules, UpdateIndexingConfiguration, GetIndexingConfiguration, DescribeIndex, ListIndices, SearchIndex, DescribeEndpoint, Publish (HTTP), GetRetainedMessage, ListRetainedMessages, MQTT-over-WebSocket pub/sub, DescribeEventConfigurations, UpdateEventConfigurations, CreateDomainConfiguration, DescribeDomainConfiguration, ListDomainConfigurations, UpdateDomainConfiguration, DeleteDomainConfiguration, TagResource, UntagResource, ListTagsForResource | 68 operations + **MQTT 3.1.1 and 5.0 over WebSocket** (negotiated per connection) on the gateway port — clients use the address returned by `DescribeEndpoint`; local CA signs `CreateKeysAndCertificate` certificates (CA persists across restarts when `PERSIST_STATE=1`); multi-tenancy via transparent topic prefixing (same pattern as Transfer Family's shared SFTP listener); no plain TCP 1883 (real AWS IoT requires TLS or SigV4 on every connection), but a **native mTLS MQTT listener on 8883** serves device SDK binaries by default — the client certificate is optional (no certificate means the default account, like an unsigned WebSocket upgrade) and, when presented, must be registered `ACTIVE` in exactly one account, which then serves the session; unknown, inactive or doubly-registered certificates get a "not authorized" CONNACK (see `IOT_MTLS_PORT` in the environment table); local CA cert available at `GET /_ministack/iot/ca.pem` for SDK trust configuration; IoT policies are stored but **not enforced** on the data plane, except on mTLS MQTT connections with `AUTH=true`; **fleet indexing** works the way it does on AWS — `UpdateIndexingConfiguration` turns the `AWS_Things` index on (Terraform `aws_iot_indexing_configuration`), and searching while `thingIndexingMode` is `OFF` answers `ResourceNotFoundException`; `SearchIndex` then queries the live registry + classic shadows with `AND`-separated `thingName` / `thingTypeName` / `thingGroupNames` / `attributes.*` / `shadow.reported.*` / `shadow.desired.*` terms (`*` / `?` wildcards, `maxResults` / `nextToken` paging) — there is no projection to build, so hits are always current; the deprecated principal-policy family (`AttachPrincipalPolicy` / `DetachPrincipalPolicy` / `ListPrincipalPolicies` / `ListPolicyPrincipals`) maps 1:1 onto the modern policy-target store; **topic rules fire on matching publishes** (incl. Basic Ingest `$aws/rules/<name>`) with SQL SELECT projection (`topic()`, `timestamp()`, `encode()`, `newuuid()`, `replace()`, `clientid()`, `principal()`, `traceid()`, `isUndefined()`), **WHERE-clause evaluation** (comparisons, `IN`, `LIKE`, `BETWEEN`, `IS NULL`, `regexp_matches`, bare boolean attributes, composed with `AND` / `OR` and parenthesised grouping; missing attributes fail closed as on AWS; unparseable SQL → `SqlParseException`), and `lambda` / `republish` / `dynamoDBv2` / `sns` / `sqs` actions dispatched in-process with the rule's `errorAction` on failure; **device shadows over MQTT** — the `$aws/things/<thing>/shadow[/name/<name>]/{get,update,delete}` reserved topics drive the shadow store and reply on `accepted` / `rejected` (with `delta` and `documents` on update); a **CA-certificate registry** (`RegisterCACertificate` and friends) with the just-in-time-registration `registered` event on `$aws/events/certificates/registered/{caCertificateId}`; a **provisioning-template registry** (`CreateProvisioningTemplate` and friends) — storage + CRUD only, so `provisioningRoleArn` is presence-checked but not resolved and the fleet-provisioning MQTT workflow (`$aws/provisioning-templates/...`) is not implemented; and `SearchIndex` answers `connectivity.connected` / `connectivity.timestamp` / `connectivity.disconnectReason` when `thingConnectivityIndexingMode` is `STATUS`, deriving `connected` from the live session registry; the broker publishes the presence and subscription lifecycle events (`$aws/events/presence/connected\|disconnected/{clientId}`, `$aws/events/subscriptions/subscribed\|unsubscribed/{clientId}`) || **IoT Wireless** | GetPositionEstimate | Single operation (`POST /position-estimate`, SigV4 scope `iotwireless`, endpoint prefix `api.iotwireless`). **The response is the raw GeoJSON blob** — the output shape's `payload` trait — so boto3 hands back a `StreamingBody` under `GeoJsonPayload`, not a JSON envelope. Resolves from `Ip` only: `WiFiAccessPoints` / `CellTowers` / `Gnss` are accepted and ignored, `Timestamp` and `AdvancedConfiguration` only reach `properties`, and the estimate is synthetic + deterministic — the canonical IP (an IPv4-mapped IPv6 address counts as its IPv4 form) hashes onto lon [-180, 180) / lat [-60, 60), 4 decimals — so the same address always answers the same estimate and consumer tests can assert on it. `properties` carry `horizontalAccuracy` 1000000 (the value of one live call) and `horizontalConfidenceLevel` 0.68 (the default the AWS IoT Core Device Location guide documents — `AdvancedConfiguration.WiFiCellular.ConfidencePercent` overrides it, divided by 100, within the 50 to 99 the model allows) plus `timestamp`, which is always there: AWS documents the request's `Timestamp` as the resolve time and the receive time as its substitute when the caller sends none, so send a `Timestamp` and the whole blob is byte-identical. The real payload's `country` and city/state/postal properties are omitted for that determinism. An input with no resolver hint and an `IpAddress` that `ipaddress.ip_address()` refuses answer `ValidationException` (those two wordings are recorded from the live service; every other message in this service is MiniStack's own, since none is documented); a `Timestamp` that is not a Unix timestamp, and a `ConfidencePercent` outside the model's range, are `ValidationException` too; a valid address that is **not globally routable or is multicast** (private, loopback, TEST-NET, multicast groups, ...) answers `ResourceNotFoundException` `Cannot find position for the IP address <ip>`, mirroring the real service's refusal when its geo database has no entry. A well-formed request whose only measurements are WLAN/cell/GNSS is `ResourceNotFoundException` too — the developer guide documents 404 for exactly that ("no location information was found or solved ... The MAC address or cellular tower information is not sufficient ... The GNSS payload is not sufficient"), and 400 for measurement data formatted incorrectly. Stateless — nothing persists || **EventBridge Scheduler** | CreateSchedule, GetSchedule, UpdateSchedule, DeleteSchedule, ListSchedules, CreateScheduleGroup, GetScheduleGroup, DeleteScheduleGroup, ListScheduleGroups, TagResource, UntagResource, ListTagsForResource | 12 actions; schedules **fire their targets** — a background sweep invokes each enabled schedule's target (Lambda, SQS, SNS, Step Functions) when due, honoring `State`, `StartDate`/`EndDate`, and `ActionAfterCompletion: DELETE`; schedule groups with cascading deletes; `rate()`, `cron()`, `at()` expressions; group/prefix/state filters on list; default group auto-created; CFN `AWS::Scheduler::Schedule` and `AWS::Scheduler::ScheduleGroup` supported || **EKS** | CreateCluster, DescribeCluster, ListClusters, DeleteCluster, CreateNodegroup, DescribeNodegroup, ListNodegroups, DeleteNodegroup, CreateAddon, DescribeAddon, ListAddons, UpdateAddon, DeleteAddon, AssociateEncryptionConfig, CreateAccessEntry, DescribeAccessEntry, ListAccessEntries, UpdateAccessEntry, DeleteAccessEntry, AssociateAccessPolicy, DisassociateAccessPolicy, ListAssociatedAccessPolicies, AssociateIdentityProviderConfig, DescribeIdentityProviderConfig, DisassociateIdentityProviderConfig, ListIdentityProviderConfigs, CreatePodIdentityAssociation, DescribePodIdentityAssociation, ListPodIdentityAssociations, UpdatePodIdentityAssociation, DeletePodIdentityAssociation, TagResource, UntagResource, ListTagsForResource | `CreateCluster` spawns a real **k3s** container (75 MB) with a full Kubernetes API server; `kubectl`, Helm, and any K8s tooling work out of the box; cascading delete removes nodegroups and k3s container; addon CRUD (e.g. `vpc-cni`, `coredns`, `kube-proxy`, `aws-ebs-csi-driver`) at `/clusters/{name}/addons` flips status to `ACTIVE` on create / update; `AssociateEncryptionConfig` at `/clusters/{name}/encryption-config/associate` records KMS encryption config (rejects re-association, AWS-shape `update` envelope); **Access Entries** (modern post-1.29 IAM bindings — replaces aws-auth ConfigMap) at `/clusters/{name}/access-entries[/{principalArn}[/access-policies[/{policyArn}]]]` for Crossplane / Terraform `aws_eks_access_entry` + `aws_eks_access_policy_association`; OIDC discovery + JWKS served at the cluster's `identity.oidc.issuer` URL so Terraform's `aws_iam_openid_connect_provider` (IRSA) works against ministack; **OIDC Identity Provider Config** (`AssociateIdentityProviderConfig` / `DescribeIdentityProviderConfig` / `DisassociateIdentityProviderConfig` / `ListIdentityProviderConfigs`) at `/clusters/{name}/identity-provider-configs[/{verb}]` — one OIDC IdP per cluster, issuer + clientId + claims forwarded to the k3s API server via `--kube-apiserver-arg=oidc-*` flags, tags reachable via `ListTagsForResource`; CFN `AWS::EKS::Cluster` and `AWS::EKS::Nodegroup` supported |diff --git a/ministack/app.py b/ministack/app.pyindex 01fc8d09..1b536122 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -2140,12 +2140,20 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: d# IAM enforcement for S3 virtual-hosted requestsif AUTH:- from ministack.core.iam_actions import _s3_action, extract_resource_arn, s3_additional_checks+ from ministack.core.iam_actions import (+ _s3_action,+ extract_resource_arn,+ s3_additional_checks,+ s3_service_context,+ )s3_action = _s3_action(method, vhost_path, query_params)if s3_action:s3_resource = extract_resource_arn("s3", method, vhost_path, headers, body, query_params, "", "")- denied = _enforce_data_plane("s3", f"s3:{s3_action}", headers, query_params, "", resource_arn=s3_resource)+ denied = _enforce_data_plane(+ "s3", f"s3:{s3_action}", headers, query_params, "", resource_arn=s3_resource,+ service_context=s3_service_context(f"s3:{s3_action}", query_params),+ )if denied:return denied# A copy also reads its source, a batch delete is one check per@@ -2598,6 +2606,7 @@ async def _dispatch_service_request(extract_iam_action,extract_resource_arn,logs_service_context,+ s3_service_context,)from ministack.core.iam_evaluator import AuthError, enforce, pin_request_callerfrom ministack.core.responses import get_account_id@@ -2610,7 +2619,9 @@ async def _dispatch_service_request(service, method, path, headers, body, routing_params, region, get_account_id())service_context = (- dynamodb_service_context(body) if service == "dynamodb" else None+ dynamodb_service_context(body) if service == "dynamodb"+ else s3_service_context(iam_action, query_params) if service == "s3"+ else None)if service == "logs":from ministack.services import cloudwatch_logsdiff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex 16a2bcdf..377df845 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -1788,6 +1788,20 @@ def dynamodb_transaction_checks(return checks+def s3_service_context(iam_action: str, query_params: dict | None) -> dict:+ """The s3:prefix, s3:delimiter and s3:max-keys a ListBucket or ListBucketVersions request sends."""+ if iam_action not in ("s3:ListBucket", "s3:ListBucketVersions"):+ return {}+ context = {}+ for param in ("prefix", "delimiter", "max-keys"):+ value = (query_params or {}).get(param)+ if isinstance(value, list):+ value = value[0] if value else None+ if value is not None:+ context[f"s3:{param}"] = value+ return context++def dynamodb_service_context(body: bytes) -> dict:"""The DynamoDB condition keys a request carries.diff --git a/ministack/core/x509_utils.py b/ministack/core/x509_utils.pyindex 738a3b0b..ed749c82 100644--- a/ministack/core/x509_utils.py+++ b/ministack/core/x509_utils.py@@ -24,29 +24,32 @@ from __future__ import annotationsimport datetime as _dtimport hashlib+import importlib.utilimport loggingimport warningslogger = logging.getLogger("x509_utils")-try:- from cryptography import x509- from cryptography.exceptions import InvalidSignature- from cryptography.hazmat.primitives import hashes, serialization- from cryptography.hazmat.primitives.asymmetric import ec, rsa- from cryptography.x509.oid import NameOID-- HAS_CRYPTO = True-except ImportError: # pragma: no cover - exercised only when extras missing- HAS_CRYPTO = False+# Imported on first use: `cryptography` is ~11 MiB that an idle server never needs.+HAS_CRYPTO = importlib.util.find_spec("cryptography") is not None+x509 = InvalidSignature = hashes = serialization = ec = rsa = NameOID = Nonedef _require_crypto() -> None:+ global x509, InvalidSignature, hashes, serialization, ec, rsa, NameOIDif not HAS_CRYPTO:raise RuntimeError("ministack.core.x509_utils requires the `cryptography` package. ""Install Ministack with `[full]` extras or add cryptography>=41.0.")+ if x509 is None:+ from cryptography import x509 as _x509+ from cryptography.exceptions import InvalidSignature+ from cryptography.hazmat.primitives import hashes, serialization+ from cryptography.hazmat.primitives.asymmetric import ec, rsa+ from cryptography.x509.oid import NameOID++ x509 = _x509def generate_ca(diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex c48fc128..7624770a 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -1189,18 +1189,10 @@ def _with_stack_tags(resource_type: str, props: dict, stack_tags: list,own = [{"Key": key, "Value": value} for key, value in own.items()]own_list = [t for t in (own or []) if isinstance(t, dict) and "Key" in t]present = {t["Key"] for t in own_list}- if resource_type in ("AWS::IAM::User", "AWS::IAM::Role"):- _validate_iam_identity_tag_keys(resource_type, own_list)- present = {_iam._identity_tag_key(k) for k in present}- extra = {k: v for k, v in extra.items() if _iam._identity_tag_key(k) not in present}- else:- extra = {k: v for k, v in extra.items() if k not in present}merged = own_list + [{"Key": key, "Value": value}- for key, value in extra.items()+ for key, value in extra.items() if key not in present]- if resource_type in ("AWS::IAM::User", "AWS::IAM::Role"):- _validate_iam_identity_tag_keys(resource_type, merged)out = dict(props)out[prop] = mergedreturn out@@ -2394,9 +2386,9 @@ def _lambda_url_delete(physical_id, props):# --- IAM Role ---def _validate_iam_identity_tag_keys(resource_type, tags):- """Validate only user/role key uniqueness, before merging or changing state."""+ """IAM's refusal of user/role tag keys that repeat without case, before any state changes."""if _iam._identity_tags_have_duplicate_keys([{"Key": t.get("Key", "")} for t in tags]):- raise ValueError(f"{resource_type} Tags contain duplicate keys (case insensitive)")+ raise ValueError(_iam.DUPLICATE_IDENTITY_TAG_KEYS)def _iam_role_create(logical_id, props, stack_name):diff --git a/ministack/services/cognito.py b/ministack/services/cognito.pyindex bb899d8b..e49c3a70 100644--- a/ministack/services/cognito.py+++ b/ministack/services/cognito.py@@ -599,6 +599,13 @@ def _restore_state(data):data.get("user_pools", {}),lambda pool_id, _pool: _region_from_pool_id(pool_id),)+ # Older state stored 60 for an unset validity; 60 hours exceeds AWS's one-day cap.+ for pool in _user_pools.all_values():+ for client in (pool.get("_clients") or {}).values():+ units = client.get("TokenValidityUnits") or {}+ for kind in ("AccessToken", "IdToken"):+ if client.get(f"{kind}Validity") == 60 and not units.get(kind):+ client[f"{kind}Validity"] = None_restore_regional_store(_pool_domain_map,@@ -1105,12 +1112,7 @@ _FEDERATION_RESERVED_CLAIMS = frozenset(def _drop_unmapped_reserved_claims(claims: dict, attr_mapping: dict) -> dict:- """Drop registered token claims from InboundFederation output unless mapped.-- A Lambda that echoes the whole ``idToken`` back would otherwise land- ``iss`` / ``exp`` / ``iat`` in ``user_attrs``, and ``_fake_token`` copies- those over Cognito's own claims. Real Cognito only keeps mapped claims.- """+ """Registered token claims from InboundFederation output count only when mapped."""mapped = set(attr_mapping.values())return {k: v for k, v in claims.items()if k not in _FEDERATION_RESERVED_CLAIMS or k in mapped}@@ -1123,17 +1125,7 @@ class _InboundFederationRejected(Exception):def _apply_inbound_federation_trigger(pool_id: str, client_id: str, username: str,provider_name: str, provider_type: str,attributes: dict) -> dict:- """Invoke the pool's InboundFederation Lambda before AttributeMapping.-- Emulates ``InboundFederation_ExternalProvider``: the Lambda receives the- raw IdP data (``samlResponse`` as a SAML Attribute name -> value map, or- ``idToken`` / ``userInfo`` claims) and returns- ``response.userAttributesToMap`` keyed by IdP claim name, which replaces- the IdP's own value for that claim as the AttributeMapping input.- Fail-closed like PreSignUp: a Lambda failure aborts the sign-in.-- Returns ``{}`` when the pool has no ``LambdaConfig.InboundFederation``.- """+ """The InboundFederation Lambda's userAttributesToMap, ``{}`` when unconfigured; a failure raises."""pool = _user_pools.get(pool_id)cfg = ((pool or {}).get("LambdaConfig") or {}).get("InboundFederation")arn = cfg.get("LambdaArn") if isinstance(cfg, dict) else None@@ -2125,21 +2117,17 @@ def _oidc_callback_url(pool: dict) -> str:def _saml_sso_url_from_metadata(metadata_xml: str) -> str:- """Return the IdP SingleSignOnService Location, preferring HTTP-Redirect; "" if unresolvable."""+ """The IdP's HTTP-Redirect SingleSignOnService Location, the binding Cognito sends AuthnRequests on; "" if none."""if not metadata_xml:return ""try:root = safe_xml_parse(metadata_xml.strip())except Exception:return ""- services = [- el for el in root.iter("{urn:oasis:names:tc:SAML:2.0:metadata}SingleSignOnService")- if el.get("Location")- ]- for el in services:- if el.get("Binding") == "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect":+ for el in root.iter("{urn:oasis:names:tc:SAML:2.0:metadata}SingleSignOnService"):+ if el.get("Binding") == "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" and el.get("Location"):return el.get("Location")- return services[0].get("Location") if services else ""+ return ""def _build_saml_authn_request(pool: dict, destination: str) -> str:@@ -6078,7 +6066,7 @@ def _oauth2_authorize_federation(query_params):if not sso_url:return error_response_json("InvalidParameterException",- "SAML provider has no IDPSSOEndpoint, MetadataFile with SingleSignOnService, or MetadataURL.",+ "SAML provider has no IDPSSOEndpoint, MetadataFile with an HTTP-Redirect SingleSignOnService, or MetadataURL.",400)saml_request = _build_saml_authn_request(pool, sso_url)redirect_url = sso_url + ("&" if "?" in sso_url else "?") + urlencode({@@ -6227,13 +6215,12 @@ def _saml2_idp_response(body: bytes, query_params):# Apply attribute mapping: IdP claim name → Cognito attribute nameattr_mapping = provider.get("AttributeMapping", {})reverse_mapping = {v: k for k, v in attr_mapping.items()} # IdP claim → Cognito attr- idp_attrs = dict(saml_data.get("attributes", {}))try:- idp_attrs.update(_drop_unmapped_reserved_claims(- _apply_inbound_federation_trigger(- pool_id, client_id, name_id, provider_name, "SAML",- {"samlResponse": saml_data["attributes"]}),- attr_mapping))+ to_map = _apply_inbound_federation_trigger(+ pool_id, client_id, f"{provider_name}_{name_id}", provider_name, "SAML",+ {"samlResponse": saml_data["attributes"]})+ idp_attrs = (_drop_unmapped_reserved_claims(to_map, attr_mapping) if to_map+ else dict(saml_data.get("attributes", {})))except _InboundFederationRejected as e:logger.info("Cognito: InboundFederation Lambda rejected SAML sign-in for %s: %s",name_id, e)@@ -6462,19 +6449,17 @@ def _oauth2_idp_response(method, body, query_params):# as the SAML branch.attr_mapping = provider.get("AttributeMapping", {})reverse_mapping = {v: k for k, v in attr_mapping.items()}- idp_claims = {k: str(v) for k, v in claims.items()- if k not in _FEDERATION_RESERVED_CLAIMS- and isinstance(v, (str, int, float, bool))}try:- idp_claims.update(_drop_unmapped_reserved_claims(- _apply_inbound_federation_trigger(- pool_id, client_id, str(claims.get("sub") or ""), provider_name, "OIDC",- {"idToken": claims}),- attr_mapping))+ to_map = _apply_inbound_federation_trigger(+ pool_id, client_id, f"{provider_name}_{claims.get('sub') or claims.get('email') or ''}",+ provider_name, "OIDC", {"idToken": claims})except _InboundFederationRejected as e:logger.info("Cognito: InboundFederation Lambda rejected OIDC sign-in for %s: %s",claims.get("sub"), e)return error_response_json("UserLambdaValidationException", str(e), 400)+ idp_claims = (_drop_unmapped_reserved_claims(to_map, attr_mapping) if to_map+ else {k: str(v) for k, v in claims.items()+ if k not in _FEDERATION_RESERVED_CLAIMS and isinstance(v, (str, int, float, bool))})user_attrs = {}for idp_claim, value in idp_claims.items():user_attrs[reverse_mapping.get(idp_claim, idp_claim)] = valuediff --git a/ministack/services/iam.py b/ministack/services/iam.pyindex 82cc047d..81629070 100644--- a/ministack/services/iam.py+++ b/ministack/services/iam.py@@ -422,7 +422,7 @@ def _create_user(p):f"User with name {name} already exists.", ns="iam")tags = _extract_tags(p)if _identity_tags_have_duplicate_keys(tags):- return _error(400, "InvalidInput", "Duplicate tag keys found. Tag keys are case insensitive.", ns="iam")+ return _error(400, "InvalidInput", DUPLICATE_IDENTITY_TAG_KEYS, ns="iam")path = _p(p, "Path") or "/"_users[name] = {"UserName": name,@@ -551,7 +551,7 @@ def _create_role(p):f"Role with name {name} already exists.", ns="iam")tags = _extract_tags(p)if _identity_tags_have_duplicate_keys(tags):- return _error(400, "InvalidInput", "Duplicate tag keys found. Tag keys are case insensitive.", ns="iam")+ return _error(400, "InvalidInput", DUPLICATE_IDENTITY_TAG_KEYS, ns="iam")path = _p(p, "Path") or "/"_roles[name] = {"RoleName": name,@@ -1446,7 +1446,7 @@ def _tag_role(p):f"Role {role_name} not found.", ns="iam")new_tags = _extract_tags(p)if _identity_tags_have_duplicate_keys(new_tags):- return _error(400, "InvalidInput", "Duplicate tag keys found. Tag keys are case insensitive.", ns="iam")+ return _error(400, "InvalidInput", DUPLICATE_IDENTITY_TAG_KEYS, ns="iam")existing = {_identity_tag_key(t["Key"]): t for t in role["Tags"]}for t in new_tags:existing[_identity_tag_key(t["Key"])] = t@@ -1483,12 +1483,11 @@ def _list_role_tags(p):# -------------------- Tags: users ---------------------def _identity_tag_key(key):- """Compare IAM user/role keys without case, retaining the stored spelling.+DUPLICATE_IDENTITY_TAG_KEYS = "Duplicate tag keys found. Please note that Tag keys are case insensitive."- Evidence: the IAM tagging guide, not a real AWS run. Other IAM resources- keep their case-sensitive tag handling.- """++def _identity_tag_key(key):+ """User and role tag keys compare without case; the stored spelling is kept."""return key.lower()@@ -1505,7 +1504,7 @@ def _tag_user(p):f"The user with name {user_name} cannot be found.", ns="iam")new_tags = _extract_tags(p)if _identity_tags_have_duplicate_keys(new_tags):- return _error(400, "InvalidInput", "Duplicate tag keys found. Tag keys are case insensitive.", ns="iam")+ return _error(400, "InvalidInput", DUPLICATE_IDENTITY_TAG_KEYS, ns="iam")existing = {_identity_tag_key(t["Key"]): t for t in user["Tags"]}for t in new_tags:existing[_identity_tag_key(t["Key"])] = tdiff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex 74ff8b57..ea6cefe8 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -10078,6 +10078,11 @@ _mtls_lock = asyncio.Lock()# Every live connection's writer, so that stopping the listener can close them# deliberately and in bounded time (see ``mtls_stop``)._mtls_sessions: set[asyncio.StreamWriter] = set()+# Built on the first connection, not at boot, and dropped when the listener stops.+_mtls_ssl_context: ssl.SSLContext | None = None+_mtls_context_lock = asyncio.Lock()+# TLS upgrades in flight, held so the loop keeps a reference to each task.+_mtls_upgrades: set[asyncio.Task] = set()# Digests of the trust anchors already loaded into the live TLS context;# emptied whenever a context is built, since a fresh one starts with none._mtls_loaded_anchors: set[str] = set()@@ -10340,17 +10345,10 @@ async def _mtls_start_locked() -> None:if port is None:returntry:- # Building the context can mint the server certificate — and, on first- # boot, the CA — which is RSA keygen, so keep it off the event loop.- ctx = await asyncio.to_thread(_mtls_build_ssl_context)- except Exception as e:- _mtls_logger.warning(- "IoT mTLS: could not build the TLS context (%s); listener unavailable", e- )- return- try:- _mtls_server = await asyncio.start_server(- _mtls_handle_conn, host="0.0.0.0", port=port, ssl=ctx+ # Bound without TLS: the context imports `cryptography` and mints the+ # server certificate (and the CA), which waits for the first device.+ _mtls_server = await asyncio.get_running_loop().create_server(+ _MtlsAcceptor, host="0.0.0.0", port=port)except OSError as e:_mtls_logger.warning(@@ -10365,7 +10363,8 @@ async def _mtls_start_locked() -> None:async def _mtls_stop_locked() -> None:- global _mtls_server+ global _mtls_server, _mtls_ssl_context+ _mtls_ssl_context = Noneif _mtls_server is None and not _mtls_sessions:returnif _mtls_server is not None:@@ -10652,6 +10651,55 @@ async def _mtls_close(writer: asyncio.StreamWriter) -> None:pass+async def _mtls_context() -> ssl.SSLContext | None:+ """The listener's TLS context, built once on first use; None refuses the connection and a later one retries."""+ global _mtls_ssl_context+ async with _mtls_context_lock:+ if _mtls_ssl_context is None:+ try:+ # RSA keygen on first use, so keep it off the event loop.+ _mtls_ssl_context = await asyncio.to_thread(_mtls_build_ssl_context)+ except Exception as e:+ _mtls_logger.warning(+ "IoT mTLS: could not build the TLS context (%s); connection refused", e+ )+ return None+ return _mtls_ssl_context+++class _MtlsAcceptor(asyncio.Protocol):+ """Accepts plaintext, upgrades it to TLS, then serves the stream session.++ Reading is paused before anything arrives, so the ClientHello stays in the+ kernel buffer until ``loop.start_tls`` takes over the transport.+ """++ def connection_made(self, transport):+ transport.pause_reading()+ task = asyncio.get_running_loop().create_task(self._upgrade(transport))+ _mtls_upgrades.add(task)+ task.add_done_callback(_mtls_upgrades.discard)++ async def _upgrade(self, transport):+ loop = asyncio.get_running_loop()+ ctx = await _mtls_context()+ if ctx is None or transport.is_closing():+ transport.abort()+ return+ reader = asyncio.StreamReader(loop=loop)+ protocol = asyncio.StreamReaderProtocol(reader, loop=loop)+ try:+ tls_transport = await loop.start_tls(transport, protocol, ctx, server_side=True)+ except Exception as e:+ _mtls_logger.debug("IoT mTLS: TLS handshake failed: %s", e)+ transport.abort()+ return+ # start_tls does not call connection_made on the new protocol.+ protocol.connection_made(tls_transport)+ writer = asyncio.StreamWriter(tls_transport, protocol, reader, loop)+ await _mtls_handle_conn(reader, writer)++async def _mtls_handle_conn(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:"""Track the connection for as long as it lives, then serve it, so that``mtls_stop`` can close every peer in bounded time."""diff --git a/ministack/services/signer.py b/ministack/services/signer.pyindex a7e749fa..470d17f7 100644--- a/ministack/services/signer.py+++ b/ministack/services/signer.py@@ -45,11 +45,11 @@ Behaviour that follows the live service (measured 2026-08-26 unless noted):`signingParameters`, and `signatureExpiresAt` = createdAt plus theprofile's `signatureValidityPeriod` (default 135 months, per thePutSigningProfile reference).- * Under AUTH=true, PutSigningProfile on the IoT and FreeRTOS platforms+ * PutSigningProfile on the Lambda and Notation platforms refuses any+ `signingMaterial`. Under AUTH=true, on the IoT and FreeRTOS platforms itrefuses a profile without `signingMaterial` and a certificate ARN thatis malformed, in another region or account, unknown to ACM or not- issued; on the Lambda and Notation platforms it refuses any- `signingMaterial`. Without AUTH all of these are accepted.+ issued; without AUTH those are accepted.Deliberate divergences from AWS, each pinned by a test:@@ -304,14 +304,14 @@ def _validate_signing_material(material):return None-def _signing_material_problem(platform_id, material):- """The refusal of signingMaterial the platform cannot use, checked before the profile name."""+def _signing_material_problem(platform_id, material, auth):+ """The refusal of signingMaterial the platform cannot use, checked before the profile name; the ARN checks need AUTH."""if platform_id in _SIGNER_KEY_PLATFORMS:if material is None:return Nonereturn _coded_error(400, "ValidationException", "InvalidProfileParameters",f"Signing material should not be present when using {platform_id} platform.")- if platform_id not in _ACM_SIGNED_PLATFORMS:+ if not auth or platform_id not in _ACM_SIGNED_PLATFORMS:return Noneif material is None:return _coded_error(400, "ValidationException", "ValidationException",@@ -863,7 +863,7 @@ def _put_signing_profile(name, body):return problemfrom ministack.app import AUTHplatform_id, material = body["platformId"], body.get("signingMaterial")- problem = _signing_material_problem(platform_id, material) if AUTH else None+ problem = _signing_material_problem(platform_id, material, AUTH)if problem is not None:return problemif name in _profiles:diff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.pyindex 365ac31c..0e42583f 100644--- a/ministack/services/stepfunctions.py+++ b/ministack/services/stepfunctions.py@@ -3709,10 +3709,7 @@ def _dispatch_aws_sdk_json(service_info, service_name, action, input_data):f"Service '{service_key}' is not available in MiniStack",)- if service_info.get("param_case") == "lower-camel":- wire_data = _convert_keys_to_camel(input_data or {})- else:- wire_data = input_data+ wire_data = _sdk_json_params(service_info, service_key, pascal_action, input_data)# Secrets Manager's SFN SDK integration takes literal UTF-8 text for# SecretBinary; its HTTP API takes base64. Translate only at this boundary,# without changing the state input or guessing whether the text is base64.@@ -3762,11 +3759,7 @@ _SDK_MEMBER_NAME_OVERRIDES = {("AttributeValue", "NULL"): "Nul"}def _sdk_json_result(service_key, action, result):- """A JSON-protocol aws-sdk result as Step Functions returns it. Step- Functions parses the response with the AWS SDK for Java v2, so the- operation's output model decides the shape: structure members take the- SDK's names, map keys are data and stay as sent (DynamoDB attribute names,- tag keys), timestamps become ISO 8601 and absent members are left out."""+ """A JSON-protocol aws-sdk result shaped by the operation's output model, as Step Functions returns it."""model = _service_model(service_key)shape = (model.operation_model(action).output_shapeif model is not None and action in model.operation_names else None)@@ -3794,6 +3787,38 @@ def _sdk_json_value(value, shape):return value+_SDK_PARAM_NAME_OVERRIDES = {(shape, sdk): wire for (shape, wire), sdk in _SDK_MEMBER_NAME_OVERRIDES.items()}+++def _sdk_json_params(service_info, service_key, action, input_data):+ """aws-sdk Parameters on the wire, renamed by the operation's input model; map keys are data."""+ model = _service_model(service_key)+ shape = (model.operation_model(action).input_shape+ if model is not None and action in model.operation_names else None)+ if shape is None:+ if service_info.get("param_case") == "lower-camel":+ return _convert_keys_to_camel(input_data or {})+ return input_data+ return _sdk_json_param_value(input_data or {}, shape)+++def _sdk_json_param_value(value, shape):+ if shape.type_name == "structure" and isinstance(value, dict) and not getattr(shape, "is_document_type", False):+ by_sdk_name = {_api_name_to_sfn_key(name): name for name in shape.members}+ renamed = {}+ for key, item in value.items():+ name = (key if key in shape.members+ else _SDK_PARAM_NAME_OVERRIDES.get((shape.name, key)) or by_sdk_name.get(key, key))+ member = shape.members.get(name)+ renamed[name] = _sdk_json_param_value(item, member) if member is not None else item+ return renamed+ if shape.type_name == "list" and isinstance(value, list):+ return [_sdk_json_param_value(item, shape.member) for item in value]+ if shape.type_name == "map" and isinstance(value, dict):+ return {key: _sdk_json_param_value(item, shape.value) for key, item in value.items()}+ return value++def _flatten_query_params(data, prefix=""):"""Flatten a JSON dict into AWS query-protocol form params.diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 642a5347..79b8f891 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -21,6 +21,8 @@ from ministack.services.cloudformation.provisioners import (_CONDITIONALLY_REPLACING_PROPERTIES,_REPLACING_PROPERTIES,_RESOURCE_HANDLERS,+ _reconcile_tag_list,+ _with_stack_tags,)from ministack.services.cloudformation.stacks import _diff_resources@@ -35165,3 +35167,135 @@ def test_cfn_events_rule_invalid_bus_arn_is_rejected(cfn, eb, bus_ref):assert not any(rule["Name"] == name for rule in eb.list_rules(EventBusName="default")["Rules"])finally:_delete_cfn_test_stack(cfn, name)+++_IDENTITY_TAG_TRUST = {"Statement": [{"Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"},+ "Action": "sts:AssumeRole"}]}+++def _identity_tag_map(tags):+ result = {t["Key"]: t["Value"] for t in tags}+ assert len(result) == len(tags), f"Duplicate tag keys in response: {tags}"+ return result+++def _identity_custom_tag_map(tags):+ return _identity_tag_map([t for t in tags if not t["Key"].lower().startswith("aws:")])+++def _identity_template(resource, name, tags, after=False):+ props = {f"{resource.title()}Name": name, "Tags": tags}+ if resource == "role":+ props.update(AssumeRolePolicyDocument=_IDENTITY_TAG_TRUST, Description="After" if after else "Before")+ else:+ props["Path"] = "/after/" if after else "/before/"+ return json.dumps({"Resources": {"Identity": {"Type": f"AWS::IAM::{resource.title()}", "Properties": props}}})++[email protected]("resource", ["user", "role"])[email protected]("source", ["template", "stack"])+def test_cfn_iam_identity_tag_case_update_and_removal(cfn, iam, resource, source):+ name = f"cfn-{resource}-tag-case-{_uuid_mod.uuid4().hex[:8]}"+ params = {f"{resource.title()}Name": name}+ original_tag = {"Key": "Department", "Value": "Finance"}+ body = _identity_template(resource, name, [original_tag] if source == "template" else [])+ cfn.create_stack(StackName=name, TemplateBody=body, Capabilities=["CAPABILITY_NAMED_IAM"],+ Tags=[original_tag] if source == "stack" else [])+ try:+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"+ before = getattr(iam, f"get_{resource}")(**params)[resource.title()]+ assert _identity_custom_tag_map(before["Tags"]) == {"Department": "Finance"}+ # First change only the key's spelling, then change its value too.+ for value in ["Finance", "HR"]:+ desired_tags = [{"Key": "department", "Value": value}, {"Key": "Added", "Value": "New"}]+ body = _identity_template(resource, name, desired_tags if source == "template" else [])+ cfn.update_stack(StackName=name, TemplateBody=body,+ Tags=desired_tags if source == "stack" else [], Capabilities=["CAPABILITY_NAMED_IAM"])+ assert _wait_stack(cfn, name)["StackStatus"] == "UPDATE_COMPLETE"+ identity = getattr(iam, f"get_{resource}")(**params)[resource.title()]+ assert identity[f"{resource.title()}Id"] == before[f"{resource.title()}Id"]+ assert _identity_custom_tag_map(identity["Tags"]) == {"department": value, "Added": "New"}+ # Change a managed key's spelling externally; do not add unrelated external tags.+ getattr(iam, f"tag_{resource}")(**params, Tags=[{"Key": "DEPARTMENT", "Value": "ExternalEdit"}])+ assert _identity_custom_tag_map(getattr(iam, f"list_{resource}_tags")(**params)["Tags"]) == {+ "DEPARTMENT": "ExternalEdit", "Added": "New"}+ cfn.update_stack(StackName=name, TemplateBody=_identity_template(resource, name, []), Tags=[],+ Capabilities=["CAPABILITY_NAMED_IAM"])+ assert _wait_stack(cfn, name)["StackStatus"] == "UPDATE_COMPLETE"+ identity = getattr(iam, f"get_{resource}")(**params)[resource.title()]+ assert identity[f"{resource.title()}Id"] == before[f"{resource.title()}Id"]+ assert _identity_custom_tag_map(getattr(iam, f"list_{resource}_tags")(**params)["Tags"]) == {}+ finally:+ _delete_cfn_test_stack(cfn, name)++[email protected]("resource", ["user", "role"])+def test_cfn_iam_identity_stack_tag_differing_only_in_case_fails_the_resource(cfn, iam, resource):+ """Stack and resource tag keys merge case-sensitively, so IAM receives both spellings and refuses them."""+ name = f"cfn-{resource}-tag-merge-{_uuid_mod.uuid4().hex[:8]}"+ cfn.create_stack(StackName=name, Capabilities=["CAPABILITY_NAMED_IAM"],+ TemplateBody=_identity_template(resource, name, [{"Key": "department", "Value": "Resource"}]),+ Tags=[{"Key": "Department", "Value": "Stack"}])+ try:+ assert _wait_stack(cfn, name)["StackStatus"] == "ROLLBACK_COMPLETE"+ reasons = [e.get("ResourceStatusReason", "") for e in cfn.describe_stack_events(StackName=name)["StackEvents"]+ if e["LogicalResourceId"] == "Identity" and e["ResourceStatus"] == "CREATE_FAILED"]+ assert any("Duplicate tag keys found. Please note that Tag keys are case insensitive." in r+ for r in reasons), reasons+ with pytest.raises(iam.exceptions.NoSuchEntityException):+ getattr(iam, f"get_{resource}")(**{f"{resource.title()}Name": name})+ finally:+ _delete_cfn_test_stack(cfn, name)++[email protected]("operation", ["create", "update"])[email protected]("resource", ["user", "role"])+def test_cfn_iam_identity_duplicate_tag_keys_leave_state_unchanged(cfn, iam, operation, resource):+ name = f"cfn-{resource}-tag-duplicate-{_uuid_mod.uuid4().hex[:8]}"+ params = {f"{resource.title()}Name": name}+ before = None+ if operation == "update":+ cfn.create_stack(StackName=name, TemplateBody=_identity_template(resource, name, [{"Key": "Department", "Value": "Finance"}]),+ Capabilities=["CAPABILITY_NAMED_IAM"])+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"+ before = getattr(iam, f"get_{resource}")(**params)[resource.title()]+ try:+ # Both duplicate forms use the predicate covered by the IAM API tests.+ tags = [{"Key": "Department", "Value": "HR"}, {"Key": "department", "Value": "HR"}]+ getattr(cfn, f"{operation}_stack")(StackName=name, TemplateBody=_identity_template(resource, name, tags, after=True),+ Capabilities=["CAPABILITY_NAMED_IAM"])+ assert _wait_stack(cfn, name)["StackStatus"] == (+ "UPDATE_ROLLBACK_COMPLETE" if operation == "update" else "ROLLBACK_COMPLETE")+ if before is not None:+ assert getattr(iam, f"get_{resource}")(**params)[resource.title()] == before+ else:+ with pytest.raises(iam.exceptions.NoSuchEntityException):+ getattr(iam, f"get_{resource}")(**params)+ finally:+ _delete_cfn_test_stack(cfn, name)++[email protected]("resource_type", ["AWS::SQS::Queue", "AWS::SSM::Parameter"])+def test_cfn_other_resource_stack_tag_merge_remains_case_sensitive(resource_type):+ # Protect the list/map branches of the shared merge without provisioning other services.+ props = {"Tags": [{"Key": "department", "Value": "Resource"}]} if resource_type == "AWS::SQS::Queue" else {+ "Tags": {"department": "Resource"}}+ import copy++ original = copy.deepcopy(props)+ result = _with_stack_tags(resource_type, props, [{"Key": "Department", "Value": "Stack"}],+ "stack-name", "stack-id", "Resource")+ tags = result["Tags"]+ actual = tags if isinstance(tags, dict) else _identity_tag_map(tags)+ assert {k: v for k, v in actual.items() if not k.lower().startswith("aws:")} == {+ "Department": "Stack", "department": "Resource"}+ assert props == original+++def test_cfn_other_resource_tag_reconciliation_remains_case_sensitive():+ store = [{"Key": "Department", "Value": "External"}, {"Key": "department", "Value": "Before"}]+ _reconcile_tag_list(store, {"Tags": [{"Key": "department", "Value": "Before"}]},+ {"Tags": [{"Key": "DEPARTMENT", "Value": "After"}]})+ assert _identity_tag_map(store) == {"Department": "External", "DEPARTMENT": "After"}+ _reconcile_tag_list(store, {"Tags": [{"Key": "DEPARTMENT", "Value": "After"}]}, {})+ assert _identity_tag_map(store) == {"Department": "External"}diff --git a/tests/test_cognito.py b/tests/test_cognito.pyindex dc2da7ec..88c8ef6b 100644--- a/tests/test_cognito.py+++ b/tests/test_cognito.py@@ -1720,6 +1720,30 @@ def test_cognito_token_lifetimes_follow_client_validity(cognito_idp):assert refresh_claims["exp"] - refresh_claims["iat"] == 30 * 86400+def test_cognito_restore_drops_the_old_default_token_validity():+ """State saved before validities were honoured stored 60 for unset ones; a 60 with a unit stays."""+ from ministack.core.responses import AccountRegionScopedDict++ mod = _cognito_module()+ account, region, pid = "111111111111", "eu-central-1", "eu-central-1_old"+ clients = {+ "unset": {"AccessTokenValidity": 60, "IdTokenValidity": 60, "TokenValidityUnits": {}},+ "minutes": {"AccessTokenValidity": 60, "IdTokenValidity": 60,+ "TokenValidityUnits": {"AccessToken": "minutes", "IdToken": "minutes"}},+ "set": {"AccessTokenValidity": 2, "IdTokenValidity": 3, "TokenValidityUnits": {}},+ }+ saved = AccountRegionScopedDict()+ saved.set_scoped(account, region, pid, {"Id": pid, "_clients": clients})+ try:+ mod.reset()+ mod.load_persisted_state({"user_pools": saved})+ restored = mod._user_pools.get_scoped(account, region, pid)["_clients"]+ assert {cid: (c["AccessTokenValidity"], c["IdTokenValidity"]) for cid, c in restored.items()} == {+ "unset": (None, None), "minutes": (60, 60), "set": (2, 3)}+ finally:+ mod.reset()++def test_cognito_describe_identity(cognito_identity):resp = cognito_identity.create_identity_pool(IdentityPoolName="DescribeIdPool",@@ -2554,6 +2578,27 @@ def test_cognito_oauth2_authorize_saml_metadata_file(cognito_idp):assert "SAMLRequest=" in location+def test_cognito_oauth2_authorize_saml_metadata_file_without_redirect_binding(cognito_idp):+ pid, cid = _setup_saml_pool(cognito_idp)+ metadata = (+ '<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" entityID="https://idp.example.com/e">'+ '<IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">'+ '<SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"'+ ' Location="https://post.example.com/sso"/>'+ '</IDPSSODescriptor></EntityDescriptor>'+ )+ cognito_idp.create_identity_provider(+ UserPoolId=pid, ProviderName="PostOnlySAML", ProviderType="SAML",+ ProviderDetails={"MetadataFile": metadata},+ )+ with pytest.raises(urllib.error.HTTPError) as exc:+ _no_redirect_opener.open(+ f"{ENDPOINT}/oauth2/authorize?response_type=code&client_id={cid}"+ f"&redirect_uri=http://localhost:3000/callback&identity_provider=PostOnlySAML&scope=openid")+ assert exc.value.code == 400+ assert "HTTP-Redirect SingleSignOnService" in exc.value.read().decode()++def test_cognito_oauth2_authorize_invalid_client(cognito_idp):"""GET /oauth2/authorize with unknown client_id returns 400."""url = f"{ENDPOINT}/oauth2/authorize?response_type=code&client_id=nonexistent&redirect_uri=http://x&identity_provider=X"@@ -10822,6 +10867,38 @@ def test_cognito_inbound_federation_trigger_missing_function_fails_sign_in(cognicognito_idp.admin_get_user(UserPoolId=pid, Username="[email protected]")+def test_cognito_inbound_federation_trigger_map_replaces_idp_attributes(cognito_idp, lam):+ handler = (+ "def handler(event, ctx):\n"+ " assert event['userName'] == 'TestSAML_replace-name-id', event['userName']\n"+ " event['response']['userAttributesToMap'] = {'given_name': 'Kept'}\n"+ " return event\n"+ )+ fn_arn = _create_inbound_federation_lambda(lam, "ministack-inbound-fed-replace", handler)+ pid, cid = _setup_saml_pool(cognito_idp, lambda_config={"InboundFederation": {"LambdaVersion": "V1_0", "LambdaArn": fn_arn}})+ status, _ = _saml_idpresponse(cid, _build_mock_saml_response(+ name_id="replace-name-id", attributes={_INBOUND_EMAIL_CLAIM: "[email protected]", "family_name": "Dropped"}))+ assert status == 302+ attrs = {a["Name"]: a["Value"] for a in+ cognito_idp.admin_get_user(UserPoolId=pid, Username="TestSAML_replace-name-id")["UserAttributes"]}+ assert attrs["given_name"] == "Kept"+ assert "family_name" not in attrs+ assert attrs.get("email", "") != "[email protected]"+++def test_cognito_inbound_federation_trigger_empty_map_keeps_idp_attributes(cognito_idp, lam):+ handler = "def handler(event, ctx):\n return event\n"+ fn_arn = _create_inbound_federation_lambda(lam, "ministack-inbound-fed-noop", handler)+ pid, cid = _setup_saml_pool(cognito_idp, lambda_config={"InboundFederation": {"LambdaVersion": "V1_0", "LambdaArn": fn_arn}})+ status, _ = _saml_idpresponse(cid, _build_mock_saml_response(+ name_id="noop-name-id", attributes={_INBOUND_EMAIL_CLAIM: "[email protected]", "family_name": "Kept"}))+ assert status == 302+ attrs = {a["Name"]: a["Value"] for a in+ cognito_idp.admin_get_user(UserPoolId=pid, Username="TestSAML_noop-name-id")["UserAttributes"]}+ assert attrs["email"] == "[email protected]"+ assert attrs["family_name"] == "Kept"++def test_cognito_inbound_federation_trigger_unconfigured_pool_keeps_idp_attributes(cognito_idp):pid, cid = _setup_saml_pool(cognito_idp)diff --git a/tests/test_iam.py b/tests/test_iam.pyindex b501095d..f05aa970 100644--- a/tests/test_iam.py+++ b/tests/test_iam.py@@ -230,6 +230,93 @@ def test_iam_user_tags_serialized_in_get_user(iam):assert tags == {"Team": "core", "Env": "dev"}iam.delete_user(UserName=name)++_IDENTITY_TAG_TRUST = {"Statement": [{"Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"},+ "Action": "sts:AssumeRole"}]}+++def _identity_tag_map(tags):+ result = {t["Key"]: t["Value"] for t in tags}+ assert len(result) == len(tags), f"Duplicate tag keys in response: {tags}"+ return result++[email protected]("resource", ["user", "role"])+def test_iam_identity_tag_keys_ignore_case_and_preserve_spelling(iam, resource):+ name = f"tag-case-{resource}-{_uuid_mod.uuid4().hex[:8]}"+ params = {f"{resource.title()}Name": name}+ create_params = {"AssumeRolePolicyDocument": json.dumps(_IDENTITY_TAG_TRUST)} if resource == "role" else {}+ original = [{"Key": "Department", "Value": "Finance"}, {"Key": "ExternalKey", "Value": "Keep"}]+ getattr(iam, f"create_{resource}")(**params, **create_params, Tags=original)+ try:+ assert _identity_tag_map(getattr(iam, f"get_{resource}")(**params)[resource.title()]["Tags"]) == _identity_tag_map(original)+ # Untag must match both the original spelling and a subsequently changed spelling.+ getattr(iam, f"untag_{resource}")(**params, TagKeys=["DEPARTMENT"])+ assert getattr(iam, f"list_{resource}_tags")(**params)["Tags"] == [original[1]]+ getattr(iam, f"tag_{resource}")(**params, Tags=[original[0]])+ # A spelling-only update and a case-sensitive value change must both take effect.+ for key, value in [("department", "Finance"), ("DEPARTMENT", "finance")]:+ getattr(iam, f"tag_{resource}")(**params, Tags=[{"Key": key, "Value": value}])+ expected = {key: value, "ExternalKey": "Keep"}+ assert _identity_tag_map(getattr(iam, f"get_{resource}")(**params)[resource.title()]["Tags"]) == expected+ assert _identity_tag_map(getattr(iam, f"list_{resource}_tags")(**params)["Tags"]) == expected+ getattr(iam, f"untag_{resource}")(**params, TagKeys=["DePaRtMeNt", "missing"])+ assert getattr(iam, f"list_{resource}_tags")(**params)["Tags"] == [original[1]]+ finally:+ getattr(iam, f"delete_{resource}")(**params)++[email protected]("resource", ["user", "role"])[email protected]("operation", ["create", "tag"])[email protected]("second_key", ["Department", "department"])+def test_iam_identity_duplicate_tag_keys_reject_entire_request(iam, resource, operation, second_key):+ params = {f"{resource.title()}Name": f"tag-duplicate-{resource}-{_uuid_mod.uuid4().hex[:8]}"}+ create_params = {"AssumeRolePolicyDocument": json.dumps(_IDENTITY_TAG_TRUST)} if resource == "role" else {}+ original = [{"Key": "Department", "Value": "Finance"}]+ if operation == "tag":+ getattr(iam, f"create_{resource}")(**params, **create_params, Tags=original)+ try:+ with pytest.raises(ClientError) as exc:+ getattr(iam, f"{operation}_{resource}")(**params,+ **(create_params if operation == "create" else {}), Tags=[+ {"Key": "Unrelated", "Value": "MustNotBeAdded"},+ {"Key": "Department", "Value": "HR"}, {"Key": second_key, "Value": "HR"},+ ])+ assert exc.value.response["Error"]["Code"] == "InvalidInput"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+ if operation == "tag":+ assert getattr(iam, f"list_{resource}_tags")(**params)["Tags"] == original+ else:+ with pytest.raises(iam.exceptions.NoSuchEntityException):+ getattr(iam, f"get_{resource}")(**params)+ finally:+ try:+ getattr(iam, f"delete_{resource}")(**params)+ except iam.exceptions.NoSuchEntityException:+ pass++[email protected]("resource", ["policy", "instance_profile"])+def test_iam_other_resource_tag_keys_remain_case_sensitive(iam, resource):+ name = f"tag-case-{resource}-{_uuid_mod.uuid4().hex[:8]}"+ tags = [{"Key": "Costcenter", "Value": "1234"}, {"Key": "costcenter", "Value": "5678"}]+ if resource == "policy":+ arn = iam.create_policy(PolicyName=name, PolicyDocument=json.dumps({+ "Statement": [{"Effect": "Allow", "Action": "s3:ListBucket", "Resource": "*"}],+ }), Tags=[tags[0]])["Policy"]["Arn"]+ params = {"PolicyArn": arn}+ else:+ iam.create_instance_profile(InstanceProfileName=name, Tags=[tags[0]])+ params = {"InstanceProfileName": name}+ try:+ getattr(iam, f"tag_{resource}")(**params, Tags=[tags[1]])+ assert _identity_tag_map(getattr(iam, f"list_{resource}_tags")(**params)["Tags"]) == _identity_tag_map(tags)+ getattr(iam, f"untag_{resource}")(**params, TagKeys=["Costcenter"])+ assert getattr(iam, f"list_{resource}_tags")(**params)["Tags"] == [tags[1]]+ finally:+ getattr(iam, f"delete_{resource}")(**params)++def test_iam_attach_role_policy(iam):policy_arn = "arn:aws:iam::000000000000:policy/iam-test-policy"iam.attach_role_policy(RoleName="iam-test-role", PolicyArn=policy_arn)diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex 9f0dfb60..00a7b7a0 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -4991,3 +4991,40 @@ def test_stage_policy_is_enforced_on_dispatch(monkeypatch, prefix, suffix, case,assert bool(dispatched) == (expected == 200)if expected == 403:assert f"apigateway:{method}" in json.loads(body)["message"]++[email protected]("addressing", ["path", "virtual"])+def test_s3_list_grants_scoped_by_prefix_condition(monkeypatch, addressing):+ """s3:prefix, s3:delimiter and s3:max-keys come from a ListBucket or ListBucketVersions request."""+ from ministack import app as app_mod++ monkeypatch.setattr(app_mod, "AUTH", True)+ iam, root_s3 = _local_client("iam"), _local_client("s3")+ name = f"prefix-{time.time_ns()}"+ bucket = name+ root_s3.create_bucket(Bucket=bucket)+ iam.create_user(UserName=name)+ iam.put_user_policy(UserName=name, PolicyName="home", PolicyDocument=json.dumps({+ "Version": "2012-10-17", "Statement": [{+ "Effect": "Allow", "Action": ["s3:ListBucket", "s3:ListBucketVersions"],+ "Resource": f"arn:aws:s3:::{bucket}",+ "Condition": {"StringLike": {"s3:prefix": ["home/alice/*"]}, "StringEquals": {"s3:delimiter": "/"},+ "NumericLessThanEquals": {"s3:max-keys": "100"}},+ }]}))+ key = iam.create_access_key(UserName=name)["AccessKey"]+ try:+ s3 = _local_client("s3", key["AccessKeyId"], key["SecretAccessKey"], addressing_style=addressing)+ allowed = {"Prefix": "home/alice/", "Delimiter": "/", "MaxKeys": 100}+ s3.list_objects_v2(Bucket=bucket, **allowed)+ s3.list_objects(Bucket=bucket, **allowed)+ s3.list_object_versions(Bucket=bucket, **allowed)+ for refused in ({**allowed, "Prefix": "home/bob/"}, {**allowed, "Delimiter": "-"},+ {**allowed, "MaxKeys": 101}, {"Delimiter": "/", "MaxKeys": 100}):+ assert _failure(lambda: s3.list_objects_v2(Bucket=bucket, **refused)) == ("AccessDenied", 403)+ assert _failure(lambda: s3.list_object_versions(+ Bucket=bucket, **{**allowed, "Prefix": "home/bob/"})) == ("AccessDenied", 403)+ finally:+ iam.delete_access_key(UserName=name, AccessKeyId=key["AccessKeyId"])+ iam.delete_user_policy(UserName=name, PolicyName="home")+ iam.delete_user(UserName=name)+ root_s3.delete_bucket(Bucket=bucket)diff --git a/tests/test_iam_tag_case.py b/tests/test_iam_tag_case.pydeleted file mode 100644index 95a51353..00000000--- a/tests/test_iam_tag_case.py+++ /dev/null@@ -1,220 +0,0 @@-"""IAM tagging guide / API references and MiniStack tests, not real AWS runs."""--import copy-import json-import uuid--import pytest-from botocore.exceptions import ClientError-from test_cfn import _delete_cfn_test_stack, _wait_stack--from ministack.services.cloudformation.provisioners import _reconcile_tag_list, _with_stack_tags--_TRUST = {"Statement": [{"Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"},- "Action": "sts:AssumeRole"}]}---def _tags(tags):- result = {t["Key"]: t["Value"] for t in tags}- assert len(result) == len(tags), f"Duplicate tag keys in response: {tags}"- return result---def _custom_tags(tags):- return _tags([t for t in tags if not t["Key"].lower().startswith("aws:")])--[email protected]("resource", ["user", "role"])-def test_iam_identity_tag_keys_ignore_case_and_preserve_spelling(iam, resource):- name = f"tag-case-{resource}-{uuid.uuid4().hex[:8]}"- params = {f"{resource.title()}Name": name}- create_params = {"AssumeRolePolicyDocument": json.dumps(_TRUST)} if resource == "role" else {}- original = [{"Key": "Department", "Value": "Finance"}, {"Key": "ExternalKey", "Value": "Keep"}]- getattr(iam, f"create_{resource}")(**params, **create_params, Tags=original)- try:- assert _tags(getattr(iam, f"get_{resource}")(**params)[resource.title()]["Tags"]) == _tags(original)- # Untag must match both the original spelling and a subsequently changed spelling.- getattr(iam, f"untag_{resource}")(**params, TagKeys=["DEPARTMENT"])- assert getattr(iam, f"list_{resource}_tags")(**params)["Tags"] == [original[1]]- getattr(iam, f"tag_{resource}")(**params, Tags=[original[0]])- # A spelling-only update and a case-sensitive value change must both take effect.- for key, value in [("department", "Finance"), ("DEPARTMENT", "finance")]:- getattr(iam, f"tag_{resource}")(**params, Tags=[{"Key": key, "Value": value}])- expected = {key: value, "ExternalKey": "Keep"}- assert _tags(getattr(iam, f"get_{resource}")(**params)[resource.title()]["Tags"]) == expected- assert _tags(getattr(iam, f"list_{resource}_tags")(**params)["Tags"]) == expected- getattr(iam, f"untag_{resource}")(**params, TagKeys=["DePaRtMeNt", "missing"])- assert getattr(iam, f"list_{resource}_tags")(**params)["Tags"] == [original[1]]- finally:- getattr(iam, f"delete_{resource}")(**params)--[email protected]("resource", ["user", "role"])[email protected]("operation", ["create", "tag"])[email protected]("second_key", ["Department", "department"])-def test_iam_identity_duplicate_tag_keys_reject_entire_request(iam, resource, operation, second_key):- params = {f"{resource.title()}Name": f"tag-duplicate-{resource}-{uuid.uuid4().hex[:8]}"}- create_params = {"AssumeRolePolicyDocument": json.dumps(_TRUST)} if resource == "role" else {}- original = [{"Key": "Department", "Value": "Finance"}]- if operation == "tag":- getattr(iam, f"create_{resource}")(**params, **create_params, Tags=original)- try:- with pytest.raises(ClientError) as exc:- getattr(iam, f"{operation}_{resource}")(**params,- **(create_params if operation == "create" else {}), Tags=[- {"Key": "Unrelated", "Value": "MustNotBeAdded"},- {"Key": "Department", "Value": "HR"}, {"Key": second_key, "Value": "HR"},- ])- assert exc.value.response["Error"]["Code"] == "InvalidInput"- assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400- if operation == "tag":- assert getattr(iam, f"list_{resource}_tags")(**params)["Tags"] == original- else:- with pytest.raises(iam.exceptions.NoSuchEntityException):- getattr(iam, f"get_{resource}")(**params)- finally:- try:- getattr(iam, f"delete_{resource}")(**params)- except iam.exceptions.NoSuchEntityException:- pass--[email protected]("resource", ["policy", "instance_profile"])-def test_iam_other_resource_tag_keys_remain_case_sensitive(iam, resource):- name = f"tag-case-{resource}-{uuid.uuid4().hex[:8]}"- tags = [{"Key": "Costcenter", "Value": "1234"}, {"Key": "costcenter", "Value": "5678"}]- if resource == "policy":- arn = iam.create_policy(PolicyName=name, PolicyDocument=json.dumps({- "Statement": [{"Effect": "Allow", "Action": "s3:ListBucket", "Resource": "*"}],- }), Tags=[tags[0]])["Policy"]["Arn"]- params = {"PolicyArn": arn}- else:- iam.create_instance_profile(InstanceProfileName=name, Tags=[tags[0]])- params = {"InstanceProfileName": name}- try:- getattr(iam, f"tag_{resource}")(**params, Tags=[tags[1]])- assert _tags(getattr(iam, f"list_{resource}_tags")(**params)["Tags"]) == _tags(tags)- getattr(iam, f"untag_{resource}")(**params, TagKeys=["Costcenter"])- assert getattr(iam, f"list_{resource}_tags")(**params)["Tags"] == [tags[1]]- finally:- getattr(iam, f"delete_{resource}")(**params)---def _identity_template(resource, name, tags, after=False):- props = {f"{resource.title()}Name": name, "Tags": tags}- if resource == "role":- props.update(AssumeRolePolicyDocument=_TRUST, Description="After" if after else "Before")- else:- props["Path"] = "/after/" if after else "/before/"- return json.dumps({"Resources": {"Identity": {"Type": f"AWS::IAM::{resource.title()}", "Properties": props}}})--[email protected]("resource", ["user", "role"])[email protected]("source", ["template", "stack"])-def test_cfn_iam_identity_tag_case_update_and_removal(cfn, iam, resource, source):- name = f"cfn-{resource}-tag-case-{uuid.uuid4().hex[:8]}"- params = {f"{resource.title()}Name": name}- original_tag = {"Key": "Department", "Value": "Finance"}- body = _identity_template(resource, name, [original_tag] if source == "template" else [])- cfn.create_stack(StackName=name, TemplateBody=body, Capabilities=["CAPABILITY_NAMED_IAM"],- Tags=[original_tag] if source == "stack" else [])- try:- assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"- before = getattr(iam, f"get_{resource}")(**params)[resource.title()]- assert _custom_tags(before["Tags"]) == {"Department": "Finance"}- # First change only the key's spelling, then change its value too.- for value in ["Finance", "HR"]:- desired_tags = [{"Key": "department", "Value": value}, {"Key": "Added", "Value": "New"}]- body = _identity_template(resource, name, desired_tags if source == "template" else [])- cfn.update_stack(StackName=name, TemplateBody=body,- Tags=desired_tags if source == "stack" else [], Capabilities=["CAPABILITY_NAMED_IAM"])- assert _wait_stack(cfn, name)["StackStatus"] == "UPDATE_COMPLETE"- identity = getattr(iam, f"get_{resource}")(**params)[resource.title()]- assert identity[f"{resource.title()}Id"] == before[f"{resource.title()}Id"]- assert _custom_tags(identity["Tags"]) == {"department": value, "Added": "New"}- # Change a managed key's spelling externally; do not add unrelated external tags.- getattr(iam, f"tag_{resource}")(**params, Tags=[{"Key": "DEPARTMENT", "Value": "ExternalEdit"}])- assert _custom_tags(getattr(iam, f"list_{resource}_tags")(**params)["Tags"]) == {- "DEPARTMENT": "ExternalEdit", "Added": "New"}- cfn.update_stack(StackName=name, TemplateBody=_identity_template(resource, name, []), Tags=[],- Capabilities=["CAPABILITY_NAMED_IAM"])- assert _wait_stack(cfn, name)["StackStatus"] == "UPDATE_COMPLETE"- identity = getattr(iam, f"get_{resource}")(**params)[resource.title()]- assert identity[f"{resource.title()}Id"] == before[f"{resource.title()}Id"]- assert _custom_tags(getattr(iam, f"list_{resource}_tags")(**params)["Tags"]) == {}- finally:- _delete_cfn_test_stack(cfn, name)--[email protected]("resource", ["user", "role"])-def test_cfn_iam_identity_stack_tag_merge_preserves_resource_spelling(cfn, iam, resource):- """At 50 custom tags, a case-insensitive merge must not create a 51st key.-- IAM allows 50 user/role tags; aws: tags do not count toward that limit:- https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateUser.html- https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html- https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-properties-resource-tags.html- """- name = f"cfn-{resource}-tag-merge-{uuid.uuid4().hex[:8]}"- own = [{"Key": "department", "Value": "Resource"}, *[- {"Key": f"Key-{i}", "Value": "Value"} for i in range(48)]]- cfn.create_stack(StackName=name, TemplateBody=_identity_template(resource, name, own), Capabilities=["CAPABILITY_NAMED_IAM"],- Tags=[{"Key": "Department", "Value": "Stack"}, {"Key": "StackOnly", "Value": "Keep"}])- try:- assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"- actual = getattr(iam, f"list_{resource}_tags")(**{f"{resource.title()}Name": name})["Tags"]- assert [t for t in actual if t["Key"].lower() == "department"] == [own[0]]- assert _custom_tags(actual) == {**_tags(own), "StackOnly": "Keep"}- finally:- _delete_cfn_test_stack(cfn, name)--[email protected]("operation", ["create", "update"])[email protected]("resource", ["user", "role"])-def test_cfn_iam_identity_duplicate_tag_keys_leave_state_unchanged(cfn, iam, operation, resource):- name = f"cfn-{resource}-tag-duplicate-{uuid.uuid4().hex[:8]}"- params = {f"{resource.title()}Name": name}- before = None- if operation == "update":- cfn.create_stack(StackName=name, TemplateBody=_identity_template(resource, name, [{"Key": "Department", "Value": "Finance"}]),- Capabilities=["CAPABILITY_NAMED_IAM"])- assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"- before = getattr(iam, f"get_{resource}")(**params)[resource.title()]- try:- # Both duplicate forms use the predicate covered by the IAM API tests.- tags = [{"Key": "Department", "Value": "HR"}, {"Key": "department", "Value": "HR"}]- getattr(cfn, f"{operation}_stack")(StackName=name, TemplateBody=_identity_template(resource, name, tags, after=True),- Capabilities=["CAPABILITY_NAMED_IAM"])- assert _wait_stack(cfn, name)["StackStatus"] == (- "UPDATE_ROLLBACK_COMPLETE" if operation == "update" else "ROLLBACK_COMPLETE")- if before is not None:- assert getattr(iam, f"get_{resource}")(**params)[resource.title()] == before- else:- with pytest.raises(iam.exceptions.NoSuchEntityException):- getattr(iam, f"get_{resource}")(**params)- finally:- _delete_cfn_test_stack(cfn, name)--[email protected]("resource_type", ["AWS::SQS::Queue", "AWS::SSM::Parameter"])-def test_cfn_other_resource_stack_tag_merge_remains_case_sensitive(resource_type):- # Protect the list/map branches of the shared merge without provisioning other services.- props = {"Tags": [{"Key": "department", "Value": "Resource"}]} if resource_type == "AWS::SQS::Queue" else {- "Tags": {"department": "Resource"}}- original = copy.deepcopy(props)- result = _with_stack_tags(resource_type, props, [{"Key": "Department", "Value": "Stack"}],- "stack-name", "stack-id", "Resource")- tags = result["Tags"]- actual = tags if isinstance(tags, dict) else _tags(tags)- assert {k: v for k, v in actual.items() if not k.lower().startswith("aws:")} == {- "Department": "Stack", "department": "Resource"}- assert props == original---def test_cfn_other_resource_tag_reconciliation_remains_case_sensitive():- store = [{"Key": "Department", "Value": "External"}, {"Key": "department", "Value": "Before"}]- _reconcile_tag_list(store, {"Tags": [{"Key": "department", "Value": "Before"}]},- {"Tags": [{"Key": "DEPARTMENT", "Value": "After"}]})- assert _tags(store) == {"Department": "External", "DEPARTMENT": "After"}- _reconcile_tag_list(store, {"Tags": [{"Key": "DEPARTMENT", "Value": "After"}]}, {})- assert _tags(store) == {"Department": "External"}diff --git a/tests/test_signer.py b/tests/test_signer.pyindex cf71d2f4..2ed01f7a 100644--- a/tests/test_signer.py+++ b/tests/test_signer.py@@ -1341,13 +1341,13 @@ _NOT_FOUND = (404, "ResourceNotFoundException", "CertificateNotFound", "Could no])def test_signer_put_profile_refuses_unusable_signing_material_under_auth(monkeypatch, in_process, auth, platform,arn, refusal):- """Under AUTH=true PutSigningProfile refuses what AWS refuses; without AUTH every profile is created."""+ """Under AUTH=true PutSigningProfile refuses what AWS refuses; without AUTH only the Lambda and Notation refusal stays."""from ministack import app as app_modmonkeypatch.setattr(app_mod, "AUTH", auth)put, _certificate = in_processstatus, error_type, code, message = put(platform, arn)- if auth:+ if auth or refusal[2] == "InvalidProfileParameters":assert (status, error_type, code, message) == (*refusal[:3], refusal[3].format(arn=arn))else:assert (status, error_type, code, message) == (200, None, None, None)diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.pyindex 54729311..42ddf46f 100644--- a/tests/test_stepfunctions.py+++ b/tests/test_stepfunctions.py@@ -2645,6 +2645,42 @@ def test_sfn_aws_sdk_json_results_rename_nested_members(sfn_sync, sm):assert secret["SecretVersionsToStages"] == {version: ["AWSCURRENT"]}+def test_sfn_aws_sdk_ecs_and_ecr_parameters_reach_the_service(sfn_sync, ecs, ecr):+ """SDK member names in Parameters reach a camelCase-wire service under its wire names."""+ suffix = _uuid_mod.uuid4().hex[:8]+ cluster, repo_a, repo_b = f"sdk-cl-{suffix}", f"sdk-repo-a-{suffix}", f"sdk-repo-b-{suffix}"+ ecs.create_cluster(clusterName=cluster)+ ecr.create_repository(repositoryName=repo_a)+ ecr.create_repository(repositoryName=repo_b)+ try:+ clusters = _run_sdk_task(sfn_sync, f"sdk-ecs-{suffix}", "ecs:describeClusters", {"Clusters": [cluster]})+ assert [c["ClusterName"] for c in clusters["Clusters"]] == [cluster]+ missing = _run_sdk_task(sfn_sync, f"sdk-ecs-miss-{suffix}", "ecs:describeClusters",+ {"Clusters": [f"{cluster}-missing"]})+ [failure] = missing["Failures"]+ assert failure["Arn"].endswith(f"cluster/{cluster}-missing")+ repos = _run_sdk_task(sfn_sync, f"sdk-ecr-{suffix}", "ecr:describeRepositories",+ {"RepositoryNames": [repo_a]})+ assert [r["RepositoryName"] for r in repos["Repositories"]] == [repo_a]+ finally:+ ecs.delete_cluster(cluster=cluster)+ ecr.delete_repository(repositoryName=repo_a)+ ecr.delete_repository(repositoryName=repo_b)+++def test_sfn_aws_sdk_cloudwatchlogs_tag_keys_keep_their_case(sfn_sync, logs):+ """Map keys in Parameters are data: tag keys reach the service as written."""+ group = f"/sdk/tags-{_uuid_mod.uuid4().hex[:8]}"+ logs.create_log_group(logGroupName=group)+ try:+ arn = logs.describe_log_groups(logGroupNamePrefix=group)["logGroups"][0]["arn"].removesuffix(":*")+ _run_sdk_task(sfn_sync, f"sdk-logs-tag-{group[-8:]}", "cloudwatchlogs:tagResource",+ {"ResourceArn": arn, "Tags": {"Team-Name": "data", "CostCentre": "42"}})+ assert logs.list_tags_for_resource(resourceArn=arn)["tags"] == {"Team-Name": "data", "CostCentre": "42"}+ finally:+ logs.delete_log_group(logGroupName=group)++def test_sfn_aws_sdk_rds_create_and_describe_instance(sfn, sfn_sync):"""aws-sdk:rds CreateDBInstance + DescribeDBInstances via query-protocol dispatch."""import uuid as _uuid