Skip to content

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

feat(iot): MQTT over TLS on 8883, inside the iot service (#1422)

iot-rocket38b8597f669e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d0b2fe84..9b3be612 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+- **IoT Core — native mTLS MQTT listener on port 8883** — the embedded broker spoke MQTT only over WebSocket, so AWS IoT Device SDK binaries could not connect. The broker now also listens for MQTT over TLS on port 8883 (`IOT_MTLS_ENABLED=0` turns it off, `IOT_MTLS_PORT` moves it), on by default when `cryptography` is available, configured exactly like the Transfer Family SFTP listener. The broker certificate is minted from the local CA (`GET /_ministack/iot/ca.pem`). The client certificate is optional and follows the rule S3 applies to a presigned URL: a client that presents none is served under `MINISTACK_ACCOUNT_ID`, exactly like an unsigned MQTT-over-WebSocket upgrade, while one that presents a certificate has it read against the registry. Registered `ACTIVE` in exactly one account serves that account and region; unknown, not `ACTIVE`, or `ACTIVE` in several accounts is refused with a "not authorized" CONNACK (0x05, reason code 0x87 for MQTT 5 clients), so `UpdateCertificate` to `INACTIVE` cuts a device off the way it does on AWS. Contributed by @iot-rocket.
+
## [1.4.20] — 2026-08-19
### Added
diff --git a/README.md b/README.md
index 30cfd30f..4686d382 100644
--- a/README.md
+++ b/README.md
@@ -585,8 +585,8 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i
| **CodeBuild** | CreateProject, BatchGetProjects, ListProjects, UpdateProject, DeleteProject, StartBuild, BatchGetBuilds, StopBuild, ListBuilds, ListBuildsForProject, BatchDeleteBuilds | 11 actions; project and build metadata stored in-memory; builds complete immediately with SUCCEEDED status by default. Set `MINISTACK_CODEBUILD_EXECUTE=1` and mount the Docker socket to **really run them**: the project's inline buildspec goes to the official AWS CodeBuild local agent, which runs the phases in `environment.image`, and `BatchGetBuilds` reports live `phases` with a real `SUCCEEDED`/`FAILED` outcome. Execution needs the workspace shared with the host at the **same path** (`-v /tmp/ministack-codebuild:/tmp/ministack-codebuild`), because the agent bind-mounts it into the build container; a build gets `AWS_ENDPOINT_URL` pointing back at MiniStack, honours `timeoutInMinutes`, and is stopped by `StopBuild`. An executed build streams the agent output into its `logs.groupName` / `logs.streamName`, so `aws logs tail` reads the build log back |
| **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 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); 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 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 |
| **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. |
@@ -806,6 +806,8 @@ end-to-end without any client config.
| `RDS_PERSIST` | `0` | Set `1` to use Docker named volumes for RDS containers instead of tmpfs. Storage grows dynamically with no fixed cap |
| `MINISTACK_RDS_PUBLIC_ENDPOINT` | `0` | Set `1` when MiniStack itself runs in a Docker container but RDS clients connect from outside that network (remote MiniStack host, host-side clients, CI runners). `DescribeDBInstances` then returns `{MINISTACK_HOST, host_port}` — the externally-reachable host-published port — instead of the container-internal address. Set `MINISTACK_HOST` to the host clients will use |
| `MINISTACK_RDS_PG_CLUSTER_REPLICATION` | `0` | Set `1` to give the second and later members of an Aurora PostgreSQL cluster their own hot-standby containers streaming from the writer (real read-only replicas; the cluster `ReaderEndpoint` resolves to one when available). Requires `DOCKER_NETWORK`. Off: all members alias the writer's single shared container |
+| `IOT_MTLS_ENABLED` | _(unset = on)_ | Set `0` to stop the IoT mTLS MQTT listener from binding (same shape as `SFTP_ENABLED`). It is on whenever `cryptography` is installed |
+| `IOT_MTLS_PORT` | `8883` | Port of the IoT mTLS MQTT listener. Device SDK binaries connect here with the local CA from `GET /_ministack/iot/ca.pem` as their trust store. The client certificate is optional: without one the session runs under `MINISTACK_ACCOUNT_ID`, with one it must be registered `ACTIVE` in exactly one account (which then serves it) or the connection is refused with a "not authorized" CONNACK (0x05, or reason code 0x87 for MQTT 5) |
| `DSQL_BASE_PORT` | `25432` | Starting host port for Aurora DSQL cluster proxies (one port per cluster) |
| `DSQL_STRICT` | `0` | Set `1` to run a real Postgres container per DSQL cluster (requires Docker; capped by a fixed port window off `DSQL_BASE_PORT`, default 30 — further clusters are metadata-only stubs). Default `0` is control-plane-only |
| `DSQL_PG_IMAGE` | `postgres:16-alpine` | Image used for per-cluster DSQL backend containers |
diff --git a/ministack/app.py b/ministack/app.py
index 7d79a0f1..edefc34c 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -2020,6 +2020,27 @@ async def _handle_lifespan(scope, receive, send):
await transfer.sftp_start()
except Exception as e:
logger.warning("Transfer SFTP startup failed: %s", e)
+ # Start the IoT mTLS MQTT listener, for the same reason and in the
+ # same place: it mints its server certificate from the Local CA and
+ # attributes devices via the certificate registry, both of which
+ # come out of persistence. On by default (port 8883) when
+ # cryptography is available, like the SFTP listener;
+ # IOT_MTLS_ENABLED=0 turns it off and IOT_MTLS_PORT moves it. The
+ # opt-out skips the iot import for the same reason SFTP's does:
+ # nothing else this boot may need the module, and importing it
+ # costs heap.
+ _iot_mtls_env = os.environ.get("IOT_MTLS_ENABLED", "").strip().lower()
+ if _iot_mtls_env in ("0", "false", "no", "off"):
+ logger.debug(
+ "IOT_MTLS_ENABLED=%s — skipping iot module import.", _iot_mtls_env
+ )
+ else:
+ try:
+ from ministack.services import iot as _iot_svc
+
+ await _iot_svc.mtls_start()
+ except Exception as e:
+ logger.warning("IoT mTLS listener startup failed: %s", e)
# Start DSQL wire proxies for clusters restored from persistence.
# Guarded on the module already being loaded (i.e. it had state
# or was used this boot) so we never import dsql just for this.
@@ -2061,6 +2082,12 @@ async def _handle_lifespan(scope, receive, send):
await transfer.sftp_stop()
except Exception as e:
logger.debug("Transfer SFTP shutdown error: %s", e)
+ _iot_mod = sys.modules.get("ministack.services.iot")
+ if _iot_mod is not None:
+ try:
+ await _iot_mod.mtls_stop()
+ except Exception as e:
+ logger.debug("IoT mTLS shutdown error: %s", e)
_stop_docker_containers()
await send({"type": "lifespan.shutdown.complete"})
return
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index b6c890ec..ae2eab3a 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -52,6 +52,7 @@ import json
import logging
import os
import re
+import ssl
import struct
import time
import uuid
@@ -63,6 +64,7 @@ from ministack.core.persistence import load_state
from ministack.core.responses import (
AccountRegionScopedDict,
_request_account_id,
+ _request_region,
error_response_json,
get_account_id,
get_region,
@@ -136,6 +138,27 @@ def get_ca_cert_pem() -> str:
return cert_pem
+# Server certificate for the mTLS MQTT listener (the broker's TCP transport,
+# further down in this file). Persisted alongside the CA in the same snapshot:
+# a device that pinned the broker's chain keeps working across restarts,
+# exactly like the client certificates the CA signed.
+_mtls_server_cert_pem: str | None = None
+_mtls_server_key_pem: str | None = None
+
+
+def get_mtls_server_cert() -> tuple[str | None, str | None]:
+ """Return the persisted (cert_pem, key_pem) of the mTLS listener, if any."""
+ return _mtls_server_cert_pem, _mtls_server_key_pem
+
+
+def set_mtls_server_cert(cert_pem: str, key_pem: str) -> None:
+ """Record a freshly minted mTLS listener certificate for persistence."""
+ global _mtls_server_cert_pem, _mtls_server_key_pem
+ with _CA_LOCK:
+ _mtls_server_cert_pem = cert_pem
+ _mtls_server_key_pem = key_pem
+
+
# ---------------------------------------------------------------------------
# Broker state
# ---------------------------------------------------------------------------
@@ -210,12 +233,19 @@ def get_state() -> dict:
"ca": {"ca_cert_pem": _ca_cert_pem, "ca_key_pem": _ca_key_pem}
if _ca_cert_pem and _ca_key_pem
else {},
+ "mtls_server": {
+ "cert_pem": _mtls_server_cert_pem,
+ "key_pem": _mtls_server_key_pem,
+ }
+ if _mtls_server_cert_pem and _mtls_server_key_pem
+ else {},
"mqtt_broker": _broker_get_state(),
}
def restore_state(data: dict | None) -> None:
global _ca_cert_pem, _ca_key_pem
+ global _mtls_server_cert_pem, _mtls_server_key_pem
if not data:
return
_things.update(data.get("things", {}))
@@ -239,11 +269,20 @@ def restore_state(data: dict | None) -> None:
_ca_cert_pem = cert
_ca_key_pem = key
logger.info("Local CA: restored from persisted state")
+ mtls_data = data.get("mtls_server")
+ if mtls_data:
+ cert = mtls_data.get("cert_pem")
+ key = mtls_data.get("key_pem")
+ if cert and key:
+ with _CA_LOCK:
+ _mtls_server_cert_pem = cert
+ _mtls_server_key_pem = key
_broker_restore_state(data.get("mqtt_broker"))
def reset() -> None:
global _ca_cert_pem, _ca_key_pem
+ global _mtls_server_cert_pem, _mtls_server_key_pem
_things.clear()
_thing_types.clear()
_thing_groups.clear()
@@ -263,6 +302,16 @@ def reset() -> None:
with _CA_LOCK:
_ca_cert_pem = None
_ca_key_pem = None
+ _mtls_server_cert_pem = None
+ _mtls_server_key_pem = None
+ # The mTLS listener's server certificate and trust anchors were minted from
+ # the CA we just dropped, so it has to re-bind with fresh material. Cheap
+ # when the listener never started: with no bound loop the call returns
+ # immediately.
+ try:
+ mtls_schedule_restart()
+ except Exception:
+ logger.debug("IoT mTLS: restart after reset failed", exc_info=True)
try:
@@ -5324,6 +5373,7 @@ MQTT_5 = 5
# MQTT 3.1.1 CONNACK return codes (§3.2.2.3).
CONNACK_311_ACCEPTED = 0x00
CONNACK_311_UNACCEPTABLE_PROTOCOL_VERSION = 0x01
+CONNACK_311_NOT_AUTHORIZED = 0x05
# MQTT 5 reason codes, only the ones this broker produces (§2.4). Success and
# Normal disconnection share the value 0x00.
@@ -5331,6 +5381,7 @@ RC5_SUCCESS = 0x00
RC5_NO_MATCHING_SUBSCRIBERS = 0x10
RC5_NO_SUBSCRIPTION_EXISTED = 0x11
RC5_MALFORMED_PACKET = 0x81
+RC5_NOT_AUTHORIZED = 0x87
RC5_SESSION_TAKEN_OVER = 0x8E
RC5_TOPIC_NAME_INVALID = 0x90
@@ -6278,6 +6329,28 @@ class _WSSession:
)
+async def _feed_session(session: _WSSession, data: bytes, max_buffer: int) -> bool:
+ """Push raw MQTT bytes into ``session`` and dispatch every complete packet.
+
+ Returns False when the connection must be dropped — either the accumulated
+ frame buffer blew past ``max_buffer`` or a packet handler asked to stop
+ (DISCONNECT, invalid publish topic). Shared by the WebSocket transport and
+ the optional mTLS TCP listener; ``_take_packet`` does the framing, so both
+ transports see identical semantics for partial and coalesced packets.
+ """
+ session._buffer.extend(data)
+ if len(session._buffer) > max_buffer:
+ _broker_logger.warning("IoT broker: frame buffer overflow, dropping connection")
+ return False
+ while True:
+ pkt = session._take_packet()
+ if pkt is None:
+ return True
+ pkt_type, flags, body = pkt
+ if not await session.handle_packet(pkt_type, flags, body):
+ return False
+
+
async def handle_websocket(
scope: dict, receive, send, account_id: str, region: str
) -> None:
@@ -6322,18 +6395,8 @@ async def handle_websocket(
if text is None:
continue
continue
- session._buffer.extend(data)
- if len(session._buffer) > max_buffer:
- _broker_logger.warning("IoT broker: WS buffer overflow, dropping connection")
+ if not await _feed_session(session, data, max_buffer):
break
- while True:
- pkt = session._take_packet()
- if pkt is None:
- break
- pkt_type, flags, body = pkt
- cont = await session.handle_packet(pkt_type, flags, body)
- if not cont:
- return
except Exception:
_broker_logger.exception("IoT broker WebSocket session failed")
finally:
@@ -6346,3 +6409,584 @@ async def handle_websocket(
await send({"type": "websocket.close", "code": 1000})
except Exception:
pass
+
+
+# ---------------------------------------------------------------------------
+# mTLS MQTT listener — the broker's TCP transport
+# ---------------------------------------------------------------------------
+# The broker above speaks MQTT over WebSocket on the gateway port, which real
+# device binaries built on the AWS IoT Device SDK cannot use: they open a plain
+# TCP socket, present a client certificate, and speak MQTT directly. This
+# listener is that transport. Everything above the socket is the same broker —
+# ``_WSSession`` handles framing and packet semantics unchanged, fed through
+# ``_feed_session`` exactly like the WebSocket path.
+#
+# On by default at port 8883 (the MQTT-over-TLS port AWS uses), configured the
+# way the Transfer Family SFTP listener is: it starts when the optional
+# ``cryptography`` package is importable, ``IOT_MTLS_ENABLED=0`` turns it off,
+# and ``IOT_MTLS_PORT`` moves it. A port that cannot be bound (8883 is a
+# popular port, a local broker may already hold it) degrades to a log line
+# rather than failing the boot.
+#
+# The listener's server certificate is minted from the Local CA (the one that
+# signs ``CreateKeysAndCertificate`` leaves, served at
+# ``GET /_ministack/iot/ca.pem``), so a device trusting that one file verifies
+# the broker.
+#
+# The client certificate is OPTIONAL and the rule for it is the one S3 already
+# applies to a presigned URL: a request carrying no credential is served, and
+# a request carrying one that does not hold up is refused. Concretely:
+#
+# * no client certificate: the session runs under ``MINISTACK_ACCOUNT_ID``,
+# exactly like an unsigned MQTT-over-WebSocket upgrade. Nothing is required
+# of a caller that claims nothing.
+# * a certificate registered ACTIVE in exactly one account: that account and
+# region serve the session, which is what gives a device fleet per-tenant
+# isolation without any credential handling.
+# * a certificate that is unknown, not ACTIVE, or ACTIVE in several accounts:
+# refused with a "not authorized" MQTT CONNACK. This reads the X.509
+# identity lifecycle that the registry already keeps and that the control plane already
+# enforces (deleting an ACTIVE certificate is CertificateStateException
+# 406), so it is not policy evaluation and not a credential check; a
+# deactivated certificate stops working, which is what makes deactivation
+# mean anything and what real AWS IoT does. The ambiguous case cannot be
+# attributed at all: two registrations see byte-identical bytes, so any
+# tie-break would award the session to whoever registered the copy.
+#
+# The TLS layer adds one constraint of its own: a presented chain is verified,
+# so a certificate from a CA the listener does not trust fails the handshake
+# before any of the above. The trusted set is the Local CA plus every ACTIVE
+# CA in the registry.
+
+_MTLS_DEFAULT_PORT = 8883
+_MTLS_READ_CHUNK = 65536
+# How long a client whose certificate was refused gets to send its CONNECT
+# before the connection is dropped without a CONNACK.
+_MTLS_REFUSE_READ_TIMEOUT = 5.0
+_MTLS_REFUSE_MAX_BYTES = 8192
+
+_mtls_logger = logging.getLogger("iot_mtls")
+_mtls_server: asyncio.AbstractServer | None = None
+_mtls_loop: asyncio.AbstractEventLoop | None = None
+_mtls_lock = asyncio.Lock()
+# Every live connection's writer, so that stopping the listener can close them
+# deliberately and in bounded time (see ``mtls_stop``).
+_mtls_sessions: set[asyncio.StreamWriter] = set()
+# Digests of the trust anchors already loaded into the live TLS context;
+# emptied whenever a context is built, since a fresh one starts with none.
+_mtls_loaded_anchors: set[str] = set()
+
+import importlib.util as _importlib_util
+
+_CRYPTOGRAPHY_AVAILABLE = _importlib_util.find_spec("cryptography") is not None
+
+
+def _mtls_is_truthy(value: str) -> bool:
+ return value.strip().lower() in ("1", "true", "yes", "on")
+
+
+def _mtls_port() -> int | None:
+ """The listener port, or None when the configured value is unusable."""
+ raw = os.environ.get("IOT_MTLS_PORT", "").strip()
+ if not raw:
+ return _MTLS_DEFAULT_PORT
+ try:
+ port = int(raw)
+ except ValueError:
+ _mtls_logger.warning(
+ "IoT mTLS: IOT_MTLS_PORT=%r is not a number; listener disabled", raw
+ )
+ return None
+ if not 0 < port < 65536:
+ _mtls_logger.warning(
+ "IoT mTLS: IOT_MTLS_PORT=%d is not a usable port; listener disabled", port
+ )
+ return None
+ return port
+
+
+def mtls_enabled() -> bool:
+ """True when the listener should run.
+
+ The same two conditions the SFTP listener uses, in the same order: the
+ optional dependency has to be importable (no ``cryptography`` means no CA
+ to mint a server certificate from, so the listener stays off rather than
+ failing the boot), and ``IOT_MTLS_ENABLED`` has to be unset or truthy.
+ """
+ if not _CRYPTOGRAPHY_AVAILABLE:
+ return False
+ raw = os.environ.get("IOT_MTLS_ENABLED")
+ if raw is not None and not _mtls_is_truthy(raw):
+ return False
+ return _mtls_port() is not None
+
+
+def _mtls_server_cert_sans() -> tuple[list[str], list[str]]:
+ """(dns_names, ip_addresses) for the listener's certificate.
+
+ Device SDKs verify the broker hostname, so the certificate carries every
+ name a device plausibly dials: the loopbacks, this machine's hostname (the
+ name compose networks resolve a container by), and ``MINISTACK_HOST``.
+ """
+ import ipaddress
+ import socket as _socket
+
+ dns_names = ["localhost"]
+ ip_addresses = ["127.0.0.1", "::1"]
+ candidates = [os.environ.get("MINISTACK_HOST", "localhost"), _socket.gethostname()]
+ for candidate in candidates:
+ if not candidate:
+ continue
+ try:
+ ipaddress.ip_address(candidate)
+ except ValueError:
+ if candidate not in dns_names:
+ dns_names.append(candidate)
+ else:
+ if candidate not in ip_addresses:
+ ip_addresses.append(candidate)
+ return dns_names, ip_addresses
+
+
+def _mtls_cert_is_reusable(cert_pem: str, ca_cert_pem: str) -> bool:
+ """True when a persisted server certificate still matches the current CA
+ and still covers every configured name."""
+ from cryptography import x509
+
+ # The CA subject name is a constant, so issuer equality alone would also
+ # accept a leaf signed by a *previous* CA generation — which is exactly
+ # what a reset leaves behind. certificate_is_signed_by verifies the
+ # signature as well.
+ if not certificate_is_signed_by(cert_pem, ca_cert_pem):
+ return False
+ try:
+ leaf = x509.load_pem_x509_certificate(cert_pem.encode("utf-8"))
+ san = leaf.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
+ present = {str(v) for v in san.get_values_for_type(x509.DNSName)}
+ present |= {str(v) for v in san.get_values_for_type(x509.IPAddress)}
+ wanted_dns, wanted_ips = _mtls_server_cert_sans()
+ return set(wanted_dns) <= present and set(wanted_ips) <= present
+ except Exception:
+ return False
+
+
+def _mtls_ensure_server_cert() -> tuple[str, str]:
+ """Return the listener's (cert_pem, key_pem), minting one when needed.
+
+ A persisted certificate is reused as long as the current CA signed it and
+ it still carries every configured SAN, so devices keep their pinned chain
+ across restarts.
+ """
+ from ministack.core.x509_utils import sign_leaf_certificate
+
+ ca_cert_pem, ca_key_pem = _ensure_ca()
+ cert_pem, key_pem = get_mtls_server_cert()
+ if cert_pem and key_pem and _mtls_cert_is_reusable(cert_pem, ca_cert_pem):
+ return cert_pem, key_pem
+
+ dns_names, ip_addresses = _mtls_server_cert_sans()
+ cert_pem, key_pem, _public_pem = sign_leaf_certificate(
+ ca_cert_pem,
+ ca_key_pem,
+ common_name="Ministack IoT Broker",
+ san_dns=dns_names,
+ san_ips=ip_addresses,
+ )
+ set_mtls_server_cert(cert_pem, key_pem)
+ _mtls_logger.info(
+ "IoT mTLS: issued broker certificate for %s", ", ".join(dns_names + ip_addresses)
+ )
+ return cert_pem, key_pem
+
+
+def _mtls_registered_ca_pems() -> list[str]:
+ """ACTIVE CA certificates from the CA registry, across every scope.
+
+ The store is scoped by account and region; a single listener serves every
+ tenant, so it is read across all scopes. Only ACTIVE CAs qualify:
+ registering a CA without activating it is how AWS says "not yet", and
+ honouring that keeps ``UpdateCACertificate`` meaningful for connections
+ opened after it.
+ """
+ pems = []
+ for record in list(_ca_certificates._data.values()):
+ if not isinstance(record, dict) or record.get("status") != "ACTIVE":
+ continue
+ pem = record.get("certificatePem")
+ if isinstance(pem, str) and pem.strip():
+ pems.append(pem)
+ return pems
+
+
+def _mtls_trust_anchors() -> list[str]:
+ """CAs whose client certificates verify at the TLS layer: the Local CA plus
+ every ACTIVE registered CA. Presenting a certificate is optional, so this
+ set only decides which presented chains survive the handshake; who a
+ session belongs to is decided afterwards, in ``_mtls_serve_conn``."""
+ return [get_ca_cert_pem(), *_mtls_registered_ca_pems()]
+
+
+def _mtls_refresh_trust_anchors(ctx: ssl.SSLContext) -> None:
+ """Load every anchor the context does not already have.
+
+ Anchors are loaded one PEM at a time so that a single unparseable
+ registered certificate costs only itself, and each is remembered — by
+ digest, including the ones that failed — so a handshake never repeats the
+ work or the warning. ``load_verify_locations`` is additive and a live
+ context cannot forget an anchor, so a CA deactivated after loading stays
+ trusted at the TLS layer until ``reset()`` rebinds; the session-attribution
+ lookup still runs per connection.
+ """
+ for pem in _mtls_trust_anchors():
+ digest = hashlib.sha256(pem.encode("utf-8")).hexdigest()
+ if digest in _mtls_loaded_anchors:
+ continue
+ _mtls_loaded_anchors.add(digest)
+ try:
+ ctx.load_verify_locations(cadata=pem)
+ except Exception as e:
+ _mtls_logger.warning("IoT mTLS: ignoring an unusable trust anchor: %s", e)
+
+
+def _mtls_on_client_hello(
+ ssl_object: ssl.SSLObject, server_name: str | None, ctx: ssl.SSLContext
+) -> None:
+ """Pull newly registered CAs in mid-handshake, before the peer is verified.
+
+ A CA registered while the listener is bound has to be trusted without a
+ restart, and ``sni_callback`` is the only hook that runs late enough to see
+ the current registry yet early enough to matter. It runs on every
+ handshake, including those carrying no server name — which is what a
+ device dialling the broker by IP sends. An exception here aborts the
+ handshake with an internal-error alert, so nothing is allowed to escape.
+ """
+ try:
+ _mtls_refresh_trust_anchors(ctx)
+ except Exception:
+ _mtls_logger.warning("IoT mTLS: trust-anchor refresh failed", exc_info=True)
+
+
+def _mtls_build_ssl_context() -> ssl.SSLContext:
+ import tempfile
+
+ ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ ctx.minimum_version = ssl.TLSVersion.TLSv1_2
+ # Optional, not required: the WebSocket path accepts any client, and this
+ # transport keeps that default. A presented certificate is verified (that
+ # is the TLS layer's rule, not ours) and then used purely as a tenancy
+ # signal; absence of one falls back the same way an unsigned WS upgrade
+ # does.
+ ctx.verify_mode = ssl.CERT_OPTIONAL
+ cert_pem, key_pem = _mtls_ensure_server_cert()
+ # load_cert_chain only takes paths; a combined cert+key file is the least
+ # material to leave on disk, and it is unlinked before the handshake.
+ with tempfile.NamedTemporaryFile("w", suffix=".pem", delete=False) as fh:
+ fh.write(cert_pem)
+ fh.write(key_pem)
+ chain_path = fh.name
+ try:
+ ctx.load_cert_chain(chain_path)
+ finally:
+ try:
+ os.unlink(chain_path)
+ except OSError:
+ pass
+ _mtls_loaded_anchors.clear()
+ _mtls_refresh_trust_anchors(ctx)
+ ctx.sni_callback = _mtls_on_client_hello
+ return ctx
+
+
+async def mtls_start() -> None:
+ """Idempotent: bind the mTLS MQTT listener, unless disabled."""
+ if not mtls_enabled():
+ _mtls_logger.info("IoT mTLS: disabled (cryptography missing or IOT_MTLS_ENABLED=0)")
+ return
+ async with _mtls_lock:
+ await _mtls_start_locked()
+
+
+async def mtls_stop() -> None:
+ """Close the listener and, with it, the sessions running on it.
+
+ Bounded by construction, whatever is connected: the listening socket is
+ closed synchronously and each live connection is aborted, so nothing here
+ waits on a peer to acknowledge anything.
+
+ Note what is deliberately *not* here — ``await server.wait_closed()``.
+ Since Python 3.12.1 that waits for every established connection to finish
+ as well as for the acceptor, which for a broker means "until the last
+ device disconnects", i.e. indefinitely. Awaiting it while holding the lock
+ wedged both callers: ``lifespan.shutdown`` hung with a device attached, and
+ a ``reset()`` rebind never reached its start half.
+
+ Devices are disconnected rather than left running: on shutdown the process
+ is going away, and on ``reset()`` the CA that signed their certificates has
+ just been dropped. Device SDKs reconnect on their own.
+ """
+ async with _mtls_lock:
+ await _mtls_stop_locked()
+
+
+async def _mtls_start_locked() -> None:
+ global _mtls_server, _mtls_loop
+ if _mtls_server is not None:
+ return
+ port = _mtls_port()
+ if port is None:
+ return
+ try:
+ # Building the context can mint the server certificate — and, on first
+ # boot, the CA — which is RSA keygen, so keep it off the event loop.
+ ctx = await asyncio.to_thread(_mtls_build_ssl_context)
+ except Exception as e:
+ _mtls_logger.warning(
+ "IoT mTLS: could not build the TLS context (%s); listener unavailable", e
+ )
+ return
+ try:
+ _mtls_server = await asyncio.start_server(
+ _mtls_handle_conn, host="0.0.0.0", port=port, ssl=ctx
+ )
+ except OSError as e:
+ _mtls_logger.warning(
+ "IoT mTLS: failed to bind port %d (%s); listener unavailable", port, e
+ )
+ _mtls_server = None
+ return
+ _mtls_loop = asyncio.get_running_loop()
+ _mtls_logger.info(
+ "IoT mTLS: MQTT listening on port %d (client certificate optional)", port
+ )
+
+
+async def _mtls_stop_locked() -> None:
+ global _mtls_server
+ if _mtls_server is None and not _mtls_sessions:
+ return
+ if _mtls_server is not None:
+ try:
+ _mtls_server.close()
+ except Exception as e:
+ _mtls_logger.debug("IoT mTLS: error closing the listener: %s", e)
+ _mtls_server = None
+ for writer in list(_mtls_sessions):
+ try:
+ # abort(), not close(): closing a TLS transport sends close_notify
+ # and then waits for the peer's, which a device that has stopped
+ # reading never sends — the same unbounded wait this function
+ # exists to avoid, just one layer down.
+ writer.transport.abort()
+ except Exception as e:
+ _mtls_logger.debug("IoT mTLS: error closing a session: %s", e)
+ _mtls_sessions.clear()
+ _mtls_loaded_anchors.clear()
+ _mtls_logger.info("IoT mTLS: stopped")
+
+
+async def _mtls_restart() -> None:
+ """Rebind with fresh TLS material, under a single lock acquisition, so two
+ resets in flight cannot interleave and no connection is accepted against
+ half-replaced material."""
+ try:
+ async with _mtls_lock:
+ await _mtls_stop_locked()
+ if mtls_enabled():
+ await _mtls_start_locked()
+ except Exception:
+ _mtls_logger.warning("IoT mTLS: restart failed", exc_info=True)
+
+
+def mtls_schedule_restart() -> None:
+ """Rebind the listener with fresh TLS material, from any thread.
+
+ ``reset()`` runs in a worker thread, so it cannot await; it hands the
+ restart back to the event loop the listener was bound on. The rebind
+ disconnects whatever was attached: the CA those sessions were admitted on
+ no longer exists.
+ """
+ loop = _mtls_loop
+ if loop is None or loop.is_closed():
+ return
+ try:
+ loop.call_soon_threadsafe(lambda: asyncio.ensure_future(_mtls_restart()))
+ except RuntimeError as e:
+ _mtls_logger.debug("IoT mTLS: could not schedule a restart: %s", e)
+
+
+def _mtls_active_registrations(cert_id: str) -> list[tuple[str, str, dict]]:
+ """Every (account_id, region, record) holding this certificate ACTIVE."""
+ return [
+ (account_id, region, record)
+ for (account_id, region, key), record in list(_certificates._data.items())
+ if key == cert_id and isinstance(record, dict) and record.get("status") == "ACTIVE"
+ ]
+
+
+def _mtls_refusal_reason(cert_id: str) -> str:
+ """Why a presented certificate was refused, for the log line, including the
+ ambiguous case, which is the one an operator needs spelled out."""
+ active = _mtls_active_registrations(cert_id)
+ if len(active) > 1:
+ scopes = ", ".join(f"{a}/{r}" for a, r, _record in sorted(active, key=lambda m: m[:2]))
+ return f"registered ACTIVE in {len(active)} scopes ({scopes}); owner is ambiguous"
+ for (_account_id, _region, key), record in list(_certificates._data.items()):
+ if key == cert_id and isinstance(record, dict):
+ return f"status {record.get('status')!r}"
+ return "not registered"
+
+
+def _mtls_resolve_identity(der: bytes | None) -> tuple[str, str] | None:
+ """Map a peer certificate (or none) to (account_id, region), or None.
+
+ None means "this connection is refused". Presenting no certificate is not
+ refused: that caller claims nothing and is served under the default
+ account, the same way ``_ws_resolve_iot_account_id`` treats an unsigned
+ WebSocket upgrade. A certificate that IS presented is read against the
+ registry, which is the identity lifecycle this service already keeps:
+ ACTIVE in exactly one account selects it, and unknown, not ACTIVE, or
+ ACTIVE in several accounts is refused by the caller with a "not
+ authorized" CONNACK.
+ """
+ if not der:
+ return (
+ os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000"),
+ os.environ.get("MINISTACK_REGION", "us-east-1"),
+ )
+ # Same derivation as x509_utils.get_certificate_id, without a PEM round-trip.
+ cert_id = hashlib.sha256(der).hexdigest()
+ active = _mtls_active_registrations(cert_id)
+ if len(active) == 1:
+ account_id, region, _record = active[0]
+ return account_id, region
+ return None
+
+
+async def _mtls_refuse(
+ reader: asyncio.StreamReader, writer: asyncio.StreamWriter, cert_id: str
+) -> None:
+ """Answer an unusable client certificate with a "not authorized" CONNACK
+ (0x05, or reason code 0x87 for an MQTT 5 client), then close.
+
+ AWS closes the socket without a CONNACK unless just-in-time registration
+ applies. Diverging here is deliberate: an emulator's job is
+ diagnosability, "not authorized" is reported cleanly by every device SDK,
+ and a TLS-layer rejection could not tell the user "unknown" from
+ "deactivated".
+ """
+ _mtls_logger.warning(
+ "IoT mTLS: refusing client certificate %s (%s)", cert_id, _mtls_refusal_reason(cert_id)
+ )
+ buffer = bytearray()
+ try:
+ while len(buffer) < _MTLS_REFUSE_MAX_BYTES:
+ data = await asyncio.wait_for(
+ reader.read(_MTLS_READ_CHUNK), timeout=_MTLS_REFUSE_READ_TIMEOUT
+ )
+ if not data:
+ return
+ buffer.extend(data)
+ if len(buffer) < 2:
+ continue
+ try:
+ remaining, header_end = _decode_remaining_length(bytes(buffer), 1)
+ except ValueError:
+ continue
+ if len(buffer) < header_end + remaining:
+ continue
+ if (buffer[0] >> 4) & 0x0F == PKT_CONNECT:
+ # The CONNACK has to match the client's protocol level: a v5
+ # client handed the two-byte 3.1.1 form dies in its decoder
+ # instead of reporting the refusal, and 0x05 is not a defined
+ # v5 reason code.
+ body = bytes(buffer[header_end:header_end + remaining])
+ try:
+ _proto_name, level_at = _read_string(body, 0)
+ protocol_level = body[level_at]
+ except (ValueError, IndexError):
+ protocol_level = MQTT_311
+ if protocol_level == MQTT_5:
+ connack = _make_connack(
+ return_code=RC5_NOT_AUTHORIZED, protocol_version=MQTT_5
+ )
+ else:
+ connack = _make_connack(return_code=CONNACK_311_NOT_AUTHORIZED)
+ writer.write(connack)
+ await writer.drain()
+ return
+ except (asyncio.TimeoutError, OSError, ssl.SSLError):
+ return
+
+
+async def _mtls_close(writer: asyncio.StreamWriter) -> None:
+ try:
+ writer.close()
+ await writer.wait_closed()
+ except (OSError, ssl.SSLError):
+ pass
+
+
+async def _mtls_handle_conn(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ """Track the connection for as long as it lives, then serve it, so that
+ ``mtls_stop`` can close every peer in bounded time."""
+ _mtls_sessions.add(writer)
+ try:
+ await _mtls_serve_conn(reader, writer)
+ finally:
+ _mtls_sessions.discard(writer)
+
+
+async def _mtls_serve_conn(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ ssl_object = writer.get_extra_info("ssl_object")
+ der = ssl_object.getpeercert(binary_form=True) if ssl_object is not None else None
+ owner = _mtls_resolve_identity(der)
+ if owner is None:
+ try:
+ await _mtls_refuse(reader, writer, hashlib.sha256(der).hexdigest())
+ finally:
+ await _mtls_close(writer)
+ return
+ account_id, region = owner
+
+ async def _tcp_send(message: dict) -> None:
+ """Adapter for the two ASGI messages a session ever sends."""
+ message_type = message.get("type")
+ if message_type == "websocket.send":
+ writer.write(message["bytes"])
+ await writer.drain()
+ elif message_type == "websocket.close":
+ writer.close()
+
+ account_token = _request_account_id.set(account_id)
+ region_token = _request_region.set(region)
+ session = _WSSession(_tcp_send, account_id, region)
+ max_buffer = _max_frame_buffer_bytes()
+ _mtls_logger.info(
+ "IoT mTLS: connection from %s serving %s/%s (%s)",
+ writer.get_extra_info("peername"),
+ account_id,
+ region,
+ "certificate presented" if der else "no client certificate",
+ )
+ try:
+ while True:
+ data = await reader.read(_MTLS_READ_CHUNK)
+ if not data:
+ break
+ if not await _feed_session(session, data, max_buffer):
+ break
+ except (OSError, ssl.SSLError) as e:
+ _mtls_logger.debug("IoT mTLS: connection dropped: %s", e)
+ except Exception:
+ _mtls_logger.exception("IoT mTLS session failed")
+ finally:
+ try:
+ await session.cleanup()
+ except Exception:
+ _mtls_logger.exception("IoT mTLS: session cleanup failed")
+ for var, token in ((_request_account_id, account_token), (_request_region, region_token)):
+ try:
+ var.reset(token)
+ except ValueError:
+ pass
+ await _mtls_close(writer)
diff --git a/tests/conftest.py b/tests/conftest.py
index edbf97ed..f5d2756b 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -232,6 +232,28 @@ _SERIAL_TESTS = {
"tests/test_iot_data.py::test_mqtt5_retain_handling_1_replays_only_for_a_new_subscription",
"tests/test_iot_data.py::test_mqtt5_will_with_properties_fires_on_transport_drop",
"tests/test_iot_data.py::test_mqtt5_malformed_will_properties_answer_connack_0x81",
+ # The mTLS MQTT listener tests (in test_iot_data.py, with the rest of the
+ # broker) drive private MiniStack subprocesses on their own ports rather
+ # than the shared server — the same reason test_tls.py runs its subprocess
+ # tests serially. Several of them time a process's startup, rebind or
+ # shutdown, which is exactly what xdist load makes unreliable.
+ "tests/test_iot_data.py::test_mtls_on_by_default",
+ "tests/test_iot_data.py::test_mtls_disabled_by_env",
+ "tests/test_iot_data.py::test_mtls_connect_and_connack",
+ "tests/test_iot_data.py::test_mtls_subscribe_receives_http_publish",
+ "tests/test_iot_data.py::test_mtls_publish_is_brokered",
+ "tests/test_iot_data.py::test_mtls_no_client_cert_uses_default_account",
+ "tests/test_iot_data.py::test_mtls_unregistered_cert_gets_connack_5",
+ "tests/test_iot_data.py::test_mtls_mqtt5_refusal_is_v5_connack",
+ "tests/test_iot_data.py::test_mtls_inactive_cert_refused",
+ "tests/test_iot_data.py::test_mtls_ambiguous_cert_is_refused",
+ "tests/test_iot_data.py::test_mtls_registered_ca_chain_connects",
+ "tests/test_iot_data.py::test_mtls_account_scoped_delivery",
+ "tests/test_iot_data.py::test_mtls_garbage_bytes_dropped",
+ "tests/test_iot_data.py::test_mtls_duplicate_client_id_evicts_first_connection",
+ "tests/test_iot_data.py::test_mtls_listener_survives_reset",
+ "tests/test_iot_data.py::test_mtls_reset_rebinds_with_a_device_connected",
+ "tests/test_iot_data.py::test_mtls_shutdown_completes_with_a_device_connected",
}
diff --git a/tests/test_iot_data.py b/tests/test_iot_data.py
index 0833b448..811e024b 100644
--- a/tests/test_iot_data.py
+++ b/tests/test_iot_data.py
@@ -15,15 +15,22 @@ import base64
import io as _io
import json
import os
+import socket
+import ssl
import struct
+import subprocess
+import sys
import threading
import time
+import urllib.request
import uuid
import zipfile as _zipfile
from urllib.parse import quote, urlparse
from conftest import patch_endpoint_dns
+import boto3
import pytest
+from botocore.config import Config
from botocore.exceptions import ClientError
ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
@@ -2833,3 +2840,732 @@ def test_mqtt5_malformed_will_properties_answer_connack_0x81():
pkt_type, body = _run(scenario())
assert pkt_type == PKT_CONNACK
assert body[1] == RC5_MALFORMED_PACKET
+
+
+# ---------------------------------------------------------------------------
+# MQTT over TLS (the broker's TCP transport, port 8883)
+# ---------------------------------------------------------------------------
+# The tests below drive private MiniStack processes on free ports (the shape
+# test_tls.py uses) rather than the suite-wide server on 4566: the listener is
+# a process-level socket, and half of what these pin is how it behaves at
+# startup, on reset and at shutdown. They reuse the MQTT codec above, so only
+# the TLS plumbing is new. IOT_MTLS_PORT is pinned per instance because the
+# listener is on by default at 8883 and parallel servers would contend for it.
+
+REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+HYPERCORN_CONF = "file:ministack/core/hypercorn_conf.py"
+MTLS_REGION = "us-east-1"
+
+
+def _free_port() -> int:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.bind(("127.0.0.1", 0))
+ return s.getsockname()[1]
+
+
+def _spawn(env_extra: dict, port: int, log_path=None) -> subprocess.Popen:
+ """Start a private MiniStack. With `log_path`, its output is captured there
+ (combined stdout/stderr) so a test can assert on what it did or did not log.
+
+ The listener is off here by default: it is on by default at 8883, and a
+ fleet of private test servers all reaching for that one port would leave
+ every instance but the first degraded. Tests that want it pass
+ ``IOT_MTLS_ENABLED=1`` plus their own free port; the default-on test
+ removes the key instead.
+ """
+ env = {
+ **os.environ,
+ "LOG_LEVEL": "WARNING",
+ "PERSIST_STATE": "0",
+ "IOT_MTLS_ENABLED": "0",
+ # These private servers must not touch (or reap) Docker containers
+ # belonging to the host or to the shared test server.
+ "DOCKER_HOST": "unix:///nonexistent-skip-reap",
+ **env_extra,
+ }
+ env = {k: v for k, v in env.items() if v is not None}
+ sink = subprocess.DEVNULL if log_path is None else open(log_path, "wb")
+ try:
+ return subprocess.Popen(
+ [sys.executable, "-m", "hypercorn", "ministack.app:app",
+ "-c", HYPERCORN_CONF,
+ "--bind", f"127.0.0.1:{port}",
+ "--log-level", "warning"],
+ env=env,
+ stdout=sink,
+ stderr=subprocess.STDOUT,
+ cwd=REPO_ROOT,
+ )
+ finally:
+ if sink is not subprocess.DEVNULL:
+ sink.close()
+
+
+def _wait_health(url: str, timeout: float = 30.0) -> None:
+ deadline = time.time() + timeout
+ last = None
+ while time.time() < deadline:
+ try:
+ urllib.request.urlopen(url, timeout=2)
+ return
+ except Exception as e:
+ last = e
+ time.sleep(0.3)
+ raise AssertionError(f"{url} did not come up within {timeout}s: {last!r}")
+
+
+def _terminate(proc: subprocess.Popen) -> None:
+ proc.terminate()
+ try:
+ proc.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait(timeout=5)
+
+
+class _Broker:
+ """A private MiniStack instance with the mTLS listener bound."""
+
+ def __init__(self, http_port: int, mqtt_port: int, log_path=None):
+ self.http_port = http_port
+ self.mqtt_port = mqtt_port
+ self.log_path = log_path
+ self.url = f"http://127.0.0.1:{http_port}"
+
+ def log(self) -> str:
+ """This instance's captured output. Why the listener refused a
+ certificate is only visible here, and it is part of what it promises.
+ """
+ assert self.log_path is not None, "this instance was spawned without capture"
+ return self.log_path.read_text(errors="replace")
+
+ def client(self, service: str, access_key: str = "test"):
+ return boto3.client(
+ service,
+ endpoint_url=self.url,
+ aws_access_key_id=access_key,
+ aws_secret_access_key="test",
+ region_name=MTLS_REGION,
+ config=Config(region_name=MTLS_REGION, retries={"max_attempts": 0}),
+ )
+
+ def ca_pem(self) -> str:
+ with urllib.request.urlopen(f"{self.url}/_ministack/iot/ca.pem", timeout=5) as resp:
+ return resp.read().decode("utf-8")
+
+
[email protected](scope="module")
+def broker(tmp_path_factory):
+ # The importorskip sits in the fixture rather than at module scope: the
+ # rest of this file needs no X.509 machinery.
+ pytest.importorskip("cryptography")
+ http_port = _free_port()
+ mqtt_port = _free_port()
+ log_path = tmp_path_factory.mktemp("mtls-broker") / "server.log"
+ proc = _spawn(
+ {"IOT_MTLS_ENABLED": "1", "IOT_MTLS_PORT": str(mqtt_port)}, http_port, log_path=log_path
+ )
+ try:
+ _wait_health(f"http://127.0.0.1:{http_port}/_ministack/health")
+ yield _Broker(http_port, mqtt_port, log_path)
+ finally:
+ _terminate(proc)
+
+
+# ---------------------------------------------------------------------------
+# Certificates and TLS client
+# ---------------------------------------------------------------------------
+
+
+def _new_cert(broker: _Broker, access_key: str = "test", set_active: bool = True):
+ """CreateKeysAndCertificate under `access_key`'s account."""
+ resp = broker.client("iot", access_key).create_keys_and_certificate(setAsActive=set_active)
+ return resp["certificateId"], resp["certificatePem"], resp["keyPair"]["PrivateKey"]
+
+
+def _client_context(broker: _Broker, cert_pem: str | None, key_pem: str | None, tmp_path):
+ ctx = ssl.create_default_context(cadata=broker.ca_pem())
+ if cert_pem is not None:
+ chain = tmp_path / f"{uuid.uuid4().hex}.pem"
+ chain.write_text(cert_pem + key_pem)
+ ctx.load_cert_chain(str(chain))
+ return ctx
+
+
+def _mtls_connect(broker: _Broker, cert_pem, key_pem, tmp_path, timeout: float = 10.0):
+ """Open a TLS socket to the listener, verifying the broker's chain."""
+ ctx = _client_context(broker, cert_pem, key_pem, tmp_path)
+ raw = socket.create_connection(("127.0.0.1", broker.mqtt_port), timeout=timeout)
+ # `server_hostname` is checked against the certificate's SANs, so this also
+ # pins that the broker certificate carries a usable `localhost` name.
+ return ctx.wrap_socket(raw, server_hostname="localhost")
+
+
+def _split_publish(body: bytes) -> tuple[str, bytes]:
+ topic_len = struct.unpack_from("!H", body, 0)[0]
+ return body[2:2 + topic_len].decode("utf-8"), body[2 + topic_len:]
+
+
+class _Peer:
+ """A connected MQTT client over the TLS socket."""
+
+ def __init__(self, sock):
+ self.sock = sock
+ self.buf = bytearray()
+ # Retained messages are delivered from inside broker_subscribe, i.e.
+ # *before* the SUBACK — park any PUBLISH seen while waiting for an ack.
+ self.publishes: list[tuple[str, bytes]] = []
+
+ def send(self, data: bytes) -> None:
+ self.sock.sendall(data)
+
+ def next_packet(self, timeout: float = 5.0):
+ """Return the next (type, flags, body), or None on EOF/timeout."""
+ deadline = time.time() + timeout
+ while True:
+ parsed = _parse_packet(bytes(self.buf))
+ if parsed is not None:
+ ptype, flags, body, consumed = parsed
+ del self.buf[:consumed]
+ return ptype, flags, body
+ remaining = deadline - time.time()
+ if remaining <= 0:
+ return None
+ self.sock.settimeout(remaining)
+ try:
+ chunk = self.sock.recv(4096)
+ except (socket.timeout, ssl.SSLError):
+ return None
+ if not chunk:
+ return None
+ self.buf.extend(chunk)
+
+ def connect(self, client_id: str, timeout: float = 5.0):
+ self.send(_make_connect(client_id))
+ return self.next_packet(timeout=timeout)
+
+ def subscribe(self, topic: str, packet_id: int = 1, timeout: float = 5.0):
+ """Send SUBSCRIBE and return the SUBACK packet."""
+ self.send(_make_subscribe(packet_id, topic))
+ deadline = time.time() + timeout
+ while True:
+ pkt = self.next_packet(timeout=max(0.0, deadline - time.time()))
+ if pkt is None:
+ return None
+ ptype, _flags, body = pkt
+ if ptype == PKT_PUBLISH:
+ self.publishes.append(_split_publish(body))
+ continue
+ return pkt
+
+ def next_publish(self, timeout: float = 5.0):
+ """Return (topic, payload) of the next PUBLISH, or None."""
+ if self.publishes:
+ return self.publishes.pop(0)
+ deadline = time.time() + timeout
+ while True:
+ pkt = self.next_packet(timeout=max(0.0, deadline - time.time()))
+ if pkt is None:
+ return None
+ ptype, _flags, body = pkt
+ if ptype != PKT_PUBLISH:
+ continue
+ return _split_publish(body)
+
+ def wait_disconnected(self, timeout: float = 5.0) -> bool:
+ """True once the broker has hung up. Distinct from `next_packet`
+ returning None, which is also what a quiet-but-live session looks like.
+ """
+ deadline = time.time() + timeout
+ while True:
+ remaining = deadline - time.time()
+ if remaining <= 0:
+ return False
+ self.sock.settimeout(remaining)
+ try:
+ if not self.sock.recv(4096):
+ return True
+ except (socket.timeout, TimeoutError):
+ return False
+ except OSError:
+ # A TLS alert or a reset instead of a clean close: still a hangup.
+ return True
+
+ def close(self) -> None:
+ try:
+ self.sock.close()
+ except OSError:
+ pass
+
+
+def _refused_below_mqtt(broker, cert_pem, key_pem, tmp_path, client_id: str) -> bool:
+ """True when the listener refuses this certificate before MQTT begins.
+
+ TLS 1.3 lets the server finish its half of the handshake before it has
+ verified the client's certificate, so a refusal reaches the client only
+ after it already believes it is connected — as an alert, as a broken pipe,
+ or as a silent EOF, depending on timing. Asserting on any one of those
+ shapes pins the platform rather than the behaviour; what the listener
+ actually promises is that no CONNACK comes back.
+ """
+ try:
+ peer = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ except OSError:
+ return True
+ try:
+ return peer.connect(client_id) is None
+ except OSError:
+ return True
+ finally:
+ peer.close()
+
+
+def _assert_connack(pkt, return_code: int = 0) -> None:
+ assert pkt is not None, "no CONNACK received"
+ ptype, _flags, body = pkt
+ assert ptype == PKT_CONNACK, f"expected CONNACK, got packet type {ptype}"
+ assert body[1] == return_code, f"CONNACK return code {body[1]}, expected {return_code}"
+
+
+# ---------------------------------------------------------------------------
+# Tests
+# ---------------------------------------------------------------------------
+
+
+def test_mtls_on_by_default(tmp_path):
+ """Without IOT_MTLS_PORT the listener reaches for 8883 on its own.
+
+ The default port may legitimately be taken (another instance on the same
+ machine, this very suite's shared server), and a busy port degrades to a
+ log line by design — so the assertion is on the attempt: the log names
+ port 8883, either listening or failing to bind, without anyone setting a
+ variable. When the bind did succeed, a TCP probe pins that it is real.
+ """
+ pytest.importorskip("cryptography")
+ log = tmp_path / "default-on.log"
+ http_port = _free_port()
+ proc = _spawn({"LOG_LEVEL": "INFO", "IOT_MTLS_ENABLED": None}, http_port, log_path=log)
+ try:
+ _wait_health(f"http://127.0.0.1:{http_port}/_ministack/health")
+ text = log.read_text(errors="replace")
+ listening = "MQTT listening on port 8883" in text
+ degraded = "failed to bind port 8883" in text
+ assert listening or degraded, f"no default-on attempt in the log:\n{text}"
+ if listening:
+ with socket.create_connection(("127.0.0.1", 8883), timeout=5):
+ pass
+ finally:
+ _terminate(proc)
+
+
+def test_mtls_disabled_by_env(tmp_path):
+ """IOT_MTLS_ENABLED=0 switches the listener off entirely, the way
+ SFTP_ENABLED does for the Transfer Family listener — down to the lifespan
+ skipping the iot module import, which is the line asserted on."""
+ log = tmp_path / "disabled.log"
+ http_port = _free_port()
+ proc = _spawn({"LOG_LEVEL": "DEBUG"}, http_port, log_path=log)
+ try:
+ _wait_health(f"http://127.0.0.1:{http_port}/_ministack/health")
+ text = log.read_text(errors="replace")
+ assert "skipping iot module import" in text, f"no opt-out line in the log:\n{text}"
+ assert "MQTT listening on port" not in text
+ finally:
+ _terminate(proc)
+
+
+def test_mtls_connect_and_connack(broker, tmp_path):
+ """A CA-signed, ACTIVE certificate connects and gets CONNACK 0."""
+ _cert_id, cert_pem, key_pem = _new_cert(broker)
+ peer = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ try:
+ _assert_connack(peer.connect(_unique("device")))
+ finally:
+ peer.close()
+
+
+def test_mtls_subscribe_receives_http_publish(broker, tmp_path):
+ """An HTTP `iot-data publish` reaches a subscriber on the TLS transport."""
+ _cert_id, cert_pem, key_pem = _new_cert(broker)
+ topic = _unique("mtls/http")
+ peer = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ try:
+ _assert_connack(peer.connect(_unique("device")))
+ ptype, _flags, _body = peer.subscribe(topic)
+ assert ptype == PKT_SUBACK
+
+ broker.client("iot-data").publish(topic=topic, payload=b"from-http")
+ assert peer.next_publish() == (topic, b"from-http")
+ finally:
+ peer.close()
+
+
+def test_mtls_publish_is_brokered(broker, tmp_path):
+ """A PUBLISH over TLS goes through the broker: retained, then replayed to a
+ second TLS subscriber."""
+ _cert_id, cert_pem, key_pem = _new_cert(broker)
+ topic = _unique("mtls/retained")
+
+ publisher = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ try:
+ _assert_connack(publisher.connect(_unique("publisher")))
+ publisher.send(_make_publish(topic, b"sticky", retain=True))
+ # PUBLISH has no ack at QoS 0; give the broker a moment to store it.
+ time.sleep(0.5)
+ finally:
+ publisher.close()
+
+ subscriber = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ try:
+ _assert_connack(subscriber.connect(_unique("subscriber")))
+ subscriber.subscribe(topic)
+ assert subscriber.next_publish() == (topic, b"sticky")
+ finally:
+ subscriber.close()
+
+
+def test_mtls_no_client_cert_uses_default_account(broker, tmp_path):
+ """No client certificate connects fine, exactly like the WebSocket path,
+ and the session runs under the default account."""
+ topic = _unique("mtls/anonymous")
+ peer = _Peer(_mtls_connect(broker, None, None, tmp_path))
+ try:
+ _assert_connack(peer.connect(_unique("anonymous")))
+ peer.subscribe(topic)
+
+ broker.client("iot-data", access_key="111111111111").publish(
+ topic=topic, payload=b"someone-else"
+ )
+ assert peer.next_publish(timeout=2.0) is None, "leaked across accounts"
+
+ broker.client("iot-data", access_key="000000000000").publish(
+ topic=topic, payload=b"default-account"
+ )
+ assert peer.next_publish() == (topic, b"default-account")
+ finally:
+ peer.close()
+
+
+def test_mtls_unregistered_cert_gets_connack_5(broker, tmp_path):
+ """A certificate the registry does not know is refused, not served.
+
+ Presenting a certificate is a claim of identity, so it is read against the
+ registry; the no-certificate case above is the one that gets the default
+ account.
+ """
+ cert_id, cert_pem, key_pem = _new_cert(broker)
+ iot = broker.client("iot")
+ iot.update_certificate(certificateId=cert_id, newStatus="INACTIVE")
+ iot.delete_certificate(certificateId=cert_id)
+
+ peer = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ try:
+ _assert_connack(peer.connect(_unique("ghost")), return_code=5)
+ assert peer.next_packet(timeout=3.0) is None, "expected the broker to close"
+ finally:
+ peer.close()
+ refusals = [line for line in broker.log().splitlines() if cert_id in line]
+ assert refusals and "not registered" in refusals[-1], refusals
+
+
+def test_mtls_mqtt5_refusal_is_v5_connack(broker, tmp_path):
+ """An MQTT 5 client refused over TLS gets a *v5* CONNACK.
+
+ Reason code 0x87 ("Not authorized") plus a property block — not the
+ two-byte 3.1.1 form, which a v5 SDK's decoder would die on instead of
+ reporting the refusal.
+ """
+ cert_id, cert_pem, key_pem = _new_cert(broker)
+ iot = broker.client("iot")
+ iot.update_certificate(certificateId=cert_id, newStatus="INACTIVE")
+ iot.delete_certificate(certificateId=cert_id)
+
+ peer = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ try:
+ peer.send(_make_connect(_unique("ghost-v5"), protocol_level=MQTT_5))
+ pkt = peer.next_packet(timeout=5.0)
+ assert pkt is not None, "no CONNACK received"
+ ptype, _flags, body = pkt
+ assert ptype == PKT_CONNACK, f"expected CONNACK, got packet type {ptype}"
+ assert body[1] == 0x87, f"reason code {body[1]:#x}, expected 0x87 (not authorized)"
+ assert len(body) >= 3 and body[2] == 0x00, "v5 CONNACK property block missing"
+ finally:
+ peer.close()
+
+
+def test_mtls_inactive_cert_refused(broker, tmp_path):
+ """Deactivating a certificate cuts the device off.
+
+ This is the lifecycle the control plane already enforces (an ACTIVE
+ certificate cannot be deleted, `CertificateStateException` 406), read at
+ connect time: without it, `UpdateCertificate` to INACTIVE would mean
+ nothing on the wire.
+ """
+ cert_id, cert_pem, key_pem = _new_cert(broker, access_key="111111111111")
+ iot = broker.client("iot", access_key="111111111111")
+
+ peer = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ try:
+ _assert_connack(peer.connect(_unique("before-deactivation")))
+ finally:
+ peer.close()
+
+ iot.update_certificate(certificateId=cert_id, newStatus="INACTIVE")
+
+ peer = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ try:
+ _assert_connack(peer.connect(_unique("deactivated")), return_code=5)
+ finally:
+ peer.close()
+
+ iot.update_certificate(certificateId=cert_id, newStatus="ACTIVE")
+
+ peer = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ try:
+ _assert_connack(peer.connect(_unique("reactivated")))
+ finally:
+ peer.close()
+
+
+def test_mtls_ambiguous_cert_is_refused(broker, tmp_path):
+ """A certificate two accounts hold ACTIVE is refused, not awarded.
+
+ `RegisterCertificate` accepts any PEM from any caller, so 222222222222 can
+ register a copy of 111111111111's device certificate. Both registrations
+ see byte-identical bytes, so a tie-break would decide the tenancy by
+ something like account-id order, handing the device's session to whoever
+ registered the copy. The connection is refused instead, the log names both
+ scopes, and the device is back on its own account once only one
+ registration is left ACTIVE.
+ """
+ cert_id, cert_pem, key_pem = _new_cert(broker, access_key="111111111111")
+
+ peer = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ try:
+ _assert_connack(peer.connect(_unique("before-the-copy")))
+ finally:
+ peer.close()
+
+ hijacker = broker.client("iot", access_key="222222222222")
+ hijacker.register_certificate(certificatePem=cert_pem, setAsActive=True)
+
+ peer = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ try:
+ _assert_connack(peer.connect(_unique("contested")), return_code=5)
+ finally:
+ peer.close()
+
+ # A refusal an operator cannot explain is the failure mode this listener
+ # exists to avoid, and "your certificate is registered twice" is not a
+ # guess anyone makes unaided, so the log names the reason and both scopes.
+ refusals = [line for line in broker.log().splitlines() if cert_id in line]
+ assert refusals, "the refusal was not logged"
+ assert "ambiguous" in refusals[-1], refusals[-1]
+ assert "111111111111/us-east-1" in refusals[-1], refusals[-1]
+ assert "222222222222/us-east-1" in refusals[-1], refusals[-1]
+
+ hijacker.update_certificate(certificateId=cert_id, newStatus="INACTIVE")
+
+ peer = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ try:
+ _assert_connack(peer.connect(_unique("uncontested-again")))
+ finally:
+ peer.close()
+
+
+def test_mtls_registered_ca_chain_connects(broker, tmp_path):
+ """A leaf signed by a CA registered through the API connects.
+
+ The listener reads its trust anchors out of the IoT CA registry on every
+ handshake, so this pins both properties that follow from that: a CA
+ registered long after the listener bound is trusted without a restart, and
+ only an ACTIVE one is.
+ """
+ from ministack.core.x509_utils import generate_ca, sign_leaf_certificate
+
+ iot = broker.client("iot")
+ ca_pem, ca_key = generate_ca(common_name="Registered Device CA")
+ ca_id = iot.register_ca_certificate(caCertificate=ca_pem, setAsActive=False)[
+ "certificateId"
+ ]
+ leaf_pem, leaf_key, _public = sign_leaf_certificate(
+ ca_pem, ca_key, common_name="registered-ca-device"
+ )
+ iot.register_certificate(
+ certificatePem=leaf_pem, caCertificatePem=ca_pem, setAsActive=True
+ )
+
+ # The leaf itself is registered ACTIVE, so its CA's status is the only thing
+ # left that can refuse it — and an untrusted anchor is refused by TLS,
+ # below MQTT.
+ assert _refused_below_mqtt(
+ broker, leaf_pem, leaf_key, tmp_path, _unique("too-early")
+ ), "a leaf signed by an INACTIVE CA reached the broker"
+
+ iot.update_ca_certificate(certificateId=ca_id, newStatus="ACTIVE")
+
+ peer = _Peer(_mtls_connect(broker, leaf_pem, leaf_key, tmp_path))
+ try:
+ _assert_connack(peer.connect(_unique("registered-ca-device")))
+ finally:
+ peer.close()
+
+
+def test_mtls_account_scoped_delivery(broker, tmp_path):
+ """The client certificate decides the tenant: a device whose certificate is
+ owned by 111111111111 sees that account's traffic and nobody else's."""
+ _cert_id, cert_pem, key_pem = _new_cert(broker, access_key="111111111111")
+ topic = _unique("mtls/tenant")
+
+ peer = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ try:
+ _assert_connack(peer.connect(_unique("tenant-device")))
+ peer.subscribe(topic)
+
+ broker.client("iot-data", access_key="000000000000").publish(
+ topic=topic, payload=b"other-tenant"
+ )
+ assert peer.next_publish(timeout=2.0) is None, "leaked across accounts"
+
+ broker.client("iot-data", access_key="111111111111").publish(
+ topic=topic, payload=b"own-tenant"
+ )
+ assert peer.next_publish() == (topic, b"own-tenant")
+ finally:
+ peer.close()
+
+
+def test_mtls_garbage_bytes_dropped(broker, tmp_path):
+ """Junk after the handshake kills that connection only."""
+ _cert_id, cert_pem, key_pem = _new_cert(broker)
+ junk = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ try:
+ junk.send(bytes([0xFF]) * 64)
+ junk.send(os.urandom(256))
+ junk.next_packet(timeout=2.0)
+ finally:
+ junk.close()
+
+ peer = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ try:
+ _assert_connack(peer.connect(_unique("after-junk")))
+ finally:
+ peer.close()
+
+
+def test_mtls_duplicate_client_id_evicts_first_connection(broker, tmp_path):
+ """A second CONNECT with the same client id closes the first socket — the
+ session adapter's `websocket.close` translation."""
+ _cert_id, cert_pem, key_pem = _new_cert(broker)
+ client_id = _unique("twin")
+
+ first = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ second = None
+ try:
+ _assert_connack(first.connect(client_id))
+ second = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ _assert_connack(second.connect(client_id))
+ assert first.next_packet(timeout=5.0) is None, "first connection should be closed"
+ finally:
+ first.close()
+ if second is not None:
+ second.close()
+
+
+def _await_rebind(broker, tmp_path, client_id: str, timeout: float = 15.0) -> None:
+ """Block until a certificate minted from the current CA gets CONNACK 0.
+
+ The rebind after a reset is scheduled on the event loop from reset's worker
+ thread, so it lands some time after the HTTP call returns; until it does,
+ the listener is either down or still serving the previous CA's certificate.
+ Failing this is what "the listener did not come back" looks like.
+ """
+ deadline = time.time() + timeout
+ last_error: Exception | None = None
+ while time.time() < deadline:
+ try:
+ _cert_id, cert_pem, key_pem = _new_cert(broker)
+ peer = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ try:
+ _assert_connack(peer.connect(_unique(client_id)))
+ return
+ finally:
+ peer.close()
+ except (ssl.SSLError, OSError, AssertionError) as e:
+ last_error = e
+ time.sleep(0.5)
+ raise AssertionError(
+ f"listener did not come back within {timeout}s after reset: {last_error!r}"
+ )
+
+
+def _reset(broker, timeout: float = 10.0) -> None:
+ urllib.request.urlopen(
+ urllib.request.Request(f"{broker.url}/_ministack/reset", data=b"", method="POST"),
+ timeout=timeout,
+ )
+
+
+def test_mtls_listener_survives_reset(broker, tmp_path):
+ """`/_ministack/reset` regenerates the CA; the listener rebinds with fresh
+ material instead of serving a certificate nobody can verify."""
+ _reset(broker)
+ _await_rebind(broker, tmp_path, "post-reset")
+
+
+def test_mtls_reset_rebinds_with_a_device_connected(broker, tmp_path):
+ """A live session does not hold the rebind hostage.
+
+ `asyncio.Server.wait_closed()` waits for established connections as well as
+ for the acceptor since Python 3.12.1, so a stop that awaited it never
+ returned while a device was attached — and since the restart awaited the
+ stop while both shared a lock, the listener stayed down for the life of the
+ process. The connected device is disconnected instead of outliving the CA
+ that admitted it, which is also what makes the rebind bounded.
+ """
+ _cert_id, cert_pem, key_pem = _new_cert(broker)
+ peer = _Peer(_mtls_connect(broker, cert_pem, key_pem, tmp_path))
+ try:
+ _assert_connack(peer.connect(_unique("attached")))
+ _reset(broker)
+ # Asserted before the socket is closed, and with it still open: closing
+ # it first is what un-wedged the old code, so the whole point is that
+ # nothing on the client's side has to happen for the rebind to land.
+ assert peer.wait_disconnected(timeout=10.0), (
+ "the session outlived the CA and the registry entry that admitted it"
+ )
+ _await_rebind(broker, tmp_path, "post-reset-with-device")
+ finally:
+ peer.close()
+
+
+def test_mtls_shutdown_completes_with_a_device_connected(tmp_path):
+ """A connected device does not stop the process from shutting down.
+
+ Same defect as the reset above, on the other caller: `lifespan.shutdown`
+ awaits `mtls_stop`, so an unbounded stop hangs the shutdown and the server
+ only ever dies by SIGKILL. A private instance, because the assertion is
+ about how this one terminates.
+ """
+ pytest.importorskip("cryptography")
+ http_port, mqtt_port = _free_port(), _free_port()
+ proc = _spawn({"IOT_MTLS_ENABLED": "1", "IOT_MTLS_PORT": str(mqtt_port)}, http_port)
+ peer = None
+ try:
+ _wait_health(f"http://127.0.0.1:{http_port}/_ministack/health")
+ private = _Broker(http_port, mqtt_port)
+ _cert_id, cert_pem, key_pem = _new_cert(private)
+ peer = _Peer(_mtls_connect(private, cert_pem, key_pem, tmp_path))
+ _assert_connack(peer.connect(_unique("still-here")))
+
+ proc.terminate()
+ try:
+ proc.wait(timeout=25)
+ except subprocess.TimeoutExpired:
+ raise AssertionError(
+ "the server did not shut down within 25s with a device connected"
+ ) from None
+ finally:
+ if peer is not None:
+ peer.close()
+ _terminate(proc)