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
feat(iot): add SetDefaultPolicyVersion and check AttachPolicy targets (#2173)
iot-rocketa2ce8e58405b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 878c0346..580a401f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,24 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Fixed+- **IoT — `AttachPolicy` to a target that does not exist** — `AttachPolicy` and `AttachPrincipalPolicy` accepted any target string; they now answer `ResourceNotFoundException` for an unknown certificate or thing group, `InvalidRequestException` for anything else that is not a certificate, a thing group (`AttachPolicy` only) or a Cognito identity id, and `AccessDeniedException` for another account's certificate, which also fails an `AWS::IoT::PolicyPrincipalAttachment` naming such a principal. Contributed by @iot-rocket.+- **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 — `SetDefaultPolicyVersion`** — the call was missing (`PATCH /policies/{policyName}/version/{policyVersionId}` answered `Unsupported policy path`), so only `CreatePolicyVersion` with `setAsDefault` could move a policy's default version; it now sets the default that `GetPolicy`, `GetPolicyVersion`, `ListPolicyVersions` and the MQTT policy evaluation under `AUTH=true` use, deleting the default version answers `DeleteConflictException` (409) instead of 400, and `ListPolicyVersions` lists the newest version first. Contributed by @iot-rocket.### Added- **Auth — REST API resource policies are evaluated under `AUTH=true`** — an API Gateway resource policy took no part in the decision; for an `execute-api:Invoke` a statement naming the calling user or role now allows the call without an identity policy, a statement naming only the account still needs one, a Deny wins over an identity Allow, and a call without a SigV4 signature (none, or a bearer token) to a method without authorization passes only when the policy, if any, allows everyone, else it answers `ACCESS_DENIED` with API Gateway's message. Contributed by @iot-rocket.- **Auth — KMS key policies are evaluated under `AUTH=true`** — a key policy took no part in the decision; it now has to allow even in the key's own account: a statement naming the calling user or role allows the call without an identity policy, identity policies count only when the key policy has a statement for the account (the default key policy does), and a Deny wins over an identity Allow. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex 8570328e..4b5ec030 100644--- a/README.md+++ b/README.md@@ -647,7 +647,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i| **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, 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, EnableTopicRule, DisableTopicRule, 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 | 70 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 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, SetDefaultPolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, AttachPrincipalPolicy, DetachPrincipalPolicy, ListPrincipalPolicies, ListPolicyPrincipals, CreateTopicRule, GetTopicRule, ReplaceTopicRule, DeleteTopicRule, ListTopicRules, EnableTopicRule, DisableTopicRule, 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 | 71 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/services/iot.py b/ministack/services/iot.pyindex 02809b18..e851131d 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -2845,6 +2845,8 @@ def _handle_policy(method: str, path: str, body: bytes, qp: dict) -> tuple:return _get_policy_version(name, version_id)if method == "DELETE":return _delete_policy_version(name, version_id)+ if method == "PATCH":+ return _set_default_policy_version(name, version_id)# /policies/{name}/versionif len(parts) == 2 and parts[1] == "version":@@ -3023,7 +3025,7 @@ def _list_policy_versions(name: str) -> tuple:"isDefaultVersion": v["isDefaultVersion"],"createDate": v.get("createDate"),}- for vid, v in p["versions"].items()+ for vid, v in sorted(p["versions"].items(), key=lambda item: int(item[0]), reverse=True)]})@@ -3036,15 +3038,40 @@ def _delete_policy_version(name: str, version_id: str) -> tuple:return _error_not_found("PolicyVersion", version_id)if p["defaultVersionId"] == version_id:return error_response_json(- "InvalidRequestException",- "Cannot delete the default policy version",- 400,+ "DeleteConflictException",+ f"Cannot delete a default policy version (name={name}, versionId={version_id})",+ 409,)del p["versions"][version_id]_policies[name] = preturn json_response({})+def _set_default_policy_version(name: str, version_id: str) -> tuple:+ """SetDefaultPolicyVersion: 200 with an empty body, also for the current default."""+ if not version_id.isdigit():+ return error_response_json(+ "InvalidRequestException",+ "1 validation error detected: Value at 'policyVersionId' failed to satisfy constraint: "+ "Member must satisfy regular expression pattern: [0-9]+",+ 400,+ )+ p = _policies.get(name)+ if p is None:+ return _error_not_found("Policy", name)+ if version_id not in p["versions"]:+ return error_response_json(+ "ResourceNotFoundException",+ f"Policy version does not exist (name={name}, versionId={version_id})",+ 404,+ )+ for vid, v in p["versions"].items():+ v["isDefaultVersion"] = vid == version_id+ p["defaultVersionId"] = version_id+ _policies[name] = p+ return 200, {}, b""++# AttachPolicy / DetachPolicy via /target-policies/{policyName}# Body: {"target": "arn:..."}@@ -3069,12 +3096,13 @@ def _handle_target_policy(method: str, path: str, body: bytes, qp: dict) -> tupl)-def _change_policy_target(name: str, target: str | None, *, attach: bool) -> tuple:+def _change_policy_target(name: str, target: str | None, *, attach: bool, principal: bool = False) -> tuple:"""``AttachPolicy`` / ``DetachPolicy`` over the policy and certificate stores.The data core behind both the modern ``/target-policies/{policyName}``route and the deprecated ``/principal-policies/{policyName}`` one, so- neither has to synthesize a request for the other.+ neither has to synthesize a request for the other. ``principal`` selects+ the deprecated call's refusals."""p = _policies.get(name)if p is None:@@ -3083,6 +3111,10 @@ def _change_policy_target(name: str, target: str | None, *, attach: bool) -> tupreturn error_response_json("InvalidRequestException", "target is required", 400)+ if attach:+ err = _policy_target_error(target, principal=principal)+ if err:+ return errcert_id = target.rsplit("/", 1)[-1]cert = _certificates.get(cert_id)if attach:@@ -3102,6 +3134,51 @@ def _change_policy_target(name: str, target: str | None, *, attach: bool) -> tupreturn json_response({})+# A Cognito identity id, the one target that is not an ARN.+_COGNITO_IDENTITY_ID_RE = re.compile(r"[\w-]+:[0-9a-f-]+")+++def _policy_target_error(target: str, *, principal: bool) -> tuple | None:+ """AttachPolicy's refusal of ``target`` (AttachPrincipalPolicy's with ``principal``), or ``None``."""+ if _COGNITO_IDENTITY_ID_RE.fullmatch(target):+ return None+ try:+ spec = parse_arn(target)+ except ArnParseError:+ spec = None+ if spec is None:+ if principal and target.startswith("arn:"):+ return error_response_json("InvalidRequestException", "ARN not in proper syntax.", 400)+ message = "Invalid principal type" if principal else "Invalid Target"+ return error_response_json("InvalidRequestException", message, 400)+ kind, _, resource_id = spec.resource.partition("/")+ if spec.service != "iot" or kind not in (("cert",) if principal else ("cert", "thinggroup")):+ message = "The given ARN does not represent a cert" if principal else f"Invalid Target: {target}"+ return error_response_json("InvalidRequestException", message, 400)+ if spec.account_id != get_account_id():+ return error_response_json(+ "AccessDeniedException",+ "Cross account not allowed. Please check the account of the resource specified.",+ 403,+ )+ if spec.region != get_region() and not principal:+ return error_response_json("InvalidRequestException", "Invalid Target", 400)+ if kind == "thinggroup":+ if resource_id in _thing_groups:+ return None+ return error_response_json(+ "ResourceNotFoundException",+ f"Cannot find requested thing group for accountId: {get_account_id()} and thing group name: "+ f"{resource_id}",+ 404,+ )+ if resource_id in _certificates:+ return None+ return error_response_json(+ "ResourceNotFoundException", "The certificate given in the principal does not exist.", 404+ )++def _policy_targets(name: str) -> list | None:"""The targets attached to policy ``name``, or ``None`` if it does not exist."""p = _policies.get(name)@@ -3160,7 +3237,7 @@ def _handle_principal_policy(method: str, path: str, headers: dict, qp: dict) ->return error_response_json("InvalidRequestException", "x-amzn-iot-principal header is required", 400)- return _change_policy_target(name, principal, attach=method == "PUT")+ return _change_policy_target(name, principal, attach=method == "PUT", principal=True)def _list_principal_policies(headers: dict, qp: dict) -> tuple:diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 79b8f891..7ed6f5a8 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -1186,6 +1186,28 @@ def test_cfn_iot_principal_attachments(cfn, iot_client):iot_client.describe_thing(thingName=thing2)+def test_cfn_iot_policy_principal_attachment_unknown_certificate(cfn, iot_client):+ """A PolicyPrincipalAttachment to an unknown certificate fails the stack and rolls the policy back."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack, policy = f"cfn-ppa-{uid}", f"cfn-ppa-{uid}"+ document = {"Version": "2012-10-17", "Statement": [+ {"Effect": "Allow", "Action": "iot:Connect", "Resource": "*"}]}+ try:+ cfn.create_stack(StackName=stack, TemplateBody=json.dumps({"Resources": {+ "Pol": {"Type": "AWS::IoT::Policy", "Properties": {"PolicyName": policy, "PolicyDocument": document}},+ "Ppa": {"Type": "AWS::IoT::PolicyPrincipalAttachment", "Properties": {+ "PolicyName": {"Ref": "Pol"},+ "Principal": {"Fn::Sub": "arn:aws:iot:${AWS::Region}:${AWS::AccountId}:cert/" + "ab" * 32}}},+ }}))+ assert _wait_stack(cfn, stack)["StackStatus"] == "ROLLBACK_COMPLETE"+ assert "The certificate given in the principal does not exist." in _cfn_iot_failure(+ cfn, stack, "Ppa", "CREATE_FAILED")+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.get_policy(policyName=policy)+ finally:+ _delete_cfn_test_stack(cfn, stack)++def test_cfn_iot_delete_keeps_what_is_attached_outside_the_stack(cfn, iot_client):"""A certificate with a policy or a thing attached outside the stack isdeactivated and then fails its delete, as is a thing with an outsidediff --git a/tests/test_iot.py b/tests/test_iot.pyindex 34e5560f..9f77985e 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -1486,6 +1486,103 @@ def test_iot_policy_versions(iot_client):iot_client.delete_policy(policyName=name)+def _connect_policy(client_id: str) -> str:+ return json.dumps({"Version": "2012-10-17", "Statement": [+ {"Effect": "Allow", "Action": "iot:Connect", "Resource": f"arn:aws:iot:*:*:client/{client_id}"}]})+++def test_iot_set_default_policy_version(iot_client):+ name = _unique("policy")+ iot_client.create_policy(policyName=name, policyDocument=_POLICY_DOC)+ v2_doc = _connect_policy("other")+ iot_client.create_policy_version(policyName=name, policyDocument=v2_doc, setAsDefault=False)++ def versions():+ return {v["versionId"]: v["isDefaultVersion"]+ for v in iot_client.list_policy_versions(policyName=name)["policyVersions"]}++ try:+ # Newest version first.+ assert list(versions().items()) == [("2", False), ("1", True)]+ # Setting the current default again is accepted as well; both answer 200 with no body.+ for _ in range(2):+ resp = iot_client.set_default_policy_version(policyName=name, policyVersionId="2")+ assert resp.pop("ResponseMetadata")["HTTPStatusCode"] == 200+ assert resp == {}+ got = iot_client.get_policy(policyName=name)+ assert (got["defaultVersionId"], got["policyDocument"]) == ("2", v2_doc)+ assert versions() == {"1": False, "2": True}+ for vid, default in (("1", False), ("2", True)):+ assert iot_client.get_policy_version(+ policyName=name, policyVersionId=vid)["isDefaultVersion"] is default++ # The new default cannot be deleted, the old one can.+ with pytest.raises(ClientError) as ei:+ iot_client.delete_policy_version(policyName=name, policyVersionId="2")+ err = ei.value.response+ assert (err["ResponseMetadata"]["HTTPStatusCode"], err["Error"]["Code"], err["Error"]["Message"]) == (+ 409, "DeleteConflictException", f"Cannot delete a default policy version (name={name}, versionId=2)")+ iot_client.delete_policy_version(policyName=name, policyVersionId="1")+ assert versions() == {"2": True}+ finally:+ for vid, default in versions().items():+ if not default:+ iot_client.delete_policy_version(policyName=name, policyVersionId=vid)+ iot_client.delete_policy(policyName=name)+++def test_iot_set_default_policy_version_refusals(iot_client):+ name = _unique("policy")+ iot_client.create_policy(policyName=name, policyDocument=_POLICY_DOC)+ try:+ for version, status, code, message in (+ ("9", 404, "ResourceNotFoundException", f"Policy version does not exist (name={name}, versionId=9)"),+ ("abc", 400, "InvalidRequestException", "1 validation error detected: Value at 'policyVersionId' failed "+ "to satisfy constraint: Member must satisfy regular expression pattern: [0-9]+"),+ ):+ with pytest.raises(ClientError) as ei:+ iot_client.set_default_policy_version(policyName=name, policyVersionId=version)+ err = ei.value.response+ assert (err["ResponseMetadata"]["HTTPStatusCode"], err["Error"]["Code"], err["Error"]["Message"]) == (+ status, code, message)+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.set_default_policy_version(policyName=_unique("nope"), policyVersionId="1")+ assert iot_client.get_policy(policyName=name)["defaultVersionId"] == "1"+ finally:+ iot_client.delete_policy(policyName=name)+++def test_iot_default_policy_version_persists():+ import asyncio++ from ministack.core.responses import set_request_account_id, set_request_region+ from ministack.services import iot as iot_module++ name = _unique("policy")++ async def _call(method, path, payload=None):+ set_request_account_id("123456789012")+ set_request_region("eu-west-1")+ body = json.dumps(payload).encode() if payload else b""+ return await iot_module.handle_request(method, path, {}, body, {})++ async def _run():+ assert (await _call("POST", f"/policies/{name}", {"policyDocument": _POLICY_DOC}))[0] == 200+ assert (await _call("POST", f"/policies/{name}/version", {"policyDocument": _connect_policy("a")}))[0] == 200+ status, _headers, answer = await _call("PATCH", f"/policies/{name}/version/2")+ assert (status, answer) == (200, b"")+ saved = iot_module.get_state()+ iot_module.reset()+ iot_module.load_persisted_state(saved)+ _status, _headers, body = await _call("GET", f"/policies/{name}")+ return json.loads(body)["defaultVersionId"]++ try:+ assert asyncio.run(_run()) == "2"+ finally:+ iot_module.reset()++def test_iot_attach_detach_policy(iot_client):pytest.importorskip("cryptography")name = _unique("policy")@@ -1505,6 +1602,57 @@ def test_iot_attach_detach_policy(iot_client):iot_client.delete_certificate(certificateId=cert["certificateId"])+def test_iot_attach_policy_refuses_unknown_targets(iot_client):+ """AttachPolicy takes only a certificate or thing group of this account and region, or a Cognito identity id."""+ pytest.importorskip("cryptography")+ name, group = _unique("policy"), _unique("group")+ iot_client.create_policy(policyName=name, policyDocument=_POLICY_DOC)+ iot_client.create_thing_group(thingGroupName=group)+ cert = iot_client.create_keys_and_certificate(setAsActive=False)+ cert_arn, cert_id = cert["certificateArn"], cert["certificateId"]+ region, account = cert_arn.split(":")[3:5]+ prefix = f"arn:aws:iot:{region}:{account}"+ cognito = f"{region}:00000000-0000-0000-0000-000000000000"+ no_cert = (404, "ResourceNotFoundException", "The certificate given in the principal does not exist.")+ refused = {+ f"{prefix}:cert/{'ab' * 32}": no_cert,+ f"{prefix}:cert/abc": no_cert,+ f"arn:aws:iot:eu-central-1:{account}:cert/{cert_id}": (400, "InvalidRequestException", "Invalid Target"),+ f"arn:aws:iot:{region}:111122223333:cert/{cert_id}": (+ 403, "AccessDeniedException",+ "Cross account not allowed. Please check the account of the resource specified."),+ "not-an-arn": (400, "InvalidRequestException", "Invalid Target"),+ f"{region}:not-a-uuid": (400, "InvalidRequestException", "Invalid Target"),+ f"{prefix}:thinggroup/nogroup": (+ 404, "ResourceNotFoundException",+ f"Cannot find requested thing group for accountId: {account} and thing group name: nogroup"),+ f"{prefix}:thing/t1": (400, "InvalidRequestException", f"Invalid Target: {prefix}:thing/t1"),+ f"{prefix}:policy/{name}": (400, "InvalidRequestException", f"Invalid Target: {prefix}:policy/{name}"),+ f"arn:aws:iam::{account}:user/u1": (+ 400, "InvalidRequestException", f"Invalid Target: arn:aws:iam::{account}:user/u1"),+ }+ try:+ for target, expected in refused.items():+ with pytest.raises(ClientError) as ei:+ iot_client.attach_policy(policyName=name, target=target)+ err = ei.value.response+ assert (err["ResponseMetadata"]["HTTPStatusCode"], err["Error"]["Code"], err["Error"]["Message"]) == (+ expected), target+ allowed = [cert_arn, f"{prefix}:thinggroup/{group}", cognito]+ for target in allowed:+ iot_client.attach_policy(policyName=name, target=target)+ assert sorted(iot_client.list_targets_for_policy(policyName=name)["targets"]) == sorted(allowed)+ for target in [f"{prefix}:cert/{'ab' * 32}", f"{prefix}:thinggroup/nogroup", *allowed]:+ iot_client.detach_policy(policyName=name, target=target)+ assert iot_client.list_targets_for_policy(policyName=name)["targets"] == []+ finally:+ for target in iot_client.list_targets_for_policy(policyName=name)["targets"]:+ iot_client.detach_policy(policyName=name, target=target)+ iot_client.delete_policy(policyName=name)+ iot_client.delete_thing_group(thingGroupName=group)+ iot_client.delete_certificate(certificateId=cert_id)++def test_iot_delete_policy_refused_while_versioned_or_attached(iot_client):"""A non-default version is refused before an attachment."""pytest.importorskip("cryptography")@@ -1612,6 +1760,49 @@ def test_iot_legacy_principal_policy_family(iot_client):iot_client.delete_certificate(certificateId=cert["certificateId"])+def test_iot_legacy_attach_principal_policy_refuses_unknown_principals(iot_client):+ """AttachPrincipalPolicy takes only a certificate of this account, in any region, or a Cognito identity id."""+ pytest.importorskip("cryptography")+ name, group = _unique("policy"), _unique("group")+ iot_client.create_policy(policyName=name, policyDocument=_POLICY_DOC)+ iot_client.create_thing_group(thingGroupName=group)+ cert = iot_client.create_keys_and_certificate(setAsActive=False)+ cert_arn, cert_id = cert["certificateArn"], cert["certificateId"]+ region, account = cert_arn.split(":")[3:5]+ prefix = f"arn:aws:iot:{region}:{account}"+ not_a_cert = (400, "InvalidRequestException", "The given ARN does not represent a cert")+ refused = {+ f"{prefix}:cert/{'ab' * 32}": (+ 404, "ResourceNotFoundException", "The certificate given in the principal does not exist."),+ f"arn:aws:iot:{region}:111122223333:cert/{cert_id}": (+ 403, "AccessDeniedException",+ "Cross account not allowed. Please check the account of the resource specified."),+ "not-an-arn": (400, "InvalidRequestException", "Invalid principal type"),+ "foo:bar": (400, "InvalidRequestException", "Invalid principal type"),+ "arn:aws:iot:cert/none": (400, "InvalidRequestException", "ARN not in proper syntax."),+ f"{prefix}:thinggroup/{group}": not_a_cert,+ f"{prefix}:thing/t1": not_a_cert,+ }+ try:+ for principal, expected in refused.items():+ with pytest.raises(ClientError) as ei:+ iot_client.attach_principal_policy(policyName=name, principal=principal)+ err = ei.value.response+ assert (err["ResponseMetadata"]["HTTPStatusCode"], err["Error"]["Code"], err["Error"]["Message"]) == (+ expected), principal+ allowed = [cert_arn, f"arn:aws:iot:eu-central-1:{account}:cert/{cert_id}",+ f"{region}:00000000-0000-0000-0000-000000000000"]+ for principal in allowed:+ iot_client.attach_principal_policy(policyName=name, principal=principal)+ assert sorted(iot_client.list_policy_principals(policyName=name)["principals"]) == sorted(allowed)+ finally:+ for principal in iot_client.list_policy_principals(policyName=name)["principals"]:+ iot_client.detach_principal_policy(policyName=name, principal=principal)+ iot_client.delete_policy(policyName=name)+ iot_client.delete_thing_group(thingGroupName=group)+ iot_client.delete_certificate(certificateId=cert_id)++def test_iot_legacy_principal_policy_unknown_policy_404(iot_client):with pytest.raises(ClientError) as ei:iot_client.attach_principal_policy(@@ -7443,6 +7634,47 @@ def test_mqtt_connect_evaluates_certificate_policies(monkeypatch):]+def test_mqtt_connect_follows_the_default_policy_version(monkeypatch):+ """Under AUTH=true iot:Connect is evaluated on the version SetDefaultPolicyVersion made the default."""+ import ministack.app as _app+ from ministack.services import iot as iot_module++ monkeypatch.setattr(_app, "AUTH", True)+ name = _unique("policy")++ def doc(client_id):+ return json.dumps({"Version": "2012-10-17", "Statement": [+ {"Effect": "Allow", "Action": "iot:Connect", "Resource": f"{_POLICY_ARN}:client/{client_id}"}]})++ async def _connects(cert_id, client_id):+ session, sent, keep = await _policy_connect(cert_id, client_id)+ await session.cleanup()+ return keep++ async def _run():+ cert_id = await _policy_device(iot_module)+ arn = f"{_POLICY_ARN}:cert/{cert_id}"+ for method, path, payload in (+ ("POST", f"/policies/{name}", {"policyDocument": doc("dev")}),+ ("POST", f"/policies/{name}/version", {"policyDocument": doc("other")}),+ ("PUT", f"/target-policies/{name}", {"target": arn}),+ ):+ assert (await iot_module.handle_request(method, path, {}, json.dumps(payload).encode(), {}))[0] == 200+ outcomes = []+ for version in ("2", "1"):+ assert (await iot_module.handle_request("PATCH", f"/policies/{name}/version/{version}", {}, b"", {}))[+ 0] == 200+ outcomes.append((version, await _connects(cert_id, "dev"), await _connects(cert_id, "other")))+ return outcomes++ try:+ outcomes = asyncio.run(_run())+ finally:+ iot_module.reset()+ iot_module.broker_reset()+ assert outcomes == [("2", False, True), ("1", True, False)]++def test_mqtt_connect_resolves_policy_variables(monkeypatch):"""Thing variables resolve only when the client id is a thing attached tothe certificate; the common name comes from the certificate subject."""