Skip to content

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

feat(iot): add fleet provisioning by claim over MQTT (#2177)

iot-rocketd0cb469f2e5d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index be86929d..31e90f58 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,6 +25,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
+- **IoT — fleet provisioning by claim** — `CreateProvisioningClaim` issues a five-minute claim certificate that the mTLS listener accepts until it expires, and a device connected with it (or with any registered certificate) gets a certificate from `$aws/certificates/create/json` and registers itself through `$aws/provisioning-templates/<name>/provision/json`: the template's parameters, `Ref` and `Fn::Join` are resolved, the thing is created or checked against its `OverrideSettings`, and the certificate is activated and attached to the thing and the template's policies, with AWS's replies and rejections on the requesting connection; with `AUTH=true` a claim connection is limited to the certificate topics and its own template's, as on AWS. Contributed by @iot-rocket.
- **IoT — presigned URLs in job documents** — devices got `${aws:iot:s3-presigned-url:<url>}` and `${aws:iot:s3-presigned-url-v2:<url>}` placeholders as written; the `iot-jobs-data` API and the MQTT jobs topics now replace each with a SigV4 presigned GET URL of MiniStack's S3, signed with a session of `presignedUrlConfig.roleArn` and valid for `expiresInSec`, and `CreateJob` and `CreateJobTemplate` refuse a placeholder without a role or an S3 object URL with AWS's messages. Contributed by @iot-rocket.
- **IoT — job documents from S3** — `CreateJob` and `CreateJobTemplate` read a `documentSource` (`s3://` or an S3 object URL) from MiniStack's S3 once, at creation, where they stored a `{"documentSource": "<url>"}` placeholder. A missing bucket or object, an object that is not JSON or is over 32 KB and a URL that names no S3 host are refused with AWS's messages, and `CreateJob` refuses `document` together with `documentSource`. Devices get every job document re-serialized as AWS sends it, without spaces and without object members that are null, while `GetJobDocument` keeps the stored text. Contributed by @iot-rocket.
- **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.
diff --git a/README.md b/README.md
index 3c8ff884..c0876f95 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 read from MiniStack's S3**: a job or job template created with an `s3://` or S3 object URL keeps the object's content as its document, read once at creation; a missing bucket or object, a non-JSON object or one over 32 KB is refused, and so is a URL whose host is not S3. **Presigned URLs**: a `${aws:iot:s3-presigned-url:<url>}` or `-v2` placeholder needs `presignedUrlConfig.roleArn`, and what devices receive (HTTP and MQTT) carries a SigV4 presigned GET URL of MiniStack's S3 instead, signed with a session of that role. The URL is path style on the host the device used, and an IoT endpoint host drops everything up to and including its region label. **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, 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, or with `AUTH=true` a close without one as on AWS (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, CreateProvisioningClaim, 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 | 72 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 or be an unexpired provisioning claim, which then serves the session; unknown, inactive or doubly-registered certificates get a "not authorized" CONNACK, or with `AUTH=true` a close without one as on AWS (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) with **fleet provisioning by claim**: `CreateProvisioningClaim`, then `CreateKeysAndCertificate` and `RegisterThing` over MQTT on the JSON topics (`$aws/certificates/create/json`, `$aws/provisioning-templates/<name>/provision/json`), answered on the requesting connection, and with `AUTH=true` a claim connection may use only the certificate topics and its own template's `provision` topics; `provisioningRoleArn` is presence-checked but not resolved and the pre-provisioning hook is not invoked; 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 |
@@ -893,7 +893,7 @@ come from `repositoryCredentials.credentialsParameter` (a Secrets Manager secret
| `MINISTACK_RDS_PUBLIC_ENDPOINT` | `0` | Set `1` when MiniStack itself runs in a Docker container but RDS clients connect from outside that network (remote MiniStack host, host-side clients, CI runners). `DescribeDBInstances` then returns `{MINISTACK_HOST, host_port}` — the externally-reachable host-published port — instead of the container-internal address. Set `MINISTACK_HOST` to the host clients will use |
| `MINISTACK_RDS_PG_CLUSTER_REPLICATION` | `0` | Set `1` to give the second and later members of an Aurora PostgreSQL cluster their own hot-standby containers streaming from the writer (real read-only replicas; the cluster `ReaderEndpoint` resolves to one when available). Requires `DOCKER_NETWORK`. Off: all members alias the writer's single shared container |
| `IOT_MTLS_ENABLED` | _(unset = on)_ | Set `0` to stop the IoT mTLS MQTT listener from binding (same shape as `SFTP_ENABLED`). It is on whenever `cryptography` is installed |
-| `IOT_MTLS_PORT` | `8883` | Port of the IoT mTLS MQTT listener. Device SDK binaries connect here with the local CA from `GET /_ministack/iot/ca.pem` as their trust store. The client certificate is optional: without one the session runs under `MINISTACK_ACCOUNT_ID`, with one it must be registered `ACTIVE` in exactly one account (which then serves it) or the connection is refused with a "not authorized" CONNACK (0x05, or reason code 0x87 for MQTT 5); with `AUTH=true` it is closed after the CONNECT without a CONNACK, as on AWS, and the log names the reason either way. A CONNECT that the policies of an `ACTIVE` certificate refuse under `AUTH=true` gets CONNACK 0x87 on MQTT 5 and a close without a CONNACK on 3.1.1 |
+| `IOT_MTLS_PORT` | `8883` | Port of the IoT mTLS MQTT listener. Device SDK binaries connect here with the local CA from `GET /_ministack/iot/ca.pem` as their trust store. The client certificate is optional: without one the session runs under `MINISTACK_ACCOUNT_ID`, with one it must be registered `ACTIVE` in exactly one account (which then serves it) or be an unexpired provisioning claim, or the connection is refused with a "not authorized" CONNACK (0x05, or reason code 0x87 for MQTT 5); with `AUTH=true` it is closed after the CONNECT without a CONNACK, as on AWS, and the log names the reason either way. A CONNECT that the policies of an `ACTIVE` certificate refuse under `AUTH=true` gets CONNACK 0x87 on MQTT 5 and a close without a CONNACK on 3.1.1 |
| `DSQL_BASE_PORT` | `25432` | Starting host port for Aurora DSQL cluster proxies (one port per cluster) |
| `DSQL_STRICT` | `0` | Set `1` to run a real Postgres container per DSQL cluster (requires Docker; capped by a fixed port window off `DSQL_BASE_PORT`, default 30 — further clusters are metadata-only stubs). Default `0` is control-plane-only |
| `DSQL_PG_IMAGE` | `postgres:16-alpine` | Image used for per-cluster DSQL backend containers |
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 9f25251e..8039c80c 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -20,9 +20,10 @@ Implements the JSON/REST APIs under ``iot.{region}.amazonaws.com``:
``$aws/events/certificates/registered/{caCertificateId}``
- Provisioning templates: ``CreateProvisioningTemplate``,
``DescribeProvisioningTemplate``, ``ListProvisioningTemplates``,
- ``UpdateProvisioningTemplate``, ``DeleteProvisioningTemplate`` —
- storage + CRUD only: the fleet-provisioning MQTT workflow
- (``$aws/provisioning-templates/...``) is not implemented, and
+ ``UpdateProvisioningTemplate``, ``DeleteProvisioningTemplate``,
+ ``CreateProvisioningClaim``, and fleet provisioning over MQTT
+ (``$aws/certificates/create/json`` and
+ ``$aws/provisioning-templates/{name}/provision/json``);
``provisioningRoleArn`` is presence-checked but not resolved
(MiniStack does not validate IAM role ARNs elsewhere either)
- Policies: ``CreatePolicy``, ``CreatePolicyVersion``, ``AttachPolicy``,
@@ -146,6 +147,10 @@ _ca_certificates: AccountRegionScopedDict = AccountRegionScopedDict()
_registration_codes: AccountRegionScopedDict = AccountRegionScopedDict()
# Provisioning templates (CreateProvisioningTemplate & friends): templateName -> record
_provisioning_templates: AccountRegionScopedDict = AccountRegionScopedDict()
+# Claim certificates (CreateProvisioningClaim): certificateId -> record, until they expire
+_provisioning_claims: AccountRegionScopedDict = AccountRegionScopedDict()
+# Ownership tokens of certificates created over MQTT: token -> record, until they expire
+_ownership_tokens: AccountRegionScopedDict = AccountRegionScopedDict()
_jobs: AccountRegionScopedDict = AccountRegionScopedDict() # jobId -> Job dict
# (thingName, jobId) -> JobExecution dict — tuple keys, same pattern as _shadows
_job_executions: AccountRegionScopedDict = AccountRegionScopedDict()
@@ -278,6 +283,8 @@ def get_state() -> dict:
"ca_certificates": copy.deepcopy(_ca_certificates),
"registration_codes": copy.deepcopy(_registration_codes),
"provisioning_templates": copy.deepcopy(_provisioning_templates),
+ "provisioning_claims": copy.deepcopy(_provisioning_claims),
+ "ownership_tokens": copy.deepcopy(_ownership_tokens),
"jobs": copy.deepcopy(_jobs),
"job_executions": copy.deepcopy(_job_executions),
"job_templates": copy.deepcopy(_job_templates),
@@ -317,6 +324,8 @@ def _restore_state(data: dict | None) -> None:
_ca_certificates.update(data.get("ca_certificates", {}))
_registration_codes.update(data.get("registration_codes", {}))
_provisioning_templates.update(data.get("provisioning_templates", {}))
+ _provisioning_claims.update(data.get("provisioning_claims", {}))
+ _ownership_tokens.update(data.get("ownership_tokens", {}))
_jobs.update(data.get("jobs", {}))
_job_executions.update(data.get("job_executions", {}))
_job_templates.update(data.get("job_templates", {}))
@@ -369,6 +378,8 @@ def reset() -> None:
_ca_certificates.clear()
_registration_codes.clear()
_provisioning_templates.clear()
+ _provisioning_claims.clear()
+ _ownership_tokens.clear()
_jobs.clear()
_job_executions.clear()
_job_templates.clear()
@@ -1865,9 +1876,10 @@ async def _remove_thing_from_group(payload: dict) -> tuple:
# ---------------------------------------------------------------------------
# Provisioning templates
#
-# Storage + CRUD only: the fleet-provisioning MQTT workflow
-# ($aws/provisioning-templates/{name}/provision/*) is not implemented, and
-# provisioningRoleArn is presence-checked but never resolved — MiniStack does
+# CRUD, CreateProvisioningClaim and the fleet provisioning MQTT API (JSON
+# topics) that applies a template to a certificate created over MQTT. The
+# pre-provisioning hook is stored but not invoked, and provisioningRoleArn is
+# presence-checked but never resolved — MiniStack does
# not validate IAM role ARNs elsewhere either. Template versions are not
# modeled: a template always carries defaultVersionId 1. Wire shapes and
# error messages mirror a live probe of the real service (2026-08-26).
@@ -1925,14 +1937,16 @@ def _provisioning_template_not_found(name: str) -> tuple:
def _handle_provisioning_template(method: str, path: str, body: bytes) -> tuple:
suffix = path[len("/provisioning-templates/"):]
- if "/" in suffix:
+ name, _, sub = suffix.partition("/")
+ if sub and (method, sub) != ("POST", "provisioning-claim"):
return error_response_json(
"InvalidRequestException", f"Unsupported IoT path: {method} {path}", 400
)
- name = suffix
err = _validate_provisioning_template_name(name)
if err:
return err
+ if sub:
+ return _create_provisioning_claim(name)
if method == "GET":
return _describe_provisioning_template(name)
if method == "PATCH":
@@ -2056,6 +2070,348 @@ def _delete_provisioning_template(name: str) -> tuple:
return json_response({})
+# A claim certificate expires five minutes after it is issued, at the end of its
+# X.509 validity; an ownership token expires after an hour.
+_PROVISIONING_CLAIM_SECONDS = 300
+_OWNERSHIP_TOKEN_SECONDS = 3600
+
+
+def _drop_expired(store: AccountRegionScopedDict) -> None:
+ """Forget the claims or ownership tokens past their expiration, in every scope."""
+ now = time.time()
+ for key, record in list(store._data.items()):
+ if record["expiration"] <= now:
+ store._data.pop(key, None)
+
+
+def _create_provisioning_claim(name: str) -> tuple:
+ """``CreateProvisioningClaim``: a claim certificate kept out of the certificate registry."""
+ if _provisioning_templates.get(name) is None:
+ return _provisioning_template_not_found(name)
+ try:
+ ca_cert_pem, ca_key_pem = _ensure_ca()
+ cert_pem, private_pem, public_pem = sign_leaf_certificate(
+ ca_cert_pem=ca_cert_pem,
+ ca_key_pem=ca_key_pem,
+ common_name="AWS IoT Certificate",
+ days_valid=_PROVISIONING_CLAIM_SECONDS / 86400,
+ )
+ except RuntimeError as e:
+ return error_response_json("InternalFailureException", str(e), 503)
+ from cryptography import x509
+
+ leaf = x509.load_pem_x509_certificate(cert_pem.encode("utf-8"))
+ not_after = getattr(leaf, "not_valid_after_utc", None) or leaf.not_valid_after.replace(
+ tzinfo=timezone.utc
+ )
+ cert_id = get_certificate_id(cert_pem)
+ _drop_expired(_provisioning_claims)
+ _provisioning_claims[cert_id] = {
+ "certificateId": cert_id,
+ "templateName": name,
+ "expiration": not_after.timestamp(),
+ }
+ return json_response({
+ "certificateId": cert_id,
+ "certificatePem": cert_pem,
+ "keyPair": {"PublicKey": public_pem, "PrivateKey": private_pem},
+ "expiration": not_after.timestamp(),
+ })
+
+
+# The fleet provisioning MQTT API (JSON payloads). A request is answered on the
+# connection that published it, and nowhere else.
+_FLEET_CREATE_TOPIC = "$aws/certificates/create/json"
+_FLEET_TEMPLATES_PREFIX = "$aws/provisioning-templates/"
+_FLEET_PROVISION_SUFFIX = "/provision/json"
+_CERTIFICATE_ID_PARAMETER = "AWS::IoT::Certificate::Id"
+
+
+def _parse_fleet_provisioning_topic(topic: str) -> tuple[str, str | None] | None:
+ """``("create", None)`` for CreateKeysAndCertificate, ``("provision", template)`` for RegisterThing."""
+ if topic == _FLEET_CREATE_TOPIC:
+ return "create", None
+ if topic.startswith(_FLEET_TEMPLATES_PREFIX) and topic.endswith(_FLEET_PROVISION_SUFFIX):
+ name = topic[len(_FLEET_TEMPLATES_PREFIX):-len(_FLEET_PROVISION_SUFFIX)]
+ if name and "/" not in name:
+ return "provision", name
+ return None
+
+
+def _fleet_rejected(code: str, message: str, status: int = 400) -> tuple[str, dict]:
+ return "rejected", {"statusCode": status, "errorCode": code, "errorMessage": message}
+
+
+class _ProvisioningRejected(Exception):
+ """A RegisterThing request the template cannot be applied to."""
+
+ def __init__(self, code: str, message: str):
+ super().__init__(message)
+ self.reply = _fleet_rejected(code, message)
+
+
+def _provisioning_failed(message: str) -> _ProvisioningRejected:
+ """A registry refusal, worded the way AWS relays it on ``/rejected``."""
+ return _ProvisioningRejected(
+ "ProvisioningFailed",
+ f"{message} (Service: AWSIot; Status Code: 400; Error Code: "
+ f"ResourceRegistrationFailureException; Request ID: {new_uuid()}; Proxy: null)",
+ )
+
+
+async def _fleet_provisioning_reply(
+ account_id: str, region: str, operation: str, template_name: str | None, payload: bytes
+) -> tuple[str, dict]:
+ """The reply suffix (``accepted`` or ``rejected``) and document for one request."""
+ if operation == "create":
+ return await _fleet_create_keys_and_certificate(account_id, region)
+ try:
+ return await _fleet_register_thing(account_id, region, template_name, payload)
+ except _ProvisioningRejected as e:
+ return e.reply
+
+
+async def _fleet_create_keys_and_certificate(account_id: str, region: str) -> tuple[str, dict]:
+ """``CreateKeysAndCertificate`` over MQTT: a PENDING_ACTIVATION certificate and its ownership token."""
+
+ def _issue() -> tuple[str, str, str]:
+ ca_cert_pem, ca_key_pem = _ensure_ca()
+ return sign_leaf_certificate(ca_cert_pem, ca_key_pem, "AWS IoT Certificate")
+
+ try:
+ # RSA key generation, kept off the broker's loop.
+ cert_pem, private_pem, _public_pem = await asyncio.to_thread(_issue)
+ except RuntimeError as e:
+ return _fleet_rejected("InternalFailure", str(e), 500)
+ cert_id = get_certificate_id(cert_pem)
+ token = secrets.token_urlsafe(48)
+ with request_scope(account_id, region):
+ _certificates[cert_id] = _certificate_record(cert_id, cert_pem, "PENDING_ACTIVATION")
+ _drop_expired(_ownership_tokens)
+ _ownership_tokens[token] = {
+ "certificateId": cert_id,
+ "expiration": time.time() + _OWNERSHIP_TOKEN_SECONDS,
+ }
+ return "accepted", {
+ "certificateId": cert_id,
+ "certificatePem": cert_pem,
+ "privateKey": private_pem,
+ "certificateOwnershipToken": token,
+ }
+
+
+async def _fleet_register_thing(
+ account_id: str, region: str, template_name: str, payload: bytes
+) -> tuple[str, dict]:
+ """``RegisterThing``: apply the template to the certificate the ownership token stands for."""
+ try:
+ request = json.loads(payload)
+ except (ValueError, UnicodeDecodeError):
+ request = None
+ if not isinstance(request, dict):
+ return _fleet_rejected("InvalidPayload", "Message cannot be parsed")
+ with request_scope(account_id, region):
+ template = _provisioning_templates.get(template_name)
+ if template is None:
+ return _fleet_rejected(
+ "InvalidTemplate", f"Template with name {template_name} does not exist."
+ )
+ if not template.get("enabled"):
+ return _fleet_rejected("InvalidTemplate", f"Template {template_name} is not enabled.")
+ token = request.get("certificateOwnershipToken")
+ record = _ownership_tokens.get(token) if isinstance(token, str) else None
+ cert = (
+ _certificates.get(record["certificateId"])
+ if record is not None and record["expiration"] > time.time()
+ else None
+ )
+ if cert is None:
+ return _fleet_rejected(
+ "InvalidCertificateOwnershipToken", "Certificate ownership token is invalid."
+ )
+ parameters = request.get("parameters")
+ parameters = parameters if isinstance(parameters, dict) else {}
+ plan = _provisioning_plan(template, parameters, cert["certificateId"])
+ thing_name = await _apply_provisioning_plan(plan, cert)
+ reply = {"deviceConfiguration": plan["deviceConfiguration"]}
+ if thing_name is not None:
+ reply["thingName"] = thing_name
+ return "accepted", reply
+
+
+def _provisioning_plan(template: dict, parameters: dict, cert_id: str) -> dict:
+ """The template's resources with ``Ref`` and ``Fn::Join`` resolved against the parameters."""
+ body = template["templateBody"]
+ body = json.loads(body) if isinstance(body, str) else body
+ declared = body.get("Parameters")
+ values = {
+ name: spec["Default"]
+ for name, spec in (declared.items() if isinstance(declared, dict) else ())
+ if isinstance(spec, dict) and "Default" in spec
+ }
+ values.update(parameters)
+ values[_CERTIFICATE_ID_PARAMETER] = cert_id
+
+ def resolve(value):
+ if isinstance(value, list):
+ return [resolve(v) for v in value]
+ if not isinstance(value, dict):
+ return value
+ if len(value) == 1:
+ function, argument = next(iter(value.items()))
+ if function == "Ref":
+ if argument not in values:
+ raise _ProvisioningRejected(
+ "InvalidParameters", f"Cannot resolve reference value: {argument}"
+ )
+ return values[argument]
+ if (
+ function == "Fn::Join"
+ and isinstance(argument, list)
+ and len(argument) == 2
+ and isinstance(argument[1], list)
+ ):
+ return str(argument[0]).join(str(resolve(v)) for v in argument[1])
+ if function.startswith("Fn::"):
+ raise _ProvisioningRejected(
+ "InvalidTemplate",
+ f"Template {template['templateName']} uses {function}, "
+ "which MiniStack does not resolve.",
+ )
+ return {k: resolve(v) for k, v in value.items()}
+
+ plan = {"thing": None, "status": "ACTIVE", "policies": []}
+ resources = body.get("Resources")
+ for resource in resources.values() if isinstance(resources, dict) else ():
+ if not isinstance(resource, dict):
+ continue
+ properties = resolve(resource.get("Properties") or {})
+ kind = resource.get("Type")
+ if kind == "AWS::IoT::Thing":
+ plan["thing"] = (properties, resource.get("OverrideSettings") or {})
+ elif kind == "AWS::IoT::Certificate":
+ plan["status"] = str(properties.get("Status") or "ACTIVE").upper()
+ elif kind == "AWS::IoT::Policy":
+ if "PolicyDocument" in properties:
+ raise _ProvisioningRejected(
+ "InvalidTemplate",
+ f"Template {template['templateName']} creates a policy from a "
+ "PolicyDocument, which MiniStack does not support.",
+ )
+ plan["policies"].append(properties.get("PolicyName"))
+ plan["deviceConfiguration"] = resolve(body.get("DeviceConfiguration") or {})
+ return plan
+
+
+def _java_map(attributes: dict) -> str:
+ return "{" + ", ".join(f"{k}={v}" for k, v in sorted(attributes.items())) + "}"
+
+
+async def _apply_provisioning_plan(plan: dict, cert: dict) -> str | None:
+ """Create or update the thing, then activate and attach the certificate; a rejection changes nothing."""
+ account = get_account_id()
+ for policy in plan["policies"]:
+ if _policies.get(policy) is None:
+ raise _provisioning_failed(
+ "Register thing workflow execution terminates due to: Policy default version not found"
+ )
+ if plan["thing"] is None:
+ name = None
+ else:
+ properties, overrides = plan["thing"]
+ name = properties.get("ThingName")
+ if not isinstance(name, str) or not _NAME_RE.match(name):
+ raise _provisioning_failed("Invalid thingName: must match [a-zA-Z0-9:_-]{1,128}")
+ attributes = properties.get("AttributePayload")
+ type_name = properties.get("ThingTypeName")
+ groups = properties.get("ThingGroups")
+ if type_name and type_name not in _thing_types:
+ raise _provisioning_failed(
+ "Register thing workflow execution terminates due to: "
+ f"Thing Type {account}:{type_name} not found."
+ )
+ for group in groups or ():
+ if group not in _thing_groups:
+ raise _provisioning_failed(
+ "Register thing workflow execution terminates due to: "
+ f"ThingGroup {account}:{group} not found."
+ )
+ thing = _things.get(name)
+ if thing is None:
+ _create_thing(name, {
+ "attributePayload": {"attributes": attributes or {}},
+ "thingTypeName": type_name or None,
+ })
+ join, leave = list(groups or ()), []
+ else:
+ update, join, leave = _provisioning_thing_changes(
+ thing, attributes, type_name, groups, overrides
+ )
+ if update:
+ _update_thing(name, update)
+ for group in join:
+ await _add_thing_to_group({"thingGroupName": group, "thingName": name})
+ for group in leave:
+ await _remove_thing_from_group({"thingGroupName": group, "thingName": name})
+ thing = _things[name]
+ if cert["certificateArn"] not in thing.setdefault("principals", []):
+ thing["principals"].append(cert["certificateArn"])
+ _things[name] = thing
+ if thing["thingArn"] not in cert.setdefault("attachedThings", []):
+ cert["attachedThings"].append(thing["thingArn"])
+ cert["status"] = plan["status"]
+ _certificates[cert["certificateId"]] = cert
+ for policy in plan["policies"]:
+ _change_policy_target(policy, cert["certificateArn"], attach=True)
+ return name
+
+
+def _provisioning_thing_changes(
+ thing: dict, attributes, type_name, groups, overrides: dict
+) -> tuple[dict, list, list]:
+ """The UpdateThing payload and the groups to join and leave for a thing that exists."""
+ update: dict = {}
+ join: list = []
+ leave: list = []
+ if attributes is not None:
+ current = thing.get("attributes") or {}
+ setting = overrides.get("AttributePayload")
+ if setting == "MERGE":
+ attributes = {**current, **attributes}
+ if setting in ("REPLACE", "MERGE"):
+ update["attributePayload"] = {"attributes": attributes}
+ elif setting != "DO_NOTHING" and attributes != current:
+ raise _provisioning_failed(
+ f"Existing AttributePayload: {_java_map(current)} conflicts with "
+ f"AttributePayload: {_java_map(attributes)} in Template."
+ )
+ if type_name is not None:
+ current = thing.get("thingTypeName")
+ setting = overrides.get("ThingTypeName")
+ if setting == "REPLACE":
+ update["thingTypeName"] = type_name
+ elif setting != "DO_NOTHING" and type_name != current:
+ raise _provisioning_failed(
+ f"Existing ThingType: {current or 'null'} conflicts with "
+ f"ThingType: {type_name} in Template."
+ )
+ if groups is not None:
+ current = list(thing.get("thingGroupNames") or [])
+ setting = overrides.get("ThingGroups")
+ if setting in ("REPLACE", "MERGE"):
+ join = [g for g in groups if g not in current]
+ leave = [g for g in current if g not in groups] if setting == "REPLACE" else []
+ elif setting != "DO_NOTHING" and set(groups) != set(current):
+ existing = ", ".join(
+ f"{{GroupName: {g},GroupArn: {_thing_group_arn(g)}}}" for g in current
+ )
+ raise _provisioning_failed(
+ f"Existing ThingGroups: [{existing}] conflict with "
+ f"ThingGroups: [{', '.join(groups)}] in Template."
+ )
+ return update, join, leave
+
+
# ---------------------------------------------------------------------------
# Certificates
# ---------------------------------------------------------------------------
@@ -7817,14 +8173,40 @@ def _parsed_iot_policy(document: str, context: tuple) -> list:
return parse_policy_document(_POLICY_VARIABLE_RE.sub(substitute, document))
[email protected]_cache(maxsize=256)
+def _provisioning_claim_policy(template_name: str) -> str:
+ """The policy of a claim certificate: its template's fleet provisioning topics and nothing else."""
+ topics = [
+ "$aws/certificates/create/*",
+ "$aws/certificates/create-from-csr/*",
+ f"$aws/provisioning-templates/{template_name}/provision/*",
+ ]
+ return json.dumps({"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "iot:Connect", "Resource": "*"},
+ {"Effect": "Allow", "Action": ["iot:Publish", "iot:Receive"],
+ "Resource": [f"arn:aws:iot:*:*:topic/{topic}" for topic in topics]},
+ {"Effect": "Allow", "Action": "iot:Subscribe",
+ "Resource": [f"arn:aws:iot:*:*:topicfilter/{topic}" for topic in topics]},
+ ]})
+
+
def _mqtt_policy_allows(
- account_id: str, region: str, certificate_id: str, context: dict, action: str, resource: str
+ account_id: str,
+ region: str,
+ certificate_id: str,
+ context: dict,
+ action: str,
+ resource: str,
+ provisioning_template: str | None = None,
) -> bool:
- """Whether the policies attached to the certificate allow ``action`` on ``resource``."""
- with request_scope(account_id, region):
- record = _certificates.get(certificate_id) or {}
- policies = [_policies.get(name) for name in record.get("attachedPolicies", [])]
- documents = [p["versions"][p["defaultVersionId"]]["document"] for p in policies if p]
+ """Whether the policies attached to the certificate, or a claim's own policy, allow ``action`` on ``resource``."""
+ if provisioning_template is not None:
+ documents = [_provisioning_claim_policy(provisioning_template)]
+ else:
+ with request_scope(account_id, region):
+ record = _certificates.get(certificate_id) or {}
+ policies = [_policies.get(name) for name in record.get("attachedPolicies", [])]
+ documents = [p["versions"][p["defaultVersionId"]]["document"] for p in policies if p]
ctx = EvalContext(
principal_arn=f"arn:aws:iot:{region}:{account_id}:cert/{certificate_id}",
principal_type="Certificate",
@@ -9554,6 +9936,8 @@ class _WSSession:
# The client certificate of an mTLS session; its policies are evaluated
# under AUTH=true.
self.certificate_id: str | None = None
+ # The template of a provisioning claim certificate, which has a policy of its own.
+ self.provisioning_template: str | None = None
self._policy_context: dict = {}
def disconnect_reason(self) -> str:
@@ -9607,6 +9991,27 @@ class _WSSession:
versionNumber=self._presence_version,
)
+ async def _answer_fleet_provisioning(
+ self, topic: str, operation: str, template_name: str | None, payload: bytes
+ ) -> None:
+ """Answer a fleet provisioning request on this connection only, if it subscribed to the reply."""
+ try:
+ async with publishing_events():
+ kind, doc = await _fleet_provisioning_reply(
+ self.account_id, self.region, operation, template_name, payload
+ )
+ except Exception:
+ _broker_logger.warning("IoT fleet provisioning failed for %r", topic, exc_info=True)
+ return
+ reply_topic = f"{topic}/{kind}"
+ granted = [
+ self._sub_granted_qos.get(sid, 0)
+ for sid, topic_filter in self._sub_filters.items()
+ if _subscription_matches(topic_filter, reply_topic)
+ ]
+ if granted:
+ await self.deliver_to_client(reply_topic, json.dumps(doc).encode("utf-8"), max(granted))
+
def _alloc_packet_id(self) -> int:
pid = self._next_pid
self._next_pid = (self._next_pid % 65535) + 1
@@ -9742,7 +10147,13 @@ class _WSSession:
def _policy_allows(self, action: str, resource: str) -> bool:
"""Whether this session may do ``action`` on ``resource``."""
return not self._evaluates_policies() or _mqtt_policy_allows(
- self.account_id, self.region, self.certificate_id, self._policy_context, action, resource
+ self.account_id,
+ self.region,
+ self.certificate_id,
+ self._policy_context,
+ action,
+ resource,
+ self.provisioning_template,
)
def _publish_allowed(self, topic: str, retain: bool) -> bool:
@@ -10053,6 +10464,9 @@ class _WSSession:
await self.send_bytes(_make_puback(packet_id, reason_code=reason))
else:
await self.send_bytes(_make_puback(packet_id))
+ fleet = _parse_fleet_provisioning_topic(topic)
+ if fleet is not None:
+ await self._answer_fleet_provisioning(topic, *fleet, payload)
return True
if pkt_type == PKT_SUBSCRIBE:
@@ -10382,6 +10796,9 @@ async def handle_websocket(
# * a certificate registered ACTIVE in exactly one account: that account and
# region serve the session, which is what gives a device fleet per-tenant
# isolation without any credential handling.
+# * a claim certificate from CreateProvisioningClaim, until it expires: the
+# account and region of its template serve the session, and under AUTH=true
+# it may use only that template's fleet provisioning topics.
# * a certificate that is unknown, not ACTIVE, or ACTIVE in several accounts:
# refused with a "not authorized" MQTT CONNACK, or under AUTH=true closed
# without one, as on AWS. This reads the X.509
@@ -10787,28 +11204,40 @@ def _mtls_refusal_reason(cert_id: str) -> str:
return "not registered"
-def _mtls_resolve_identity(der: bytes | None) -> tuple[str, str] | None:
- """Map a peer certificate (or none) to (account_id, region), or None.
+def _mtls_resolve_identity(der: bytes | None) -> tuple[str, str, str | None] | None:
+ """Map a peer certificate (or none) to (account_id, region, claim template), or None.
None means "this connection is refused". Presenting no certificate is not
refused: that caller claims nothing and is served under the default
account, the same way ``_ws_resolve_iot_account_id`` treats an unsigned
WebSocket upgrade. A certificate that IS presented is read against the
registry, which is the identity lifecycle this service already keeps:
- ACTIVE in exactly one account selects it, and unknown, not ACTIVE, or
- ACTIVE in several accounts is refused by the caller (``_mtls_refuse``).
+ ACTIVE in exactly one account selects it, as does an unexpired
+ provisioning claim, and unknown, not ACTIVE, or ACTIVE in several
+ accounts is refused by the caller (``_mtls_refuse``). The claim template
+ is set for a provisioning claim only.
"""
if not der:
return (
os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000"),
os.environ.get("MINISTACK_REGION", "us-east-1"),
+ None,
)
# Same derivation as x509_utils.get_certificate_id, without a PEM round-trip.
cert_id = hashlib.sha256(der).hexdigest()
active = _mtls_active_registrations(cert_id)
if len(active) == 1:
account_id, region, _record = active[0]
- return account_id, region
+ return account_id, region, None
+ return _mtls_claim_scope(cert_id)
+
+
+def _mtls_claim_scope(cert_id: str) -> tuple[str, str, str] | None:
+ """(account_id, region, templateName) of the unexpired provisioning claim with this certificate id, or None."""
+ now = time.time()
+ for (account_id, region, key), record in list(_provisioning_claims._data.items()):
+ if key == cert_id and record["expiration"] > now:
+ return account_id, region, record["templateName"]
return None
@@ -11074,7 +11503,7 @@ async def _mtls_serve_conn(reader: asyncio.StreamReader, writer: asyncio.StreamW
finally:
await _mtls_close(writer)
return
- account_id, region = owner
+ account_id, region, provisioning_template = owner
async def _tcp_send(message: dict) -> None:
"""Adapter for the two ASGI messages a session ever sends."""
@@ -11094,6 +11523,7 @@ async def _mtls_serve_conn(reader: asyncio.StreamReader, writer: asyncio.StreamW
certificate_id = hashlib.sha256(der).hexdigest() if der else None
session = _WSSession(_tcp_send, account_id, region, certificate_id)
session.certificate_id = certificate_id
+ session.provisioning_template = provisioning_template
max_buffer = _max_frame_buffer_bytes()
_mtls_logger.info(
"IoT mTLS: connection from %s serving %s/%s (%s)",
diff --git a/tests/conftest.py b/tests/conftest.py
index 9b3ab83f..7c8153a9 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -381,6 +381,8 @@ _SERIAL_TESTS = {
"tests/test_iot_data.py::test_mtls_ambiguous_cert_is_refused",
"tests/test_iot_data.py::test_mtls_registered_cert_connects_whatever_its_ca",
"tests/test_iot_data.py::test_mtls_registered_ca_chain_connects",
+ "tests/test_iot_data.py::test_mtls_provisioning_claim_connects_and_provisions",
+ "tests/test_iot_data.py::test_mtls_auth_provisioning_claim_is_held_to_its_templates_topics",
"tests/test_iot_data.py::test_mtls_jitr_certificate_is_listed_by_its_ca",
"tests/test_iot_data.py::test_mtls_jitr_auto_registers_an_unknown_cert_without_connack",
"tests/test_iot_data.py::test_mtls_jitr_under_an_sni_only_ca_needs_sni",
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 84da1ad2..a6817e85 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -2353,6 +2353,14 @@ class TestResourceArn:
from ministack.core.iam_actions import extract_resource_arn
assert extract_resource_arn("iot", "GET", "/provisioning-templates/fleet", {}, b"", {}, "us-east-1", "123") == "arn:aws:iot:us-east-1:123:provisioningtemplate/fleet"
+ def test_iot_provisioning_claim(self):
+ from ministack.core.iam_actions import extract_iam_action, extract_resource_arn
+ path = "/provisioning-templates/fleet/provisioning-claim"
+ assert extract_iam_action("iot", "POST", path, {}, b"", {}) == "iot:CreateProvisioningClaim"
+ assert extract_resource_arn(
+ "iot", "POST", path, {}, b"", {}, "us-east-1", "123"
+ ) == "arn:aws:iot:us-east-1:123:provisioningtemplate/fleet"
+
def test_iot_job_template(self):
from ministack.core.iam_actions import extract_resource_arn
assert extract_resource_arn(
diff --git a/tests/test_iot.py b/tests/test_iot.py
index 9f77985e..ce78db91 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -1812,7 +1812,7 @@ def test_iot_legacy_principal_policy_unknown_policy_404(iot_client):
# ---------------------------------------------------------------------------
-# Provisioning templates (storage + CRUD — no fleet-provisioning MQTT workflow)
+# Provisioning templates and fleet provisioning by claim
# ---------------------------------------------------------------------------
@@ -1984,6 +1984,577 @@ def test_iot_provisioning_template_pre_provisioning_hook_roundtrip(iot_client):
iot_client.delete_provisioning_template(templateName=name)
+def test_iot_create_provisioning_claim(iot_client):
+ """A claim certificate expires in five minutes and stays out of the registry; an unknown template is 404."""
+ from cryptography import x509
+
+ name = _unique("provtemplate")
+ iot_client.create_provisioning_template(
+ templateName=name,
+ templateBody=_provisioning_template_body(),
+ provisioningRoleArn="arn:aws:iam::000000000000:role/provisioning",
+ )
+ try:
+ claim = iot_client.create_provisioning_claim(templateName=name)
+ assert set(claim) - {"ResponseMetadata"} == {
+ "certificateId", "certificatePem", "keyPair", "expiration",
+ }
+ assert set(claim["keyPair"]) == {"PublicKey", "PrivateKey"}
+ expiration = claim["expiration"].timestamp()
+ assert 290 <= expiration - time.time() <= 300
+ leaf = x509.load_pem_x509_certificate(claim["certificatePem"].encode())
+ assert leaf.not_valid_after_utc.timestamp() == expiration
+
+ with pytest.raises(ClientError) as ei:
+ iot_client.describe_certificate(certificateId=claim["certificateId"])
+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ listed = {c["certificateId"] for c in iot_client.list_certificates()["certificates"]}
+ assert claim["certificateId"] not in listed
+
+ with pytest.raises(ClientError) as ei:
+ iot_client.create_provisioning_claim(templateName=f"{name}-x")
+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ assert ei.value.response["Error"]["Message"] == f"Unable to find template named {name}-x"
+ finally:
+ iot_client.delete_provisioning_template(templateName=name)
+
+
+# Fleet provisioning over MQTT, driven in-process through a broker session.
+
+_FLEET_ACCOUNT = "123456789012"
+_FLEET_REGION = "us-east-1"
+_FLEET_CREATE = "$aws/certificates/create/json"
+_FLEET_ROLE = "arn:aws:iam::123456789012:role/provisioning"
+_FLEET_REQUEST_ID = r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
+
+
+def _fleet_template(**overrides) -> dict:
+ """A required parameter, one with a default, Fn::Join and a device configuration."""
+ return {
+ "Parameters": {
+ "SerialNumber": {"Type": "String"},
+ "Color": {"Type": "String", "Default": "red"},
+ },
+ "Resources": {
+ "thing": {
+ "Type": "AWS::IoT::Thing",
+ "Properties": {
+ "ThingName": {"Fn::Join": ["", ["fleet-", {"Ref": "SerialNumber"}]]},
+ "AttributePayload": {
+ "serial": {"Ref": "SerialNumber"},
+ "color": {"Ref": "Color"},
+ },
+ },
+ },
+ "certificate": {
+ "Type": "AWS::IoT::Certificate",
+ "Properties": {
+ "CertificateId": {"Ref": "AWS::IoT::Certificate::Id"},
+ "Status": "ACTIVE",
+ },
+ },
+ "policy": {"Type": "AWS::IoT::Policy", "Properties": {"PolicyName": "fleet-device"}},
+ },
+ "DeviceConfiguration": {"greeting": "hello"},
+ **overrides,
+ }
+
+
+def _fleet_cdk_template(override_settings=None, status="Active") -> dict:
+ """The shape a CDK-deployed fleet template has: every value from a parameter."""
+ thing = {
+ "Type": "AWS::IoT::Thing",
+ "Properties": {
+ "ThingName": {"Ref": "ThingName"},
+ "ThingTypeName": {"Ref": "ThingTypeName"},
+ "AttributePayload": {},
+ "ThingGroups": [{"Ref": "ThingGroup"}],
+ },
+ }
+ if override_settings is not None:
+ thing["OverrideSettings"] = override_settings
+ return {
+ "Parameters": {
+ "ThingName": {"Type": "String"},
+ "ThingTypeName": {"Type": "String"},
+ "ThingGroup": {"Type": "String"},
+ "AWS::IoT::Certificate::Id": {"Type": "String"},
+ },
+ "Resources": {
+ "thing": thing,
+ "certificate": {
+ "Type": "AWS::IoT::Certificate",
+ "Properties": {
+ "CertificateId": {"Ref": "AWS::IoT::Certificate::Id"},
+ "Status": status,
+ },
+ },
+ "policy_1": {"Type": "AWS::IoT::Policy", "Properties": {"PolicyName": "fleet-device"}},
+ "policy_2": {"Type": "AWS::IoT::Policy", "Properties": {"PolicyName": "fleet-extra"}},
+ },
+ }
+
+
+async def _fleet_request(method, path, body=None, account=_FLEET_ACCOUNT, region=_FLEET_REGION):
+ """One in-process control-plane call: (status, decoded body)."""
+ from ministack.services import iot as iot_module
+
+ with iot_module.request_scope(account, region):
+ status, _headers, raw = await iot_module.handle_request(
+ method, path, {}, json.dumps(body).encode() if body is not None else b"", {}
+ )
+ return status, json.loads(raw) if raw else {}
+
+
+async def _fleet_setup(templates: dict, account=_FLEET_ACCOUNT, region=_FLEET_REGION):
+ """The two policies the templates attach, and each template, enabled."""
+ for policy in ("fleet-device", "fleet-extra"):
+ await _fleet_request(
+ "POST", f"/policies/{policy}",
+ {"policyDocument": json.dumps({"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "iot:Connect", "Resource": "*"}]})},
+ account, region,
+ )
+ for name, body in templates.items():
+ status, _ = await _fleet_request(
+ "POST", "/provisioning-templates",
+ {"templateName": name, "templateBody": json.dumps(body), "enabled": True,
+ "provisioningRoleArn": _FLEET_ROLE},
+ account, region,
+ )
+ assert status == 200
+
+
+async def _fleet_client(client_id, templates=(), account=_FLEET_ACCOUNT, region=_FLEET_REGION):
+ """A session subscribed to the replies of CreateKeysAndCertificate and of each template."""
+ send, sent = _mock_send()
+ session = _IoTWSSession(send, account, region)
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body(client_id))
+ filters = [f"{_FLEET_CREATE}/+"] + [
+ f"$aws/provisioning-templates/{t}/provision/json/+" for t in templates
+ ]
+ await session.handle_packet(
+ PKT_SUBSCRIBE, 0x02, _build_subscribe_body(1, [(f, 1) for f in filters])
+ )
+ sent.clear()
+ return session, sent
+
+
+async def _fleet_publish(session, sent, topic, payload):
+ """PUBLISH at QoS 1; the one reply this session got, as (topic, document), or None."""
+ sent.clear()
+ await session.handle_packet(
+ PKT_PUBLISH, 0x02, _encode_string(topic) + struct.pack("!H", 9) + payload
+ )
+ replies = [
+ (reply_topic, json.loads(body))
+ for reply_topic, body, _qos, _pid, _dup in _extract_publish_frames(sent)
+ if reply_topic.startswith(f"{topic}/")
+ ]
+ assert len(replies) <= 1
+ return replies[0] if replies else None
+
+
+async def _fleet_certificate(session, sent):
+ """CreateKeysAndCertificate over MQTT: the accepted document."""
+ topic, created = await _fleet_publish(session, sent, _FLEET_CREATE, b"")
+ assert topic == f"{_FLEET_CREATE}/accepted"
+ return created
+
+
+def _fleet_register(token, **parameters) -> bytes:
+ return json.dumps({"certificateOwnershipToken": token, "parameters": parameters}).encode()
+
+
+def _fleet_provision_topic(template: str) -> str:
+ return f"$aws/provisioning-templates/{template}/provision/json"
+
+
+def _fleet_rejection(template, code, message):
+ return (
+ f"{_fleet_provision_topic(template)}/rejected",
+ {"statusCode": 400, "errorCode": code, "errorMessage": message},
+ )
+
+
+def _assert_provisioning_failed(reply, template, message):
+ """A ProvisioningFailed rejection carrying ``message`` and AWS's registry suffix."""
+ topic, doc = reply
+ assert topic == f"{_fleet_provision_topic(template)}/rejected"
+ assert (doc["statusCode"], doc["errorCode"]) == (400, "ProvisioningFailed")
+ assert re.fullmatch(
+ re.escape(f"{message} (Service: AWSIot; Status Code: 400; Error Code: "
+ "ResourceRegistrationFailureException; Request ID: ")
+ + _FLEET_REQUEST_ID + re.escape("; Proxy: null)"),
+ doc["errorMessage"],
+ ), doc["errorMessage"]
+
+
+async def _fleet_certificate_state(cert_id):
+ """(status, attached policy names, attached thing names) of a registry certificate."""
+ _status, desc = await _fleet_request("GET", f"/certificates/{cert_id}")
+ arn = desc["certificateDescription"]["certificateArn"]
+ _status, policies = await _fleet_request("POST", f"/attached-policies/{arn}")
+ from ministack.services import iot as iot_module
+
+ with iot_module.request_scope(_FLEET_ACCOUNT, _FLEET_REGION):
+ things = iot_module._list_principal_things({"x-amzn-principal": arn}, {})
+ return (
+ desc["certificateDescription"]["status"],
+ sorted(p["policyName"] for p in policies["policies"]),
+ json.loads(things[2])["things"],
+ )
+
+
+async def _fleet_thing(name):
+ """(attributes, thing type, sorted groups) of a thing, or None."""
+ status, thing = await _fleet_request("GET", f"/things/{name}")
+ if status != 200:
+ return None
+ _status, groups = await _fleet_request("GET", f"/things/{name}/thing-groups")
+ return (
+ thing["attributes"],
+ thing.get("thingTypeName"),
+ sorted(g["groupName"] for g in groups["thingGroups"]),
+ )
+
+
+def test_fleet_provisioning_create_keys_and_certificate_answers_the_requester_only():
+ """CreateKeysAndCertificate over MQTT makes a PENDING_ACTIVATION certificate and answers only the requester."""
+ from ministack.services import iot as iot_module
+
+ iot_module.reset()
+ reset()
+
+ async def _run():
+ session, sent = await _fleet_client("fleet-claim")
+ other, other_sent = await _fleet_client("fleet-observer")
+ created = await _fleet_certificate(session, sent)
+ assert set(created) == {
+ "certificateId", "certificatePem", "privateKey", "certificateOwnershipToken",
+ }
+ assert created["privateKey"].startswith("-----BEGIN RSA PRIVATE KEY-----")
+ assert _extract_publish_frames(other_sent) == []
+ status, _cert, _things = await _fleet_certificate_state(created["certificateId"])
+ assert status == "PENDING_ACTIVATION"
+ # A client that did not subscribe to the replies gets none.
+ quiet_send, quiet_sent = _mock_send()
+ quiet = _IoTWSSession(quiet_send, _FLEET_ACCOUNT, _FLEET_REGION)
+ await quiet.handle_packet(PKT_CONNECT, 0, _build_connect_body("fleet-quiet"))
+ assert await _fleet_publish(quiet, quiet_sent, _FLEET_CREATE, b"") is None
+ for s in (session, other, quiet):
+ await s.cleanup()
+
+ try:
+ asyncio.run(_run())
+ finally:
+ iot_module.reset()
+ reset()
+
+
+def test_fleet_provisioning_register_thing_applies_the_template():
+ """RegisterThing checks the token and parameters first, then applies the template; the token registers again."""
+ from ministack.services import iot as iot_module
+
+ iot_module.reset()
+ reset()
+
+ async def _run():
+ await _fleet_setup({"fleet": _fleet_template()})
+ session, sent = await _fleet_client("fleet-claim", ["fleet"])
+ created = await _fleet_certificate(session, sent)
+ token, provision = created["certificateOwnershipToken"], _fleet_provision_topic("fleet")
+
+ reply = await _fleet_publish(session, sent, provision, _fleet_register("made-up"))
+ assert reply == _fleet_rejection(
+ "fleet", "InvalidCertificateOwnershipToken", "Certificate ownership token is invalid."
+ )
+ reply = await _fleet_publish(session, sent, provision, b"not json")
+ assert reply == _fleet_rejection("fleet", "InvalidPayload", "Message cannot be parsed")
+ reply = await _fleet_publish(session, sent, provision, _fleet_register(token))
+ assert reply == _fleet_rejection(
+ "fleet", "InvalidParameters", "Cannot resolve reference value: SerialNumber"
+ )
+ assert await _fleet_thing("fleet-SN1") is None
+
+ accepted = (
+ f"{provision}/accepted",
+ {"deviceConfiguration": {"greeting": "hello"}, "thingName": "fleet-SN1"},
+ )
+ reply = await _fleet_publish(session, sent, provision, _fleet_register(token, SerialNumber="SN1"))
+ assert reply == accepted
+ assert await _fleet_thing("fleet-SN1") == ({"serial": "SN1", "color": "red"}, None, [])
+ assert await _fleet_certificate_state(created["certificateId"]) == (
+ "ACTIVE", ["fleet-device"], ["fleet-SN1"],
+ )
+ reply = await _fleet_publish(session, sent, provision, _fleet_register(token, SerialNumber="SN1"))
+ assert reply == accepted
+ await session.cleanup()
+
+ try:
+ asyncio.run(_run())
+ finally:
+ iot_module.reset()
+ reset()
+
+
+def test_fleet_provisioning_register_thing_refusals_change_nothing():
+ """A refused RegisterThing leaves the certificate PENDING_ACTIVATION and creates no thing."""
+ from ministack.services import iot as iot_module
+
+ iot_module.reset()
+ reset()
+ no_policy = _fleet_template()
+ no_policy["Resources"]["policy"]["Properties"]["PolicyName"] = "fleet-none"
+ sub = _fleet_template()
+ sub["Resources"]["thing"]["Properties"]["ThingName"] = {"Fn::Sub": "fleet-${SerialNumber}"}
+ templates = {
+ "fleet": _fleet_template(), "fleet-cdk": _fleet_cdk_template({}),
+ "fleet-nopol": no_policy, "fleet-sub": sub,
+ }
+
+ async def _run():
+ await _fleet_setup(templates)
+ await _fleet_request("POST", "/thing-types/fleet-type", {})
+ await _fleet_request("POST", "/thing-groups/fleet-group", {})
+ await _fleet_request(
+ "PATCH", "/provisioning-templates/fleet", {"enabled": False}
+ )
+ session, sent = await _fleet_client("fleet-claim", [*templates, "fleet-none"])
+ created = await _fleet_certificate(session, sent)
+ token = created["certificateOwnershipToken"]
+
+ reply = await _fleet_publish(
+ session, sent, _fleet_provision_topic("fleet-none"), _fleet_register(token)
+ )
+ assert reply == _fleet_rejection(
+ "fleet-none", "InvalidTemplate", "Template with name fleet-none does not exist."
+ )
+ reply = await _fleet_publish(
+ session, sent, _fleet_provision_topic("fleet"), _fleet_register(token, SerialNumber="SN2")
+ )
+ assert reply == _fleet_rejection("fleet", "InvalidTemplate", "Template fleet is not enabled.")
+ cdk = _fleet_provision_topic("fleet-cdk")
+ reply = await _fleet_publish(session, sent, cdk, _fleet_register(
+ token, ThingName="fleet-c", ThingTypeName="fleet-notype", ThingGroup="fleet-group"))
+ _assert_provisioning_failed(
+ reply, "fleet-cdk",
+ "Register thing workflow execution terminates due to: "
+ f"Thing Type {_FLEET_ACCOUNT}:fleet-notype not found.",
+ )
+ reply = await _fleet_publish(session, sent, cdk, _fleet_register(
+ token, ThingName="fleet-c", ThingTypeName="fleet-type", ThingGroup="fleet-nogroup"))
+ _assert_provisioning_failed(
+ reply, "fleet-cdk",
+ "Register thing workflow execution terminates due to: "
+ f"ThingGroup {_FLEET_ACCOUNT}:fleet-nogroup not found.",
+ )
+ reply = await _fleet_publish(
+ session, sent, _fleet_provision_topic("fleet-nopol"),
+ _fleet_register(token, SerialNumber="SN3"),
+ )
+ _assert_provisioning_failed(
+ reply, "fleet-nopol",
+ "Register thing workflow execution terminates due to: Policy default version not found",
+ )
+ reply = await _fleet_publish(
+ session, sent, _fleet_provision_topic("fleet-sub"),
+ _fleet_register(token, SerialNumber="SN4"),
+ )
+ assert reply == _fleet_rejection(
+ "fleet-sub", "InvalidTemplate",
+ "Template fleet-sub uses Fn::Sub, which MiniStack does not resolve.",
+ )
+ for name in ("fleet-c", "fleet-SN2", "fleet-SN3", "fleet-SN4"):
+ assert await _fleet_thing(name) is None
+ assert await _fleet_certificate_state(created["certificateId"]) == (
+ "PENDING_ACTIVATION", [], [],
+ )
+ await session.cleanup()
+
+ try:
+ asyncio.run(_run())
+ finally:
+ iot_module.reset()
+ reset()
+
+
+def test_fleet_provisioning_existing_thing_follows_override_settings():
+ """An existing thing that differs from the template fails unless OverrideSettings allow it; FAIL is no setting."""
+ from ministack.services import iot as iot_module
+
+ iot_module.reset()
+ reset()
+ templates = {
+ "fleet": _fleet_template(),
+ "fleet-cdk": _fleet_cdk_template(
+ {"AttributePayload": "DO_NOTHING", "ThingGroups": "DO_NOTHING",
+ "ThingTypeName": "DO_NOTHING"}),
+ "fleet-plain": _fleet_cdk_template(status="ACTIVE"),
+ "fleet-ovr": _fleet_cdk_template(
+ {"AttributePayload": "MERGE", "ThingTypeName": "REPLACE", "ThingGroups": "MERGE"},
+ status="ACTIVE"),
+ "fleet-fail": _fleet_cdk_template(
+ {"AttributePayload": "FAIL", "ThingTypeName": "FAIL", "ThingGroups": "FAIL"},
+ status="ACTIVE"),
+ }
+ for name in ("fleet-ovr", "fleet-fail"):
+ templates[name]["Resources"]["thing"]["Properties"]["AttributePayload"] = {
+ "color": "green"}
+
+ async def _run():
+ await _fleet_setup(templates)
+ for kind, name in (("thing-types", "fleet-type"), ("thing-types", "fleet-type2"),
+ ("thing-groups", "fleet-group"), ("thing-groups", "fleet-group2")):
+ await _fleet_request("POST", f"/{kind}/{name}", {})
+ session, sent = await _fleet_client("fleet-claim", list(templates))
+
+ first = await _fleet_certificate(session, sent)
+ await _fleet_publish(
+ session, sent, _fleet_provision_topic("fleet"),
+ _fleet_register(first["certificateOwnershipToken"], SerialNumber="SN1"),
+ )
+ second = await _fleet_certificate(session, sent)
+ token = second["certificateOwnershipToken"]
+ reply = await _fleet_publish(
+ session, sent, _fleet_provision_topic("fleet"),
+ _fleet_register(token, SerialNumber="SN1", Color="blue"),
+ )
+ _assert_provisioning_failed(
+ reply, "fleet",
+ "Existing AttributePayload: {color=red, serial=SN1} conflicts with "
+ "AttributePayload: {color=blue, serial=SN1} in Template.",
+ )
+ assert await _fleet_certificate_state(second["certificateId"]) == (
+ "PENDING_ACTIVATION", [], [],
+ )
+
+ # DO_NOTHING keeps everything; "Active" activates the certificate.
+ cdk = {"ThingTypeName": "fleet-type", "ThingGroup": "fleet-group"}
+ reply = await _fleet_publish(
+ session, sent, _fleet_provision_topic("fleet-cdk"),
+ _fleet_register(token, ThingName="fleet-SN1", **cdk),
+ )
+ assert reply == (
+ f"{_fleet_provision_topic('fleet-cdk')}/accepted",
+ {"deviceConfiguration": {}, "thingName": "fleet-SN1"},
+ )
+ assert await _fleet_thing("fleet-SN1") == ({"serial": "SN1", "color": "red"}, None, [])
+ assert await _fleet_certificate_state(second["certificateId"]) == (
+ "ACTIVE", ["fleet-device", "fleet-extra"], ["fleet-SN1"],
+ )
+
+ third = await _fleet_certificate(session, sent)
+ token = third["certificateOwnershipToken"]
+ reply = await _fleet_publish(
+ session, sent, _fleet_provision_topic("fleet-cdk"),
+ _fleet_register(token, ThingName="fleet-b", **cdk),
+ )
+ assert reply[0].endswith("/accepted")
+ assert await _fleet_thing("fleet-b") == ({}, "fleet-type", ["fleet-group"])
+
+ plain = _fleet_provision_topic("fleet-plain")
+ reply = await _fleet_publish(
+ session, sent, plain, _fleet_register(token, ThingName="fleet-b", **cdk))
+ assert reply[0] == f"{plain}/accepted"
+ reply = await _fleet_publish(session, sent, plain, _fleet_register(
+ token, ThingName="fleet-b", ThingTypeName="fleet-type2", ThingGroup="fleet-group"))
+ _assert_provisioning_failed(
+ reply, "fleet-plain",
+ "Existing ThingType: fleet-type conflicts with ThingType: fleet-type2 in Template.",
+ )
+ reply = await _fleet_publish(session, sent, plain, _fleet_register(
+ token, ThingName="fleet-b", ThingTypeName="fleet-type", ThingGroup="fleet-group2"))
+ group_arn = f"arn:aws:iot:{_FLEET_REGION}:{_FLEET_ACCOUNT}:thinggroup/fleet-group"
+ _assert_provisioning_failed(
+ reply, "fleet-plain",
+ f"Existing ThingGroups: [{{GroupName: fleet-group,GroupArn: {group_arn}}}] "
+ "conflict with ThingGroups: [fleet-group2] in Template.",
+ )
+ assert await _fleet_thing("fleet-b") == ({}, "fleet-type", ["fleet-group"])
+
+ changed = {"ThingName": "fleet-b", "ThingTypeName": "fleet-type2", "ThingGroup": "fleet-group2"}
+ reply = await _fleet_publish(
+ session, sent, _fleet_provision_topic("fleet-ovr"), _fleet_register(token, **changed))
+ assert reply[0].endswith("/accepted")
+ assert await _fleet_thing("fleet-b") == (
+ {"color": "green"}, "fleet-type2", ["fleet-group", "fleet-group2"],
+ )
+ reply = await _fleet_publish(
+ session, sent, _fleet_provision_topic("fleet-fail"), _fleet_register(token, **changed))
+ _assert_provisioning_failed(
+ reply, "fleet-fail",
+ f"Existing ThingGroups: [{{GroupName: fleet-group,GroupArn: {group_arn}}}, "
+ f"{{GroupName: fleet-group2,GroupArn: {group_arn}2}}] "
+ "conflict with ThingGroups: [fleet-group2] in Template.",
+ )
+ await session.cleanup()
+
+ try:
+ asyncio.run(_run())
+ finally:
+ iot_module.reset()
+ reset()
+
+
+def test_fleet_provisioning_claims_and_tokens_are_scoped_persisted_and_expire():
+ """Claims and ownership tokens are scoped to one account and region, persist, expire, and go with reset()."""
+ import ssl as _ssl
+
+ from ministack.services import iot as iot_module
+
+ iot_module.reset()
+ reset()
+ other_account = "210987654321"
+
+ async def _run():
+ await _fleet_setup({"fleet": _fleet_template()})
+ await _fleet_setup({"fleet": _fleet_template()}, account=other_account)
+ _status, claim = await _fleet_request("POST", "/provisioning-templates/fleet/provisioning-claim")
+ der = _ssl.PEM_cert_to_DER_cert(claim["certificatePem"])
+ assert iot_module._mtls_resolve_identity(der) == (_FLEET_ACCOUNT, _FLEET_REGION, "fleet")
+
+ session, sent = await _fleet_client("fleet-claim", ["fleet"])
+ token = (await _fleet_certificate(session, sent))["certificateOwnershipToken"]
+ await session.cleanup()
+ other, other_sent = await _fleet_client("fleet-claim", ["fleet"], account=other_account)
+ reply = await _fleet_publish(
+ other, other_sent, _fleet_provision_topic("fleet"),
+ _fleet_register(token, SerialNumber="SN1"),
+ )
+ assert reply[1]["errorCode"] == "InvalidCertificateOwnershipToken"
+ await other.cleanup()
+
+ saved = iot_module.get_state()
+ iot_module.reset()
+ assert iot_module._mtls_resolve_identity(der) is None
+ iot_module.load_persisted_state(saved)
+ assert iot_module._mtls_resolve_identity(der) == (_FLEET_ACCOUNT, _FLEET_REGION, "fleet")
+ session, sent = await _fleet_client("fleet-claim", ["fleet"])
+ reply = await _fleet_publish(
+ session, sent, _fleet_provision_topic("fleet"),
+ _fleet_register(token, SerialNumber="SN1"),
+ )
+ assert reply[0].endswith("/accepted")
+
+ for store in (iot_module._provisioning_claims, iot_module._ownership_tokens):
+ for record in store._data.values():
+ record["expiration"] = time.time() - 1
+ assert iot_module._mtls_resolve_identity(der) is None
+ reply = await _fleet_publish(
+ session, sent, _fleet_provision_topic("fleet"),
+ _fleet_register(token, SerialNumber="SN1"),
+ )
+ assert reply[1]["errorCode"] == "InvalidCertificateOwnershipToken"
+ await session.cleanup()
+
+ try:
+ asyncio.run(_run())
+ finally:
+ iot_module.reset()
+ reset()
+
+
# ---------------------------------------------------------------------------
# Fleet indexing (indexing configuration + SearchIndex)
# ---------------------------------------------------------------------------
diff --git a/tests/test_iot_data.py b/tests/test_iot_data.py
index b709ddc6..5c49cdae 100644
--- a/tests/test_iot_data.py
+++ b/tests/test_iot_data.py
@@ -4110,6 +4110,134 @@ def test_mtls_registered_ca_chain_connects(broker, tmp_path):
peer.close()
+def test_mtls_provisioning_claim_connects_and_provisions(broker, tmp_path):
+ """A claim certificate connects over mTLS and provisions a thing whose new certificate then connects."""
+ iot = broker.client("iot")
+ name, serial = _unique("fleet"), _unique("device")
+ iot.create_policy(
+ policyName=f"{name}-device",
+ policyDocument=json.dumps({"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": "iot:Connect", "Resource": "*"}]}),
+ )
+ iot.create_provisioning_template(
+ templateName=name,
+ templateBody=json.dumps({
+ "Parameters": {"SerialNumber": {"Type": "String"}},
+ "Resources": {
+ "thing": {"Type": "AWS::IoT::Thing",
+ "Properties": {"ThingName": {"Ref": "SerialNumber"}}},
+ "certificate": {"Type": "AWS::IoT::Certificate", "Properties": {
+ "CertificateId": {"Ref": "AWS::IoT::Certificate::Id"}, "Status": "ACTIVE"}},
+ "policy": {"Type": "AWS::IoT::Policy",
+ "Properties": {"PolicyName": f"{name}-device"}},
+ },
+ }),
+ enabled=True,
+ provisioningRoleArn="arn:aws:iam::000000000000:role/provisioning",
+ )
+ claim = iot.create_provisioning_claim(templateName=name)
+ create, provision = "$aws/certificates/create/json", f"$aws/provisioning-templates/{name}/provision/json"
+
+ peer = _Peer(_mtls_connect(broker, claim["certificatePem"], claim["keyPair"]["PrivateKey"], tmp_path))
+ try:
+ _assert_connack(peer.connect(_unique("claim")))
+ peer.subscribe(f"{create}/+", packet_id=1)
+ peer.subscribe(f"{provision}/+", packet_id=2)
+ peer.send(_make_publish(create, b"", qos=1, packet_id=3))
+ topic, payload = peer.next_publish()
+ assert topic == f"{create}/accepted"
+ created = json.loads(payload)
+ peer.send(_make_publish(provision, json.dumps({
+ "certificateOwnershipToken": created["certificateOwnershipToken"],
+ "parameters": {"SerialNumber": serial},
+ }).encode(), qos=1, packet_id=4))
+ assert peer.next_publish() == (
+ f"{provision}/accepted",
+ json.dumps({"deviceConfiguration": {}, "thingName": serial}).encode(),
+ )
+ finally:
+ peer.close()
+
+ device = _Peer(_mtls_connect(broker, created["certificatePem"], created["privateKey"], tmp_path))
+ try:
+ _assert_connack(device.connect(serial))
+ finally:
+ device.close()
+
+
+def test_mtls_auth_provisioning_claim_is_held_to_its_templates_topics(tmp_path):
+ """With AUTH=true a claim provisions on its template's topics and is refused anything else, as on AWS."""
+ pytest.importorskip("cryptography")
+ http_port, mqtt_port = _free_port(), _free_port()
+ proc = _spawn({"AUTH": "true", "IOT_MTLS_ENABLED": "1", "IOT_MTLS_PORT": str(mqtt_port)}, http_port)
+ try:
+ _wait_ready(f"http://127.0.0.1:{http_port}/_ministack/ready")
+ private = _Broker(http_port, mqtt_port)
+ iot = private.client("iot")
+ name = _unique("fleet")
+ iot.create_provisioning_template(
+ templateName=name,
+ templateBody=json.dumps({"Resources": {"certificate": {"Type": "AWS::IoT::Certificate", "Properties": {
+ "CertificateId": {"Ref": "AWS::IoT::Certificate::Id"}, "Status": "ACTIVE"}}}}),
+ enabled=True,
+ provisioningRoleArn="arn:aws:iam::000000000000:role/provisioning",
+ )
+ claim = iot.create_provisioning_claim(templateName=name)
+ create, provision = "$aws/certificates/create/json", f"$aws/provisioning-templates/{name}/provision/json"
+ other, unrelated = "$aws/provisioning-templates/other/provision/json", "devices/telemetry"
+
+ def claim_peer(protocol_level=MQTT_311):
+ peer = _Peer(_mtls_connect(private, claim["certificatePem"], claim["keyPair"]["PrivateKey"], tmp_path))
+ peer.send(_make_connect(_unique("claim"), protocol_level=protocol_level))
+ _assert_connack(peer.next_packet())
+ return peer
+
+ peer = claim_peer()
+ try:
+ for packet_id, topic in enumerate((f"{create}/accepted", f"{provision}/accepted"), start=1):
+ assert peer.subscribe(topic, packet_id=packet_id)[2][2:] == b"\x00", topic
+ peer.send(_make_publish(create, b"", qos=1, packet_id=3))
+ topic, payload = peer.next_publish()
+ assert topic == f"{create}/accepted"
+ request = json.dumps({"certificateOwnershipToken": json.loads(payload)["certificateOwnershipToken"]})
+ peer.send(_make_publish(provision, request.encode(), qos=1, packet_id=4))
+ assert peer.next_publish() == (f"{provision}/accepted", b'{"deviceConfiguration": {}}')
+ finally:
+ peer.close()
+
+ # MQTT 3.1.1: any refused SUBSCRIBE or PUBLISH closes the connection.
+ for packet in (
+ _make_subscribe(1, unrelated),
+ _make_subscribe(1, f"{other}/accepted"),
+ _make_publish(unrelated, b"{}", qos=1, packet_id=1),
+ _make_publish(other, b"{}", qos=1, packet_id=1),
+ ):
+ peer = claim_peer()
+ try:
+ peer.send(packet)
+ assert peer.wait_disconnected(), packet
+ finally:
+ peer.close()
+
+ # MQTT 5: SUBACK 0x87 for the refused filter and PUBACK 0x87, the connection stays.
+ peer = claim_peer(MQTT_5)
+ try:
+ for packet_id, (topic, code) in enumerate(
+ ((f"{create}/rejected", 0x00), (unrelated, 0x87), (f"{other}/accepted", 0x87)), start=1
+ ):
+ peer.send(_make_subscribe(packet_id, topic, protocol_level=MQTT_5))
+ ptype, _flags, body = peer.next_packet()
+ assert (ptype, body[3:]) == (PKT_SUBACK, bytes([code])), topic
+ for packet_id, topic in enumerate((unrelated, other), start=4):
+ peer.send(_make_publish(topic, b"{}", qos=1, packet_id=packet_id, protocol_level=MQTT_5))
+ ptype, _flags, body = peer.next_packet()
+ assert (ptype, body[2]) == (PKT_PUBACK, 0x87), topic
+ finally:
+ peer.close()
+ finally:
+ _terminate(proc)
+
+
def test_mtls_jitr_certificate_is_listed_by_its_ca(broker, tmp_path):
"""As measured on AWS, ListCertificatesByCA lists the certificate that
just-in-time registration created, while it is still PENDING_ACTIVATION."""