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 provisioning template versions (#2179)
iot-rocket5c0005096da6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6d8f4b80..cb1235e8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added+- **IoT — provisioning template versions** — `CreateProvisioningTemplateVersion`, `ListProvisioningTemplateVersions`, `DescribeProvisioningTemplateVersion` and `DeleteProvisioningTemplateVersion` answered `Unsupported IoT path` and `UpdateProvisioningTemplate` refused every `defaultVersionId` but 1; a template now keeps up to five versions whose ids are never reused, `setAsDefault` and `defaultVersionId` choose the version that `DescribeProvisioningTemplate` returns and `RegisterThing` applies, the default version cannot be deleted, and an `AWS::IoT::ProvisioningTemplate` whose `TemplateBody` changes gets a new default version (deleting the oldest at the limit), all with AWS's errors, including its message for a body that is not JSON. Contributed by @iot-rocket.- **IoT — pre-provisioning hook** — `RegisterThing` over MQTT now invokes the template's `preProvisioningHook` Lambda before the template is resolved and applies its answer the way AWS does: `parameterOverrides` are merged into the device's parameters, `allowProvisioning: false` is rejected as `AccessDenied`, and a function that fails, answers in another shape, takes longer than six seconds or may not be invoked gets AWS's `InvocationError` or `InvalidResult`. `CreateProvisioningTemplate` and `UpdateProvisioningTemplate` check the hook like AWS (a Lambda function ARN, payload version `2020-04-01`, no hook on JITP templates, and an invoke permission for `iot.amazonaws.com` that covers the template) and store the default payload version. Contributed by @iot-rocket.- **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.diff --git a/README.md b/README.mdindex 67af1546..b538a205 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, 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 Lambda is invoked before the template is applied; 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, CreateProvisioningTemplateVersion, ListProvisioningTemplateVersions, DescribeProvisioningTemplateVersion, DeleteProvisioningTemplateVersion, 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 | 76 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 Lambda is invoked before the template is applied; 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/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 7624770a..55b957b6 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -13571,11 +13571,10 @@ def _iot_provisioning_template_update(physical_id, old_props, new_props, stack_nA TemplateName change is a replacement, handled the way AWS::IoT::Policy'srename is: the new template is created and the old one removed, since atemplate no stack still declares is not left behind. TemplateBody is not- an UpdateProvisioningTemplate member (AWS stores it as a new version via- CreateProvisioningTemplateVersion, which MiniStack does not model), so a- changed body is written onto the stored record directly — the template- always stays at defaultVersionId 1. TemplateType requires replacement,- which ``_update_resource`` performs before this runs.+ an UpdateProvisioningTemplate member: a changed body becomes the new+ default version, after the oldest is deleted at the version limit.+ TemplateType requires replacement, which ``_update_resource`` performs+ before this runs."""name = new_props.get("TemplateName") or _physical_name(stack_name, logical_id or physical_id, max_len=36@@ -13600,14 +13599,21 @@ def _iot_provisioning_template_update(physical_id, old_props, new_props, stack_nraise ValueError(f"AWS::IoT::ProvisioningTemplate update failed: {resp[2]!r}")body = _iot_provisioning_template_body(new_props)tmpl = _iot._provisioning_templates.get(name)- if tmpl is not None and body and body != tmpl.get("templateBody"):+ if tmpl is not None and body and body != _iot._provisioning_template_body(tmpl):err = _iot._validate_provisioning_template_body(body)if err is not None:raise ValueError(f"AWS::IoT::ProvisioningTemplate update failed: {err[2]!r}")- tmpl["templateBody"] = body- _iot._provisioning_templates[name] = tmpl+ if len(tmpl["versions"]) >= _iot._PROVISIONING_TEMPLATE_VERSIONS_MAX:+ oldest = min(v["versionId"] for v in tmpl["versions"].values()+ if v["versionId"] != tmpl["defaultVersionId"])+ _iot._delete_provisioning_template_version(name, str(oldest))+ resp = _iot._create_provisioning_template_version(+ name, {"templateBody": body}, {"setAsDefault": "true"}+ )+ if resp[0] >= 400:+ raise ValueError(f"AWS::IoT::ProvisioningTemplate update failed: {resp[2]!r}")_iot_update_tags(_iot._provisioning_template_arn(name), old_props, new_props)return name, _iot_provisioning_template_attrs(name)diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex af457bf4..c13eadf5 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -326,6 +326,12 @@ 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", {}))+ # Older state kept a template's body on the record, as its only version.+ for record in _provisioning_templates.all_values():+ if "versions" not in record:+ body = record.pop("templateBody")+ record["versions"] = {"1": _provisioning_template_version(1, body, record["creationDate"])}+ record["lastVersionId"] = 1_provisioning_claims.update(data.get("provisioning_claims", {}))_ownership_tokens.update(data.get("ownership_tokens", {}))_jobs.update(data.get("jobs", {}))@@ -603,7 +609,7 @@ async def _route_request(if path == "/provisioning-templates" and method == "GET":return _list_provisioning_templates(qp)if path.startswith("/provisioning-templates/"):- return _handle_provisioning_template(method, path, body)+ return _handle_provisioning_template(method, path, body, qp)# Certificatesif path == "/keys-and-certificate" and method == "POST":@@ -1882,8 +1888,8 @@ async def _remove_thing_from_group(payload: dict) -> tuple:# topics) that applies a template to a certificate created over MQTT, once the# template's pre-provisioning hook allows it. 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+# not validate IAM role ARNs elsewhere either. A template keeps up to five+# body versions; Describe and RegisterThing use the default one. Wire shapes and# error messages mirror a live probe of the real service (2026-08-26).# ---------------------------------------------------------------------------@@ -1914,7 +1920,7 @@ def _validate_provisioning_template_body(body) -> tuple | None:if not isinstance(doc, dict):return error_response_json("InvalidRequestException",- "The template body is invalid: Template body is not valid JSON.",+ "The template body is invalid",400,)resources = doc.get("Resources")@@ -2007,18 +2013,30 @@ def _provisioning_template_not_found(name: str) -> tuple:)-def _handle_provisioning_template(method: str, path: str, body: bytes) -> tuple:+def _handle_provisioning_template(method: str, path: str, body: bytes, qp: dict) -> tuple:suffix = path[len("/provisioning-templates/"):]name, _, sub = suffix.partition("/")- if sub and (method, sub) != ("POST", "provisioning-claim"):+ version = sub[len("versions/"):] if sub.startswith("versions/") else None+ routes = {("POST", "provisioning-claim"), ("POST", "versions"), ("GET", "versions")}+ if sub and (method, sub) not in routes and not (+ version and "/" not in version and method in ("GET", "DELETE")+ ):return error_response_json("InvalidRequestException", f"Unsupported IoT path: {method} {path}", 400)err = _validate_provisioning_template_name(name)if err:return err- if sub:+ if sub == "provisioning-claim":return _create_provisioning_claim(name)+ if sub == "versions" and method == "POST":+ return _create_provisioning_template_version(name, _parse_body(body), qp)+ if sub == "versions":+ return _list_provisioning_template_versions(name)+ if version is not None and method == "GET":+ return _describe_provisioning_template_version(name, version)+ if version is not None:+ return _delete_provisioning_template_version(name, version)if method == "GET":return _describe_provisioning_template(name)if method == "PATCH":@@ -2061,13 +2079,14 @@ def _create_provisioning_template(payload: dict) -> tuple:record = {"templateName": name,"templateArn": _provisioning_template_arn(name),- "templateBody": payload["templateBody"],"enabled": bool(payload.get("enabled", False)),"provisioningRoleArn": payload["provisioningRoleArn"],"type": payload.get("type", "FLEET_PROVISIONING"),"defaultVersionId": 1,"creationDate": now,"lastModifiedDate": now,+ "versions": {"1": _provisioning_template_version(1, payload["templateBody"], now)},+ "lastVersionId": 1,}# The live service omits description from Describe when it was never set —# absent, not empty — so an unset one is not stored at all.@@ -2085,11 +2104,21 @@ def _create_provisioning_template(payload: dict) -> tuple:})+def _provisioning_template_version(version_id: int, body, created: float) -> dict:+ return {"versionId": version_id, "creationDate": created, "templateBody": body}+++def _provisioning_template_body(t: dict):+ """The body of the template's default version."""+ return t["versions"][str(t["defaultVersionId"])]["templateBody"]++def _describe_provisioning_template(name: str) -> tuple:t = _provisioning_templates.get(name)if t is None:return _provisioning_template_not_found(name)- return json_response(t)+ out = {k: v for k, v in t.items() if k not in ("versions", "lastVersionId")}+ return json_response({**out, "templateBody": _provisioning_template_body(t)})def _list_provisioning_templates(qp: dict) -> tuple:@@ -2115,10 +2144,10 @@ def _update_provisioning_template(name: str, payload: dict) -> tuple:if t is None:return _provisioning_template_not_found(name)version = payload.get("defaultVersionId")- if version is not None and version != t["defaultVersionId"]:+ if version is not None and str(version) not in t["versions"]:return error_response_json("InvalidRequestException",- f"ProvisioningTemplate {name!r} has no version {version}",+ f"Unable to set version {version} as the default, version does not exist",400,)hook = None if payload.get("removePreProvisioningHook") else payload.get("preProvisioningHook")@@ -2139,10 +2168,12 @@ def _update_provisioning_template(name: str, payload: dict) -> tuple:t.pop("preProvisioningHook", None)elif hook:t["preProvisioningHook"] = _provisioning_hook(hook)+ if version is not None:+ t["defaultVersionId"] = int(version)t["lastModifiedDate"] = _now_epoch()_provisioning_templates[name] = t# The live service answers 200 with an empty body — not an empty JSON- # object — and does not bump defaultVersionId.+ # object.return 200, {"Content-Type": "application/x-amz-json-1.0"}, b""@@ -2154,6 +2185,94 @@ def _delete_provisioning_template(name: str) -> tuple:return json_response({})+_PROVISIONING_TEMPLATE_VERSIONS_MAX = 5+++def _create_provisioning_template_version(name: str, payload: dict, qp: dict) -> tuple:+ """``CreateProvisioningTemplateVersion``: version ids count up and are never reused."""+ t = _provisioning_templates.get(name)+ if t is None:+ return _provisioning_template_not_found(name)+ body = payload.get("templateBody")+ if not body:+ return error_response_json("InvalidRequestException", "templateBody is required", 400)+ err = _validate_provisioning_template_body(body)+ if err:+ return err+ if len(t["versions"]) >= _PROVISIONING_TEMPLATE_VERSIONS_MAX:+ return error_response_json(+ "VersionsLimitExceededException",+ f"Can't create a template version for the template {name}, "+ "the maximum number of template versions has been reached",+ 409,+ )+ version_id = t["lastVersionId"] + 1+ now = _now_epoch()+ t["versions"][str(version_id)] = _provisioning_template_version(version_id, body, now)+ t["lastVersionId"] = version_id+ is_default = str(qp.get("setAsDefault", "")).lower() == "true"+ if is_default:+ t["defaultVersionId"] = version_id+ t["lastModifiedDate"] = now+ _provisioning_templates[name] = t+ return json_response({+ "templateArn": t["templateArn"],+ "templateName": name,+ "versionId": version_id,+ "isDefaultVersion": is_default,+ })+++def _list_provisioning_template_versions(name: str) -> tuple:+ """``ListProvisioningTemplateVersions``: all versions in one page, whatever maxResults asks for."""+ t = _provisioning_templates.get(name)+ if t is None:+ return error_response_json("ResourceNotFoundException", f"Template named {name} not found", 404)+ return json_response({"versions": [+ {+ "versionId": v["versionId"],+ "creationDate": v["creationDate"],+ "isDefaultVersion": v["versionId"] == t["defaultVersionId"],+ }+ for v in t["versions"].values()+ ]})+++def _describe_provisioning_template_version(name: str, version_id: str) -> tuple:+ t = _provisioning_templates.get(name)+ if t is None:+ return error_response_json("ResourceNotFoundException", f"Unable to find a template named {name}", 404)+ v = t["versions"].get(version_id)+ if v is None:+ return error_response_json(+ "ResourceNotFoundException",+ f"Unable to find a template version with ID {version_id} for template {name}",+ 404,+ )+ return json_response({**v, "isDefaultVersion": v["versionId"] == t["defaultVersionId"]})+++def _delete_provisioning_template_version(name: str, version_id: str) -> tuple:+ t = _provisioning_templates.get(name)+ if t is None:+ return _provisioning_template_not_found(name)+ v = t["versions"].get(version_id)+ if v is None:+ return error_response_json(+ "ResourceNotFoundException", f"Unable to find template version {version_id}", 404+ )+ if v["versionId"] == t["defaultVersionId"]:+ return error_response_json(+ "InvalidRequestException",+ f"Unable to delete template version {version_id}, it is the default version",+ 400,+ )+ del t["versions"][version_id]+ t["lastModifiedDate"] = _now_epoch()+ _provisioning_templates[name] = t+ 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@@ -2403,7 +2522,7 @@ def _provisioning_hook_overrides(result: dict) -> dict: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 = _provisioning_template_body(template)body = json.loads(body) if isinstance(body, str) else bodydeclared = body.get("Parameters")values = {diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex c647298f..6f65881c 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -1463,6 +1463,38 @@ def test_cfn_iot_provisioning_template_rename_replaces(cfn, iot_client):iot_client.describe_provisioning_template(templateName="cfn-provtemplate-new")+def test_cfn_iot_provisioning_template_body_update_adds_a_version(cfn, iot_client):+ """A TemplateBody change adds a new default version, dropping the oldest past five; other changes add none."""++ def template(description, marker):+ return json.dumps({"Resources": {"PT": {"Type": "AWS::IoT::ProvisioningTemplate", "Properties": {+ "TemplateName": "cfn-provtemplate-ver",+ "Description": description,+ "ProvisioningRoleArn": "arn:aws:iam::000000000000:role/provisioning",+ "TemplateBody": _cfn_provisioning_template_body(marker)}}}})++ def versions():+ return [(v["versionId"], v["isDefaultVersion"]) for v in iot_client.list_provisioning_template_versions(+ templateName="cfn-provtemplate-ver")["versions"]]++ cfn.create_stack(StackName="cfn-iot-provtmpl-ver", TemplateBody=template("one", "m1"))+ assert _wait_stack(cfn, "cfn-iot-provtmpl-ver")["StackStatus"] == "CREATE_COMPLETE"+ cfn.update_stack(StackName="cfn-iot-provtmpl-ver", TemplateBody=template("two", "m1"))+ assert _wait_stack(cfn, "cfn-iot-provtmpl-ver")["StackStatus"] == "UPDATE_COMPLETE"+ assert versions() == [(1, True)]+ for n in range(2, 7):+ cfn.update_stack(StackName="cfn-iot-provtmpl-ver", TemplateBody=template("two", f"m{n}"))+ assert _wait_stack(cfn, "cfn-iot-provtmpl-ver")["StackStatus"] == "UPDATE_COMPLETE"+ assert versions() == [(2, False), (3, False), (4, False), (5, False), (6, True)]+ desc = iot_client.describe_provisioning_template(templateName="cfn-provtemplate-ver")+ assert (desc["defaultVersionId"], desc["templateBody"]) == (6, _cfn_provisioning_template_body("m6"))++ cfn.delete_stack(StackName="cfn-iot-provtmpl-ver")+ _wait_stack(cfn, "cfn-iot-provtmpl-ver")+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.describe_provisioning_template(templateName="cfn-provtemplate-ver")++def test_cfn_iot_provisioning_template_generated_name(cfn, iot_client):"""TemplateName is optional in the CloudFormation schema: an omitted onegets a generated physical name that satisfies the 36-char template-namediff --git a/tests/test_iot.py b/tests/test_iot.pyindex e923df06..300d8e2a 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -1924,6 +1924,7 @@ def test_iot_provisioning_template_body_must_carry_certificate_resource(iot_clietemplateName=name, templateBody="not json{", provisioningRoleArn=role)assert ei.value.response["Error"]["Code"] == "InvalidRequestException"+ assert ei.value.response["Error"]["Message"] == "The template body is invalid"with pytest.raises(ClientError):iot_client.describe_provisioning_template(templateName=name)@@ -1951,6 +1952,161 @@ def test_iot_provisioning_template_update_unknown_404(iot_client):)+def _versioned_template_body(marker: str) -> str:+ return json.dumps({**json.loads(_provisioning_template_body()), "DeviceConfiguration": {"v": marker}})+++def test_iot_provisioning_template_versions(iot_client):+ """Version ids count up and are never reused, the default cannot be deleted, and a template keeps five."""+ name = _unique("provtemplate")+ iot_client.create_provisioning_template(+ templateName=name, templateBody=_versioned_template_body("1"),+ provisioningRoleArn="arn:aws:iam::000000000000:role/provisioning",+ )++ def listed():+ return [(v["versionId"], v["isDefaultVersion"])+ for v in iot_client.list_provisioning_template_versions(templateName=name)["versions"]]++ def describe():+ desc = iot_client.describe_provisioning_template(templateName=name)+ return desc["defaultVersionId"], json.loads(desc["templateBody"])["DeviceConfiguration"]["v"]++ assert listed() == [(1, True)]+ v1 = iot_client.describe_provisioning_template_version(templateName=name, versionId=1)+ assert (v1["versionId"], v1["isDefaultVersion"], v1["templateBody"]) == (1, True, _versioned_template_body("1"))+ assert "creationDate" in v1++ created = iot_client.create_provisioning_template_version(+ templateName=name, templateBody=_versioned_template_body("2"))+ assert created["templateName"] == name+ assert created["templateArn"].endswith(f":provisioningtemplate/{name}")+ assert (created["versionId"], created["isDefaultVersion"]) == (2, False)+ assert describe() == (1, "1")+ modified = iot_client.describe_provisioning_template(templateName=name)["lastModifiedDate"]+ created = iot_client.create_provisioning_template_version(+ templateName=name, templateBody=_versioned_template_body("3"), setAsDefault=True)+ assert (created["versionId"], created["isDefaultVersion"]) == (3, True)+ assert describe() == (3, "3")+ assert iot_client.describe_provisioning_template(templateName=name)["lastModifiedDate"] > modified+ assert listed() == [(1, False), (2, False), (3, True)]++ with pytest.raises(ClientError) as ei:+ iot_client.delete_provisioning_template_version(templateName=name, versionId=3)+ assert ei.value.response["Error"]["Code"] == "InvalidRequestException"+ assert ei.value.response["Error"]["Message"] == (+ "Unable to delete template version 3, it is the default version")++ iot_client.update_provisioning_template(templateName=name, defaultVersionId=2)+ assert describe() == (2, "2")+ iot_client.delete_provisioning_template_version(templateName=name, versionId=1)+ for missing in (1, 99): # deleted, never created+ with pytest.raises(ClientError) as ei:+ iot_client.update_provisioning_template(templateName=name, defaultVersionId=missing)+ assert ei.value.response["Error"]["Code"] == "InvalidRequestException"+ assert ei.value.response["Error"]["Message"] == (+ f"Unable to set version {missing} as the default, version does not exist")+ with pytest.raises(ClientError) as ei:+ iot_client.describe_provisioning_template_version(templateName=name, versionId=missing)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ assert ei.value.response["Error"]["Message"] == (+ f"Unable to find a template version with ID {missing} for template {name}")+ with pytest.raises(ClientError) as ei:+ iot_client.delete_provisioning_template_version(templateName=name, versionId=missing)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ assert ei.value.response["Error"]["Message"] == f"Unable to find template version {missing}"++ for version_id in (4, 5, 6):+ assert iot_client.create_provisioning_template_version(+ templateName=name, templateBody=_versioned_template_body(str(version_id)))["versionId"] == version_id+ with pytest.raises(ClientError) as ei:+ iot_client.create_provisioning_template_version(+ templateName=name, templateBody=_versioned_template_body("7"), setAsDefault=True)+ assert ei.value.response["Error"]["Code"] == "VersionsLimitExceededException"+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409+ assert ei.value.response["Error"]["Message"] == (+ f"Can't create a template version for the template {name}, "+ "the maximum number of template versions has been reached")+ assert describe() == (2, "2")+ iot_client.delete_provisioning_template_version(templateName=name, versionId=6)+ assert iot_client.create_provisioning_template_version(+ templateName=name, templateBody=_versioned_template_body("7"))["versionId"] == 7+ # All of them in one page, whatever maxResults asks for.+ page = iot_client.list_provisioning_template_versions(templateName=name, maxResults=2)+ assert [v["versionId"] for v in page["versions"]] == [2, 3, 4, 5, 7]+ assert "nextToken" not in page++ with pytest.raises(ClientError) as ei:+ iot_client.create_provisioning_template_version(templateName=name, templateBody="not json")+ assert ei.value.response["Error"]["Message"] == "The template body is invalid"+ iot_client.delete_provisioning_template(templateName=name)+++def test_iot_provisioning_template_versions_of_an_unknown_template(iot_client):+ name = _unique("provtemplate")+ calls = (+ (iot_client.list_provisioning_template_versions, {}, f"Template named {name} not found"),+ (iot_client.describe_provisioning_template_version, {"versionId": 1},+ f"Unable to find a template named {name}"),+ (iot_client.create_provisioning_template_version, {"templateBody": _provisioning_template_body()},+ f"Unable to find template named {name}"),+ (iot_client.delete_provisioning_template_version, {"versionId": 1},+ f"Unable to find template named {name}"),+ )+ for call, extra, message in calls:+ with pytest.raises(ClientError) as ei:+ call(templateName=name, **extra)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ assert ei.value.response["Error"]["Message"] == message+++def test_iot_provisioning_template_versions_persist():+ """Versions survive a state reload, and a template saved by older state comes back as version 1."""+ import asyncio++ from ministack.core.responses import set_request_account_id, set_request_region+ from ministack.services import iot as iot_module++ name = _unique("provtemplate")++ async def _call(method, path, payload=None, qp=None):+ set_request_account_id("123456789012")+ set_request_region("eu-west-1")+ body = json.dumps(payload).encode() if payload is not None else b""+ status, _headers, out = await iot_module.handle_request(method, path, {}, body, qp or {})+ return status, json.loads(out) if out else {}++ async def _run():+ assert (await _call("POST", "/provisioning-templates", {+ "templateName": name, "templateBody": _versioned_template_body("1"),+ "provisioningRoleArn": "arn:aws:iam::123456789012:role/provisioning",+ }))[0] == 200+ assert (await _call("POST", f"/provisioning-templates/{name}/versions",+ {"templateBody": _versioned_template_body("2")}, {"setAsDefault": "true"}))[0] == 200+ saved = iot_module.get_state()+ iot_module.reset()+ iot_module.load_persisted_state(saved)+ _status, out = await _call("GET", f"/provisioning-templates/{name}/versions")+ assert [(v["versionId"], v["isDefaultVersion"]) for v in out["versions"]] == [(1, False), (2, True)]+ _status, out = await _call("GET", f"/provisioning-templates/{name}")+ assert out["templateBody"] == _versioned_template_body("2")++ # What older versions saved: the body on the record and no versions.+ record = saved["provisioning_templates"].get_scoped("123456789012", "eu-west-1", name)+ record.update(templateBody=_versioned_template_body("1"), defaultVersionId=1)+ del record["versions"], record["lastVersionId"]+ iot_module.reset()+ iot_module.load_persisted_state(saved)+ _status, out = await _call("GET", f"/provisioning-templates/{name}")+ assert (out["defaultVersionId"], out["templateBody"]) == (1, _versioned_template_body("1"))+ assert "versions" not in out+ _status, out = await _call("POST", f"/provisioning-templates/{name}/versions",+ {"templateBody": _versioned_template_body("2")})+ assert out["versionId"] == 2++ asyncio.run(_run())++def _hook_function_arn(lam, iam, permission: dict | None = None) -> str:"""The ARN of a new hook function; ``permission`` grants iot.amazonaws.com the invoke, with its extra arguments."""import iodiff --git a/tests/test_iot_data.py b/tests/test_iot_data.pyindex 1d75fcec..99605de0 100644--- a/tests/test_iot_data.py+++ b/tests/test_iot_data.py@@ -4310,6 +4310,76 @@ def test_mtls_provisioning_hook_names_the_thing(broker, tmp_path):assert iot.describe_thing(thingName=thing)["thingTypeName"] == f"{name}-type"[email protected]("hook", [False, True], ids=["plain", "hook"])+def test_mtls_provisioning_applies_the_default_template_version(broker, tmp_path, hook):+ """RegisterThing applies the default version of the template, after its hook if it has one."""+ iot = broker.client("iot")+ name = _unique("fleet")+ extra = {}+ if hook:+ buf = _io.BytesIO()+ with _zipfile.ZipFile(buf, "w") as z:+ z.writestr("index.py", "def handler(event, context):\n return {'allowProvisioning': True}\n")+ role = broker.client("iam").create_role(RoleName=f"{name}-hook", AssumeRolePolicyDocument=json.dumps({+ "Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "sts:AssumeRole",+ "Principal": {"Service": "lambda.amazonaws.com"}}]}))+ lam = broker.client("lambda")+ extra["preProvisioningHook"] = {"targetArn": lam.create_function(+ FunctionName=f"{name}-hook", Runtime="python3.12", Handler="index.handler",+ Role=role["Role"]["Arn"], Code={"ZipFile": buf.getvalue()},+ )["FunctionArn"]}+ lam.add_permission(+ FunctionName=f"{name}-hook", StatementId="iot", Action="lambda:InvokeFunction",+ Principal="iot.amazonaws.com",+ )++ def body(version):+ return json.dumps({+ "Parameters": {"SerialNumber": {"Type": "String"}},+ "Resources": {+ "thing": {"Type": "AWS::IoT::Thing", "Properties": {+ "ThingName": {"Fn::Join": ["", [f"{name}-{version}-", {"Ref": "SerialNumber"}]]}}},+ "certificate": {"Type": "AWS::IoT::Certificate", "Properties": {+ "CertificateId": {"Ref": "AWS::IoT::Certificate::Id"}, "Status": "ACTIVE"}},+ },+ "DeviceConfiguration": {"version": version},+ })++ iot.create_provisioning_template(+ templateName=name, templateBody=body("v1"), enabled=True,+ provisioningRoleArn="arn:aws:iam::000000000000:role/provisioning", **extra,+ )+ 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))+ packet_ids = iter(range(3, 100))++ def register(serial, version):+ peer.send(_make_publish(create, b"", qos=1, packet_id=next(packet_ids)))+ topic, payload = peer.next_publish()+ assert topic == f"{create}/accepted"+ peer.send(_make_publish(provision, json.dumps({+ "certificateOwnershipToken": json.loads(payload)["certificateOwnershipToken"],+ "parameters": {"SerialNumber": serial},+ }).encode(), qos=1, packet_id=next(packet_ids)))+ assert peer.next_publish(timeout=10) == (f"{provision}/accepted", json.dumps({+ "deviceConfiguration": {"version": version}, "thingName": f"{name}-{version}-{serial}",+ }).encode())++ try:+ _assert_connack(peer.connect(_unique("claim")))+ peer.subscribe(f"{create}/+", packet_id=1)+ peer.subscribe(f"{provision}/+", packet_id=2)+ iot.create_provisioning_template_version(templateName=name, templateBody=body("v2"))+ register("a", "v1")+ iot.update_provisioning_template(templateName=name, defaultVersionId=2)+ register("b", "v2")+ iot.create_provisioning_template_version(templateName=name, templateBody=body("v3"), setAsDefault=True)+ register("c", "v3")+ finally:+ peer.close()++def test_mtls_jitr_certificate_is_listed_by_its_ca(broker, tmp_path):"""As measured on AWS, ListCertificatesByCA lists the certificate thatjust-in-time registration created, while it is still PENDING_ACTIVATION."""