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): provisioning-template control plane + AWS::IoT::ProvisioningTemplate (#1532)
iot-rocket2f1f829544c8
diff --git a/README.md b/README.mdindex 4aaa7078..4d5f095f 100644--- a/README.md+++ b/README.md@@ -535,6 +535,7 @@ subnet = ec2.create_subnet(| `AWS::ApiGatewayV2::Stage` | Stage ID | StageName || `AWS::ApiGatewayV2::Integration` | Integration ID | IntegrationId || `AWS::ApiGatewayV2::Route` | Route ID | RouteId |+| `AWS::IoT::ProvisioningTemplate` | Template name | TemplateArn, Arn || `AWS::SES::EmailIdentity` | Identity | EmailIdentity || `AWS::SES::ConfigurationSet` | Configuration set name | None || `AWS::SES::ConfigurationSetEventDestination` | Event destination ID | Id |@@ -586,7 +587,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; deployments complete immediately; session-based configuration retrieval with token rotation || **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, DescribeJob, ListJobs, GetJobDocument, CancelJob, DeleteJob, ListJobExecutionsForThing, DescribeJobExecution, CancelJobExecution; data plane (`iot-jobs-data`): GetPendingJobExecutions, StartNextPendingJobExecution, DescribeJobExecution (incl. the `$next` sentinel), UpdateJobExecution | 9 control-plane + 4 device data-plane operations sharing one store. Executions walk `QUEUED → IN_PROGRESS → {SUCCEEDED, FAILED, REJECTED, CANCELED}`; the remaining AWS terminal statuses (`TIMED_OUT`, `REMOVED`) are modeled and counted in `jobProcessDetails` but nothing sets them — there are no execution timeouts, and deleting a thing DELETES its executions (freeing a job that was only waiting on that thing) rather than marking them `REMOVED`. `versionNumber` gives optimistic concurrency: every transition bumps it and a stale `expectedVersion` is rejected with a 409 whose message carries the current version — coded `VersionConflictException` on the control plane and `InvalidStateTransitionException` on the device plane, each as its own service model declares. `executionNumber` is write-once (always 1: an execution is never re-queued). Devices may only report `IN_PROGRESS` / `SUCCEEDED` / `FAILED` / `REJECTED` via `UpdateJobExecution`; targets are thing or thing-group ARNs — `SNAPSHOT` jobs resolve group membership once at creation, `CONTINUOUS` jobs also pick up things added to a target group later, and a target must name a thing or thing group in the caller's own account and region (anything else is `ResourceNotFoundException`, since it would resolve to no devices at all); a non-continuous job auto-`COMPLETED`s (with `jobProcessDetails` counts) once every execution is terminal. **`documentSource` is not fetched**: a job created with an S3 `documentSource` serves a `{"documentSource": "<url>"}` placeholder as its document rather than the object's content, so the lifecycle still runs — pass `document` when the content matters. **Timestamp units differ by plane, as on AWS**: control-plane responses use `timestamp` shapes (epoch seconds — boto3 parses them to datetimes) while `iot-jobs-data` responses carry raw epoch-**millisecond** `long`s. Job state persists with the IoT store when `PERSIST_STATE=1` |-| **IoT Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, CreateKeysAndCertificate, RegisterCertificate, RegisterCertificateWithoutCA, UpdateCertificate, DeleteCertificate, GetRegistrationCode, DeleteRegistrationCode, RegisterCACertificate, DescribeCACertificate, UpdateCACertificate, ListCACertificates, DeleteCACertificate, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, AttachPrincipalPolicy, DetachPrincipalPolicy, ListPrincipalPolicies, ListPolicyPrincipals, CreateTopicRule, GetTopicRule, ReplaceTopicRule, DeleteTopicRule, ListTopicRules, UpdateIndexingConfiguration, GetIndexingConfiguration, DescribeIndex, ListIndices, SearchIndex, DescribeEndpoint, Publish (HTTP), MQTT-over-WebSocket pub/sub | 46 operations + **MQTT 3.1.1 and 5.0 over WebSocket** (negotiated per connection) on the gateway port — clients use the address returned by `DescribeEndpoint`; local CA signs `CreateKeysAndCertificate` certificates (CA persists across restarts when `PERSIST_STATE=1`); multi-tenancy via transparent topic prefixing (same pattern as Transfer Family's shared SFTP listener); no plain TCP 1883 (real AWS IoT requires TLS or SigV4 on every connection), but a **native mTLS MQTT listener on 8883** serves device SDK binaries by default — the client certificate is optional (no certificate means the default account, like an unsigned WebSocket upgrade) and, when presented, must be registered `ACTIVE` in exactly one account, which then serves the session; unknown, inactive or doubly-registered certificates get a "not authorized" CONNACK (see `IOT_MTLS_PORT` in the environment table); local CA cert available at `GET /_ministack/iot/ca.pem` for SDK trust configuration; IoT policies are stored but **not enforced** on the data plane; **fleet indexing** works the way it does on AWS — `UpdateIndexingConfiguration` turns the `AWS_Things` index on (Terraform `aws_iot_indexing_configuration`), and searching while `thingIndexingMode` is `OFF` answers `ResourceNotFoundException`; `SearchIndex` then queries the live registry + classic shadows with `AND`-separated `thingName` / `thingTypeName` / `thingGroupNames` / `attributes.*` / `shadow.reported.*` / `shadow.desired.*` terms (`*` / `?` wildcards, `maxResults` / `nextToken` paging) — there is no projection to build, so hits are always current; the deprecated principal-policy family (`AttachPrincipalPolicy` / `DetachPrincipalPolicy` / `ListPrincipalPolicies` / `ListPolicyPrincipals`) maps 1:1 onto the modern policy-target store; **topic rules fire on matching publishes** (incl. Basic Ingest `$aws/rules/<name>`) with SQL SELECT projection (`topic()`, `timestamp()`, `encode()`, `newuuid()`, `replace()`, `clientid()`, `isUndefined()`), **WHERE-clause evaluation** (comparisons, `IN`, `LIKE`, `BETWEEN`, `IS NULL`, `regexp_matches`, bare boolean attributes, composed with `AND` / `OR` and parenthesised grouping; missing attributes fail closed as on AWS; unparseable SQL → `SqlParseException`), and `lambda` / `republish` / `dynamoDBv2` / `sns` / `sqs` actions dispatched in-process with the rule's `errorAction` on failure; **device shadows over MQTT** — the `$aws/things/<thing>/shadow[/name/<name>]/{get,update,delete}` reserved topics drive the shadow store and reply on `accepted` / `rejected` (with `delta` and `documents` on update); a **CA-certificate registry** (`RegisterCACertificate` and friends) with the just-in-time-registration `registered` event on `$aws/events/certificates/registered/{caCertificateId}`; and `SearchIndex` answers `connectivity.connected` / `connectivity.timestamp` / `connectivity.disconnectReason` when `thingConnectivityIndexingMode` is `STATUS`, deriving `connected` from the live session registry |+| **IoT Core** | CreateThing, DescribeThing, ListThings, UpdateThing, DeleteThing, CreateThingType, CreateThingGroup, AddThingToThingGroup, ListThingsInThingGroup, CreateKeysAndCertificate, RegisterCertificate, RegisterCertificateWithoutCA, UpdateCertificate, DeleteCertificate, GetRegistrationCode, DeleteRegistrationCode, RegisterCACertificate, DescribeCACertificate, UpdateCACertificate, ListCACertificates, DeleteCACertificate, CreateProvisioningTemplate, DescribeProvisioningTemplate, ListProvisioningTemplates, UpdateProvisioningTemplate, DeleteProvisioningTemplate, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, AttachPrincipalPolicy, DetachPrincipalPolicy, ListPrincipalPolicies, ListPolicyPrincipals, CreateTopicRule, GetTopicRule, ReplaceTopicRule, DeleteTopicRule, ListTopicRules, UpdateIndexingConfiguration, GetIndexingConfiguration, DescribeIndex, ListIndices, SearchIndex, DescribeEndpoint, Publish (HTTP), MQTT-over-WebSocket pub/sub | 51 operations + **MQTT 3.1.1 and 5.0 over WebSocket** (negotiated per connection) on the gateway port — clients use the address returned by `DescribeEndpoint`; local CA signs `CreateKeysAndCertificate` certificates (CA persists across restarts when `PERSIST_STATE=1`); multi-tenancy via transparent topic prefixing (same pattern as Transfer Family's shared SFTP listener); no plain TCP 1883 (real AWS IoT requires TLS or SigV4 on every connection), but a **native mTLS MQTT listener on 8883** serves device SDK binaries by default — the client certificate is optional (no certificate means the default account, like an unsigned WebSocket upgrade) and, when presented, must be registered `ACTIVE` in exactly one account, which then serves the session; unknown, inactive or doubly-registered certificates get a "not authorized" CONNACK (see `IOT_MTLS_PORT` in the environment table); local CA cert available at `GET /_ministack/iot/ca.pem` for SDK trust configuration; IoT policies are stored but **not enforced** on the data plane; **fleet indexing** works the way it does on AWS — `UpdateIndexingConfiguration` turns the `AWS_Things` index on (Terraform `aws_iot_indexing_configuration`), and searching while `thingIndexingMode` is `OFF` answers `ResourceNotFoundException`; `SearchIndex` then queries the live registry + classic shadows with `AND`-separated `thingName` / `thingTypeName` / `thingGroupNames` / `attributes.*` / `shadow.reported.*` / `shadow.desired.*` terms (`*` / `?` wildcards, `maxResults` / `nextToken` paging) — there is no projection to build, so hits are always current; the deprecated principal-policy family (`AttachPrincipalPolicy` / `DetachPrincipalPolicy` / `ListPrincipalPolicies` / `ListPolicyPrincipals`) maps 1:1 onto the modern policy-target store; **topic rules fire on matching publishes** (incl. Basic Ingest `$aws/rules/<name>`) with SQL SELECT projection (`topic()`, `timestamp()`, `encode()`, `newuuid()`, `replace()`, `clientid()`, `isUndefined()`), **WHERE-clause evaluation** (comparisons, `IN`, `LIKE`, `BETWEEN`, `IS NULL`, `regexp_matches`, bare boolean attributes, composed with `AND` / `OR` and parenthesised grouping; missing attributes fail closed as on AWS; unparseable SQL → `SqlParseException`), and `lambda` / `republish` / `dynamoDBv2` / `sns` / `sqs` actions dispatched in-process with the rule's `errorAction` on failure; **device shadows over MQTT** — the `$aws/things/<thing>/shadow[/name/<name>]/{get,update,delete}` reserved topics drive the shadow store and reply on `accepted` / `rejected` (with `delta` and `documents` on update); a **CA-certificate registry** (`RegisterCACertificate` and friends) with the just-in-time-registration `registered` event on `$aws/events/certificates/registered/{caCertificateId}`; a **provisioning-template registry** (`CreateProvisioningTemplate` and friends) — storage + CRUD only, so `provisioningRoleArn` is presence-checked but not resolved and the fleet-provisioning MQTT workflow (`$aws/provisioning-templates/...`) is not implemented; and `SearchIndex` answers `connectivity.connected` / `connectivity.timestamp` / `connectivity.disconnectReason` when `thingConnectivityIndexingMode` is `STATUS`, deriving `connected` from the live session registry || **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, 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 || **OpenSearch Service** | CreateDomain, DescribeDomain, DescribeDomains, DeleteDomain, ListDomainNames, UpdateDomainConfig, DescribeDomainConfig, DescribeDomainChangeProgress, ListVersions, GetCompatibleVersions, AddTags, ListTags, RemoveTags | Management plane on `/2021-01-01/*` (`boto3.client("opensearch")`, SigV4 scope `es`). Default data plane is a stub endpoint (`<domain>.ministack.local:9200`) — set `OPENSEARCH_DATAPLANE=1` to spawn one real `opensearchproject/opensearch` container per `CreateDomain` (same pattern as ElastiCache/RDS); `DescribeDomain.Endpoint` then points at that container and `_cluster/health`/`/_search` work end-to-end. Add `OPENSEARCH_DASHBOARDS=1` (with dataplane on) to also spawn a per-domain `opensearch-dashboards` sidecar; `DescribeDomain.DashboardEndpoint` is populated. ARNs follow `arn:aws:es:<region>:<account>:domain/<name>`; Terraform `aws_opensearch_domain` resource compatible. |diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 7e2de4b4..57921ff5 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -6670,6 +6670,110 @@ def _iot_policy_delete(physical_id, props):_iot._policies.pop(physical_id, None)+def _iot_provisioning_template_body(props):+ body = props.get("TemplateBody")+ # TemplateBody is a JSON *string* in the CloudFormation schema; a template+ # that inlines it as an object is serialized, never key-cased — the+ # document's own Parameters/Resources keys are part of its contract.+ return json.dumps(body) if isinstance(body, (dict, list)) else body+++def _iot_provisioning_template_payload(name, props):+ payload = {+ "templateName": name,+ "templateBody": _iot_provisioning_template_body(props),+ "provisioningRoleArn": props.get("ProvisioningRoleArn"),+ }+ if "Description" in props:+ payload["description"] = props["Description"]+ if "Enabled" in props:+ payload["enabled"] = props["Enabled"]+ if "TemplateType" in props:+ payload["type"] = props["TemplateType"]+ if props.get("PreProvisioningHook"):+ payload["preProvisioningHook"] = _pascal_to_camel(props["PreProvisioningHook"])+ return payload+++def _iot_provisioning_template_attrs(name):+ arn = _iot._provisioning_template_arn(name)+ # Real CloudFormation exposes the ARN as TemplateArn; Arn is kept alongside+ # for symmetry with the other IoT provisioners here.+ return {"TemplateArn": arn, "Arn": arn}+++def _iot_provisioning_template_create(logical_id, props, stack_name):+ # TemplateName is optional in the CloudFormation schema; template names cap+ # at 36 chars, so the generated fallback must stay within that.+ name = props.get("TemplateName") or _physical_name(+ stack_name, logical_id, max_len=36+ )+ resp = _iot._create_provisioning_template(+ _iot_provisioning_template_payload(name, props)+ )+ if resp[0] == 409:+ # Re-create of a surviving template (rollback replay re-enters create):+ # adopt it and apply the declared properties in place instead of+ # failing the stack. Tradeoff: a template the user created out of band+ # under the same name is adopted too (and mutated/deleted with the+ # stack from here on) — an accepted simplification.+ return _iot_provisioning_template_update(name, {}, props, stack_name, logical_id)+ if resp[0] >= 400:+ raise ValueError(f"AWS::IoT::ProvisioningTemplate create failed: {resp[2]!r}")+ return name, _iot_provisioning_template_attrs(name)+++def _iot_provisioning_template_update(physical_id, old_props, new_props, stack_name,+ logical_id=None):+ """Apply a template change in place through UpdateProvisioningTemplate.++ A TemplateName change is a replacement, handled the way AWS::IoT::Policy's+ rename is: the new template is created and the old one removed, since a+ template 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 is create-only on AWS+ (a change replaces the template); a changed value is ignored here.+ """+ name = new_props.get("TemplateName") or _physical_name(+ stack_name, logical_id or physical_id, max_len=36+ )+ if name != physical_id:+ created = _iot_provisioning_template_create(+ logical_id or physical_id, new_props, stack_name+ )+ _iot_provisioning_template_delete(physical_id, old_props)+ return created+ payload = _iot_provisioning_template_payload(name, new_props)+ payload.pop("templateName", None)+ payload.pop("templateBody", None)+ payload.pop("type", None)+ # A member the stack omits must stay untouched, not be nulled — e.g. a+ # template update without ProvisioningRoleArn keeps the stored role.+ payload = {k: v for k, v in payload.items() if v is not None}+ if new_props.get("PreProvisioningHook") is None and old_props.get("PreProvisioningHook"):+ payload["removePreProvisioningHook"] = True+ resp = _iot._update_provisioning_template(name, payload)+ if resp[0] >= 400:+ raise 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"):+ 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+ return name, _iot_provisioning_template_attrs(name)+++def _iot_provisioning_template_delete(physical_id, props):+ _iot._delete_provisioning_template(physical_id)++def _cognito_identity_pool_role_attachment_create(logical_id, props, stack_name):iid = props.get("IdentityPoolId")if not iid:@@ -6988,6 +7092,12 @@ _RESOURCE_HANDLERS = {"update_with_logical_id": True,"delete": _iot_policy_delete,},+ "AWS::IoT::ProvisioningTemplate": {+ "create": _iot_provisioning_template_create,+ "update": _iot_provisioning_template_update,+ "update_with_logical_id": True,+ "delete": _iot_provisioning_template_delete,+ },"AWS::Cognito::IdentityPoolRoleAttachment": {"create": _cognito_identity_pool_role_attachment_create,"delete": _cognito_identity_pool_role_attachment_delete,diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex a4576823..53ce5a47 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -14,6 +14,13 @@ Implements the JSON/REST APIs under ``iot.{region}.amazonaws.com``:``ListCACertificates``, ``DeleteCACertificate``; registering a devicecertificate under a CA with auto-registration enabled publishes the AWSJITR event to ``$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+ ``provisioningRoleArn`` is presence-checked but not resolved+ (MiniStack does not validate IAM role ARNs elsewhere either)- Policies: ``CreatePolicy``, ``CreatePolicyVersion``, ``AttachPolicy``,``DetachPolicy``, etc., plus the deprecated principal-policy family(``AttachPrincipalPolicy`` / ``DetachPrincipalPolicy`` /@@ -105,6 +112,8 @@ _indexing_config: AccountRegionScopedDict = AccountRegionScopedDict()_ca_certificates: AccountRegionScopedDict = AccountRegionScopedDict()# JITR registration code — a single "code" key per account/region_registration_codes: AccountRegionScopedDict = AccountRegionScopedDict()+# Provisioning templates (CreateProvisioningTemplate & friends): templateName -> record+_provisioning_templates: AccountRegionScopedDict = AccountRegionScopedDict()_jobs: AccountRegionScopedDict = AccountRegionScopedDict() # jobId -> Job dict# (thingName, jobId) -> JobExecution dict — tuple keys, same pattern as _shadows_job_executions: AccountRegionScopedDict = AccountRegionScopedDict()@@ -228,6 +237,7 @@ def get_state() -> dict:"indexing_config": copy.deepcopy(_indexing_config),"ca_certificates": copy.deepcopy(_ca_certificates),"registration_codes": copy.deepcopy(_registration_codes),+ "provisioning_templates": copy.deepcopy(_provisioning_templates),"jobs": copy.deepcopy(_jobs),"job_executions": copy.deepcopy(_job_executions),"ca": {"ca_cert_pem": _ca_cert_pem, "ca_key_pem": _ca_key_pem}@@ -258,6 +268,7 @@ def restore_state(data: dict | None) -> None:_indexing_config.update(data.get("indexing_config", {}))_ca_certificates.update(data.get("ca_certificates", {}))_registration_codes.update(data.get("registration_codes", {}))+ _provisioning_templates.update(data.get("provisioning_templates", {}))_jobs.update(data.get("jobs", {}))_job_executions.update(data.get("job_executions", {}))ca_data = data.get("ca")@@ -297,6 +308,7 @@ def reset() -> None:_indexing_config.clear()_ca_certificates.clear()_registration_codes.clear()+ _provisioning_templates.clear()_jobs.clear()_job_executions.clear()with _CA_LOCK:@@ -382,6 +394,10 @@ def _topic_rule_arn(name: str) -> str:return f"arn:aws:iot:{get_region()}:{get_account_id()}:rule/{name}"+def _provisioning_template_arn(name: str) -> str:+ return f"arn:aws:iot:{get_region()}:{get_account_id()}:provisioningtemplate/{name}"++# Rule names are stricter than other IoT resources: [a-zA-Z0-9_] only._RULE_NAME_RE = re.compile(r"^[a-zA-Z0-9_]{1,128}$")@@ -495,6 +511,14 @@ async def handle_request(if path.startswith("/thing-groups/"):return _handle_thing_group(method, path, body, qp)+ # Provisioning templates+ if path == "/provisioning-templates" and method == "POST":+ return _create_provisioning_template(_parse_body(body))+ if path == "/provisioning-templates" and method == "GET":+ return _list_provisioning_templates(qp)+ if path.startswith("/provisioning-templates/"):+ return _handle_provisioning_template(method, path, body)+# Certificatesif path == "/keys-and-certificate" and method == "POST":return _create_keys_and_certificate(qp)@@ -1075,6 +1099,198 @@ def _remove_thing_from_group(payload: dict) -> tuple:return json_response({})+# ---------------------------------------------------------------------------+# 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+# 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).+# ---------------------------------------------------------------------------++# Template names are shorter and stricter than most IoT names: no colons,+# 36 chars max.+_PROVISIONING_TEMPLATE_NAME_RE = re.compile(r"^[0-9A-Za-z_-]{1,36}$")+++def _validate_provisioning_template_name(name: str | None) -> tuple | None:+ if not name or not _PROVISIONING_TEMPLATE_NAME_RE.match(name):+ return error_response_json(+ "InvalidRequestException",+ "Invalid templateName: must match [0-9A-Za-z_-]{1,36}",+ 400,+ )+ return None+++def _validate_provisioning_template_body(body) -> tuple | None:+ """The live service refuses a body without an AWS::IoT::Certificate+ resource; its message is quoted verbatim below."""+ doc = body+ if not isinstance(doc, dict):+ try:+ doc = json.loads(body)+ except (TypeError, ValueError):+ doc = None+ if not isinstance(doc, dict):+ return error_response_json(+ "InvalidRequestException",+ "The template body is invalid: Template body is not valid JSON.",+ 400,+ )+ resources = doc.get("Resources")+ values = resources.values() if isinstance(resources, dict) else ()+ if not any(+ isinstance(r, dict) and r.get("Type") == "AWS::IoT::Certificate"+ for r in values+ ):+ return error_response_json(+ "InvalidRequestException",+ "The template body is invalid: Template must have certificate resource.",+ 400,+ )+ return None+++def _provisioning_template_not_found(name: str) -> tuple:+ return error_response_json(+ "ResourceNotFoundException", f"Unable to find template named {name}", 404+ )+++def _handle_provisioning_template(method: str, path: str, body: bytes) -> tuple:+ suffix = path[len("/provisioning-templates/"):]+ if "/" in suffix:+ 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 method == "GET":+ return _describe_provisioning_template(name)+ if method == "PATCH":+ return _update_provisioning_template(name, _parse_body(body))+ if method == "DELETE":+ return _delete_provisioning_template(name)+ return error_response_json(+ "InvalidRequestException", f"Unsupported method: {method}", 400+ )+++def _create_provisioning_template(payload: dict) -> tuple:+ name = payload.get("templateName")+ err = _validate_provisioning_template_name(name)+ if err:+ return err+ for field in ("templateBody", "provisioningRoleArn"):+ if not payload.get(field):+ return error_response_json(+ "InvalidRequestException", f"{field} is required", 400+ )+ err = _validate_provisioning_template_body(payload["templateBody"])+ if err:+ return err+ if name in _provisioning_templates:+ return error_response_json(+ "ResourceAlreadyExistsException",+ f"Template with name {name} already exists",+ 409,+ )+ now = _now_epoch()+ 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,+ }+ # The live service omits description from Describe when it was never set —+ # absent, not empty — so an unset one is not stored at all.+ if payload.get("description"):+ record["description"] = payload["description"]+ if payload.get("preProvisioningHook"):+ record["preProvisioningHook"] = payload["preProvisioningHook"]+ _provisioning_templates[name] = record+ logger.info("IoT provisioning template created: %s", name)+ return json_response({+ "templateArn": record["templateArn"],+ "templateName": name,+ "defaultVersionId": 1,+ })+++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)+++def _list_provisioning_templates(qp: dict) -> tuple:+ """``GET /provisioning-templates`` — no pagination (house convention).++ Summaries carry exactly what the live service's do — in particular no+ ``description``, even for a template that has one.+ """+ summary_keys = (+ "templateArn", "templateName",+ "creationDate", "lastModifiedDate", "enabled", "type",+ )+ return json_response({+ "templates": [+ {k: t[k] for k in summary_keys}+ for t in _provisioning_templates.values()+ ]+ })+++def _update_provisioning_template(name: str, payload: dict) -> tuple:+ t = _provisioning_templates.get(name)+ if t is None:+ return _provisioning_template_not_found(name)+ version = payload.get("defaultVersionId")+ if version is not None and version != t["defaultVersionId"]:+ return error_response_json(+ "InvalidRequestException",+ f"ProvisioningTemplate {name!r} has no version {version}",+ 400,+ )+ if "description" in payload:+ # Same absent-not-empty rule as create: clearing removes the key.+ if payload["description"]:+ t["description"] = payload["description"]+ else:+ t.pop("description", None)+ for field in ("enabled", "provisioningRoleArn"):+ if field in payload:+ t[field] = payload[field]+ if payload.get("removePreProvisioningHook"):+ t.pop("preProvisioningHook", None)+ elif payload.get("preProvisioningHook"):+ t["preProvisioningHook"] = payload["preProvisioningHook"]+ 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.+ return 200, {"Content-Type": "application/x-amz-json-1.0"}, b""+++def _delete_provisioning_template(name: str) -> tuple:+ if _provisioning_templates.get(name) is None:+ return _provisioning_template_not_found(name)+ del _provisioning_templates[name]+ logger.info("IoT provisioning template deleted: %s", name)+ return json_response({})++# ---------------------------------------------------------------------------# Certificates# ---------------------------------------------------------------------------diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 76473042..88d5ee6a 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -650,6 +650,155 @@ def test_cfn_iot_policy_rename_replaces_the_policy(cfn, iot_client):_wait_stack(cfn, "cfn-iot-pol-ren")+def _cfn_provisioning_template_body(marker="one"):+ # The IoT control plane refuses a body without an AWS::IoT::Certificate+ # resource, so every stack body carries one; `marker` varies the body so a+ # stack update can carry a genuinely changed TemplateBody.+ return json.dumps({+ "Parameters": {"SerialNumber": {"Type": "String"}},+ "Resources": {+ "certificate": {"Type": "AWS::IoT::Certificate",+ "Properties": {"CertificateId":+ {"Ref": "AWS::IoT::Certificate::Id"}}},+ "thing": {"Type": "AWS::IoT::Thing",+ "Properties": {"ThingName": {"Ref": "SerialNumber"},+ "AttributePayload": {"Attributes":+ {"marker": marker}}}},+ },+ })+++def test_cfn_iot_provisioning_template(cfn, iot_client):+ """AWS::IoT::ProvisioningTemplate provisions onto the IoT control plane+ instead of rolling the stack back, is readable through the real API, and+ Description + TemplateBody changes apply in place under the same+ physical id."""++ def template(description, body):+ return json.dumps({+ "Resources": {"PT": {"Type": "AWS::IoT::ProvisioningTemplate", "Properties": {+ "TemplateName": "cfn-provtemplate",+ "Description": description,+ "Enabled": True,+ "ProvisioningRoleArn": "arn:aws:iam::000000000000:role/provisioning",+ "TemplateBody": body}}},+ "Outputs": {"Name": {"Value": {"Ref": "PT"}},+ "Arn": {"Value": {"Fn::GetAtt": ["PT", "TemplateArn"]}}},+ })++ body_before = _cfn_provisioning_template_body("before")+ cfn.create_stack(StackName="cfn-iot-provtmpl",+ TemplateBody=template("before", body_before))+ stack = _wait_stack(cfn, "cfn-iot-provtmpl")+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}+ assert outputs["Name"] == "cfn-provtemplate"+ assert outputs["Arn"].endswith(":provisioningtemplate/cfn-provtemplate")++ desc = iot_client.describe_provisioning_template(templateName="cfn-provtemplate")+ assert desc["description"] == "before"+ assert desc["enabled"] is True+ assert desc["templateBody"] == body_before+ assert desc["templateArn"] == outputs["Arn"]++ body_after = _cfn_provisioning_template_body("after")+ cfn.update_stack(StackName="cfn-iot-provtmpl",+ TemplateBody=template("after", body_after))+ stack = _wait_stack(cfn, "cfn-iot-provtmpl")+ assert stack["StackStatus"] == "UPDATE_COMPLETE"+ assert next(+ o["OutputValue"] for o in stack["Outputs"] if o["OutputKey"] == "Name"+ ) == "cfn-provtemplate"+ desc = iot_client.describe_provisioning_template(templateName="cfn-provtemplate")+ assert desc["description"] == "after"+ assert desc["enabled"] is True+ assert desc["templateBody"] == body_after+ assert desc["provisioningRoleArn"] == "arn:aws:iam::000000000000:role/provisioning"++ cfn.delete_stack(StackName="cfn-iot-provtmpl")+ _wait_stack(cfn, "cfn-iot-provtmpl")+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.describe_provisioning_template(templateName="cfn-provtemplate")+++def test_cfn_iot_provisioning_template_rename_replaces(cfn, iot_client):+ """A TemplateName change replaces the template the way AWS::IoT::Policy's+ rename does: new physical id, old template gone."""+ body = _cfn_provisioning_template_body()++ def template(name):+ return json.dumps({+ "Resources": {"PT": {"Type": "AWS::IoT::ProvisioningTemplate", "Properties": {+ "TemplateName": name,+ "ProvisioningRoleArn": "arn:aws:iam::000000000000:role/provisioning",+ "TemplateBody": body}}},+ "Outputs": {"Name": {"Value": {"Ref": "PT"}}},+ })++ cfn.create_stack(StackName="cfn-iot-provtmpl-ren",+ TemplateBody=template("cfn-provtemplate-old"))+ assert _wait_stack(cfn, "cfn-iot-provtmpl-ren")["StackStatus"] == "CREATE_COMPLETE"++ cfn.update_stack(StackName="cfn-iot-provtmpl-ren",+ TemplateBody=template("cfn-provtemplate-new"))+ stack = _wait_stack(cfn, "cfn-iot-provtmpl-ren")+ assert stack["StackStatus"] == "UPDATE_COMPLETE"+ assert next(+ o["OutputValue"] for o in stack["Outputs"] if o["OutputKey"] == "Name"+ ) == "cfn-provtemplate-new"+ iot_client.describe_provisioning_template(templateName="cfn-provtemplate-new")+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.describe_provisioning_template(templateName="cfn-provtemplate-old")++ cfn.delete_stack(StackName="cfn-iot-provtmpl-ren")+ _wait_stack(cfn, "cfn-iot-provtmpl-ren")+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.describe_provisioning_template(templateName="cfn-provtemplate-new")+++def test_cfn_iot_provisioning_template_generated_name(cfn, iot_client):+ """TemplateName is optional in the CloudFormation schema: an omitted one+ gets a generated physical name that satisfies the 36-char template-name+ limit, and an in-place update keeps that name stable."""++ def template(description):+ return json.dumps({+ "Resources": {"PT": {"Type": "AWS::IoT::ProvisioningTemplate", "Properties": {+ "Description": description,+ "ProvisioningRoleArn": "arn:aws:iam::000000000000:role/provisioning",+ "TemplateBody": _cfn_provisioning_template_body()}}},+ "Outputs": {"Name": {"Value": {"Ref": "PT"}}},+ })++ cfn.create_stack(StackName="cfn-iot-provtmpl-auto",+ TemplateBody=template("before"))+ stack = _wait_stack(cfn, "cfn-iot-provtmpl-auto")+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ name = next(+ o["OutputValue"] for o in stack["Outputs"] if o["OutputKey"] == "Name"+ )+ assert re.fullmatch(r"[0-9A-Za-z_-]{1,36}", name)+ assert iot_client.describe_provisioning_template(+ templateName=name+ )["description"] == "before"++ cfn.update_stack(StackName="cfn-iot-provtmpl-auto",+ TemplateBody=template("after"))+ stack = _wait_stack(cfn, "cfn-iot-provtmpl-auto")+ assert stack["StackStatus"] == "UPDATE_COMPLETE"+ assert next(+ o["OutputValue"] for o in stack["Outputs"] if o["OutputKey"] == "Name"+ ) == name+ assert iot_client.describe_provisioning_template(+ templateName=name+ )["description"] == "after"++ cfn.delete_stack(StackName="cfn-iot-provtmpl-auto")+ _wait_stack(cfn, "cfn-iot-provtmpl-auto")+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.describe_provisioning_template(templateName=name)++def test_cfn_lambda_layer_version_permission(cfn, lam):"""AWS::Lambda::LayerVersionPermission attaches a statement to the reallayer version's policy, readable via GetLayerVersionPolicy. (#1345, item 5)"""diff --git a/tests/test_iot.py b/tests/test_iot.pyindex 7236365e..ae147008 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -592,6 +592,179 @@ def test_iot_legacy_principal_policy_unknown_policy_404(iot_client):assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+# ---------------------------------------------------------------------------+# Provisioning templates (storage + CRUD — no fleet-provisioning MQTT workflow)+# ---------------------------------------------------------------------------+++def _provisioning_template_body() -> str:+ # The real service refuses a body without an AWS::IoT::Certificate+ # resource, so every valid test body carries one.+ return json.dumps({+ "Parameters": {"SerialNumber": {"Type": "String"}},+ "Resources": {+ "certificate": {+ "Type": "AWS::IoT::Certificate",+ "Properties": {"CertificateId": {"Ref": "AWS::IoT::Certificate::Id"}},+ },+ "thing": {+ "Type": "AWS::IoT::Thing",+ "Properties": {"ThingName": {"Ref": "SerialNumber"}},+ },+ },+ })+++def test_iot_provisioning_template_lifecycle(iot_client):+ name = _unique("provtemplate")+ body = _provisioning_template_body()+ role = "arn:aws:iam::000000000000:role/provisioning"++ created = iot_client.create_provisioning_template(+ templateName=name,+ description="fleet template",+ templateBody=body,+ enabled=True,+ provisioningRoleArn=role,+ type="FLEET_PROVISIONING",+ )+ assert created["templateName"] == name+ assert created["templateArn"].endswith(f":provisioningtemplate/{name}")+ assert created["defaultVersionId"] == 1++ desc = iot_client.describe_provisioning_template(templateName=name)+ assert desc["templateArn"] == created["templateArn"]+ assert desc["description"] == "fleet template"+ assert desc["templateBody"] == body+ assert desc["enabled"] is True+ assert desc["provisioningRoleArn"] == role+ assert desc["type"] == "FLEET_PROVISIONING"+ assert desc["defaultVersionId"] == 1+ assert "creationDate" in desc and "lastModifiedDate" in desc++ listed = iot_client.list_provisioning_templates()["templates"]+ summary = next(t for t in listed if t["templateName"] == name)+ assert summary["templateArn"] == created["templateArn"]+ assert summary["enabled"] is True+ assert summary["type"] == "FLEET_PROVISIONING"+ # Summaries carry no body, role, or description — same as the live service.+ assert "templateBody" not in summary+ assert "provisioningRoleArn" not in summary+ assert "description" not in summary++ with pytest.raises(ClientError) as ei:+ iot_client.create_provisioning_template(+ templateName=name, templateBody=body, provisioningRoleArn=role+ )+ assert ei.value.response["Error"]["Code"] == "ResourceAlreadyExistsException"+ assert ei.value.response["Error"]["Message"] == (+ f"Template with name {name} already exists"+ )++ updated = iot_client.update_provisioning_template(+ templateName=name, description="updated", enabled=False+ )+ # The live service answers 200 with an empty body and no version bump.+ assert set(updated) == {"ResponseMetadata"}+ desc = iot_client.describe_provisioning_template(templateName=name)+ assert desc["description"] == "updated"+ assert desc["enabled"] is False+ assert desc["defaultVersionId"] == 1+ # An unmentioned field survives the update.+ assert desc["provisioningRoleArn"] == role++ iot_client.delete_provisioning_template(templateName=name)+ with pytest.raises(ClientError) as ei:+ iot_client.describe_provisioning_template(templateName=name)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ assert ei.value.response["Error"]["Message"] == (+ f"Unable to find template named {name}"+ )+++def test_iot_provisioning_template_body_must_carry_certificate_resource(iot_client):+ """A body without an AWS::IoT::Certificate resource is refused with the+ live service's message; unparseable body JSON is refused too."""+ name = _unique("provtemplate")+ role = "arn:aws:iam::000000000000:role/provisioning"+ no_cert = json.dumps({"Resources": {+ "thing": {"Type": "AWS::IoT::Thing", "Properties": {"ThingName": "t"}},+ }})++ with pytest.raises(ClientError) as ei:+ iot_client.create_provisioning_template(+ templateName=name, templateBody=no_cert, provisioningRoleArn=role+ )+ assert ei.value.response["Error"]["Code"] == "InvalidRequestException"+ assert ei.value.response["Error"]["Message"] == (+ "The template body is invalid: Template must have certificate resource."+ )++ with pytest.raises(ClientError) as ei:+ iot_client.create_provisioning_template(+ templateName=name, templateBody="not json{", provisioningRoleArn=role+ )+ assert ei.value.response["Error"]["Code"] == "InvalidRequestException"++ with pytest.raises(ClientError):+ iot_client.describe_provisioning_template(templateName=name)+++def test_iot_provisioning_template_name_validation(iot_client):+ role = "arn:aws:iam::000000000000:role/provisioning"+ for bad in ("x" * 37, "no:colons"):+ with pytest.raises(ClientError) as ei:+ iot_client.create_provisioning_template(+ templateName=bad,+ templateBody=_provisioning_template_body(),+ provisioningRoleArn=role,+ )+ assert ei.value.response["Error"]["Code"] == "InvalidRequestException"+++def test_iot_provisioning_template_update_unknown_404(iot_client):+ name = _unique("provtemplate")+ with pytest.raises(ClientError) as ei:+ iot_client.update_provisioning_template(templateName=name, enabled=True)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ assert ei.value.response["Error"]["Message"] == (+ f"Unable to find template named {name}"+ )+++def test_iot_provisioning_template_pre_provisioning_hook_roundtrip(iot_client):+ name = _unique("provtemplate")+ hook = {+ "payloadVersion": "2020-04-01",+ "targetArn": "arn:aws:lambda:us-east-1:000000000000:function:hook",+ }+ iot_client.create_provisioning_template(+ templateName=name,+ templateBody=_provisioning_template_body(),+ provisioningRoleArn="arn:aws:iam::000000000000:role/provisioning",+ preProvisioningHook=hook,+ )+ try:+ assert iot_client.describe_provisioning_template(+ templateName=name+ )["preProvisioningHook"] == hook++ iot_client.update_provisioning_template(+ templateName=name, removePreProvisioningHook=True+ )+ desc = iot_client.describe_provisioning_template(templateName=name)+ assert "preProvisioningHook" not in desc++ iot_client.update_provisioning_template(+ templateName=name, preProvisioningHook=hook+ )+ assert iot_client.describe_provisioning_template(+ templateName=name+ )["preProvisioningHook"] == hook+ finally:+ iot_client.delete_provisioning_template(templateName=name)++# ---------------------------------------------------------------------------# Fleet indexing (indexing configuration + SearchIndex)# ---------------------------------------------------------------------------