Skip to content

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

feat(iot): run the pre-provisioning hook of a fleet template (#2178)

iot-rocket9f046e9dabc5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 31e90f58..6d8f4b80 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,6 +25,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
+- **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.
- **IoT — job documents from S3** — `CreateJob` and `CreateJobTemplate` read a `documentSource` (`s3://` or an S3 object URL) from MiniStack's S3 once, at creation, where they stored a `{"documentSource": "<url>"}` placeholder. A missing bucket or object, an object that is not JSON or is over 32 KB and a URL that names no S3 host are refused with AWS's messages, and `CreateJob` refuses `document` together with `documentSource`. Devices get every job document re-serialized as AWS sends it, without spaces and without object members that are null, while `GetJobDocument` keeps the stored text. Contributed by @iot-rocket.
diff --git a/README.md b/README.md
index c0876f95..67af1546 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 is not invoked; and `SearchIndex` answers `connectivity.connected` / `connectivity.timestamp` / `connectivity.disconnectReason` when `thingConnectivityIndexingMode` is `STATUS`, deriving `connected` from the live session registry; the broker publishes the presence and subscription lifecycle events (`$aws/events/presence/connected\|disconnected/{clientId}`, `$aws/events/subscriptions/subscribed\|unsubscribed/{clientId}`) |
+| **IoT 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 Wireless** | GetPositionEstimate | Single operation (`POST /position-estimate`, SigV4 scope `iotwireless`, endpoint prefix `api.iotwireless`). **The response is the raw GeoJSON blob** — the output shape's `payload` trait — so boto3 hands back a `StreamingBody` under `GeoJsonPayload`, not a JSON envelope. Resolves from `Ip` only: `WiFiAccessPoints` / `CellTowers` / `Gnss` are accepted and ignored, `Timestamp` and `AdvancedConfiguration` only reach `properties`, and the estimate is synthetic + deterministic — the canonical IP (an IPv4-mapped IPv6 address counts as its IPv4 form) hashes onto lon [-180, 180) / lat [-60, 60), 4 decimals — so the same address always answers the same estimate and consumer tests can assert on it. `properties` carry `horizontalAccuracy` 1000000 (the value of one live call) and `horizontalConfidenceLevel` 0.68 (the default the AWS IoT Core Device Location guide documents — `AdvancedConfiguration.WiFiCellular.ConfidencePercent` overrides it, divided by 100, within the 50 to 99 the model allows) plus `timestamp`, which is always there: AWS documents the request's `Timestamp` as the resolve time and the receive time as its substitute when the caller sends none, so send a `Timestamp` and the whole blob is byte-identical. The real payload's `country` and city/state/postal properties are omitted for that determinism. An input with no resolver hint and an `IpAddress` that `ipaddress.ip_address()` refuses answer `ValidationException` (those two wordings are recorded from the live service; every other message in this service is MiniStack's own, since none is documented); a `Timestamp` that is not a Unix timestamp, and a `ConfidencePercent` outside the model's range, are `ValidationException` too; a valid address that is **not globally routable or is multicast** (private, loopback, TEST-NET, multicast groups, ...) answers `ResourceNotFoundException` `Cannot find position for the IP address <ip>`, mirroring the real service's refusal when its geo database has no entry. A well-formed request whose only measurements are WLAN/cell/GNSS is `ResourceNotFoundException` too — the developer guide documents 404 for exactly that ("no location information was found or solved ... The MAC address or cellular tower information is not sufficient ... The GNSS payload is not sufficient"), and 400 for measurement data formatted incorrectly. Stateless — nothing persists |
| **EventBridge Scheduler** | CreateSchedule, GetSchedule, UpdateSchedule, DeleteSchedule, ListSchedules, CreateScheduleGroup, GetScheduleGroup, DeleteScheduleGroup, ListScheduleGroups, TagResource, UntagResource, ListTagsForResource | 12 actions; schedules **fire their targets** — a background sweep invokes each enabled schedule's target (Lambda, SQS, SNS, Step Functions) when due, honoring `State`, `StartDate`/`EndDate`, and `ActionAfterCompletion: DELETE`; schedule groups with cascading deletes; `rate()`, `cron()`, `at()` expressions; group/prefix/state filters on list; default group auto-created; CFN `AWS::Scheduler::Schedule` and `AWS::Scheduler::ScheduleGroup` supported |
| **EKS** | CreateCluster, DescribeCluster, ListClusters, DeleteCluster, CreateNodegroup, DescribeNodegroup, ListNodegroups, DeleteNodegroup, CreateAddon, DescribeAddon, ListAddons, UpdateAddon, DeleteAddon, AssociateEncryptionConfig, CreateAccessEntry, DescribeAccessEntry, ListAccessEntries, UpdateAccessEntry, DeleteAccessEntry, AssociateAccessPolicy, DisassociateAccessPolicy, ListAssociatedAccessPolicies, AssociateIdentityProviderConfig, DescribeIdentityProviderConfig, DisassociateIdentityProviderConfig, ListIdentityProviderConfigs, CreatePodIdentityAssociation, DescribePodIdentityAssociation, ListPodIdentityAssociations, UpdatePodIdentityAssociation, DeletePodIdentityAssociation, TagResource, UntagResource, ListTagsForResource | `CreateCluster` spawns a real **k3s** container (75 MB) with a full Kubernetes API server; `kubectl`, Helm, and any K8s tooling work out of the box; cascading delete removes nodegroups and k3s container; addon CRUD (e.g. `vpc-cni`, `coredns`, `kube-proxy`, `aws-ebs-csi-driver`) at `/clusters/{name}/addons` flips status to `ACTIVE` on create / update; `AssociateEncryptionConfig` at `/clusters/{name}/encryption-config/associate` records KMS encryption config (rejects re-association, AWS-shape `update` envelope); **Access Entries** (modern post-1.29 IAM bindings — replaces aws-auth ConfigMap) at `/clusters/{name}/access-entries[/{principalArn}[/access-policies[/{policyArn}]]]` for Crossplane / Terraform `aws_eks_access_entry` + `aws_eks_access_policy_association`; OIDC discovery + JWKS served at the cluster's `identity.oidc.issuer` URL so Terraform's `aws_iam_openid_connect_provider` (IRSA) works against ministack; **OIDC Identity Provider Config** (`AssociateIdentityProviderConfig` / `DescribeIdentityProviderConfig` / `DisassociateIdentityProviderConfig` / `ListIdentityProviderConfigs`) at `/clusters/{name}/identity-provider-configs[/{verb}]` — one OIDC IdP per cluster, issuer + clientId + claims forwarded to the k3s API server via `--kube-apiserver-arg=oidc-*` flags, tags reachable via `ListTagsForResource`; CFN `AWS::EKS::Cluster` and `AWS::EKS::Nodegroup` supported |
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 8039c80c..af457bf4 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -23,7 +23,8 @@ Implements the JSON/REST APIs under ``iot.{region}.amazonaws.com``:
``UpdateProvisioningTemplate``, ``DeleteProvisioningTemplate``,
``CreateProvisioningClaim``, and fleet provisioning over MQTT
(``$aws/certificates/create/json`` and
- ``$aws/provisioning-templates/{name}/provision/json``);
+ ``$aws/provisioning-templates/{name}/provision/json``, after the
+ template's pre-provisioning hook allows it);
``provisioningRoleArn`` is presence-checked but not resolved
(MiniStack does not validate IAM role ARNs elsewhere either)
- Policies: ``CreatePolicy``, ``CreatePolicyVersion``, ``AttachPolicy``,
@@ -93,6 +94,7 @@ from typing import Awaitable, Callable
from urllib.parse import parse_qs, parse_qsl
from ministack.core.arn import ArnParseError, parse_arn
+from ministack.core.concurrency import run_reentrant
from ministack.core.iam_evaluator import EvalContext, evaluate, parse_policy_document
from ministack.core.responses import (
AccountRegionScopedDict,
@@ -1877,8 +1879,8 @@ async def _remove_thing_from_group(payload: dict) -> tuple:
# Provisioning templates
#
# CRUD, CreateProvisioningClaim and the fleet provisioning MQTT API (JSON
-# topics) that applies a template to a certificate created over MQTT. The
-# pre-provisioning hook is stored but not invoked, and provisioningRoleArn is
+# 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
@@ -1929,6 +1931,76 @@ def _validate_provisioning_template_body(body) -> tuple | None:
return None
+_PROVISIONING_HOOK_PAYLOAD_VERSION = "2020-04-01"
+_LAMBDA_FUNCTION_ARN_RE = re.compile(
+ r"^arn:aws[a-z-]*:lambda:[a-z0-9-]+:\d{12}:function:[A-Za-z0-9_-]+(:[A-Za-z0-9$_-]+)?$"
+)
+
+
+def _validate_provisioning_hook(hook, template_type: str, template_arn: str) -> tuple | None:
+ """The live service's checks of a ``preProvisioningHook``, the function's policy last."""
+ hook = hook if isinstance(hook, dict) else {}
+ version, target = hook.get("payloadVersion"), hook.get("targetArn")
+ if version is not None and not re.fullmatch(r"[0-9-]+", str(version)):
+ return error_response_json(
+ "InvalidRequestException",
+ "1 validation error detected: Value at 'preProvisioningHook.payloadVersion' failed "
+ "to satisfy constraint: Member must satisfy regular expression pattern: ^[0-9-]+$",
+ 400,
+ )
+ if template_type == "JITP":
+ return error_response_json(
+ "InvalidRequestException",
+ "Provisioning hook is not supported for template type: JITP",
+ 400,
+ )
+ if not isinstance(target, str) or not _LAMBDA_FUNCTION_ARN_RE.match(target):
+ return error_response_json("InvalidRequestException", "Invalid arguments in the call", 400)
+ if version not in (None, _PROVISIONING_HOOK_PAYLOAD_VERSION):
+ return error_response_json(
+ "InvalidRequestException",
+ "The hook version cannot be supported by AWS Iot, the supported versions are: "
+ f"[{_PROVISIONING_HOOK_PAYLOAD_VERSION}]",
+ 400,
+ )
+ if _provisioning_hook_function(target, template_arn) is None:
+ return error_response_json(
+ "InvalidRequestException", f"Access denied during lambda validation: {target}", 400
+ )
+ return None
+
+
+def _provisioning_hook(hook: dict) -> dict:
+ """A validated hook as the live service stores it, with its default payloadVersion."""
+ return {
+ "payloadVersion": hook.get("payloadVersion") or _PROVISIONING_HOOK_PAYLOAD_VERSION,
+ "targetArn": hook["targetArn"],
+ }
+
+
+def _provisioning_hook_function(target_arn: str, template_arn: str) -> dict | None:
+ """The hook function's execution record, if its policy lets iot.amazonaws.com invoke it for the template."""
+ from ministack.core.iam_evaluator import EvalContext, evaluate_resource_policy
+ from ministack.services import lambda_svc
+
+ base, _config, _name = lambda_svc._get_base_func_record_for_ref(target_arn)
+ func, config, _name = lambda_svc._get_func_record_for_ref(target_arn)
+ if base is None or func is None or config is None:
+ return None
+ ctx = EvalContext(
+ principal_arn="*",
+ principal_type="Service",
+ principal_account="",
+ action="lambda:InvokeFunction",
+ resource_arn=target_arn,
+ region=get_region(),
+ service_context={"aws:sourcearn": template_arn, "aws:sourceaccount": get_account_id()},
+ )
+ if evaluate_resource_policy(base.get("policy"), ctx, service="iot.amazonaws.com").decision != "Allow":
+ return None
+ return lambda_svc._execution_record_for_config(func, config)
+
+
def _provisioning_template_not_found(name: str) -> tuple:
return error_response_json(
"ResourceNotFoundException", f"Unable to find template named {name}", 404
@@ -1972,6 +2044,13 @@ def _create_provisioning_template(payload: dict) -> tuple:
or _tags_error(payload.get("tags"), required=False))
if err:
return err
+ hook = payload.get("preProvisioningHook")
+ if hook:
+ err = _validate_provisioning_hook(
+ hook, payload.get("type", "FLEET_PROVISIONING"), _provisioning_template_arn(name)
+ )
+ if err:
+ return err
if name in _provisioning_templates:
return error_response_json(
"ResourceAlreadyExistsException",
@@ -1994,8 +2073,8 @@ def _create_provisioning_template(payload: dict) -> tuple:
# 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"]
+ if hook:
+ record["preProvisioningHook"] = _provisioning_hook(hook)
_provisioning_templates[name] = record
_set_created_tags(record["templateArn"], payload.get("tags"))
logger.info("IoT provisioning template created: %s", name)
@@ -2042,6 +2121,11 @@ def _update_provisioning_template(name: str, payload: dict) -> tuple:
f"ProvisioningTemplate {name!r} has no version {version}",
400,
)
+ hook = None if payload.get("removePreProvisioningHook") else payload.get("preProvisioningHook")
+ if hook:
+ err = _validate_provisioning_hook(hook, t["type"], t["templateArn"])
+ if err:
+ return err
if "description" in payload:
# Same absent-not-empty rule as create: clearing removes the key.
if payload["description"]:
@@ -2053,8 +2137,8 @@ def _update_provisioning_template(name: str, payload: dict) -> tuple:
t[field] = payload[field]
if payload.get("removePreProvisioningHook"):
t.pop("preProvisioningHook", None)
- elif payload.get("preProvisioningHook"):
- t["preProvisioningHook"] = payload["preProvisioningHook"]
+ elif hook:
+ t["preProvisioningHook"] = _provisioning_hook(hook)
t["lastModifiedDate"] = _now_epoch()
_provisioning_templates[name] = t
# The live service answers 200 with an empty body — not an empty JSON
@@ -2145,9 +2229,9 @@ def _fleet_rejected(code: str, message: str, status: int = 400) -> tuple[str, di
class _ProvisioningRejected(Exception):
"""A RegisterThing request the template cannot be applied to."""
- def __init__(self, code: str, message: str):
+ def __init__(self, code: str, message: str, status: int = 400):
super().__init__(message)
- self.reply = _fleet_rejected(code, message)
+ self.reply = _fleet_rejected(code, message, status)
def _provisioning_failed(message: str) -> _ProvisioningRejected:
@@ -2160,13 +2244,14 @@ def _provisioning_failed(message: str) -> _ProvisioningRejected:
async def _fleet_provisioning_reply(
- account_id: str, region: str, operation: str, template_name: str | None, payload: bytes
+ account_id: str, region: str, operation: str, template_name: str | None, payload: bytes,
+ connection: dict,
) -> tuple[str, dict]:
"""The reply suffix (``accepted`` or ``rejected``) and document for one request."""
if operation == "create":
return await _fleet_create_keys_and_certificate(account_id, region)
try:
- return await _fleet_register_thing(account_id, region, template_name, payload)
+ return await _fleet_register_thing(account_id, region, template_name, payload, connection)
except _ProvisioningRejected as e:
return e.reply
@@ -2201,7 +2286,7 @@ async def _fleet_create_keys_and_certificate(account_id: str, region: str) -> tu
async def _fleet_register_thing(
- account_id: str, region: str, template_name: str, payload: bytes
+ account_id: str, region: str, template_name: str, payload: bytes, connection: dict
) -> tuple[str, dict]:
"""``RegisterThing``: apply the template to the certificate the ownership token stands for."""
try:
@@ -2231,6 +2316,19 @@ async def _fleet_register_thing(
)
parameters = request.get("parameters")
parameters = parameters if isinstance(parameters, dict) else {}
+ if template.get("preProvisioningHook"):
+ parameters = await _run_provisioning_hook(template, {
+ **connection,
+ "certificateId": cert["certificateId"],
+ "certificatePem": cert["certificatePem"],
+ "templateArn": template["templateArn"],
+ "parameters": parameters,
+ })
+ cert = _certificates.get(cert["certificateId"])
+ if cert is None:
+ return _fleet_rejected(
+ "InvalidCertificateOwnershipToken", "Certificate ownership token is invalid."
+ )
plan = _provisioning_plan(template, parameters, cert["certificateId"])
thing_name = await _apply_provisioning_plan(plan, cert)
reply = {"deviceConfiguration": plan["deviceConfiguration"]}
@@ -2239,6 +2337,70 @@ async def _fleet_register_thing(
return "accepted", reply
+# A hook that has not answered six seconds after it was invoked fails the request.
+_PROVISIONING_HOOK_SECONDS = 6
+_HOOK_INVALID_RESULT = ("InvalidResult", "Provisioning hook result is in an invalid format.")
+
+
+async def _run_provisioning_hook(template: dict, event: dict) -> dict:
+ """Invoke the template's pre-provisioning hook: the parameters with its overrides, or a rejection."""
+ from ministack.services import lambda_svc
+
+ exec_record = _provisioning_hook_function(
+ template["preProvisioningHook"]["targetArn"], template["templateArn"]
+ )
+ if exec_record is None:
+ raise _ProvisioningRejected("InvocationError", "Access denied while invoking Lambda function")
+ invocation = run_reentrant(
+ lambda_svc._execute_function_with_config_scope, exec_record, event,
+ thread_name="ministack-iot-provisioning-hook",
+ )
+ try:
+ # Past the limit the function keeps running; only its answer is dropped.
+ result = await asyncio.wait_for(asyncio.shield(invocation), _PROVISIONING_HOOK_SECONDS)
+ except Exception:
+ result = None
+ if not isinstance(result, dict) or result.get("throttle"):
+ raise _ProvisioningRejected(
+ "InvocationError", "A failure occurred while invoking the provisioning hook."
+ )
+ if result.get("error"):
+ raise _ProvisioningRejected(
+ "InvocationError", "The provisioning hook was not executed successfully."
+ )
+ return {**event["parameters"], **_provisioning_hook_overrides(result)}
+
+
+def _provisioning_hook_overrides(result: dict) -> dict:
+ """The ``parameterOverrides`` of an answer that allows provisioning, or a rejection."""
+ answer = result.get("body")
+ if isinstance(answer, bytes) or (isinstance(answer, str) and result.get("raw_payload")):
+ try:
+ answer = json.loads(answer)
+ except ValueError:
+ raise _ProvisioningRejected(*_HOOK_INVALID_RESULT) from None
+ if answer is None:
+ raise _ProvisioningRejected("InvalidResult", "The provisioning hook did not return a response.")
+ answer = answer if isinstance(answer, dict) else {}
+ allow, overrides = answer.get("allowProvisioning"), answer.get("parameterOverrides")
+ # Read the way a Java boolean field reads JSON: "true", "TRUE" and 1 allow.
+ if isinstance(allow, str):
+ allow = {"true": True, "false": False}.get(allow.lower())
+ elif not isinstance(allow, (bool, int, float)):
+ allow = None
+ if allow is None or not isinstance(overrides, (dict, type(None))) or any(
+ isinstance(value, (dict, list)) for value in (overrides or {}).values()
+ ):
+ raise _ProvisioningRejected(*_HOOK_INVALID_RESULT)
+ if not allow:
+ raise _ProvisioningRejected("AccessDenied", "Access Denied", 403)
+ # Numbers and booleans become strings; null leaves the parameter unresolved.
+ return {
+ name: value if value is None or isinstance(value, str) else json.dumps(value)
+ for name, value in (overrides or {}).items()
+ }
+
+
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"]
@@ -2260,7 +2422,7 @@ def _provisioning_plan(template: dict, parameters: dict, cert_id: str) -> dict:
if len(value) == 1:
function, argument = next(iter(value.items()))
if function == "Ref":
- if argument not in values:
+ if values.get(argument) is None:
raise _ProvisioningRejected(
"InvalidParameters", f"Cannot resolve reference value: {argument}"
)
@@ -9995,10 +10157,14 @@ class _WSSession:
self, topic: str, operation: str, template_name: str | None, payload: bytes
) -> None:
"""Answer a fleet provisioning request on this connection only, if it subscribed to the reply."""
+ # What a pre-provisioning hook learns about the requester.
+ connection = {"clientId": self._client_id}
+ if self._principal != self.account_id:
+ connection["claimCertificateId"] = self._principal
try:
async with publishing_events():
kind, doc = await _fleet_provisioning_reply(
- self.account_id, self.region, operation, template_name, payload
+ self.account_id, self.region, operation, template_name, payload, connection
)
except Exception:
_broker_logger.warning("IoT fleet provisioning failed for %r", topic, exc_info=True)
diff --git a/tests/conftest.py b/tests/conftest.py
index 7c8153a9..ebc1142b 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -383,6 +383,7 @@ _SERIAL_TESTS = {
"tests/test_iot_data.py::test_mtls_registered_ca_chain_connects",
"tests/test_iot_data.py::test_mtls_provisioning_claim_connects_and_provisions",
"tests/test_iot_data.py::test_mtls_auth_provisioning_claim_is_held_to_its_templates_topics",
+ "tests/test_iot_data.py::test_mtls_provisioning_hook_names_the_thing",
"tests/test_iot_data.py::test_mtls_jitr_certificate_is_listed_by_its_ca",
"tests/test_iot_data.py::test_mtls_jitr_auto_registers_an_unknown_cert_without_connack",
"tests/test_iot_data.py::test_mtls_jitr_under_an_sni_only_ca_needs_sni",
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 7492bc7b..c647298f 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -1506,6 +1506,55 @@ def test_cfn_iot_provisioning_template_generated_name(cfn, iot_client):
iot_client.describe_provisioning_template(templateName=name)
+def test_cfn_iot_provisioning_template_pre_provisioning_hook(cfn, iot_client):
+ """A hook needs the invoke permission for iot.amazonaws.com; without it the stack rolls back."""
+
+ def template(name, permission):
+ resources = {
+ "Fn": {"Type": "AWS::Lambda::Function", "Properties": {
+ "FunctionName": name, "Runtime": "python3.12", "Handler": "index.handler",
+ "Role": "arn:aws:iam::000000000000:role/hook",
+ "Code": {"ZipFile": "def handler(e, c):\n return {'allowProvisioning': True}\n"}}},
+ "PT": {"Type": "AWS::IoT::ProvisioningTemplate", "Properties": {
+ "TemplateName": name,
+ "Enabled": True,
+ "ProvisioningRoleArn": "arn:aws:iam::000000000000:role/provisioning",
+ "TemplateBody": _cfn_provisioning_template_body(),
+ "PreProvisioningHook": {"TargetArn": {"Fn::GetAtt": ["Fn", "Arn"]}}}},
+ }
+ if permission:
+ resources["Perm"] = {"Type": "AWS::Lambda::Permission", "Properties": {
+ "FunctionName": {"Ref": "Fn"}, "Action": "lambda:InvokeFunction",
+ "Principal": "iot.amazonaws.com"}}
+ resources["PT"]["DependsOn"] = "Perm"
+ return json.dumps({"Resources": resources,
+ "Outputs": {"Hook": {"Value": {"Fn::GetAtt": ["Fn", "Arn"]}}}})
+
+ try:
+ cfn.create_stack(StackName="cfn-iot-provhook",
+ TemplateBody=template("cfn-provhook", True))
+ stack = _wait_stack(cfn, "cfn-iot-provhook")
+ assert stack["StackStatus"] == "CREATE_COMPLETE"
+ assert iot_client.describe_provisioning_template(
+ templateName="cfn-provhook"
+ )["preProvisioningHook"] == {
+ "payloadVersion": "2020-04-01", "targetArn": stack["Outputs"][0]["OutputValue"],
+ }
+
+ cfn.create_stack(StackName="cfn-iot-provhook-denied",
+ TemplateBody=template("cfn-provhook-denied", False))
+ assert _wait_stack(cfn, "cfn-iot-provhook-denied")["StackStatus"] == "ROLLBACK_COMPLETE"
+ reasons = [
+ e.get("ResourceStatusReason", "")
+ for e in cfn.describe_stack_events(StackName="cfn-iot-provhook-denied")["StackEvents"]
+ if e["LogicalResourceId"] == "PT" and e["ResourceStatus"] == "CREATE_FAILED"
+ ]
+ assert reasons and "Access denied during lambda validation" in reasons[0]
+ finally:
+ for stack_name in ("cfn-iot-provhook", "cfn-iot-provhook-denied"):
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
def _cfn_job_template(template_id, **overrides):
props = {
"JobTemplateId": template_id,
diff --git a/tests/test_iot.py b/tests/test_iot.py
index ce78db91..e923df06 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -1951,11 +1951,35 @@ def test_iot_provisioning_template_update_unknown_404(iot_client):
)
-def test_iot_provisioning_template_pre_provisioning_hook_roundtrip(iot_client):
+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 io
+ import zipfile
+
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", "def handler(event, context):\n return {'allowProvisioning': True}\n")
+ name = _unique("provhook")
+ role = iam.create_role(RoleName=name, AssumeRolePolicyDocument=json.dumps({
+ "Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "sts:AssumeRole",
+ "Principal": {"Service": "lambda.amazonaws.com"}}]}))
+ arn = lam.create_function(
+ FunctionName=name, Runtime="python3.12", Role=role["Role"]["Arn"],
+ Handler="index.handler", Code={"ZipFile": buf.getvalue()},
+ )["FunctionArn"]
+ if permission is not None:
+ lam.add_permission(
+ FunctionName=name, StatementId="iot", Action="lambda:InvokeFunction",
+ Principal="iot.amazonaws.com", **permission,
+ )
+ return arn
+
+
+def test_iot_provisioning_template_pre_provisioning_hook_roundtrip(iot_client, lam, iam):
name = _unique("provtemplate")
hook = {
"payloadVersion": "2020-04-01",
- "targetArn": "arn:aws:lambda:us-east-1:000000000000:function:hook",
+ "targetArn": _hook_function_arn(lam, iam, {}),
}
iot_client.create_provisioning_template(
templateName=name,
@@ -1984,6 +2008,75 @@ def test_iot_provisioning_template_pre_provisioning_hook_roundtrip(iot_client):
iot_client.delete_provisioning_template(templateName=name)
+def test_iot_provisioning_template_pre_provisioning_hook_validation(iot_client, lam, iam):
+ """Create and Update refuse a hook iot.amazonaws.com may not invoke for this template; payloadVersion defaults."""
+ name = _unique("provtemplate")
+ template_arn = f"arn:aws:iot:us-east-1:000000000000:provisioningtemplate/{name}"
+ allowed = _hook_function_arn(lam, iam, {})
+ own_source = _hook_function_arn(lam, iam, {"SourceArn": template_arn})
+ no_permission = _hook_function_arn(lam, iam)
+ other_source = _hook_function_arn(lam, iam, {"SourceArn": f"{template_arn}-other"})
+ missing = f"{allowed}-missing"
+ denied = "Access denied during lambda validation: "
+ invalid = "Invalid arguments in the call"
+ unsupported = (
+ "The hook version cannot be supported by AWS Iot, the supported versions are: [2020-04-01]"
+ )
+ common = {
+ "templateName": name, "templateBody": _provisioning_template_body(),
+ "provisioningRoleArn": "arn:aws:iam::000000000000:role/provisioning",
+ }
+ for hook, extra, message in (
+ ({"targetArn": missing}, {}, denied + missing),
+ ({"targetArn": "not-an-arn"}, {}, invalid),
+ ({"targetArn": allowed.rsplit(":", 1)[1]}, {}, invalid),
+ ({"targetArn": "arn:aws:sns:us-east-1:000000000000:hook"}, {}, invalid),
+ ({"targetArn": allowed, "payloadVersion": "2019-01-01"}, {}, unsupported),
+ ({"targetArn": allowed, "payloadVersion": "abcdefghij"}, {},
+ "1 validation error detected: Value at 'preProvisioningHook.payloadVersion' failed to "
+ "satisfy constraint: Member must satisfy regular expression pattern: ^[0-9-]+$"),
+ ({"targetArn": allowed}, {"type": "JITP"},
+ "Provisioning hook is not supported for template type: JITP"),
+ ({"targetArn": no_permission}, {}, denied + no_permission),
+ ({"targetArn": other_source}, {}, denied + other_source),
+ ):
+ with pytest.raises(ClientError) as ei:
+ iot_client.create_provisioning_template(**common, **extra, preProvisioningHook=hook)
+ assert ei.value.response["Error"]["Code"] == "InvalidRequestException"
+ assert ei.value.response["Error"]["Message"] == message
+ with pytest.raises(ClientError) as ei:
+ iot_client.describe_provisioning_template(templateName=name)
+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+ iot_client.create_provisioning_template(**common, preProvisioningHook={"targetArn": allowed})
+ try:
+ stored = {"payloadVersion": "2020-04-01", "targetArn": allowed}
+ assert iot_client.describe_provisioning_template(
+ templateName=name
+ )["preProvisioningHook"] == stored
+ for hook, message in (
+ ({"targetArn": missing}, denied + missing),
+ ({"targetArn": no_permission}, denied + no_permission),
+ ({"targetArn": allowed, "payloadVersion": "2019-01-01"}, unsupported),
+ ):
+ with pytest.raises(ClientError) as ei:
+ iot_client.update_provisioning_template(
+ templateName=name, description="changed", preProvisioningHook=hook
+ )
+ assert ei.value.response["Error"]["Message"] == message
+ desc = iot_client.describe_provisioning_template(templateName=name)
+ assert desc["preProvisioningHook"] == stored
+ assert "description" not in desc
+ iot_client.update_provisioning_template(
+ templateName=name, preProvisioningHook={"targetArn": own_source}
+ )
+ assert iot_client.describe_provisioning_template(
+ templateName=name
+ )["preProvisioningHook"] == {"payloadVersion": "2020-04-01", "targetArn": own_source}
+ finally:
+ iot_client.delete_provisioning_template(templateName=name)
+
+
def test_iot_create_provisioning_claim(iot_client):
"""A claim certificate expires in five minutes and stays out of the registry; an unknown template is 404."""
from cryptography import x509
@@ -2125,10 +2218,12 @@ async def _fleet_setup(templates: dict, account=_FLEET_ACCOUNT, region=_FLEET_RE
assert status == 200
-async def _fleet_client(client_id, templates=(), account=_FLEET_ACCOUNT, region=_FLEET_REGION):
+async def _fleet_client(
+ client_id, templates=(), account=_FLEET_ACCOUNT, region=_FLEET_REGION, certificate_id=None
+):
"""A session subscribed to the replies of CreateKeysAndCertificate and of each template."""
send, sent = _mock_send()
- session = _IoTWSSession(send, account, region)
+ session = _IoTWSSession(send, account, region, certificate_id)
await session.handle_packet(PKT_CONNECT, 0, _build_connect_body(client_id))
filters = [f"{_FLEET_CREATE}/+"] + [
f"$aws/provisioning-templates/{t}/provision/json/+" for t in templates
@@ -2497,6 +2592,240 @@ def test_fleet_provisioning_existing_thing_follows_override_settings():
reset()
+_FLEET_HOOK_ARN = f"arn:aws:lambda:{_FLEET_REGION}:{_FLEET_ACCOUNT}:function:fleet-hook"
+_FLEET_CLAIM_ID = "c1" * 32
+
+
+def _fleet_hook(monkeypatch, answers: dict) -> list:
+ """A hook function answering ``answers[Mode]`` for the request's Mode parameter; the events it gets."""
+ from ministack.services import iot as iot_module
+ from ministack.services import lambda_svc
+
+ events = []
+
+ def _execute(_func, event):
+ events.append(event)
+ answer = answers[event["parameters"].get("Mode")]
+ return answer() if callable(answer) else answer
+
+ monkeypatch.setattr(lambda_svc, "_execute_function_with_config_scope", _execute)
+ lambda_svc._functions.clear()
+ with iot_module.request_scope(_FLEET_ACCOUNT, _FLEET_REGION):
+ lambda_svc._functions["fleet-hook"] = {
+ "config": {"FunctionName": "fleet-hook", "FunctionArn": _FLEET_HOOK_ARN},
+ "aliases": {}, "versions": {},
+ "policy": {"Version": "2012-10-17", "Id": "default", "Statement": []},
+ }
+ lambda_svc._add_permission("fleet-hook", {
+ "StatementId": "iot", "Action": "lambda:InvokeFunction", "Principal": "iot.amazonaws.com",
+ })
+ return events
+
+
+async def _fleet_hook_templates(*names):
+ for name in names:
+ status, _ = await _fleet_request(
+ "PATCH", f"/provisioning-templates/{name}",
+ {"preProvisioningHook": {"targetArn": _FLEET_HOOK_ARN}},
+ )
+ assert status == 200
+
+
+def test_fleet_provisioning_hook_gets_the_request_and_overrides_its_parameters(monkeypatch):
+ """The hook gets the device's parameters before the template is resolved, and its overrides win."""
+ from ministack.services import iot as iot_module
+ from ministack.services import lambda_svc
+
+ iot_module.reset()
+ reset()
+ events = _fleet_hook(monkeypatch, {
+ "override": {"body": {"allowProvisioning": True, "parameterOverrides": {
+ "ThingName": "fleet-o", "ThingTypeName": "fleet-type"}}},
+ "supply": {"body": {"allowProvisioning": True, "parameterOverrides": {
+ "SerialNumber": 7, "Color": True}}},
+ })
+
+ async def _run():
+ await _fleet_setup({"fleet": _fleet_template(), "fleet-cdk": _fleet_cdk_template(
+ {"AttributePayload": "DO_NOTHING", "ThingGroups": "DO_NOTHING",
+ "ThingTypeName": "DO_NOTHING"})})
+ await _fleet_request("POST", "/thing-types/fleet-type", {})
+ await _fleet_request("POST", "/thing-groups/fleet-group", {})
+ await _fleet_hook_templates("fleet", "fleet-cdk")
+ session, sent = await _fleet_client(
+ "fleet-claim", ["fleet", "fleet-cdk"], certificate_id=_FLEET_CLAIM_ID
+ )
+ created = await _fleet_certificate(session, sent)
+ token = created["certificateOwnershipToken"]
+
+ parameters = {"ThingName": "fleet-x", "ThingTypeName": "fleet-other",
+ "ThingGroup": "fleet-group", "Mode": "override"}
+ reply = await _fleet_publish(
+ session, sent, _fleet_provision_topic("fleet-cdk"), _fleet_register(token, **parameters)
+ )
+ assert reply == (
+ f"{_fleet_provision_topic('fleet-cdk')}/accepted",
+ {"deviceConfiguration": {}, "thingName": "fleet-o"},
+ )
+ assert events == [{
+ "claimCertificateId": _FLEET_CLAIM_ID,
+ "clientId": "fleet-claim",
+ "certificateId": created["certificateId"],
+ "certificatePem": created["certificatePem"],
+ "templateArn": f"arn:aws:iot:{_FLEET_REGION}:{_FLEET_ACCOUNT}:provisioningtemplate/fleet-cdk",
+ "parameters": parameters,
+ }]
+ assert await _fleet_thing("fleet-o") == ({}, "fleet-type", ["fleet-group"])
+ assert await _fleet_thing("fleet-x") is None
+
+ reply = await _fleet_publish(
+ session, sent, _fleet_provision_topic("fleet"), _fleet_register(token, Mode="supply")
+ )
+ assert reply[1]["thingName"] == "fleet-7"
+ assert events[-1]["parameters"] == {"Mode": "supply"}
+ assert await _fleet_thing("fleet-7") == ({"serial": "7", "color": "true"}, None, [])
+ await session.cleanup()
+
+ try:
+ asyncio.run(_run())
+ finally:
+ lambda_svc._functions.clear()
+ iot_module.reset()
+ reset()
+
+
+def test_fleet_provisioning_hook_answers(monkeypatch):
+ """Each hook answer gets its reply; a rejected request creates nothing, and the token is checked first."""
+ from ministack.services import iot as iot_module
+ from ministack.services import lambda_svc
+
+ iot_module.reset()
+ reset()
+ invalid = (400, "InvalidResult", "Provisioning hook result is in an invalid format.")
+ denied = (403, "AccessDenied", "Access Denied")
+ cases = {
+ "deny": ({"allowProvisioning": False}, denied),
+ "string-false": ({"allowProvisioning": "false"}, denied),
+ "zero": ({"allowProvisioning": 0}, denied),
+ "no-allow": ({"parameterOverrides": {"Color": "blue"}}, invalid),
+ "yes": ({"allowProvisioning": "yes"}, invalid),
+ "http": ({"statusCode": 400, "body": "{}"}, invalid),
+ "string": ("allow", invalid),
+ "overrides-string": ({"allowProvisioning": True, "parameterOverrides": "Color=blue"}, invalid),
+ "overrides-nested": (
+ {"allowProvisioning": True, "parameterOverrides": {"Color": {"a": "b"}}}, invalid),
+ "null": (None, (400, "InvalidResult", "The provisioning hook did not return a response.")),
+ "null-override": ({"allowProvisioning": True, "parameterOverrides": {"Color": None}},
+ (400, "InvalidParameters", "Cannot resolve reference value: Color")),
+ }
+ answers = {mode: {"body": answer} for mode, (answer, _reply) in cases.items()}
+ answers["raise"] = {"body": {"errorMessage": "boom", "errorType": "RuntimeError"}, "error": True}
+ answers["raw"] = {"body": b'"allow"'}
+ for mode, answer in (("true", "true"), ("upper", "TRUE"), ("one", 1)):
+ answers[mode] = {"body": {"allowProvisioning": answer}}
+ answers["extra"] = {"body": {"allowProvisioning": True, "extra": 1}}
+ events = _fleet_hook(monkeypatch, answers)
+
+ async def _run():
+ await _fleet_setup({"fleet": _fleet_template()})
+ await _fleet_hook_templates("fleet")
+ session, sent = await _fleet_client("fleet-claim", ["fleet"])
+ created = await _fleet_certificate(session, sent)
+ token, provision = created["certificateOwnershipToken"], _fleet_provision_topic("fleet")
+
+ reply = await _fleet_publish(
+ session, sent, provision, _fleet_register("made-up", SerialNumber="SN0", Mode="deny"))
+ assert reply[1]["errorCode"] == "InvalidCertificateOwnershipToken"
+ assert events == []
+ reply = await _fleet_publish(session, sent, provision, _fleet_register(token, Mode="deny"))
+ assert reply == (f"{provision}/rejected",
+ {"statusCode": 403, "errorCode": "AccessDenied", "errorMessage": "Access Denied"})
+ expected = {
+ **{mode: reply for mode, (_answer, reply) in cases.items()},
+ "raise": (400, "InvocationError", "The provisioning hook was not executed successfully."),
+ "raw": invalid,
+ }
+ for mode, (status, code, message) in expected.items():
+ reply = await _fleet_publish(
+ session, sent, provision, _fleet_register(token, SerialNumber=f"SN-{mode}", Mode=mode))
+ assert reply == (f"{provision}/rejected",
+ {"statusCode": status, "errorCode": code, "errorMessage": message}), mode
+ assert await _fleet_thing(f"fleet-SN-{mode}") is None
+ assert await _fleet_certificate_state(created["certificateId"]) == (
+ "PENDING_ACTIVATION", [], [],
+ )
+ for mode in ("true", "upper", "one", "extra"):
+ reply = await _fleet_publish(
+ session, sent, provision, _fleet_register(token, SerialNumber=f"SN-{mode}", Mode=mode))
+ assert reply == (f"{provision}/accepted",
+ {"deviceConfiguration": {"greeting": "hello"}, "thingName": f"fleet-SN-{mode}"})
+ assert len(events) == len(expected) + 5
+ await session.cleanup()
+
+ try:
+ asyncio.run(_run())
+ finally:
+ lambda_svc._functions.clear()
+ iot_module.reset()
+ reset()
+
+
+def test_fleet_provisioning_hook_time_limit_and_permission(monkeypatch):
+ """A slow hook fails the request without holding up the broker; one that may not be invoked is not."""
+ from ministack.services import iot as iot_module
+ from ministack.services import lambda_svc
+
+ iot_module.reset()
+ reset()
+ monkeypatch.setattr(iot_module, "_PROVISIONING_HOOK_SECONDS", 0.2)
+
+ def _slow():
+ time.sleep(0.6)
+ return {"body": {"allowProvisioning": True}}
+
+ events = _fleet_hook(monkeypatch, {"slow": _slow})
+
+ async def _run():
+ await _fleet_setup({"fleet": _fleet_template()})
+ await _fleet_hook_templates("fleet")
+ session, sent = await _fleet_client("fleet-claim", ["fleet"])
+ token = (await _fleet_certificate(session, sent))["certificateOwnershipToken"]
+ provision = _fleet_provision_topic("fleet")
+
+ started = time.monotonic()
+ reply = await _fleet_publish(
+ session, sent, provision, _fleet_register(token, SerialNumber="SN1", Mode="slow"))
+ assert time.monotonic() - started < 0.5
+ assert reply == (f"{provision}/rejected", {
+ "statusCode": 400, "errorCode": "InvocationError",
+ "errorMessage": "A failure occurred while invoking the provisioning hook.",
+ })
+ assert await _fleet_thing("fleet-SN1") is None
+
+ refused = (f"{provision}/rejected", {
+ "statusCode": 400, "errorCode": "InvocationError",
+ "errorMessage": "Access denied while invoking Lambda function",
+ })
+ with iot_module.request_scope(_FLEET_ACCOUNT, _FLEET_REGION):
+ lambda_svc._remove_permission("fleet-hook", "iot", {})
+ reply = await _fleet_publish(
+ session, sent, provision, _fleet_register(token, SerialNumber="SN2", Mode="slow"))
+ assert reply == refused
+ lambda_svc._functions.clear()
+ reply = await _fleet_publish(
+ session, sent, provision, _fleet_register(token, SerialNumber="SN3", Mode="slow"))
+ assert reply == refused
+ assert len(events) == 1
+ await session.cleanup()
+
+ try:
+ asyncio.run(_run())
+ finally:
+ lambda_svc._functions.clear()
+ iot_module.reset()
+ reset()
+
+
def test_fleet_provisioning_claims_and_tokens_are_scoped_persisted_and_expire():
"""Claims and ownership tokens are scoped to one account and region, persist, expire, and go with reset()."""
import ssl as _ssl
diff --git a/tests/test_iot_data.py b/tests/test_iot_data.py
index 5c49cdae..1d75fcec 100644
--- a/tests/test_iot_data.py
+++ b/tests/test_iot_data.py
@@ -4238,6 +4238,78 @@ def test_mtls_auth_provisioning_claim_is_held_to_its_templates_topics(tmp_path):
_terminate(proc)
+# Names the thing after its certificate and keeps the device's thing type.
+_PROVISIONING_HOOK_HANDLER = (
+ "def handler(event, context):\n"
+ " return {'allowProvisioning': True, 'parameterOverrides': {\n"
+ " 'ThingName': 'dev-' + event['certificateId'][:12],\n"
+ " 'ThingTypeName': event['parameters']['ThingTypeName']}}\n"
+)
+
+
+def test_mtls_provisioning_hook_names_the_thing(broker, tmp_path):
+ """A pre-provisioning hook Lambda names the thing that the device did not name."""
+ iot, lam = broker.client("iot"), broker.client("lambda")
+ name = _unique("fleet")
+ iot.create_thing_type(thingTypeName=f"{name}-type")
+ buf = _io.BytesIO()
+ with _zipfile.ZipFile(buf, "w") as z:
+ z.writestr("index.py", _PROVISIONING_HOOK_HANDLER)
+ 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"}}]}))
+ hook = 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",
+ )
+ iot.create_provisioning_template(
+ templateName=name,
+ templateBody=json.dumps({
+ "Parameters": {"ThingName": {"Type": "String"}, "ThingTypeName": {"Type": "String"}},
+ "Resources": {
+ "thing": {"Type": "AWS::IoT::Thing", "OverrideSettings": {
+ "AttributePayload": "DO_NOTHING", "ThingGroups": "DO_NOTHING",
+ "ThingTypeName": "DO_NOTHING"}, "Properties": {
+ "ThingName": {"Ref": "ThingName"}, "ThingTypeName": {"Ref": "ThingTypeName"},
+ "AttributePayload": {}, "ThingGroups": []}},
+ "certificate": {"Type": "AWS::IoT::Certificate", "Properties": {
+ "CertificateId": {"Ref": "AWS::IoT::Certificate::Id"}, "Status": "Active"}},
+ },
+ }),
+ enabled=True,
+ provisioningRoleArn="arn:aws:iam::000000000000:role/provisioning",
+ preProvisioningHook={"targetArn": hook},
+ )
+ claim = iot.create_provisioning_claim(templateName=name)
+ create, provision = "$aws/certificates/create/json", f"$aws/provisioning-templates/{name}/provision/json"
+
+ peer = _Peer(_mtls_connect(broker, claim["certificatePem"], claim["keyPair"]["PrivateKey"], tmp_path))
+ try:
+ _assert_connack(peer.connect(_unique("claim")))
+ peer.subscribe(f"{create}/+", packet_id=1)
+ peer.subscribe(f"{provision}/+", packet_id=2)
+ peer.send(_make_publish(create, b"", qos=1, packet_id=3))
+ topic, payload = peer.next_publish()
+ assert topic == f"{create}/accepted"
+ created = json.loads(payload)
+ peer.send(_make_publish(provision, json.dumps({
+ "certificateOwnershipToken": created["certificateOwnershipToken"],
+ "parameters": {"ThingTypeName": f"{name}-type"},
+ }).encode(), qos=1, packet_id=4))
+ thing = "dev-" + created["certificateId"][:12]
+ assert peer.next_publish(timeout=10) == (
+ f"{provision}/accepted",
+ json.dumps({"deviceConfiguration": {}, "thingName": thing}).encode(),
+ )
+ finally:
+ peer.close()
+ assert iot.describe_thing(thingName=thing)["thingTypeName"] == f"{name}-type"
+
+
def test_mtls_jitr_certificate_is_listed_by_its_ca(broker, tmp_path):
"""As measured on AWS, ListCertificatesByCA lists the certificate that
just-in-time registration created, while it is still PENDING_ACTIVATION."""