Skip to content

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

feat(iot): AWS IoT Core support (Phase 1) (#570)

Johannes Grumböck56fbc4df9b8d
diff --git a/README.md b/README.md
index dc8fa68c..1a7fe9a5 100644
--- a/README.md
+++ b/README.md
@@ -506,6 +506,7 @@ Unsupported resource types fail with `CREATE_FAILED` (or `ROLLBACK_COMPLETE` if
| **CodeBuild** | CreateProject, BatchGetProjects, ListProjects, UpdateProject, DeleteProject, StartBuild, BatchGetBuilds, StopBuild, ListBuilds, ListBuildsForProject, BatchDeleteBuilds | 11 actions; builds complete immediately with SUCCEEDED status; project and build metadata stored in-memory |
| **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, UpdateCertificate, DeleteCertificate, AttachThingPrincipal, DetachThingPrincipal, ListThingPrincipals, ListPrincipalThings, CreatePolicy, CreatePolicyVersion, AttachPolicy, DetachPolicy, ListAttachedPolicies, ListTargetsForPolicy, DescribeEndpoint, Publish (HTTP), MQTT-over-WebSocket pub/sub | 24 operations + **real MQTT 3.1.1 over WebSocket** 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 |
| **EventBridge Scheduler** | CreateSchedule, GetSchedule, UpdateSchedule, DeleteSchedule, ListSchedules, CreateScheduleGroup, GetScheduleGroup, DeleteScheduleGroup, ListScheduleGroups, TagResource, UntagResource, ListTagsForResource | 12 actions; 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, TagResource, UntagResource, ListTagsForResource | 11 operations; `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; 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. |
@@ -981,7 +982,7 @@ Errors map to Lambda's standard error shape so async-invoke retry, DLQ, destinat
│ │ AppSync Cloud Map CodeBuild │ │
│ │ AutoScaling AppConfig EKS │ │
│ │ RDS Data S3 Files Scheduler │ │
- │ │ Transfer Family │ │
+ │ │ Transfer Family IoT Core │ │
│ └────────────────────────────────────┘ │
│ │
│ In-Memory Storage + Optional Docker │
@@ -1218,6 +1219,7 @@ See [`Testcontainers/java-testcontainers`](Testcontainers/java-testcontainers),
| **Cloud Map** | ✅ | ❌ | ✅ |
| **CodeBuild** | ✅ | ✅ | ✅ |
| **Transfer Family** | ✅ | ❌ | ❌ |
+| **IoT Core** | ✅ (control + WS data plane) | ❌ | ✅ (paid tier) |
| **S3 Files** | ✅ | ❌ | ❌ |
| Cost | **Free forever** | Was free, now paid | $35+/mo |
| Docker image size | ~250MB | ~1GB | ~1GB |
diff --git a/ministack/app.py b/ministack/app.py
index 3dc475e6..ea9b261b 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -40,6 +40,52 @@ _EXECUTE_API_RE = re.compile(
)
# AppSync Events realtime WebSocket: {apiId}.appsync-realtime-api.<anything>[:port].
_APPSYNC_REALTIME_RE = re.compile(r"^([a-z0-9]+)\.appsync-realtime-api\.")
+# IoT data plane WebSocket: anything containing ".iot." in the host header.
+# Match all four AWS-shaped variants (data-ats.iot, data.iot, plain iot, plus
+# an account-prefixed iot endpoint as returned by DescribeEndpoint).
+_IOT_DATA_WS_RE = re.compile(r"\.iot\.")
+
+
+def _ws_has_mqtt_subprotocol(ws_headers: dict) -> bool:
+ """Check whether the upgrade request advertises an ``mqtt`` subprotocol."""
+ raw = ws_headers.get("sec-websocket-protocol", "")
+ for proto in (p.strip().lower() for p in raw.split(",") if p.strip()):
+ if proto in ("mqtt", "mqttv3.1", "mqttv5"):
+ return True
+ return False
+
+
+def _ws_resolve_iot_account_id(scope: dict, ws_headers: dict) -> str:
+ """Pick the account ID for an inbound IoT WebSocket upgrade.
+
+ Resolution order:
+
+ 1. ``X-Amz-Credential`` query parameter (SigV4-signed WS) — extract the
+ access key portion. If it's a 12-digit number, use it as the account.
+ 2. ``Authorization: AWS4-HMAC-SHA256`` header — same extraction.
+ 3. Fall back to ``MINISTACK_ACCOUNT_ID`` / ``000000000000``.
+
+ SigV4 signature *verification* is intentionally lax (any
+ well-formed credential is accepted); IoT policy enforcement is not yet
+ feature. The point here is multi-tenancy isolation, not auth.
+ """
+ qs = scope.get("query_string", b"").decode("utf-8", errors="replace")
+ qp = parse_qs(qs, keep_blank_values=True) if qs else {}
+
+ cred = ""
+ raw = qp.get("X-Amz-Credential") or qp.get("x-amz-credential")
+ if raw:
+ cred = raw[0] if isinstance(raw, list) else raw
+ if not cred:
+ auth = ws_headers.get("authorization", "")
+ m = re.search(r"Credential=([^,/]+)/", auth)
+ if m:
+ cred = m.group(1)
+
+ access_key = cred.split("/", 1)[0] if cred else ""
+ if access_key and re.match(r"^\d{12}$", access_key):
+ return access_key
+ return os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
# Virtual-hosted S3 bucket extraction. AWS-aligned per
# docs.aws.amazon.com/AmazonS3/latest/userguide/VirtualHosting.html and
# bucketnamingrules.html (HTTP vhost — ministack is HTTP). Works for any
@@ -84,7 +130,7 @@ def _extract_s3_vhost_bucket(host: str):
if first_tail_segment == "s3" or first_tail_segment.startswith(("s3-", "s3express-")):
return candidate
return None
-_S3_VHOST_EXCLUDE_RE = re.compile(r"\.(execute-api|alb|emr|efs|elasticache|s3-control|appsync-api|appsync-realtime-api)\.")
+_S3_VHOST_EXCLUDE_RE = re.compile(r"\.(execute-api|alb|emr|efs|elasticache|s3-control|appsync-api|appsync-realtime-api|iot)\.")
_HEALTH_PATHS = ("/_ministack/health", "/_localstack/health", "/health")
_BODY_METHODS = ("POST", "PUT", "PATCH")
_COGNITO_USERINFO_PATHS = ("/oauth2/userInfo", "/oauth2/userinfo")
@@ -225,6 +271,8 @@ SERVICE_REGISTRY = {
"airflow": {"module": "mwaa", "aliases": ("mwaa",)},
"iam": {"module": "iam"},
"imds": {"module": "imds"},
+ "iot": {"module": "iot"},
+ "iot-data": {"module": "iot_data"},
"kinesis": {"module": "kinesis"},
"kms": {"module": "kms"},
"lambda": {"module": "lambda_svc"},
@@ -288,7 +336,7 @@ _state_map = {
"eks": "eks", "backup": "backup", "pipes": "pipes",
"cloudfront_keyvaluestore": "cloudfront_keyvaluestore",
"resource_groups": "resource_groups",
- "cloudtrail": "cloudtrail",
+ "cloudtrail": "cloudtrail", "iot": "iot",
}
SERVICE_NAME_ALIASES = {
@@ -332,7 +380,8 @@ BANNER = r"""
SSM, EventBridge, Kinesis, CloudWatch, SES, SES v2, ACM, WAF v2, Step Functions,
ECS, RDS, ElastiCache, Glue, Athena, API Gateway, Firehose, Route53,
Cognito, EC2, EMR, EBS, EFS, ALB/ELBv2, CloudFormation, KMS, ECR, CloudFront,
- AppSync, Cloud Map, S3 Files, RDS Data API, CodeBuild, AppConfig, Transfer, EKS
+ AppSync, Cloud Map, S3 Files, RDS Data API, CodeBuild, AppConfig, Transfer, EKS,
+ IoT Core
"""
@@ -679,9 +728,47 @@ async def _handle_pre_body_request(method: str, path: str, headers: dict, query_
if response is not None:
return response
+ response = _handle_iot_ca_request(method, path)
+ if response is not None:
+ return response
+
return await _handle_admin_reset(path, method, query_params)
+def _handle_iot_ca_request(method: str, path: str):
+ """`GET /_ministack/iot/ca.pem` returns the Local CA root certificate.
+
+ Test code and IoT SDKs use this to configure trust for mTLS connections
+ to the local broker. The CA is generated lazily on first call.
+ """
+ if path != "/_ministack/iot/ca.pem" or method != "GET":
+ return None
+ try:
+ from ministack.services import iot
+
+ cert_pem = iot.get_ca_cert_pem()
+ except RuntimeError as e:
+ return (
+ 503,
+ {"Content-Type": "application/json"},
+ json.dumps({"message": str(e)}).encode(),
+ )
+ except Exception as e:
+ return (
+ 500,
+ {"Content-Type": "application/json"},
+ json.dumps({"message": str(e)}).encode(),
+ )
+ return (
+ 200,
+ {
+ "Content-Type": "application/x-pem-file",
+ "Content-Disposition": "attachment; filename=\"ministack-iot-ca.pem\"",
+ },
+ cert_pem.encode("utf-8"),
+ )
+
+
def _handle_transfer_sftp_ports_request(method: str, path: str):
"""`GET /_ministack/transfer/sftp-ports` returns ``{shared, per_server}``.
@@ -1441,7 +1528,8 @@ async def app(scope, receive, send):
ws_path = scope.get("path", "")
parsed = _parse_execute_api_url(ws_host, ws_path)
appsync_rt_m = _APPSYNC_REALTIME_RE.match(ws_host)
- if not parsed and not appsync_rt_m:
+ iot_ws_m = _IOT_DATA_WS_RE.search(ws_host) and _ws_has_mqtt_subprotocol(ws_headers)
+ if not parsed and not appsync_rt_m and not iot_ws_m:
msg = await receive()
if msg.get("type") == "websocket.connect":
await send({"type": "websocket.close", "code": 1008})
@@ -1452,10 +1540,17 @@ async def app(scope, receive, send):
await _get_module("apigateway").handle_websocket(
scope, receive, send, ws_api_id, path_override=_execute_path,
)
- else:
+ elif appsync_rt_m:
await _get_module("appsync_events").handle_websocket(
scope, receive, send, appsync_rt_m.group(1)
)
+ else:
+ # IoT MQTT-over-WS — resolve account_id from SigV4 query
+ # params or Authorization header, fall back to default.
+ account_id = _ws_resolve_iot_account_id(scope, ws_headers)
+ await _get_module("iot").handle_websocket(
+ scope, receive, send, account_id
+ )
except Exception:
logger.exception("Error in WebSocket dispatch")
try:
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 92f7b437..e0314e86 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -264,6 +264,30 @@ SERVICE_PATTERNS = {
"host_patterns": [r"transfer\."],
"credential_scope": "transfer",
},
+ # IoT data plane (iot-data API) MUST come before "iot" because the host
+ # `data-ats.iot.{region}.{host}` matches both `iot\.` and the more
+ # specific `data-ats\.iot\.` regexes — first-match-wins routing in
+ # detect_service() means we want iot-data to win for data plane traffic.
+ "iot-data": {
+ "host_patterns": [r"data-ats\.iot\.", r"data\.iot\."],
+ "credential_scope": "iotdata",
+ "path_prefixes": ["/topics/", "/retainedMessage"],
+ },
+ "iot": {
+ "host_patterns": [r"iot\."],
+ "credential_scope": "iot",
+ "path_prefixes": [
+ "/things",
+ "/thing-types",
+ "/thing-groups",
+ "/policies",
+ "/certificates",
+ "/keys-and-certificate",
+ "/principals",
+ "/endpoint",
+ "/target-policies",
+ ],
+ },
"appsync": {
"host_patterns": [r"appsync\."],
"path_prefixes": ["/v1/apis", "/v1/tags"],
@@ -413,6 +437,9 @@ def detect_service(method: str, path: str, headers: dict, query_params: dict) ->
"cloudfront": "cloudfront",
"codebuild": "codebuild",
"transfer": "transfer",
+ "iot": "iot",
+ "iotdata": "iot-data",
+ "iotdevicegateway": "iot-data",
"appsync": "appsync",
"servicediscovery": "servicediscovery",
"s3files": "s3files",
diff --git a/ministack/core/x509_utils.py b/ministack/core/x509_utils.py
new file mode 100644
index 00000000..fa80f6c6
--- /dev/null
+++ b/ministack/core/x509_utils.py
@@ -0,0 +1,212 @@
+"""X.509 certificate utilities for Ministack.
+
+Generic crypto helpers for generating self-signed CAs, signing leaf
+certificates, and computing certificate fingerprints. Used by the IoT
+service for its local CA and available for reuse by ACM, API Gateway
+custom domains, or any other service that needs local certificate
+operations.
+
+Requires the ``cryptography`` library (declared as part of ``[full]``
+optional deps). Functions raise ``RuntimeError`` with a clear message
+when it is not importable.
+"""
+
+from __future__ import annotations
+
+import datetime as _dt
+import hashlib
+import logging
+
+logger = logging.getLogger("x509_utils")
+
+try:
+ from cryptography import x509
+ from cryptography.hazmat.primitives import hashes, serialization
+ from cryptography.hazmat.primitives.asymmetric import ec, rsa
+ from cryptography.x509.oid import NameOID
+
+ HAS_CRYPTO = True
+except ImportError: # pragma: no cover - exercised only when extras missing
+ HAS_CRYPTO = False
+
+
+def _require_crypto() -> None:
+ if not HAS_CRYPTO:
+ raise RuntimeError(
+ "ministack.core.x509_utils requires the `cryptography` package. "
+ "Install Ministack with `[full]` extras or add cryptography>=41.0."
+ )
+
+
+def generate_ca(
+ org_name: str = "Ministack",
+ common_name: str = "Ministack Local CA",
+ days_valid: int = 3650,
+) -> tuple[str, str]:
+ """Create a fresh self-signed root CA.
+
+ Args:
+ org_name: Organization name for the CA subject.
+ common_name: Common name for the CA subject.
+ days_valid: Validity period in days.
+
+ Returns:
+ Tuple ``(cert_pem, key_pem)`` as UTF-8 strings.
+ """
+ _require_crypto()
+
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ subject = issuer = x509.Name([
+ x509.NameAttribute(NameOID.ORGANIZATION_NAME, org_name),
+ x509.NameAttribute(NameOID.COMMON_NAME, common_name),
+ ])
+ now = _dt.datetime.now(_dt.timezone.utc)
+ cert = (
+ x509.CertificateBuilder()
+ .subject_name(subject)
+ .issuer_name(issuer)
+ .public_key(key.public_key())
+ .serial_number(x509.random_serial_number())
+ .not_valid_before(now - _dt.timedelta(minutes=1))
+ .not_valid_after(now + _dt.timedelta(days=days_valid))
+ .add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
+ .add_extension(
+ x509.KeyUsage(
+ digital_signature=True,
+ content_commitment=False,
+ key_encipherment=False,
+ data_encipherment=False,
+ key_agreement=False,
+ key_cert_sign=True,
+ crl_sign=True,
+ encipher_only=False,
+ decipher_only=False,
+ ),
+ critical=True,
+ )
+ .add_extension(
+ x509.SubjectKeyIdentifier.from_public_key(key.public_key()),
+ critical=False,
+ )
+ .sign(private_key=key, algorithm=hashes.SHA256())
+ )
+ cert_pem = cert.public_bytes(serialization.Encoding.PEM).decode("utf-8")
+ key_pem = key.private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.TraditionalOpenSSL,
+ encryption_algorithm=serialization.NoEncryption(),
+ ).decode("utf-8")
+ return cert_pem, key_pem
+
+
+def sign_leaf_certificate(
+ ca_cert_pem: str,
+ ca_key_pem: str,
+ common_name: str,
+ san_dns: list[str] | None = None,
+ san_ips: list[str] | None = None,
+ days_valid: int = 825,
+ key_type: str = "rsa2048",
+) -> tuple[str, str, str]:
+ """Generate a fresh keypair and sign a leaf certificate with the given CA.
+
+ Args:
+ ca_cert_pem: CA certificate in PEM format.
+ ca_key_pem: CA private key in PEM format.
+ common_name: Subject CN of the issued certificate.
+ san_dns: Optional list of DNS names to include as SubjectAltName.
+ san_ips: Optional list of IPv4/IPv6 strings to include as SubjectAltName.
+ days_valid: Validity period in days (default 825, AWS-style).
+ key_type: ``"rsa2048"`` (default) or ``"ec256"``.
+
+ Returns:
+ Tuple ``(cert_pem, private_key_pem, public_key_pem)``.
+ """
+ _require_crypto()
+
+ ca_cert = x509.load_pem_x509_certificate(ca_cert_pem.encode("utf-8"))
+ ca_key = serialization.load_pem_private_key(
+ ca_key_pem.encode("utf-8"), password=None
+ )
+
+ if key_type == "ec256":
+ leaf_key = ec.generate_private_key(ec.SECP256R1())
+ elif key_type == "rsa2048":
+ leaf_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ else:
+ raise ValueError(f"Unsupported key_type: {key_type!r}")
+
+ subject = x509.Name([
+ x509.NameAttribute(NameOID.COMMON_NAME, common_name),
+ ])
+ now = _dt.datetime.now(_dt.timezone.utc)
+
+ builder = (
+ x509.CertificateBuilder()
+ .subject_name(subject)
+ .issuer_name(ca_cert.subject)
+ .public_key(leaf_key.public_key())
+ .serial_number(x509.random_serial_number())
+ .not_valid_before(now - _dt.timedelta(minutes=1))
+ .not_valid_after(now + _dt.timedelta(days=days_valid))
+ .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
+ .add_extension(
+ x509.KeyUsage(
+ digital_signature=True,
+ content_commitment=False,
+ key_encipherment=True,
+ data_encipherment=False,
+ key_agreement=False,
+ key_cert_sign=False,
+ crl_sign=False,
+ encipher_only=False,
+ decipher_only=False,
+ ),
+ critical=True,
+ )
+ .add_extension(
+ x509.ExtendedKeyUsage([
+ x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH,
+ x509.oid.ExtendedKeyUsageOID.SERVER_AUTH,
+ ]),
+ critical=False,
+ )
+ )
+
+ san_entries: list[x509.GeneralName] = []
+ for dns in san_dns or []:
+ san_entries.append(x509.DNSName(dns))
+ for ip in san_ips or []:
+ import ipaddress
+
+ san_entries.append(x509.IPAddress(ipaddress.ip_address(ip)))
+ if san_entries:
+ builder = builder.add_extension(
+ x509.SubjectAlternativeName(san_entries), critical=False
+ )
+
+ cert = builder.sign(private_key=ca_key, algorithm=hashes.SHA256())
+
+ cert_pem = cert.public_bytes(serialization.Encoding.PEM).decode("utf-8")
+ private_pem = leaf_key.private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.TraditionalOpenSSL,
+ encryption_algorithm=serialization.NoEncryption(),
+ ).decode("utf-8")
+ public_pem = leaf_key.public_key().public_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PublicFormat.SubjectPublicKeyInfo,
+ ).decode("utf-8")
+ return cert_pem, private_pem, public_pem
+
+
+def get_certificate_id(cert_pem: str) -> str:
+ """Return a stable 64-char hex identifier for a certificate.
+
+ Computed as the SHA-256 fingerprint of the DER encoding so it matches
+ the style of AWS IoT's ``certificateId`` (a SHA-256 hex string).
+ """
+ _require_crypto()
+ cert = x509.load_pem_x509_certificate(cert_pem.encode("utf-8"))
+ der = cert.public_bytes(serialization.Encoding.DER)
+ return hashlib.sha256(der).hexdigest()
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
new file mode 100644
index 00000000..5fdff6af
--- /dev/null
+++ b/ministack/services/iot.py
@@ -0,0 +1,2020 @@
+"""AWS IoT Core control plane emulator.
+
+Implements the JSON/REST APIs under ``iot.{region}.amazonaws.com``:
+
+ - Thing registry: ``CreateThing``, ``DescribeThing``, ``ListThings``,
+ ``UpdateThing``, ``DeleteThing``
+ - ThingType: ``CreateThingType`` and friends
+ - ThingGroup: ``CreateThingGroup`` and friends
+ - Certificates: ``CreateKeysAndCertificate``, ``RegisterCertificate``,
+ ``UpdateCertificate``, ``DeleteCertificate``,
+ ``AttachThingPrincipal`` / ``DetachThingPrincipal``
+ - Policies: ``CreatePolicy``, ``CreatePolicyVersion``, ``AttachPolicy``,
+ ``DetachPolicy``, etc.
+ - ``DescribeEndpoint`` returning a per-account hostname
+
+This is the control plane — pure HTTP/JSON, no MQTT broker
+dependency. The data plane (``iot_data.py``, ``iot_broker.py``) is
+implemented separately and only depends on this module for certificate
+lookups (mTLS).
+
+State is fully isolated per account via ``AccountScopedDict`` and persisted
+through ``get_state``/``restore_state``. The Local CA (used to sign
+``CreateKeysAndCertificate`` certificates) is also persisted so previously
+issued client certificates remain valid across restarts.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import copy
+import hashlib
+import json
+import logging
+import os
+import re
+import struct
+import time
+import uuid
+from datetime import datetime, timezone
+from typing import Awaitable, Callable
+
+from ministack.core.persistence import load_state
+from ministack.core.responses import (
+ AccountScopedDict,
+ _request_account_id,
+ error_response_json,
+ get_account_id,
+ get_region,
+ json_response,
+ new_uuid,
+)
+from ministack.core.x509_utils import (
+ generate_ca,
+ get_certificate_id,
+ sign_leaf_certificate,
+)
+
+logger = logging.getLogger("iot")
+
+_MINISTACK_HOST = os.environ.get("MINISTACK_HOST", "localhost")
+_GATEWAY_PORT = os.environ.get("GATEWAY_PORT", os.environ.get("EDGE_PORT", "4566"))
+
+# Resource name validation per AWS IoT spec: 1..128 chars, [a-zA-Z0-9:_-]
+_NAME_RE = re.compile(r"^[a-zA-Z0-9:_-]{1,128}$")
+
+
+# ---------------------------------------------------------------------------
+# Module-level state (account-scoped)
+# ---------------------------------------------------------------------------
+
+_things: AccountScopedDict = AccountScopedDict() # thingName -> Thing dict
+_thing_types: AccountScopedDict = AccountScopedDict()
+_thing_groups: AccountScopedDict = AccountScopedDict()
+_certificates: AccountScopedDict = AccountScopedDict() # certificateId -> Certificate dict
+_policies: AccountScopedDict = AccountScopedDict() # policyName -> Policy dict
+
+# Local CA state — lazily generated on first use, persisted across restarts.
+import threading
+
+_CA_LOCK = threading.Lock()
+_ca_cert_pem: str | None = None
+_ca_key_pem: str | None = None
+
+
+def _ensure_ca() -> tuple[str, str]:
+ """Return (cert_pem, key_pem), generating lazily on first use."""
+ global _ca_cert_pem, _ca_key_pem
+ if _ca_cert_pem is not None and _ca_key_pem is not None:
+ return _ca_cert_pem, _ca_key_pem
+ with _CA_LOCK:
+ if _ca_cert_pem is not None and _ca_key_pem is not None:
+ return _ca_cert_pem, _ca_key_pem
+ cert_pem, key_pem = generate_ca()
+ _ca_cert_pem = cert_pem
+ _ca_key_pem = key_pem
+ logger.info("Local CA: generated new self-signed root certificate")
+ return cert_pem, key_pem
+
+
+def get_ca_cert_pem() -> str:
+ """Return the CA certificate in PEM format. Generates the CA on first call."""
+ cert_pem, _ = _ensure_ca()
+ return cert_pem
+
+
+# ---------------------------------------------------------------------------
+# Broker state
+# ---------------------------------------------------------------------------
+
+_retained: dict[str, "_RetainedMessage"] = {}
+
+
+class _RetainedMessage:
+ __slots__ = ("payload", "qos", "topic", "ts")
+
+ def __init__(self, topic: str, payload: bytes, qos: int):
+ self.topic = topic
+ self.payload = payload
+ self.qos = qos
+ self.ts = time.time()
+
+
+def _broker_get_state() -> dict:
+ retained_list = []
+ for topic, msg in _retained.items():
+ retained_list.append({
+ "topic": msg.topic,
+ "payload": base64.b64encode(msg.payload).decode("ascii"),
+ "qos": msg.qos,
+ })
+ return {"retained": retained_list}
+
+
+def _broker_restore_state(data: dict | None) -> None:
+ if not data:
+ return
+ for entry in data.get("retained", []):
+ topic = entry["topic"]
+ payload = base64.b64decode(entry["payload"])
+ qos = entry.get("qos", 0)
+ _retained[topic] = _RetainedMessage(topic, payload, qos)
+
+
+# ---------------------------------------------------------------------------
+# Persistence
+# ---------------------------------------------------------------------------
+
+
+def get_state() -> dict:
+ return {
+ "things": copy.deepcopy(_things),
+ "thing_types": copy.deepcopy(_thing_types),
+ "thing_groups": copy.deepcopy(_thing_groups),
+ "certificates": copy.deepcopy(_certificates),
+ "policies": copy.deepcopy(_policies),
+ "ca": {"ca_cert_pem": _ca_cert_pem, "ca_key_pem": _ca_key_pem}
+ if _ca_cert_pem and _ca_key_pem
+ else {},
+ "mqtt_broker": _broker_get_state(),
+ }
+
+
+def restore_state(data: dict | None) -> None:
+ global _ca_cert_pem, _ca_key_pem
+ if not data:
+ return
+ _things.update(data.get("things", {}))
+ _thing_types.update(data.get("thing_types", {}))
+ _thing_groups.update(data.get("thing_groups", {}))
+ _certificates.update(data.get("certificates", {}))
+ _policies.update(data.get("policies", {}))
+ ca_data = data.get("ca")
+ if ca_data:
+ cert = ca_data.get("ca_cert_pem")
+ key = ca_data.get("ca_key_pem")
+ if cert and key:
+ with _CA_LOCK:
+ _ca_cert_pem = cert
+ _ca_key_pem = key
+ logger.info("Local CA: restored from persisted state")
+ _broker_restore_state(data.get("mqtt_broker"))
+
+
+def reset() -> None:
+ global _ca_cert_pem, _ca_key_pem
+ _things.clear()
+ _thing_types.clear()
+ _thing_groups.clear()
+ _certificates.clear()
+ _policies.clear()
+ with _CA_LOCK:
+ _ca_cert_pem = None
+ _ca_key_pem = None
+
+
+try:
+ _restored = load_state("iot")
+ if _restored:
+ restore_state(_restored)
+except Exception:
+ logger.exception("Failed to restore persisted IoT state; continuing with fresh store")
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _now_epoch() -> float:
+ return datetime.now(timezone.utc).timestamp()
+
+
+def _thing_arn(name: str) -> str:
+ return f"arn:aws:iot:{get_region()}:{get_account_id()}:thing/{name}"
+
+
+def _thing_type_arn(name: str) -> str:
+ return f"arn:aws:iot:{get_region()}:{get_account_id()}:thingtype/{name}"
+
+
+def _thing_group_arn(name: str) -> str:
+ return f"arn:aws:iot:{get_region()}:{get_account_id()}:thinggroup/{name}"
+
+
+def _cert_arn(certificate_id: str) -> str:
+ return f"arn:aws:iot:{get_region()}:{get_account_id()}:cert/{certificate_id}"
+
+
+def _policy_arn(name: str) -> str:
+ return f"arn:aws:iot:{get_region()}:{get_account_id()}:policy/{name}"
+
+
+def _validate_name(name: str | None, field: str) -> tuple | None:
+ if not name or not _NAME_RE.match(name):
+ return error_response_json(
+ "InvalidRequestException",
+ f"Invalid {field}: must match [a-zA-Z0-9:_-]{{1,128}}",
+ 400,
+ )
+ return None
+
+
+def _parse_body(body: bytes) -> dict:
+ if not body:
+ return {}
+ try:
+ return json.loads(body.decode("utf-8"))
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ return {}
+
+
+def _error_not_found(resource: str, name: str) -> tuple:
+ return error_response_json(
+ "ResourceNotFoundException", f"{resource} {name!r} not found", 404
+ )
+
+
+# ---------------------------------------------------------------------------
+# Top-level dispatcher
+# ---------------------------------------------------------------------------
+
+
+async def handle_request(
+ method: str, path: str, headers: dict, body: bytes, query_params: dict
+) -> tuple:
+ """Route an IoT control-plane request to the appropriate handler.
+
+ The IoT API is REST-style (not JSON 1.1 with X-Amz-Target). Routing is
+ therefore by HTTP verb + path. Path templates use AWS conventions:
+
+ * ``POST /things/{thingName}``
+ * ``GET /things/{thingName}``
+ * ``DELETE /things/{thingName}``
+ * ``POST /keys-and-certificate``
+ * ``GET /endpoint``
+
+ See the AWS IoT API Reference for the canonical mapping.
+ """
+ qp = {k: (v[0] if isinstance(v, list) else v) for k, v in query_params.items()}
+ hdr = headers or {}
+
+ # Endpoint
+ if path == "/endpoint" and method == "GET":
+ return _describe_endpoint(qp)
+
+ # Things — list/describe/update/delete
+ if path == "/things" and method == "GET":
+ return _list_things(qp)
+ # Principal lives at /things/{name}/principals — must come BEFORE generic /things/{name}
+ if path.startswith("/things/") and path.endswith("/principals"):
+ return _handle_thing_principals(method, path, hdr, body, qp)
+ if path.startswith("/things/") and method in ("POST", "GET", "PATCH", "DELETE"):
+ return _handle_thing(method, path, body, qp)
+
+ # ThingTypes
+ if path == "/thing-types" and method == "GET":
+ return _list_thing_types(qp)
+ if path.startswith("/thing-types/"):
+ return _handle_thing_type(method, path, body, qp)
+
+ # ThingGroups — special add/remove paths must come BEFORE the
+ # generic ``/thing-groups/{name}`` handler.
+ if path == "/thing-groups/addThingToThingGroup" and method in ("PUT", "POST"):
+ return _add_thing_to_group(_parse_body(body))
+ if path == "/thing-groups/removeThingFromThingGroup" and method in ("PUT", "POST"):
+ return _remove_thing_from_group(_parse_body(body))
+ if path == "/thing-groups" and method == "GET":
+ return _list_thing_groups(qp)
+ if path.startswith("/thing-groups/") and path.endswith("/things") and method == "GET":
+ return _list_things_in_thing_group(path)
+ if path.startswith("/thing-groups/"):
+ return _handle_thing_group(method, path, body, qp)
+
+ # Certificates
+ if path == "/keys-and-certificate" and method == "POST":
+ return _create_keys_and_certificate(qp)
+ if path == "/certificate/register" and method == "POST":
+ return _register_certificate(_parse_body(body), qp)
+ if path == "/certificates" and method == "GET":
+ return _list_certificates(qp)
+ if path.startswith("/certificates/") and method in ("GET", "PUT", "DELETE"):
+ return _handle_certificate(method, path, body, qp)
+
+ # Principal listing
+ if path == "/principals/things" and method == "GET":
+ return _list_principal_things(hdr, qp)
+
+ # Policies
+ if path == "/policies" and method == "GET":
+ return _list_policies(qp)
+ # Policy attachment paths — must come BEFORE generic /policies/ handler
+ if path.startswith("/target-policies/") and method in ("PUT", "POST", "DELETE"):
+ return _handle_target_policy(method, path, body, qp)
+ if path.startswith("/policy-targets/") and method in ("GET", "POST"):
+ return _list_targets_for_policy(path, qp)
+ if path.startswith("/attached-policies/") and method in ("GET", "POST"):
+ return _list_attached_policies(path, qp)
+ if path.startswith("/policies/"):
+ return _handle_policy(method, path, body, qp)
+
+ return error_response_json(
+ "InvalidRequestException", f"Unsupported IoT path: {method} {path}", 400
+ )
+
+
+# ---------------------------------------------------------------------------
+# Endpoint
+# ---------------------------------------------------------------------------
+
+
+def _describe_endpoint(qp: dict) -> tuple:
+ """Return a per-account endpoint hostname.
+
+ Format: ``{prefix}-ats.iot.{region}.{MINISTACK_HOST}:{GATEWAY_PORT}``
+ where ``prefix`` is the first 14 hex chars of SHA-256(account_id), so the
+ hostname is stable per account and looks AWS-shaped without leaking the
+ account ID.
+ """
+ endpoint_type = qp.get("endpointType", "iot:Data-ATS")
+ account_id = get_account_id()
+ prefix = hashlib.sha256(account_id.encode("utf-8")).hexdigest()[:14]
+ region = get_region()
+
+ if endpoint_type in ("iot:Data-ATS", "iot:Data", None):
+ suffix = "-ats" if endpoint_type != "iot:Data" else ""
+ host = f"{prefix}{suffix}.iot.{region}.{_MINISTACK_HOST}:{_GATEWAY_PORT}"
+ elif endpoint_type == "iot:CredentialProvider":
+ host = f"{prefix}.credentials.iot.{region}.{_MINISTACK_HOST}:{_GATEWAY_PORT}"
+ elif endpoint_type == "iot:Jobs":
+ host = f"{prefix}.jobs.iot.{region}.{_MINISTACK_HOST}:{_GATEWAY_PORT}"
+ else:
+ return error_response_json(
+ "InvalidRequestException",
+ f"Unknown endpointType: {endpoint_type}",
+ 400,
+ )
+ return json_response({"endpointAddress": host})
+
+
+# ---------------------------------------------------------------------------
+# Thing CRUD
+# ---------------------------------------------------------------------------
+
+
+def _handle_thing(method: str, path: str, body: bytes, qp: dict) -> tuple:
+ """Dispatch /things/{name} routes (sub-paths handled separately)."""
+ # /things/{name}/principals lives in _handle_thing_principals
+ suffix = path[len("/things/"):]
+ # Sub-resources (principals, etc.) handled by other branches; only handle
+ # bare /things/{name} here. Anything containing additional segments is a
+ # routing miss handled higher up.
+ if "/" in suffix:
+ return error_response_json(
+ "InvalidRequestException", f"Unsupported IoT path: {method} {path}", 400
+ )
+ name = suffix
+ err = _validate_name(name, "thingName")
+ if err:
+ return err
+
+ if method == "POST":
+ return _create_thing(name, _parse_body(body))
+ if method == "GET":
+ return _describe_thing(name)
+ if method == "PATCH":
+ return _update_thing(name, _parse_body(body))
+ if method == "DELETE":
+ return _delete_thing(name)
+ return error_response_json(
+ "InvalidRequestException", f"Unsupported method: {method}", 400
+ )
+
+
+def _create_thing(name: str, payload: dict) -> tuple:
+ attrs = (payload.get("attributePayload") or {}).get("attributes") or {}
+ type_name = payload.get("thingTypeName")
+
+ existing = _things.get(name)
+ if existing is not None:
+ # Idempotent: same config returns success; different config returns 409.
+ if (
+ existing.get("attributes") == attrs
+ and existing.get("thingTypeName") == type_name
+ ):
+ return json_response({
+ "thingName": existing["thingName"],
+ "thingArn": existing["thingArn"],
+ "thingId": existing["thingId"],
+ })
+ return error_response_json(
+ "ResourceAlreadyExistsException",
+ f"Thing {name!r} already exists with different configuration",
+ 409,
+ )
+
+ if type_name and type_name not in _thing_types:
+ return _error_not_found("ThingType", type_name)
+
+ thing_id = new_uuid()
+ record = {
+ "thingName": name,
+ "thingId": thing_id,
+ "thingArn": _thing_arn(name),
+ "thingTypeName": type_name,
+ "attributes": dict(attrs),
+ "version": 1,
+ "creationDate": _now_epoch(),
+ "principals": [],
+ "thingGroupNames": [],
+ }
+ _things[name] = record
+ logger.info("IoT Thing created: %s", name)
+ return json_response({
+ "thingName": name,
+ "thingArn": record["thingArn"],
+ "thingId": thing_id,
+ })
+
+
+def _describe_thing(name: str) -> tuple:
+ thing = _things.get(name)
+ if thing is None:
+ return _error_not_found("Thing", name)
+ body = {
+ "thingName": thing["thingName"],
+ "thingId": thing["thingId"],
+ "thingArn": thing["thingArn"],
+ "thingTypeName": thing.get("thingTypeName"),
+ "attributes": thing.get("attributes", {}),
+ "version": thing.get("version", 1),
+ "defaultClientId": thing["thingName"],
+ }
+ return json_response(body)
+
+
+def _list_things(qp: dict) -> tuple:
+ attribute_name = qp.get("attributeName")
+ attribute_value = qp.get("attributeValue")
+ thing_type_name = qp.get("thingTypeName")
+ name_prefix = qp.get("thingName")
+
+ out = []
+ for name, t in _things.items():
+ if attribute_name is not None and t.get("attributes", {}).get(attribute_name) != attribute_value:
+ continue
+ if thing_type_name is not None and t.get("thingTypeName") != thing_type_name:
+ continue
+ if name_prefix is not None and not name.startswith(name_prefix):
+ continue
+ out.append({
+ "thingName": t["thingName"],
+ "thingArn": t["thingArn"],
+ "thingTypeName": t.get("thingTypeName"),
+ "attributes": t.get("attributes", {}),
+ "version": t.get("version", 1),
+ })
+ return json_response({"things": out})
+
+
+def _update_thing(name: str, payload: dict) -> tuple:
+ thing = _things.get(name)
+ if thing is None:
+ return _error_not_found("Thing", name)
+
+ attribute_payload = payload.get("attributePayload") or {}
+ new_attrs = attribute_payload.get("attributes") or {}
+ merge = bool(attribute_payload.get("merge", False))
+
+ if merge:
+ merged = dict(thing.get("attributes", {}))
+ for k, v in new_attrs.items():
+ if v is None or v == "":
+ merged.pop(k, None)
+ else:
+ merged[k] = v
+ thing["attributes"] = merged
+ else:
+ thing["attributes"] = dict(new_attrs)
+
+ new_type = payload.get("thingTypeName")
+ if new_type is not None:
+ if new_type and new_type not in _thing_types:
+ return _error_not_found("ThingType", new_type)
+ thing["thingTypeName"] = new_type or None
+
+ thing["version"] = thing.get("version", 1) + 1
+ _things[name] = thing
+ return json_response({})
+
+
+def _delete_thing(name: str) -> tuple:
+ thing = _things.get(name)
+ if thing is None:
+ return _error_not_found("Thing", name)
+ # Detach all attached certificates
+ thing_arn = thing["thingArn"]
+ for cert_id, cert in list(_certificates.items()):
+ if thing_arn in cert.get("attachedThings", []):
+ cert["attachedThings"].remove(thing_arn)
+ _certificates[cert_id] = cert
+ # Remove from groups
+ for gname in list(thing.get("thingGroupNames", [])):
+ group = _thing_groups.get(gname)
+ if group and name in group.get("things", []):
+ group["things"].remove(name)
+ _thing_groups[gname] = group
+ del _things[name]
+ logger.info("IoT Thing deleted: %s", name)
+ return json_response({})
+
+
+# ---------------------------------------------------------------------------
+# ThingType CRUD
+# ---------------------------------------------------------------------------
+
+
+def _handle_thing_type(method: str, path: str, body: bytes, qp: dict) -> tuple:
+ suffix = path[len("/thing-types/"):]
+
+ # /thing-types/{name}/deprecate — boto3 uses POST, others may use PUT
+ if suffix.endswith("/deprecate"):
+ name = suffix[:-len("/deprecate")]
+ err = _validate_name(name, "thingTypeName")
+ if err:
+ return err
+ if method in ("POST", "PUT"):
+ return _deprecate_thing_type(name, _parse_body(body))
+ return error_response_json(
+ "InvalidRequestException", f"Unsupported method: {method}", 400
+ )
+
+ if "/" in suffix:
+ return error_response_json(
+ "InvalidRequestException", f"Unsupported IoT path: {method} {path}", 400
+ )
+
+ name = suffix
+ err = _validate_name(name, "thingTypeName")
+ if err:
+ return err
+ if method == "POST":
+ return _create_thing_type(name, _parse_body(body))
+ if method == "GET":
+ return _describe_thing_type(name)
+ if method == "DELETE":
+ return _delete_thing_type(name)
+ return error_response_json(
+ "InvalidRequestException", f"Unsupported method: {method}", 400
+ )
+
+
+def _create_thing_type(name: str, payload: dict) -> tuple:
+ if name in _thing_types:
+ return error_response_json(
+ "ResourceAlreadyExistsException",
+ f"ThingType {name!r} already exists",
+ 409,
+ )
+ props = payload.get("thingTypeProperties") or {}
+ record = {
+ "thingTypeName": name,
+ "thingTypeId": new_uuid(),
+ "thingTypeArn": _thing_type_arn(name),
+ "thingTypeProperties": {
+ "thingTypeDescription": props.get("thingTypeDescription"),
+ "searchableAttributes": list(props.get("searchableAttributes", []) or []),
+ },
+ "thingTypeMetadata": {
+ "deprecated": False,
+ "deprecationDate": None,
+ "creationDate": _now_epoch(),
+ },
+ }
+ _thing_types[name] = record
+ return json_response({
+ "thingTypeName": name,
+ "thingTypeArn": record["thingTypeArn"],
+ "thingTypeId": record["thingTypeId"],
+ })
+
+
+def _describe_thing_type(name: str) -> tuple:
+ t = _thing_types.get(name)
+ if t is None:
+ return _error_not_found("ThingType", name)
+ return json_response(t)
+
+
+def _list_thing_types(qp: dict) -> tuple:
+ return json_response({"thingTypes": list(_thing_types.values())})
+
+
+def _deprecate_thing_type(name: str, payload: dict) -> tuple:
+ t = _thing_types.get(name)
+ if t is None:
+ return _error_not_found("ThingType", name)
+ undo = bool(payload.get("undoDeprecate", False))
+ t["thingTypeMetadata"]["deprecated"] = not undo
+ t["thingTypeMetadata"]["deprecationDate"] = None if undo else _now_epoch()
+ _thing_types[name] = t
+ return json_response({})
+
+
+def _delete_thing_type(name: str) -> tuple:
+ t = _thing_types.get(name)
+ if t is None:
+ return _error_not_found("ThingType", name)
+ if not t["thingTypeMetadata"].get("deprecated"):
+ return error_response_json(
+ "InvalidRequestException",
+ "ThingType must be deprecated for at least 5 minutes before deletion",
+ 400,
+ )
+ del _thing_types[name]
+ return json_response({})
+
+
+# ---------------------------------------------------------------------------
+# ThingGroup CRUD
+# ---------------------------------------------------------------------------
+
+
+def _handle_thing_group(method: str, path: str, body: bytes, qp: dict) -> tuple:
+ suffix = path[len("/thing-groups/"):]
+ if "/" in suffix:
+ return error_response_json(
+ "InvalidRequestException", f"Unsupported IoT path: {method} {path}", 400
+ )
+ name = suffix
+ err = _validate_name(name, "thingGroupName")
+ if err:
+ return err
+ if method == "POST":
+ return _create_thing_group(name, _parse_body(body))
+ if method == "GET":
+ return _describe_thing_group(name)
+ if method == "PATCH":
+ return _update_thing_group(name, _parse_body(body))
+ if method == "DELETE":
+ return _delete_thing_group(name)
+ return error_response_json(
+ "InvalidRequestException", f"Unsupported method: {method}", 400
+ )
+
+
+def _create_thing_group(name: str, payload: dict) -> tuple:
+ if name in _thing_groups:
+ return error_response_json(
+ "ResourceAlreadyExistsException",
+ f"ThingGroup {name!r} already exists",
+ 409,
+ )
+ props = payload.get("thingGroupProperties") or {}
+ attr_payload = props.get("attributePayload") or {}
+ record = {
+ "thingGroupName": name,
+ "thingGroupId": new_uuid(),
+ "thingGroupArn": _thing_group_arn(name),
+ "thingGroupProperties": {
+ "thingGroupDescription": props.get("thingGroupDescription"),
+ "attributePayload": {"attributes": dict(attr_payload.get("attributes", {}))},
+ },
+ "version": 1,
+ "things": [],
+ "creationDate": _now_epoch(),
+ }
+ _thing_groups[name] = record
+ return json_response({
+ "thingGroupName": name,
+ "thingGroupArn": record["thingGroupArn"],
+ "thingGroupId": record["thingGroupId"],
+ })
+
+
+def _describe_thing_group(name: str) -> tuple:
+ g = _thing_groups.get(name)
+ if g is None:
+ return _error_not_found("ThingGroup", name)
+ return json_response(g)
+
+
+def _list_thing_groups(qp: dict) -> tuple:
+ return json_response({
+ "thingGroups": [
+ {"groupName": g["thingGroupName"], "groupArn": g["thingGroupArn"]}
+ for g in _thing_groups.values()
+ ]
+ })
+
+
+def _list_things_in_thing_group(path: str) -> tuple:
+ """``GET /thing-groups/{groupName}/things``."""
+ middle = path[len("/thing-groups/"):-len("/things")]
+ g = _thing_groups.get(middle)
+ if g is None:
+ return _error_not_found("ThingGroup", middle)
+ return json_response({"things": list(g.get("things", []))})
+
+
+def _update_thing_group(name: str, payload: dict) -> tuple:
+ g = _thing_groups.get(name)
+ if g is None:
+ return _error_not_found("ThingGroup", name)
+ props = payload.get("thingGroupProperties") or {}
+ if props:
+ g["thingGroupProperties"].update({
+ "thingGroupDescription": props.get("thingGroupDescription"),
+ })
+ attr_payload = props.get("attributePayload") or {}
+ if attr_payload:
+ g["thingGroupProperties"]["attributePayload"] = {
+ "attributes": dict(attr_payload.get("attributes", {}))
+ }
+ g["version"] = g.get("version", 1) + 1
+ _thing_groups[name] = g
+ return json_response({"version": g["version"]})
+
+
+def _delete_thing_group(name: str) -> tuple:
+ g = _thing_groups.get(name)
+ if g is None:
+ return _error_not_found("ThingGroup", name)
+ # Remove group from any Things that referenced it
+ for tname in list(g.get("things", [])):
+ thing = _things.get(tname)
+ if thing and name in thing.get("thingGroupNames", []):
+ thing["thingGroupNames"].remove(name)
+ _things[tname] = thing
+ del _thing_groups[name]
+ return json_response({})
+
+
+def _add_thing_to_group(payload: dict) -> tuple:
+ gname = payload.get("thingGroupName")
+ tname = payload.get("thingName")
+ if not gname or not tname:
+ return error_response_json(
+ "InvalidRequestException", "thingGroupName and thingName are required", 400
+ )
+ group = _thing_groups.get(gname)
+ if group is None:
+ return _error_not_found("ThingGroup", gname)
+ thing = _things.get(tname)
+ if thing is None:
+ return _error_not_found("Thing", tname)
+ if tname not in group.get("things", []):
+ group.setdefault("things", []).append(tname)
+ _thing_groups[gname] = group
+ if gname not in thing.get("thingGroupNames", []):
+ thing.setdefault("thingGroupNames", []).append(gname)
+ _things[tname] = thing
+ return json_response({})
+
+
+def _remove_thing_from_group(payload: dict) -> tuple:
+ gname = payload.get("thingGroupName")
+ tname = payload.get("thingName")
+ group = _thing_groups.get(gname) if gname else None
+ thing = _things.get(tname) if tname else None
+ if group is None:
+ return _error_not_found("ThingGroup", gname or "")
+ if thing is None:
+ return _error_not_found("Thing", tname or "")
+ if tname in group.get("things", []):
+ group["things"].remove(tname)
+ _thing_groups[gname] = group
+ if gname in thing.get("thingGroupNames", []):
+ thing["thingGroupNames"].remove(gname)
+ _things[tname] = thing
+ return json_response({})
+
+
+# ---------------------------------------------------------------------------
+# Certificates
+# ---------------------------------------------------------------------------
+
+
+def _create_keys_and_certificate(qp: dict) -> tuple:
+ """Generate a fresh keypair and sign a leaf certificate with the Local CA."""
+ set_active = qp.get("setAsActive", "false").lower() == "true"
+ try:
+ ca_cert_pem, ca_key_pem = _ensure_ca()
+ cert_pem, private_pem, public_pem = sign_leaf_certificate(
+ ca_cert_pem=ca_cert_pem,
+ ca_key_pem=ca_key_pem,
+ common_name="AWS IoT Certificate",
+ )
+ except RuntimeError as e:
+ return error_response_json("InternalFailureException", str(e), 503)
+ cert_id = get_certificate_id(cert_pem)
+ arn = _cert_arn(cert_id)
+ record = {
+ "certificateId": cert_id,
+ "certificateArn": arn,
+ "certificatePem": cert_pem,
+ "status": "ACTIVE" if set_active else "INACTIVE",
+ "creationDate": _now_epoch(),
+ "ownedBy": get_account_id(),
+ "caCertificateId": None,
+ "attachedThings": [],
+ "attachedPolicies": [],
+ }
+ _certificates[cert_id] = record
+ return json_response({
+ "certificateArn": arn,
+ "certificateId": cert_id,
+ "certificatePem": cert_pem,
+ "keyPair": {
+ "PublicKey": public_pem,
+ "PrivateKey": private_pem,
+ },
+ })
+
+
+def _register_certificate(payload: dict, qp: dict) -> tuple:
+ """Register a certificate that was issued elsewhere (no re-signing)."""
+ cert_pem = payload.get("certificatePem") or qp.get("certificatePem")
+ if not cert_pem:
+ return error_response_json(
+ "InvalidRequestException", "certificatePem is required", 400
+ )
+ set_active = bool(payload.get("setAsActive", False))
+ status = payload.get("status")
+ try:
+ cert_id = get_certificate_id(cert_pem)
+ except Exception as e:
+ return error_response_json(
+ "CertificateValidationException",
+ f"Invalid certificate PEM: {e}",
+ 400,
+ )
+ if cert_id in _certificates:
+ return error_response_json(
+ "ResourceAlreadyExistsException",
+ "Certificate already registered",
+ 409,
+ )
+ record = {
+ "certificateId": cert_id,
+ "certificateArn": _cert_arn(cert_id),
+ "certificatePem": cert_pem, # verbatim
+ "status": status or ("ACTIVE" if set_active else "INACTIVE"),
+ "creationDate": _now_epoch(),
+ "ownedBy": get_account_id(),
+ "caCertificateId": payload.get("caCertificatePem") and get_certificate_id(payload["caCertificatePem"]) or None,
+ "attachedThings": [],
+ "attachedPolicies": [],
+ }
+ _certificates[cert_id] = record
+ return json_response({
+ "certificateArn": record["certificateArn"],
+ "certificateId": cert_id,
+ })
+
+
+def _list_certificates(qp: dict) -> tuple:
+ return json_response({
+ "certificates": [
+ {
+ "certificateArn": c["certificateArn"],
+ "certificateId": c["certificateId"],
+ "status": c["status"],
+ "creationDate": c.get("creationDate"),
+ }
+ for c in _certificates.values()
+ ]
+ })
+
+
+def _handle_certificate(method: str, path: str, body: bytes, qp: dict) -> tuple:
+ cert_id = path[len("/certificates/"):]
+ if not cert_id or "/" in cert_id:
+ return error_response_json(
+ "InvalidRequestException", "Invalid certificate path", 400
+ )
+ record = _certificates.get(cert_id)
+ if record is None:
+ return _error_not_found("Certificate", cert_id)
+ if method == "GET":
+ return json_response({
+ "certificateDescription": {
+ "certificateArn": record["certificateArn"],
+ "certificateId": record["certificateId"],
+ "status": record["status"],
+ "certificatePem": record["certificatePem"],
+ "ownedBy": record["ownedBy"],
+ "creationDate": record.get("creationDate"),
+ }
+ })
+ if method == "PUT":
+ payload = _parse_body(body)
+ new_status = payload.get("newStatus") or qp.get("newStatus")
+ valid = {"ACTIVE", "INACTIVE", "REVOKED", "PENDING_TRANSFER", "PENDING_ACTIVATION"}
+ if new_status not in valid:
+ return error_response_json(
+ "InvalidRequestException",
+ f"newStatus must be one of {sorted(valid)}",
+ 400,
+ )
+ record["status"] = new_status
+ _certificates[cert_id] = record
+ return json_response({})
+ if method == "DELETE":
+ if record["status"] == "ACTIVE":
+ return error_response_json(
+ "CertificateStateException",
+ "Certificate is ACTIVE; deactivate before deletion",
+ 409,
+ )
+ del _certificates[cert_id]
+ return json_response({})
+ return error_response_json(
+ "InvalidRequestException", f"Unsupported method: {method}", 400
+ )
+
+
+def _handle_thing_principals(method: str, path: str, headers: dict, body: bytes, qp: dict) -> tuple:
+ """``PUT/DELETE /things/{name}/principals`` and ``GET /things/{name}/principals``.
+
+ AWS uses an ``x-amzn-principal`` header containing the principal ARN
+ (typically a certificate ARN) for ``AttachThingPrincipal`` /
+ ``DetachThingPrincipal``.
+ """
+ middle = path[len("/things/"):-len("/principals")]
+ if "/" in middle:
+ return error_response_json(
+ "InvalidRequestException", f"Unsupported IoT path: {method} {path}", 400
+ )
+ name = middle
+ thing = _things.get(name)
+ if thing is None:
+ return _error_not_found("Thing", name)
+
+ if method == "GET":
+ return json_response({"principals": list(thing.get("principals", []))})
+
+ # PUT/DELETE require x-amzn-principal header (AWS convention).
+ principal = headers.get("x-amzn-principal") or qp.get("principal")
+ if not principal:
+ return error_response_json(
+ "InvalidRequestException", "principal is required", 400
+ )
+ cert_id = principal.rsplit("/", 1)[-1]
+ cert = _certificates.get(cert_id)
+ if cert is None:
+ return _error_not_found("Principal", principal)
+
+ if method == "PUT":
+ if principal not in thing.setdefault("principals", []):
+ thing["principals"].append(principal)
+ _things[name] = thing
+ if thing["thingArn"] not in cert.setdefault("attachedThings", []):
+ cert["attachedThings"].append(thing["thingArn"])
+ _certificates[cert_id] = cert
+ return json_response({})
+ if method == "DELETE":
+ if principal in thing.get("principals", []):
+ thing["principals"].remove(principal)
+ _things[name] = thing
+ if thing["thingArn"] in cert.get("attachedThings", []):
+ cert["attachedThings"].remove(thing["thingArn"])
+ _certificates[cert_id] = cert
+ return json_response({})
+ return error_response_json(
+ "InvalidRequestException", f"Unsupported method: {method}", 400
+ )
+
+
+def _list_principal_things(headers: dict, qp: dict) -> tuple:
+ """``GET /principals/things`` with the principal in the ``x-amzn-principal`` header."""
+ principal = headers.get("x-amzn-principal") or qp.get("principal")
+ if not principal:
+ return error_response_json(
+ "InvalidRequestException", "principal is required", 400
+ )
+ cert_id = principal.rsplit("/", 1)[-1]
+ cert = _certificates.get(cert_id)
+ if cert is None:
+ return _error_not_found("Principal", principal)
+ things = []
+ for arn in cert.get("attachedThings", []):
+ tname = arn.rsplit("/", 1)[-1]
+ if tname in _things:
+ things.append(tname)
+ return json_response({"things": things})
+
+
+# ---------------------------------------------------------------------------
+# Policies
+# ---------------------------------------------------------------------------
+
+
+def _handle_policy(method: str, path: str, body: bytes, qp: dict) -> tuple:
+ suffix = path[len("/policies/"):]
+ parts = suffix.split("/")
+ name = parts[0]
+
+ err = _validate_name(name, "policyName")
+ if err:
+ return err
+
+ # /policies/{name}/version/{versionId}
+ if len(parts) >= 3 and parts[1] == "version":
+ version_id = parts[2]
+ if method == "GET":
+ return _get_policy_version(name, version_id)
+ if method == "DELETE":
+ return _delete_policy_version(name, version_id)
+
+ # /policies/{name}/version
+ if len(parts) == 2 and parts[1] == "version":
+ if method == "POST":
+ return _create_policy_version(name, _parse_body(body), qp)
+ if method == "GET":
+ return _list_policy_versions(name)
+
+ if len(parts) == 1:
+ if method == "POST":
+ return _create_policy(name, _parse_body(body))
+ if method == "GET":
+ return _get_policy(name)
+ if method == "DELETE":
+ return _delete_policy(name)
+
+ return error_response_json(
+ "InvalidRequestException", f"Unsupported policy path: {method} {path}", 400
+ )
+
+
+def _create_policy(name: str, payload: dict) -> tuple:
+ if name in _policies:
+ return error_response_json(
+ "ResourceAlreadyExistsException",
+ f"Policy {name!r} already exists",
+ 409,
+ )
+ doc = payload.get("policyDocument")
+ if not doc:
+ return error_response_json(
+ "InvalidRequestException", "policyDocument is required", 400
+ )
+ try:
+ json.loads(doc)
+ except (TypeError, json.JSONDecodeError):
+ return error_response_json(
+ "MalformedPolicyException",
+ "policyDocument is not valid JSON",
+ 400,
+ )
+ record = {
+ "policyName": name,
+ "policyArn": _policy_arn(name),
+ "defaultVersionId": "1",
+ "versions": {
+ "1": {
+ "document": doc,
+ "isDefaultVersion": True,
+ "createDate": _now_epoch(),
+ },
+ },
+ "targets": [],
+ }
+ _policies[name] = record
+ return json_response({
+ "policyName": name,
+ "policyArn": record["policyArn"],
+ "policyDocument": doc,
+ "policyVersionId": "1",
+ })
+
+
+def _get_policy(name: str) -> tuple:
+ p = _policies.get(name)
+ if p is None:
+ return _error_not_found("Policy", name)
+ default_id = p["defaultVersionId"]
+ return json_response({
+ "policyName": name,
+ "policyArn": p["policyArn"],
+ "policyDocument": p["versions"][default_id]["document"],
+ "defaultVersionId": default_id,
+ })
+
+
+def _list_policies(qp: dict) -> tuple:
+ return json_response({
+ "policies": [
+ {"policyName": p["policyName"], "policyArn": p["policyArn"]}
+ for p in _policies.values()
+ ]
+ })
+
+
+def _delete_policy(name: str) -> tuple:
+ p = _policies.get(name)
+ if p is None:
+ return _error_not_found("Policy", name)
+ if p.get("targets"):
+ return error_response_json(
+ "DeleteConflictException",
+ "Policy is attached; detach it before deletion",
+ 409,
+ )
+ del _policies[name]
+ return json_response({})
+
+
+def _create_policy_version(name: str, payload: dict, qp: dict) -> tuple:
+ p = _policies.get(name)
+ if p is None:
+ return _error_not_found("Policy", name)
+ doc = payload.get("policyDocument")
+ if not doc:
+ return error_response_json(
+ "InvalidRequestException", "policyDocument is required", 400
+ )
+ try:
+ json.loads(doc)
+ except (TypeError, json.JSONDecodeError):
+ return error_response_json(
+ "MalformedPolicyException",
+ "policyDocument is not valid JSON",
+ 400,
+ )
+ set_default = (
+ bool(payload.get("setAsDefault"))
+ or qp.get("setAsDefault", "").lower() == "true"
+ )
+ next_id = str(max(int(v) for v in p["versions"].keys()) + 1)
+ if set_default:
+ for v in p["versions"].values():
+ v["isDefaultVersion"] = False
+ p["defaultVersionId"] = next_id
+ p["versions"][next_id] = {
+ "document": doc,
+ "isDefaultVersion": set_default,
+ "createDate": _now_epoch(),
+ }
+ _policies[name] = p
+ return json_response({
+ "policyArn": p["policyArn"],
+ "policyDocument": doc,
+ "policyVersionId": next_id,
+ "isDefaultVersion": set_default,
+ })
+
+
+def _get_policy_version(name: str, version_id: str) -> tuple:
+ p = _policies.get(name)
+ if p is None:
+ return _error_not_found("Policy", name)
+ v = p["versions"].get(version_id)
+ if v is None:
+ return _error_not_found("PolicyVersion", version_id)
+ return json_response({
+ "policyArn": p["policyArn"],
+ "policyDocument": v["document"],
+ "policyVersionId": version_id,
+ "isDefaultVersion": v["isDefaultVersion"],
+ "creationDate": v.get("createDate"),
+ })
+
+
+def _list_policy_versions(name: str) -> tuple:
+ p = _policies.get(name)
+ if p is None:
+ return _error_not_found("Policy", name)
+ return json_response({
+ "policyVersions": [
+ {
+ "versionId": vid,
+ "isDefaultVersion": v["isDefaultVersion"],
+ "createDate": v.get("createDate"),
+ }
+ for vid, v in p["versions"].items()
+ ]
+ })
+
+
+def _delete_policy_version(name: str, version_id: str) -> tuple:
+ p = _policies.get(name)
+ if p is None:
+ return _error_not_found("Policy", name)
+ if version_id not in p["versions"]:
+ return _error_not_found("PolicyVersion", version_id)
+ if p["defaultVersionId"] == version_id:
+ return error_response_json(
+ "InvalidRequestException",
+ "Cannot delete the default policy version",
+ 400,
+ )
+ del p["versions"][version_id]
+ _policies[name] = p
+ return json_response({})
+
+
+# AttachPolicy / DetachPolicy via /target-policies/{policyName}
+# Body: {"target": "arn:..."}
+
+
+def _handle_target_policy(method: str, path: str, body: bytes, qp: dict) -> tuple:
+ """Handles ``/target-policies/{policyName}``.
+
+ AWS uses ``PUT`` for ``AttachPolicy`` and ``POST`` for ``DetachPolicy``
+ (yes, both write methods on the same path; the verb selects the action).
+ """
+ name = path[len("/target-policies/"):]
+ if "/" in name:
+ return error_response_json(
+ "InvalidRequestException", "Invalid target-policies path", 400
+ )
+ p = _policies.get(name)
+ if p is None:
+ return _error_not_found("Policy", name)
+ payload = _parse_body(body)
+ target = payload.get("target")
+ if not target:
+ return error_response_json(
+ "InvalidRequestException", "target is required", 400
+ )
+ if method == "PUT":
+ if target not in p.setdefault("targets", []):
+ p["targets"].append(target)
+ _policies[name] = p
+ cert_id = target.rsplit("/", 1)[-1]
+ cert = _certificates.get(cert_id)
+ if cert is not None and name not in cert.setdefault("attachedPolicies", []):
+ cert["attachedPolicies"].append(name)
+ _certificates[cert_id] = cert
+ return json_response({})
+ if method in ("POST", "DELETE"):
+ if target in p.get("targets", []):
+ p["targets"].remove(target)
+ _policies[name] = p
+ cert_id = target.rsplit("/", 1)[-1]
+ cert = _certificates.get(cert_id)
+ if cert is not None and name in cert.get("attachedPolicies", []):
+ cert["attachedPolicies"].remove(name)
+ _certificates[cert_id] = cert
+ return json_response({})
+ return error_response_json(
+ "InvalidRequestException", f"Unsupported method: {method}", 400
+ )
+
+
+def _list_targets_for_policy(path: str, qp: dict) -> tuple:
+ """``GET|POST /policy-targets/{policyName}``."""
+ name = path[len("/policy-targets/"):]
+ p = _policies.get(name)
+ if p is None:
+ return _error_not_found("Policy", name)
+ return json_response({"targets": list(p.get("targets", []))})
+
+
+def _list_attached_policies(path: str, qp: dict) -> tuple:
+ """``POST /attached-policies/{target}`` — returns policies attached to target.
+
+ The target segment is URL-encoded by the SDK (the certificate ARN
+ contains colons / slashes); the ASGI layer hands us the decoded value.
+ """
+ target = path[len("/attached-policies/"):]
+ out = []
+ for p in _policies.values():
+ if target in p.get("targets", []):
+ out.append({"policyName": p["policyName"], "policyArn": p["policyArn"]})
+ return json_response({"policies": out})
+
+
+# ---------------------------------------------------------------------------
+# Helper exports for iot_data
+# ---------------------------------------------------------------------------
+
+
+def lookup_certificate_by_id(cert_id: str) -> dict | None:
+ """Return the Certificate record for a given certificateId in the current account, or None."""
+ return _certificates.get(cert_id)
+
+
+# ===========================================================================
+# MQTT Broker — embedded MQTT 3.1.1 broker logic over WebSocket
+# ===========================================================================
+#
+# The broker owns a small in-process pub/sub registry plus an MQTT 3.1.1
+# framing layer used between the broker and WebSocket clients (per the AWS
+# WS-MQTT subprotocol).
+#
+# Architecture (mirrors Transfer Family's shared SFTP listener):
+# Client → WebSocket (gateway port) → Bridge → in-memory pub/sub
+#
+# Multi-tenancy is enforced by transparent topic prefixing: every
+# PUBLISH/SUBSCRIBE topic seen on the wire is internally prefixed with the
+# caller's account_id before it hits the registry, and the prefix is
+# stripped on outbound delivery.
+
+_broker_logger = logging.getLogger("iot_broker")
+
+# ---------------------------------------------------------------------------
+# In-memory pub/sub registry
+# ---------------------------------------------------------------------------
+
+_subscriptions: dict[str, set["_Subscription"]] = {}
+_connected_clients: dict[tuple[str, str], "_WSSession"] = {}
+_persistent_sessions: dict[tuple[str, str], "_PersistentSessionState"] = {}
+_broker_lock = asyncio.Lock()
+
+_SESSION_EXPIRY_SECONDS: int = int(os.environ.get("IOT_SESSION_EXPIRY_SECONDS", "3600"))
+_MAX_QUEUED_MESSAGES = 1000
+
+
+class _PersistentSessionState:
+ __slots__ = ("subscriptions", "queued_messages", "created_at")
+
+ def __init__(self, subscriptions: list[str], created_at: float):
+ self.subscriptions: list[str] = subscriptions
+ self.queued_messages: list[tuple[str, bytes, int]] = []
+ self.created_at: float = created_at
+
+
+def _is_session_expired(session_state: _PersistentSessionState) -> bool:
+ return (time.time() - session_state.created_at) > _SESSION_EXPIRY_SECONDS
+
+
+class _InFlightMessage:
+ __slots__ = ("packet_id", "topic", "payload", "sent_at", "retransmit_count")
+
+ def __init__(self, packet_id: int, topic: str, payload: bytes):
+ self.packet_id = packet_id
+ self.topic = topic
+ self.payload = payload
+ self.sent_at = asyncio.get_event_loop().time()
+ self.retransmit_count = 0
+
+
+_RETRANSMIT_INTERVAL_SECONDS = int(os.environ.get("IOT_RETRANSMIT_SECONDS", "10"))
+
+
+class _Subscription:
+ __slots__ = ("subscription_id", "filter_prefixed", "account_id", "deliver", "granted_qos")
+
+ def __init__(
+ self,
+ filter_prefixed: str,
+ account_id: str,
+ deliver: Callable[[str, bytes, int], Awaitable[None]],
+ granted_qos: int = 0,
+ ):
+ self.subscription_id = uuid.uuid4().hex
+ self.filter_prefixed = filter_prefixed
+ self.account_id = account_id
+ self.deliver = deliver
+ self.granted_qos = granted_qos
+
+ def __hash__(self) -> int:
+ return hash(self.subscription_id)
+
+ def __eq__(self, other) -> bool:
+ return isinstance(other, _Subscription) and other.subscription_id == self.subscription_id
+
+
+# ---------------------------------------------------------------------------
+# Topic prefixing & matching
+# ---------------------------------------------------------------------------
+
+
+def _scoped_topic(account_id: str, topic: str) -> str:
+ return f"{account_id}/{topic}"
+
+
+def _unscope_topic(account_id: str, scoped_topic: str) -> str:
+ prefix = f"{account_id}/"
+ if scoped_topic.startswith(prefix):
+ return scoped_topic[len(prefix):]
+ return scoped_topic
+
+
+def _topic_matches(filter_: str, topic: str) -> bool:
+ f_parts = filter_.split("/")
+ t_parts = topic.split("/")
+ fi = ti = 0
+ while fi < len(f_parts):
+ f = f_parts[fi]
+ if f == "#":
+ return True
+ if ti >= len(t_parts):
+ return False
+ if f != "+" and f != t_parts[ti]:
+ return False
+ fi += 1
+ ti += 1
+ return ti == len(t_parts)
+
+
+# ---------------------------------------------------------------------------
+# Topic validation
+# ---------------------------------------------------------------------------
+
+_MQTT_MAX_TOPIC_BYTES = 256
+
+
+def _validate_publish_topic(topic: str) -> bool:
+ if not topic:
+ return False
+ if "+" in topic or "#" in topic:
+ return False
+ if len(topic.encode("utf-8")) > _MQTT_MAX_TOPIC_BYTES:
+ return False
+ return True
+
+
+# ---------------------------------------------------------------------------
+# Broker public API (consumed by iot_data.py and handle_websocket)
+# ---------------------------------------------------------------------------
+
+
+def broker_is_available() -> bool:
+ return True
+
+
+async def broker_start() -> None:
+ return None
+
+
+async def broker_stop() -> None:
+ async with _broker_lock:
+ _subscriptions.clear()
+ _retained.clear()
+ _connected_clients.clear()
+ _persistent_sessions.clear()
+
+
+async def broker_publish(
+ account_id: str,
+ topic: str,
+ payload: bytes,
+ qos: int = 0,
+ retain: bool = False,
+) -> None:
+ scoped = _scoped_topic(account_id, topic)
+
+ if retain:
+ if not payload:
+ _retained.pop(scoped, None)
+ else:
+ _retained[scoped] = _RetainedMessage(scoped, payload, qos)
+
+ async with _broker_lock:
+ subs = [s for sset in _subscriptions.values() for s in sset]
+
+ for sub in subs:
+ if _topic_matches(sub.filter_prefixed, scoped):
+ try:
+ effective_qos = min(qos, sub.granted_qos)
+ await sub.deliver(_unscope_topic(sub.account_id, scoped), payload, effective_qos)
+ except Exception:
+ _broker_logger.exception("IoT broker: subscriber %s delivery failed", sub.subscription_id)
+
+ if qos >= 1:
+ for key, ps in list(_persistent_sessions.items()):
+ ps_account_id, ps_client_id = key
+ if ps_account_id != account_id:
+ continue
+ if key in _connected_clients:
+ continue
+ if _is_session_expired(ps):
+ continue
+ for filt in ps.subscriptions:
+ scoped_filter = _scoped_topic(ps_account_id, filt)
+ if _topic_matches(scoped_filter, scoped):
+ ps.queued_messages.append((topic, payload, qos))
+ if len(ps.queued_messages) > _MAX_QUEUED_MESSAGES:
+ ps.queued_messages = ps.queued_messages[-_MAX_QUEUED_MESSAGES:]
+ break
+
+
+async def broker_subscribe(
+ account_id: str,
+ topic_filter: str,
+ callback: Callable[[str, bytes, int], Awaitable[None]],
+ granted_qos: int = 0,
+) -> str:
+ filter_prefixed = _scoped_topic(account_id, topic_filter)
+ sub = _Subscription(filter_prefixed, account_id, callback, granted_qos)
+ async with _broker_lock:
+ _subscriptions.setdefault(filter_prefixed, set()).add(sub)
+ has_wildcard = "+" in topic_filter or "#" in topic_filter
+ if not has_wildcard:
+ retained_to_send = [
+ r for k, r in _retained.items() if _topic_matches(filter_prefixed, k)
+ ]
+ else:
+ retained_to_send = []
+
+ for r in retained_to_send:
+ try:
+ await sub.deliver(_unscope_topic(account_id, r.topic), r.payload, r.qos)
+ except Exception:
+ _broker_logger.exception("IoT broker: retained-message delivery failed")
+
+ return sub.subscription_id
+
+
+async def broker_unsubscribe(subscription_id: str) -> None:
+ async with _broker_lock:
+ for filter_, subs in list(_subscriptions.items()):
+ for s in list(subs):
+ if s.subscription_id == subscription_id:
+ subs.discard(s)
+ if not subs:
+ _subscriptions.pop(filter_, None)
+
+
+def broker_reset() -> None:
+ _subscriptions.clear()
+ _retained.clear()
+ _connected_clients.clear()
+ _persistent_sessions.clear()
+
+
+# ---------------------------------------------------------------------------
+# Connected-client registry & duplicate detection
+# ---------------------------------------------------------------------------
+
+
+def _register_client(account_id: str, client_id: str, session: "_WSSession") -> None:
+ _connected_clients[(account_id, client_id)] = session
+
+
+def _deregister_client(account_id: str, client_id: str) -> None:
+ _connected_clients.pop((account_id, client_id), None)
+
+
+async def _force_disconnect_duplicate(account_id: str, client_id: str) -> None:
+ key = (account_id, client_id)
+ existing = _connected_clients.get(key)
+ if existing is not None:
+ _broker_logger.info("IoT broker: duplicate client_id=%s, forcing old connection closed", client_id)
+ try:
+ await existing._send({"type": "websocket.close", "code": 1000})
+ except Exception:
+ pass
+ await existing.cleanup()
+ _connected_clients.pop(key, None)
+
+
+# ---------------------------------------------------------------------------
+# MQTT 3.1.1 frame codec
+# ---------------------------------------------------------------------------
+
+PKT_CONNECT = 1
+PKT_CONNACK = 2
+PKT_PUBLISH = 3
+PKT_PUBACK = 4
+PKT_SUBSCRIBE = 8
+PKT_SUBACK = 9
+PKT_UNSUBSCRIBE = 10
+PKT_UNSUBACK = 11
+PKT_PINGREQ = 12
+PKT_PINGRESP = 13
+PKT_DISCONNECT = 14
+
+
+def _encode_remaining_length(n: int) -> bytes:
+ out = bytearray()
+ while True:
+ byte = n & 0x7F
+ n >>= 7
+ if n > 0:
+ byte |= 0x80
+ out.append(byte)
+ if n == 0:
+ return bytes(out)
+
+
+def _decode_remaining_length(buf: bytes, offset: int) -> tuple[int, int]:
+ multiplier = 1
+ value = 0
+ pos = offset
+ while True:
+ if pos >= len(buf):
+ raise ValueError("Truncated remaining length")
+ b = buf[pos]
+ pos += 1
+ value += (b & 0x7F) * multiplier
+ if b & 0x80 == 0:
+ break
+ multiplier *= 128
+ if multiplier > 128 * 128 * 128:
+ raise ValueError("Remaining length exceeds 4 bytes")
+ return value, pos
+
+
+def _read_string(buf: bytes, offset: int) -> tuple[str, int]:
+ if offset + 2 > len(buf):
+ raise ValueError("Truncated string length")
+ n = struct.unpack_from("!H", buf, offset)[0]
+ offset += 2
+ if offset + n > len(buf):
+ raise ValueError("Truncated string body")
+ return buf[offset:offset + n].decode("utf-8"), offset + n
+
+
+def _encode_string(s: str) -> bytes:
+ raw = s.encode("utf-8")
+ return struct.pack("!H", len(raw)) + raw
+
+
+def _make_connack(return_code: int = 0, session_present: bool = False) -> bytes:
+ flags = 1 if session_present else 0
+ body = bytes([flags, return_code])
+ return bytes([PKT_CONNACK << 4]) + _encode_remaining_length(len(body)) + body
+
+
+def _make_publish(topic: str, payload: bytes, qos: int = 0, packet_id: int | None = None,
+ retain: bool = False, dup: bool = False) -> bytes:
+ fixed = (PKT_PUBLISH << 4) | (qos << 1) | (0x08 if dup else 0) | (0x01 if retain else 0)
+ body = _encode_string(topic)
+ if qos > 0:
+ if packet_id is None:
+ packet_id = 1
+ body += struct.pack("!H", packet_id)
+ body += payload
+ return bytes([fixed]) + _encode_remaining_length(len(body)) + body
+
+
+def _make_puback(packet_id: int) -> bytes:
+ return bytes([PKT_PUBACK << 4]) + bytes([2]) + struct.pack("!H", packet_id)
+
+
+def _make_suback(packet_id: int, granted_qos: list[int]) -> bytes:
+ body = struct.pack("!H", packet_id) + bytes(granted_qos)
+ return bytes([PKT_SUBACK << 4]) + _encode_remaining_length(len(body)) + body
+
+
+def _make_unsuback(packet_id: int) -> bytes:
+ return bytes([PKT_UNSUBACK << 4]) + bytes([2]) + struct.pack("!H", packet_id)
+
+
+def _make_pingresp() -> bytes:
+ return bytes([PKT_PINGRESP << 4, 0])
+
+
+# ---------------------------------------------------------------------------
+# WebSocket session driver
+# ---------------------------------------------------------------------------
+
+
+def _max_frame_buffer_bytes() -> int:
+ return int(os.environ.get("IOT_WS_FRAME_MAX_BYTES", str(16 * 1024 * 1024)))
+
+
+class _WSSession:
+ def __init__(self, send_coro, account_id: str):
+ self._send = send_coro
+ self.account_id = account_id
+ self._sub_ids: list[str] = []
+ self._sub_filters: dict[str, str] = {}
+ self._sub_granted_qos: dict[str, int] = {}
+ self._buffer = bytearray()
+ self._next_pid = 1
+ self._send_lock = asyncio.Lock()
+ self._client_id: str = ""
+ self._clean_session: bool = True
+ self._in_flight: dict[int, _InFlightMessage] = {}
+ self._retransmit_task: asyncio.Task | None = None
+ self._will_topic: str | None = None
+ self._will_message: bytes | None = None
+ self._will_qos: int = 0
+ self._will_retain: bool = False
+ self._graceful_disconnect: bool = False
+
+ def _alloc_packet_id(self) -> int:
+ pid = self._next_pid
+ self._next_pid = (self._next_pid % 65535) + 1
+ return pid
+
+ def _ensure_retransmit_timer(self) -> None:
+ if self._retransmit_task is None or self._retransmit_task.done():
+ self._retransmit_task = asyncio.ensure_future(self._retransmit_loop())
+
+ async def _retransmit_loop(self) -> None:
+ try:
+ while self._in_flight:
+ await asyncio.sleep(_RETRANSMIT_INTERVAL_SECONDS)
+ now = asyncio.get_event_loop().time()
+ for pid, msg in list(self._in_flight.items()):
+ if now - msg.sent_at >= _RETRANSMIT_INTERVAL_SECONDS:
+ msg.retransmit_count += 1
+ msg.sent_at = now
+ await self.send_bytes(
+ _make_publish(msg.topic, msg.payload, qos=1, packet_id=pid, dup=True)
+ )
+ except asyncio.CancelledError:
+ pass
+
+ async def send_bytes(self, b: bytes) -> None:
+ async with self._send_lock:
+ await self._send({"type": "websocket.send", "bytes": b})
+
+ async def deliver_to_client(self, topic: str, payload: bytes, qos: int) -> None:
+ if qos == 0:
+ await self.send_bytes(_make_publish(topic, payload, qos=0))
+ else:
+ pid = self._alloc_packet_id()
+ self._in_flight[pid] = _InFlightMessage(pid, topic, payload)
+ await self.send_bytes(_make_publish(topic, payload, qos=1, packet_id=pid))
+ self._ensure_retransmit_timer()
+
+ def _take_packet(self) -> tuple[int, int, bytes] | None:
+ if len(self._buffer) < 2:
+ return None
+ first = self._buffer[0]
+ try:
+ remaining, header_end = _decode_remaining_length(bytes(self._buffer), 1)
+ except ValueError:
+ if len(self._buffer) > 5:
+ self._buffer.clear()
+ return None
+ total = header_end + remaining
+ if len(self._buffer) < total:
+ return None
+ body = bytes(self._buffer[header_end:total])
+ del self._buffer[:total]
+ pkt_type = (first >> 4) & 0x0F
+ flags = first & 0x0F
+ return pkt_type, flags, body
+
+ async def handle_packet(self, pkt_type: int, flags: int, body: bytes) -> bool:
+ if pkt_type == PKT_CONNECT:
+ off = 0
+ _proto_name, off = _read_string(body, off)
+ off += 1 # Protocol Level
+ if off >= len(body):
+ await self.send_bytes(_make_connack(return_code=0))
+ return True
+ connect_flags = body[off]
+ off += 1
+ off += 2 # Keep Alive
+
+ will_flag = bool(connect_flags & 0x04)
+ will_qos = (connect_flags >> 3) & 0x03
+ will_retain = bool(connect_flags & 0x20)
+ clean_session = bool(connect_flags & 0x02)
+
+ self._clean_session = clean_session
+
+ if off < len(body):
+ client_id, off = _read_string(body, off)
+ else:
+ client_id = ""
+ if not client_id:
+ client_id = uuid.uuid4().hex
+ self._client_id = client_id
+
+ if will_flag:
+ if off < len(body):
+ will_topic, off = _read_string(body, off)
+ else:
+ will_topic = ""
+ if off + 2 <= len(body):
+ msg_len = struct.unpack_from("!H", body, off)[0]
+ off += 2
+ will_message = body[off:off + msg_len]
+ off += msg_len
+ else:
+ will_message = b""
+ self._will_topic = will_topic
+ self._will_message = will_message
+ self._will_qos = will_qos
+ self._will_retain = will_retain
+ else:
+ self._will_topic = None
+ self._will_message = None
+ self._will_qos = 0
+ self._will_retain = False
+
+ self._graceful_disconnect = False
+ await _force_disconnect_duplicate(self.account_id, self._client_id)
+ _register_client(self.account_id, self._client_id, self)
+
+ session_key = (self.account_id, self._client_id)
+ session_present = False
+
+ if clean_session:
+ _persistent_sessions.pop(session_key, None)
+ else:
+ existing_ps = _persistent_sessions.get(session_key)
+ if existing_ps is not None and not _is_session_expired(existing_ps):
+ session_present = True
+ for topic_filter in existing_ps.subscriptions:
+ sid = await broker_subscribe(
+ self.account_id, topic_filter, self.deliver_to_client, 1
+ )
+ self._sub_ids.append(sid)
+ self._sub_filters[sid] = topic_filter
+ self._sub_granted_qos[sid] = 1
+ await self.send_bytes(_make_connack(return_code=0, session_present=True))
+ queued = existing_ps.queued_messages[:]
+ existing_ps.queued_messages.clear()
+ for q_topic, q_payload, q_qos in queued:
+ await self.deliver_to_client(q_topic, q_payload, q_qos)
+ return True
+ else:
+ _persistent_sessions[session_key] = _PersistentSessionState(
+ subscriptions=[], created_at=time.time()
+ )
+
+ await self.send_bytes(_make_connack(return_code=0, session_present=session_present))
+ return True
+
+ if pkt_type == PKT_PUBLISH:
+ qos = (flags >> 1) & 0x03
+ retain = bool(flags & 0x01)
+ topic, off = _read_string(body, 0)
+ packet_id = None
+ if qos > 0:
+ if off + 2 > len(body):
+ return True
+ packet_id = struct.unpack_from("!H", body, off)[0]
+ off += 2
+ if not _validate_publish_topic(topic):
+ _broker_logger.warning("IoT broker: PUBLISH rejected — invalid topic: %r", topic)
+ return False
+ payload = body[off:]
+ await broker_publish(self.account_id, topic, payload, qos=qos, retain=retain)
+ if qos == 1 and packet_id is not None:
+ await self.send_bytes(_make_puback(packet_id))
+ return True
+
+ if pkt_type == PKT_SUBSCRIBE:
+ packet_id = struct.unpack_from("!H", body, 0)[0]
+ off = 2
+ granted = []
+ while off < len(body):
+ topic, off = _read_string(body, off)
+ req_qos = body[off]
+ off += 1
+ granted_qos = min(req_qos, 1)
+ granted.append(granted_qos)
+ sid = await broker_subscribe(self.account_id, topic, self.deliver_to_client, granted_qos)
+ self._sub_ids.append(sid)
+ self._sub_filters[sid] = topic
+ self._sub_granted_qos[sid] = granted_qos
+ await self.send_bytes(_make_suback(packet_id, granted))
+ return True
+
+ if pkt_type == PKT_PUBACK:
+ if len(body) >= 2:
+ packet_id = struct.unpack_from("!H", body, 0)[0]
+ self._in_flight.pop(packet_id, None)
+ return True
+
+ if pkt_type == PKT_UNSUBSCRIBE:
+ packet_id = struct.unpack_from("!H", body, 0)[0]
+ for sid in list(self._sub_ids):
+ await broker_unsubscribe(sid)
+ self._sub_ids.clear()
+ await self.send_bytes(_make_unsuback(packet_id))
+ return True
+
+ if pkt_type == PKT_PINGREQ:
+ await self.send_bytes(_make_pingresp())
+ return True
+
+ if pkt_type == PKT_DISCONNECT:
+ self._graceful_disconnect = True
+ return False
+
+ return True
+
+ async def cleanup(self) -> None:
+ if self._retransmit_task is not None and not self._retransmit_task.done():
+ self._retransmit_task.cancel()
+ try:
+ await self._retransmit_task
+ except asyncio.CancelledError:
+ pass
+ self._retransmit_task = None
+ self._in_flight.clear()
+ if not self._graceful_disconnect and self._will_topic is not None:
+ await broker_publish(
+ self.account_id,
+ self._will_topic,
+ self._will_message or b"",
+ qos=self._will_qos,
+ retain=self._will_retain,
+ )
+ if not self._clean_session and self._client_id:
+ self._preserve_session()
+ for sid in self._sub_ids:
+ await broker_unsubscribe(sid)
+ self._sub_ids.clear()
+ self._sub_filters.clear()
+ self._sub_granted_qos.clear()
+ if self._client_id:
+ _deregister_client(self.account_id, self._client_id)
+
+ def _preserve_session(self) -> None:
+ session_key = (self.account_id, self._client_id)
+ unprefixed_filters = list(self._sub_filters.values())
+ existing = _persistent_sessions.get(session_key)
+ if existing is not None:
+ existing.subscriptions = unprefixed_filters
+ existing.created_at = time.time()
+ else:
+ _persistent_sessions[session_key] = _PersistentSessionState(
+ subscriptions=unprefixed_filters, created_at=time.time()
+ )
+
+
+async def handle_websocket(scope: dict, receive, send, account_id: str) -> None:
+ """Drive an MQTT-over-WebSocket session."""
+ msg = await receive()
+ if msg.get("type") != "websocket.connect":
+ return
+
+ sub_headers = {}
+ for name, value in scope.get("headers", []):
+ try:
+ sub_headers[name.decode("latin-1").lower()] = value.decode("utf-8")
+ except UnicodeDecodeError:
+ sub_headers[name.decode("latin-1").lower()] = value.decode("latin-1")
+ requested = sub_headers.get("sec-websocket-protocol", "")
+ chosen = None
+ for proto in [p.strip() for p in requested.split(",") if p.strip()]:
+ if proto.lower() in ("mqtt", "mqttv3.1", "mqttv5"):
+ chosen = proto
+ break
+
+ accept: dict = {"type": "websocket.accept"}
+ if chosen:
+ accept["subprotocol"] = chosen
+ await send(accept)
+
+ ctx_token = _request_account_id.set(account_id)
+ session = _WSSession(send, account_id)
+ max_buffer = _max_frame_buffer_bytes()
+
+ try:
+ while True:
+ incoming = await receive()
+ mtype = incoming.get("type")
+ if mtype == "websocket.disconnect":
+ break
+ if mtype != "websocket.receive":
+ continue
+ data = incoming.get("bytes")
+ if data is None:
+ text = incoming.get("text")
+ 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")
+ 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:
+ await session.cleanup()
+ try:
+ _request_account_id.reset(ctx_token)
+ except Exception:
+ pass
+ try:
+ await send({"type": "websocket.close", "code": 1000})
+ except Exception:
+ pass
diff --git a/ministack/services/iot_data.py b/ministack/services/iot_data.py
new file mode 100644
index 00000000..af6bce95
--- /dev/null
+++ b/ministack/services/iot_data.py
@@ -0,0 +1,146 @@
+"""IoT Data Plane HTTP API (``iot-data`` AWS service).
+
+Implements the HTTP-side of the AWS IoT Data Plane. The data plane mirrors
+the broker over a small REST surface (``Publish`` is the primary
+operation; ``GetRetainedMessage`` / ``ListRetainedMessages`` are not yet implemented).
+
+Routing reaches us either through credential-scope detection (the SDK signs
+requests with the ``iotdata`` scope) or via the host pattern
+``data-ats.iot.{region}.{host}`` / ``data.iot.{region}.{host}``.
+
+Bridges into the in-memory MQTT broker via :mod:`ministack.services.iot`,
+which applies account-scoped topic prefixing transparently.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from urllib.parse import unquote
+
+from ministack.core.responses import (
+ error_response_json,
+ get_account_id,
+ json_response,
+)
+from ministack.services import iot as _iot_module
+
+logger = logging.getLogger("iot_data")
+
+
+# AWS IoT topics: max 7 segments, max 256 UTF-8 bytes total.
+_MAX_TOPIC_BYTES = 256
+
+
+def _validate_topic(topic: str) -> tuple | None:
+ """Return an error response if ``topic`` is invalid, else None."""
+ if not topic:
+ return error_response_json(
+ "InvalidRequestException", "Topic must not be empty", 400
+ )
+ if "+" in topic or "#" in topic:
+ return error_response_json(
+ "InvalidRequestException",
+ "Topic must not contain wildcard characters",
+ 400,
+ )
+ if len(topic.encode("utf-8")) > _MAX_TOPIC_BYTES:
+ return error_response_json(
+ "InvalidRequestException",
+ f"Topic exceeds {_MAX_TOPIC_BYTES} bytes",
+ 400,
+ )
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Persistence (no state of our own — broker holds it)
+# ---------------------------------------------------------------------------
+
+
+def get_state() -> dict:
+ return {}
+
+
+def restore_state(data: dict | None) -> None:
+ return None
+
+
+def reset() -> None:
+ _iot_module.broker_reset()
+
+
+# ---------------------------------------------------------------------------
+# Dispatcher
+# ---------------------------------------------------------------------------
+
+
+async def handle_request(
+ method: str, path: str, headers: dict, body: bytes, query_params: dict
+) -> tuple:
+ qp = {k: (v[0] if isinstance(v, list) else v) for k, v in query_params.items()}
+
+ if method == "POST" and path.startswith("/topics/"):
+ return await _publish(path[len("/topics/"):], body, qp)
+
+ # Placeholders — return 501 so SDKs that probe these endpoints
+ # get a clear "not implemented" rather than a generic 404.
+ if path == "/retainedMessage":
+ return error_response_json(
+ "InvalidRequestException",
+ "ListRetainedMessages is not yet implemented",
+ 501,
+ )
+ if path.startswith("/retainedMessage/"):
+ return error_response_json(
+ "InvalidRequestException",
+ "GetRetainedMessage is not yet implemented",
+ 501,
+ )
+
+ return error_response_json(
+ "InvalidRequestException", f"Unsupported iot-data path: {method} {path}", 400
+ )
+
+
+async def _publish(raw_topic: str, body: bytes, qp: dict) -> tuple:
+ """``POST /topics/{topic}`` — forward body to the broker.
+
+ ``raw_topic`` is what came after ``/topics/`` in the URL. The SDK URL-
+ encodes ``/`` separators so we decode here and validate before relaying.
+ """
+ topic = unquote(raw_topic or "")
+ err = _validate_topic(topic)
+ if err is not None:
+ return err
+
+ try:
+ qos = int(qp.get("qos", 0))
+ except (TypeError, ValueError):
+ return error_response_json(
+ "InvalidRequestException", "qos must be 0 or 1", 400
+ )
+ if qos not in (0, 1):
+ return error_response_json(
+ "InvalidRequestException", "qos must be 0 or 1", 400
+ )
+ retain = str(qp.get("retain", "")).lower() in ("1", "true", "yes")
+
+ if not _iot_module.broker_is_available():
+ return error_response_json(
+ "InternalFailureException",
+ "IoT broker is not available",
+ 503,
+ )
+
+ try:
+ await _iot_module.broker_publish(
+ get_account_id(), topic, body or b"", qos=qos, retain=retain
+ )
+ except Exception as e:
+ logger.exception("iot-data publish failed")
+ return error_response_json(
+ "InternalFailureException", f"Publish failed: {e}", 503,
+ )
+ # AWS returns 200 with empty body for Publish.
+ return 200, {"Content-Type": "application/json"}, b""
diff --git a/pyproject.toml b/pyproject.toml
index 56bf952e..f2d947b0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -49,6 +49,7 @@ dev = [
"ruff>=0.4",
"mypy-boto3-lambda (>=1.42.85,<2.0.0)",
"asyncssh>=2.14",
+ "websockets>=12.0",
]
[project.urls]
diff --git a/tests/conftest.py b/tests/conftest.py
index d44e9f6e..1b2c7ea5 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -343,6 +343,16 @@ def acm_client():
return make_client("acm")
[email protected](scope="session")
+def iot_client():
+ return make_client("iot")
+
+
[email protected](scope="session")
+def iot_data_client():
+ return make_client("iot-data")
+
+
@pytest.fixture(scope="session")
def wafv2():
return make_client("wafv2")
diff --git a/tests/test_iot.py b/tests/test_iot.py
new file mode 100644
index 00000000..afb40d48
--- /dev/null
+++ b/tests/test_iot.py
@@ -0,0 +1,427 @@
+"""Integration tests for the IoT Core control plane (Phase 1a).
+
+Exercises Things, ThingTypes, ThingGroups, Certificates (issued via the
+Local CA), Policies, and DescribeEndpoint. The data plane (broker / WS /
+iot-data Publish) is covered separately in ``test_iot_data.py``.
+"""
+
+import json
+import uuid
+
+import pytest
+from botocore.exceptions import ClientError
+
+
+def _unique(prefix: str) -> str:
+ return f"{prefix}-{uuid.uuid4().hex[:8]}"
+
+
+# ---------------------------------------------------------------------------
+# Endpoint
+# ---------------------------------------------------------------------------
+
+
+def test_iot_describe_endpoint_data_ats(iot_client):
+ resp = iot_client.describe_endpoint(endpointType="iot:Data-ATS")
+ addr = resp["endpointAddress"]
+ assert "-ats.iot." in addr
+ assert "us-east-1" in addr
+
+
+def test_iot_describe_endpoint_default_uses_data_ats(iot_client):
+ resp = iot_client.describe_endpoint()
+ assert "-ats.iot." in resp["endpointAddress"]
+
+
+def test_iot_describe_endpoint_data_legacy(iot_client):
+ resp = iot_client.describe_endpoint(endpointType="iot:Data")
+ addr = resp["endpointAddress"]
+ # Legacy endpoint omits the -ats suffix.
+ assert ".iot." in addr
+ assert "-ats.iot." not in addr
+
+
+def test_iot_describe_endpoint_unknown_type_rejected(iot_client):
+ with pytest.raises(ClientError) as ei:
+ iot_client.describe_endpoint(endpointType="iot:Bogus")
+ assert ei.value.response["Error"]["Code"] in ("InvalidRequestException",)
+
+
+# ---------------------------------------------------------------------------
+# Thing CRUD
+# ---------------------------------------------------------------------------
+
+
+def test_iot_create_describe_thing(iot_client):
+ name = _unique("thing")
+ resp = iot_client.create_thing(thingName=name)
+ assert resp["thingName"] == name
+ assert resp["thingArn"].endswith(f":thing/{name}")
+ assert resp["thingId"]
+
+ desc = iot_client.describe_thing(thingName=name)
+ assert desc["thingName"] == name
+ assert desc["version"] == 1
+ iot_client.delete_thing(thingName=name)
+
+
+def test_iot_create_thing_with_attributes(iot_client):
+ name = _unique("thing")
+ iot_client.create_thing(
+ thingName=name,
+ attributePayload={"attributes": {"color": "red", "size": "L"}},
+ )
+ desc = iot_client.describe_thing(thingName=name)
+ assert desc["attributes"] == {"color": "red", "size": "L"}
+ iot_client.delete_thing(thingName=name)
+
+
+def test_iot_create_thing_idempotent_same_config(iot_client):
+ name = _unique("thing")
+ iot_client.create_thing(
+ thingName=name,
+ attributePayload={"attributes": {"color": "red"}},
+ )
+ # Same config must not raise.
+ resp2 = iot_client.create_thing(
+ thingName=name,
+ attributePayload={"attributes": {"color": "red"}},
+ )
+ assert resp2["thingName"] == name
+ iot_client.delete_thing(thingName=name)
+
+
+def test_iot_create_thing_conflict_different_config(iot_client):
+ name = _unique("thing")
+ iot_client.create_thing(
+ thingName=name,
+ attributePayload={"attributes": {"color": "red"}},
+ )
+ with pytest.raises(ClientError) as ei:
+ iot_client.create_thing(
+ thingName=name,
+ attributePayload={"attributes": {"color": "blue"}},
+ )
+ assert ei.value.response["Error"]["Code"] == "ResourceAlreadyExistsException"
+ iot_client.delete_thing(thingName=name)
+
+
+def test_iot_describe_unknown_thing_404(iot_client):
+ with pytest.raises(ClientError) as ei:
+ iot_client.describe_thing(thingName=_unique("nope"))
+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_iot_update_thing_increments_version(iot_client):
+ name = _unique("thing")
+ iot_client.create_thing(thingName=name)
+ iot_client.update_thing(
+ thingName=name,
+ attributePayload={"attributes": {"k": "v"}},
+ )
+ desc = iot_client.describe_thing(thingName=name)
+ assert desc["version"] == 2
+ assert desc["attributes"] == {"k": "v"}
+ iot_client.delete_thing(thingName=name)
+
+
+def test_iot_list_things_filter_by_attribute(iot_client):
+ a = _unique("thing")
+ b = _unique("thing")
+ iot_client.create_thing(
+ thingName=a, attributePayload={"attributes": {"region": "eu"}}
+ )
+ iot_client.create_thing(
+ thingName=b, attributePayload={"attributes": {"region": "us"}}
+ )
+ resp = iot_client.list_things(attributeName="region", attributeValue="eu")
+ names = {t["thingName"] for t in resp["things"]}
+ assert a in names and b not in names
+ iot_client.delete_thing(thingName=a)
+ iot_client.delete_thing(thingName=b)
+
+
+def test_iot_list_things_filter_by_thing_type(iot_client):
+ type_a = _unique("type")
+ iot_client.create_thing_type(thingTypeName=type_a)
+ name = _unique("thing")
+ iot_client.create_thing(thingName=name, thingTypeName=type_a)
+
+ resp = iot_client.list_things(thingTypeName=type_a)
+ assert any(t["thingName"] == name for t in resp["things"])
+
+ iot_client.delete_thing(thingName=name)
+ iot_client.deprecate_thing_type(thingTypeName=type_a)
+ iot_client.delete_thing_type(thingTypeName=type_a)
+
+
+# ---------------------------------------------------------------------------
+# ThingType CRUD
+# ---------------------------------------------------------------------------
+
+
+def test_iot_thing_type_lifecycle(iot_client):
+ name = _unique("type")
+ iot_client.create_thing_type(thingTypeName=name)
+ desc = iot_client.describe_thing_type(thingTypeName=name)
+ assert desc["thingTypeName"] == name
+ assert desc["thingTypeMetadata"]["deprecated"] is False
+
+ iot_client.deprecate_thing_type(thingTypeName=name)
+ desc2 = iot_client.describe_thing_type(thingTypeName=name)
+ assert desc2["thingTypeMetadata"]["deprecated"] is True
+
+ iot_client.delete_thing_type(thingTypeName=name)
+ with pytest.raises(ClientError) as ei:
+ iot_client.describe_thing_type(thingTypeName=name)
+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"
+
+
+def test_iot_delete_thing_type_active_rejected(iot_client):
+ name = _unique("type")
+ iot_client.create_thing_type(thingTypeName=name)
+ with pytest.raises(ClientError) as ei:
+ iot_client.delete_thing_type(thingTypeName=name)
+ assert ei.value.response["Error"]["Code"] == "InvalidRequestException"
+ iot_client.deprecate_thing_type(thingTypeName=name)
+ iot_client.delete_thing_type(thingTypeName=name)
+
+
+# ---------------------------------------------------------------------------
+# ThingGroup CRUD + membership
+# ---------------------------------------------------------------------------
+
+
+def test_iot_thing_group_membership(iot_client):
+ gname = _unique("group")
+ tname = _unique("thing")
+ iot_client.create_thing_group(thingGroupName=gname)
+ iot_client.create_thing(thingName=tname)
+
+ iot_client.add_thing_to_thing_group(thingGroupName=gname, thingName=tname)
+ things = iot_client.list_things_in_thing_group(thingGroupName=gname)["things"]
+ assert tname in things
+
+ iot_client.remove_thing_from_thing_group(thingGroupName=gname, thingName=tname)
+ things2 = iot_client.list_things_in_thing_group(thingGroupName=gname)["things"]
+ assert tname not in things2
+
+ iot_client.delete_thing(thingName=tname)
+ iot_client.delete_thing_group(thingGroupName=gname)
+
+
+# ---------------------------------------------------------------------------
+# Certificates (issued via the Local CA)
+# ---------------------------------------------------------------------------
+
+
+def test_iot_create_keys_and_certificate_active(iot_client):
+ pytest.importorskip("cryptography")
+ resp = iot_client.create_keys_and_certificate(setAsActive=True)
+ assert resp["certificateId"]
+ assert resp["certificateArn"].endswith(":cert/" + resp["certificateId"])
+ assert "BEGIN CERTIFICATE" in resp["certificatePem"]
+ assert "BEGIN" in resp["keyPair"]["PrivateKey"]
+ assert "BEGIN PUBLIC KEY" in resp["keyPair"]["PublicKey"]
+
+ desc = iot_client.describe_certificate(certificateId=resp["certificateId"])
+ assert desc["certificateDescription"]["status"] == "ACTIVE"
+
+ # Deactivate and delete
+ iot_client.update_certificate(
+ certificateId=resp["certificateId"], newStatus="INACTIVE"
+ )
+ iot_client.delete_certificate(certificateId=resp["certificateId"])
+
+
+def test_iot_create_keys_and_certificate_inactive(iot_client):
+ pytest.importorskip("cryptography")
+ resp = iot_client.create_keys_and_certificate(setAsActive=False)
+ desc = iot_client.describe_certificate(certificateId=resp["certificateId"])
+ assert desc["certificateDescription"]["status"] == "INACTIVE"
+ iot_client.delete_certificate(certificateId=resp["certificateId"])
+
+
+def test_iot_delete_active_certificate_rejected(iot_client):
+ pytest.importorskip("cryptography")
+ resp = iot_client.create_keys_and_certificate(setAsActive=True)
+ cert_id = resp["certificateId"]
+ with pytest.raises(ClientError) as ei:
+ iot_client.delete_certificate(certificateId=cert_id)
+ assert ei.value.response["Error"]["Code"] == "CertificateStateException"
+ iot_client.update_certificate(certificateId=cert_id, newStatus="INACTIVE")
+ iot_client.delete_certificate(certificateId=cert_id)
+
+
+def test_iot_register_certificate_preserves_pem_verbatim(iot_client):
+ pytest.importorskip("cryptography")
+ # Issue a cert, capture its PEM, delete it, then re-register the SAME PEM.
+ issued = iot_client.create_keys_and_certificate(setAsActive=False)
+ cert_pem = issued["certificatePem"]
+ iot_client.delete_certificate(certificateId=issued["certificateId"])
+
+ resp = iot_client.register_certificate(
+ certificatePem=cert_pem, status="ACTIVE"
+ )
+ cert_id = resp["certificateId"]
+ desc = iot_client.describe_certificate(certificateId=cert_id)
+ assert desc["certificateDescription"]["certificatePem"] == cert_pem
+ iot_client.update_certificate(certificateId=cert_id, newStatus="INACTIVE")
+ iot_client.delete_certificate(certificateId=cert_id)
+
+
+def test_iot_attach_detach_thing_principal(iot_client):
+ pytest.importorskip("cryptography")
+ name = _unique("thing")
+ iot_client.create_thing(thingName=name)
+ cert = iot_client.create_keys_and_certificate(setAsActive=True)
+ arn = cert["certificateArn"]
+
+ iot_client.attach_thing_principal(thingName=name, principal=arn)
+ principals = iot_client.list_thing_principals(thingName=name)["principals"]
+ assert arn in principals
+ things = iot_client.list_principal_things(principal=arn)["things"]
+ assert name in things
+
+ iot_client.detach_thing_principal(thingName=name, principal=arn)
+ principals2 = iot_client.list_thing_principals(thingName=name)["principals"]
+ assert arn not in principals2
+
+ iot_client.update_certificate(certificateId=cert["certificateId"], newStatus="INACTIVE")
+ iot_client.delete_certificate(certificateId=cert["certificateId"])
+ iot_client.delete_thing(thingName=name)
+
+
+# ---------------------------------------------------------------------------
+# Policies
+# ---------------------------------------------------------------------------
+
+
+_POLICY_DOC = json.dumps(
+ {
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Action": ["iot:Connect", "iot:Publish"],
+ "Resource": "*",
+ }
+ ],
+ }
+)
+
+
+def test_iot_policy_lifecycle(iot_client):
+ name = _unique("policy")
+ resp = iot_client.create_policy(policyName=name, policyDocument=_POLICY_DOC)
+ assert resp["policyName"] == name
+ assert resp["policyVersionId"] == "1"
+
+ got = iot_client.get_policy(policyName=name)
+ assert got["defaultVersionId"] == "1"
+
+ listing = iot_client.list_policies()["policies"]
+ assert any(p["policyName"] == name for p in listing)
+
+ iot_client.delete_policy(policyName=name)
+
+
+def test_iot_create_policy_malformed_400(iot_client):
+ name = _unique("policy")
+ with pytest.raises(ClientError) as ei:
+ iot_client.create_policy(policyName=name, policyDocument="not-json")
+ assert ei.value.response["Error"]["Code"] == "MalformedPolicyException"
+
+
+def test_iot_policy_versions(iot_client):
+ name = _unique("policy")
+ iot_client.create_policy(policyName=name, policyDocument=_POLICY_DOC)
+ new_doc = json.dumps(
+ {
+ "Version": "2012-10-17",
+ "Statement": [
+ {"Effect": "Allow", "Action": "iot:Subscribe", "Resource": "*"}
+ ],
+ }
+ )
+ v2 = iot_client.create_policy_version(
+ policyName=name, policyDocument=new_doc, setAsDefault=True
+ )
+ assert v2["policyVersionId"] == "2"
+
+ versions = iot_client.list_policy_versions(policyName=name)["policyVersions"]
+ assert {v["versionId"] for v in versions} == {"1", "2"}
+ assert next(v for v in versions if v["versionId"] == "2")["isDefaultVersion"]
+
+ iot_client.delete_policy_version(policyName=name, policyVersionId="1")
+ iot_client.delete_policy(policyName=name)
+
+
+def test_iot_attach_detach_policy(iot_client):
+ pytest.importorskip("cryptography")
+ name = _unique("policy")
+ iot_client.create_policy(policyName=name, policyDocument=_POLICY_DOC)
+ cert = iot_client.create_keys_and_certificate(setAsActive=False)
+ arn = cert["certificateArn"]
+
+ iot_client.attach_policy(policyName=name, target=arn)
+ targets = iot_client.list_targets_for_policy(policyName=name)["targets"]
+ assert arn in targets
+
+ iot_client.detach_policy(policyName=name, target=arn)
+ targets2 = iot_client.list_targets_for_policy(policyName=name)["targets"]
+ assert arn not in targets2
+
+ iot_client.delete_policy(policyName=name)
+ iot_client.delete_certificate(certificateId=cert["certificateId"])
+
+
+# ---------------------------------------------------------------------------
+# Local CA admin endpoint
+# ---------------------------------------------------------------------------
+
+
+def test_iot_ca_pem_endpoint_returns_certificate():
+ pytest.importorskip("cryptography")
+ import os
+ import urllib.request
+
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+ with urllib.request.urlopen(f"{endpoint}/_ministack/iot/ca.pem", timeout=5) as resp:
+ body = resp.read().decode("utf-8")
+ assert "BEGIN CERTIFICATE" in body
+ assert "END CERTIFICATE" in body
+
+
+# ---------------------------------------------------------------------------
+# Account isolation
+# ---------------------------------------------------------------------------
+
+
+def test_iot_account_isolation():
+ """Two callers using different 12-digit access keys see different Things."""
+ import os
+
+ import boto3
+ from botocore.config import Config
+
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+
+ def _client(account_id):
+ return boto3.client(
+ "iot",
+ endpoint_url=endpoint,
+ aws_access_key_id=account_id,
+ aws_secret_access_key="test",
+ region_name="us-east-1",
+ config=Config(retries={"mode": "standard"}),
+ )
+
+ a = _client("111111111111")
+ b = _client("222222222222")
+ name = _unique("thing")
+ a.create_thing(thingName=name)
+ # Account B must not see Thing in account A.
+ b_things = {t["thingName"] for t in b.list_things().get("things", [])}
+ assert name not in b_things
+ a.delete_thing(thingName=name)
diff --git a/tests/test_iot_data.py b/tests/test_iot_data.py
new file mode 100644
index 00000000..e1da7491
--- /dev/null
+++ b/tests/test_iot_data.py
@@ -0,0 +1,359 @@
+"""Integration tests for the IoT Core data plane (Phase 1b).
+
+Covers the ``iot-data Publish`` HTTP API and the MQTT-over-WebSocket bridge
+that powers the original use case from issue #564 (Lambda publishes via
+HTTP → browser subscribes via WebSocket).
+
+The bridge implements MQTT 3.1.1 framing internally (no external broker
+binary). Multi-tenancy is enforced by transparent topic prefixing in the
+bridge layer.
+"""
+
+from __future__ import annotations
+
+import os
+import struct
+import threading
+import time
+import uuid
+from urllib.parse import quote, urlparse
+
+import pytest
+from botocore.exceptions import ClientError
+
+
+ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+
+
+def _unique(prefix: str) -> str:
+ return f"{prefix}-{uuid.uuid4().hex[:8]}"
+
+
+# ---------------------------------------------------------------------------
+# HTTP Publish (boto3 ``iot-data`` client)
+# ---------------------------------------------------------------------------
+
+
+def test_iot_data_publish_returns_200(iot_data_client):
+ resp = iot_data_client.publish(topic=_unique("topic"), payload=b"hello")
+ md = resp["ResponseMetadata"]
+ assert md["HTTPStatusCode"] == 200
+
+
+def test_iot_data_publish_accepts_qos_and_retain(iot_data_client):
+ topic = _unique("retained")
+ resp = iot_data_client.publish(
+ topic=topic, qos=1, retain=True, payload=b"sticky"
+ )
+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
+
+
+def test_iot_data_publish_rejects_wildcard_topic():
+ """Wildcard characters in publish topics must produce a 400."""
+ import urllib.request
+
+ req = urllib.request.Request(
+ f"{ENDPOINT}/topics/" + quote("foo/+/bar", safe=""),
+ data=b"x",
+ method="POST",
+ headers={"Authorization": "AWS4-HMAC-SHA256 Credential=test/0/0/iotdata/aws4_request"},
+ )
+ try:
+ urllib.request.urlopen(req, timeout=5)
+ pytest.fail("expected HTTP 400")
+ except urllib.error.HTTPError as e:
+ assert e.code == 400
+
+
+def test_iot_data_publish_rejects_empty_topic():
+ import urllib.request
+
+ req = urllib.request.Request(
+ f"{ENDPOINT}/topics/",
+ data=b"x",
+ method="POST",
+ headers={"Authorization": "AWS4-HMAC-SHA256 Credential=test/0/0/iotdata/aws4_request"},
+ )
+ try:
+ urllib.request.urlopen(req, timeout=5)
+ pytest.fail("expected error")
+ except urllib.error.HTTPError as e:
+ # Either 400 (we caught it) or 404 (router didn't match) is acceptable —
+ # both signal "this isn't a valid Publish call".
+ assert e.code in (400, 404)
+
+
+def test_iot_data_publish_oversized_topic_400():
+ import urllib.request
+
+ long_topic = "a" * 300
+ req = urllib.request.Request(
+ f"{ENDPOINT}/topics/" + quote(long_topic, safe=""),
+ data=b"x",
+ method="POST",
+ headers={"Authorization": "AWS4-HMAC-SHA256 Credential=test/0/0/iotdata/aws4_request"},
+ )
+ try:
+ urllib.request.urlopen(req, timeout=5)
+ pytest.fail("expected HTTP 400")
+ except urllib.error.HTTPError as e:
+ assert e.code == 400
+
+
+# ---------------------------------------------------------------------------
+# MQTT-over-WebSocket round-trip
+# ---------------------------------------------------------------------------
+#
+# The reference test for the unblocking use case from issue #564:
+# 1. WebSocket client subscribes to topic T
+# 2. Lambda calls iot-data Publish on T over HTTP
+# 3. WebSocket subscriber receives the message within 2 seconds.
+
+
+pytest.importorskip("websockets")
+import asyncio # noqa: E402
+
+import websockets # noqa: E402
+
+
+# Minimal MQTT 3.1.1 codec for the test client.
+
+
+def _enc_remaining(n: int) -> bytes:
+ out = bytearray()
+ while True:
+ b = n & 0x7F
+ n >>= 7
+ if n > 0:
+ b |= 0x80
+ out.append(b)
+ if n == 0:
+ return bytes(out)
+
+
+def _enc_str(s: str) -> bytes:
+ raw = s.encode("utf-8")
+ return struct.pack("!H", len(raw)) + raw
+
+
+def _make_connect(client_id: str) -> bytes:
+ body = (
+ _enc_str("MQTT") # protocol name
+ + bytes([4]) # protocol level (3.1.1)
+ + bytes([0x02]) # connect flags: clean session
+ + struct.pack("!H", 60) # keep-alive
+ + _enc_str(client_id)
+ )
+ return bytes([0x10]) + _enc_remaining(len(body)) + body
+
+
+def _make_subscribe(packet_id: int, topic: str, qos: int = 0) -> bytes:
+ body = struct.pack("!H", packet_id) + _enc_str(topic) + bytes([qos])
+ return bytes([0x82]) + _enc_remaining(len(body)) + body
+
+
+def _decode_remaining(buf: bytes, off: int) -> tuple[int, int]:
+ multiplier = 1
+ value = 0
+ pos = off
+ while True:
+ b = buf[pos]
+ pos += 1
+ value += (b & 0x7F) * multiplier
+ if b & 0x80 == 0:
+ return value, pos
+ multiplier *= 128
+
+
+def _parse_packet(buf: bytes) -> tuple[int, int, bytes, int] | None:
+ """Try to extract one packet. Returns (type, flags, body, total_consumed) or None."""
+ if len(buf) < 2:
+ return None
+ first = buf[0]
+ try:
+ remaining, header_end = _decode_remaining(buf, 1)
+ except IndexError:
+ return None
+ total = header_end + remaining
+ if len(buf) < total:
+ return None
+ return (first >> 4) & 0x0F, first & 0x0F, buf[header_end:total], total
+
+
+async def _ws_subscribe_and_collect(
+ ws_url: str, topic: str, ready_event: threading.Event, received: list, stop: threading.Event
+):
+ async with websockets.connect(ws_url, subprotocols=["mqtt"]) as ws:
+ await ws.send(_make_connect("test-client"))
+ # Wait for CONNACK
+ await asyncio.wait_for(ws.recv(), timeout=2.0)
+ # Subscribe
+ await ws.send(_make_subscribe(packet_id=1, topic=topic, qos=0))
+ # Wait for SUBACK
+ await asyncio.wait_for(ws.recv(), timeout=2.0)
+ ready_event.set()
+
+ # Collect PUBLISH frames until stop or timeout.
+ end_at = time.time() + 5
+ while not stop.is_set() and time.time() < end_at:
+ try:
+ msg = await asyncio.wait_for(ws.recv(), timeout=0.5)
+ except asyncio.TimeoutError:
+ continue
+ buf = msg if isinstance(msg, (bytes, bytearray)) else msg.encode("latin-1")
+ parsed = _parse_packet(bytes(buf))
+ if not parsed:
+ continue
+ ptype, _flags, body, _ = parsed
+ if ptype == 3: # PUBLISH
+ topic_len = struct.unpack_from("!H", body, 0)[0]
+ t = body[2:2 + topic_len].decode("utf-8")
+ payload = body[2 + topic_len:]
+ received.append((t, payload))
+
+
+def test_iot_lambda_publishes_browser_subscribes_e2e(iot_data_client):
+ """The unblocking use case from issue #564.
+
+ A WebSocket client subscribes; the iot-data HTTP Publish API delivers
+ a message that arrives over the subscribed WebSocket within 5 seconds.
+ """
+ topic = _unique("e2e/sensor")
+ parsed = urlparse(ENDPOINT)
+ ws_host = parsed.hostname or "localhost"
+ ws_port = parsed.port or 4566
+ # Use the IoT data hostname so the ASGI dispatch routes us to the broker.
+ ws_url = f"ws://prefix-ats.iot.us-east-1.{ws_host}:{ws_port}/mqtt"
+
+ ready = threading.Event()
+ stop = threading.Event()
+ received: list = []
+
+ def _runner():
+ asyncio.run(_ws_subscribe_and_collect(ws_url, topic, ready, received, stop))
+
+ t = threading.Thread(target=_runner, daemon=True)
+ t.start()
+ assert ready.wait(timeout=5), "WebSocket subscriber did not become ready"
+
+ payload = b"telemetry-from-lambda"
+ iot_data_client.publish(topic=topic, payload=payload)
+
+ deadline = time.time() + 5
+ while time.time() < deadline and not received:
+ time.sleep(0.05)
+ stop.set()
+ t.join(timeout=2)
+
+ assert received, "Subscriber did not receive any PUBLISH frames within 5s"
+ delivered_topic, delivered_payload = received[0]
+ assert delivered_topic == topic
+ assert delivered_payload == payload
+
+
+def test_iot_ws_topic_isolation_between_accounts(iot_data_client):
+ """A subscriber in account A must NOT see a publish from account B.
+
+ Multi-tenancy via transparent topic prefixing in the bridge.
+ """
+ import boto3
+ from botocore.config import Config
+
+ topic = _unique("isolation/probe")
+ parsed = urlparse(ENDPOINT)
+ ws_host = parsed.hostname or "localhost"
+ ws_port = parsed.port or 4566
+ # Subscribe as account A — embed the access key in a SigV4-shaped query
+ # parameter the bridge knows how to read.
+ cred = quote("111111111111/20240101/us-east-1/iotdevicegateway/aws4_request")
+ ws_url = (
+ f"ws://prefix-ats.iot.us-east-1.{ws_host}:{ws_port}/mqtt"
+ f"?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential={cred}"
+ )
+
+ ready = threading.Event()
+ stop = threading.Event()
+ received: list = []
+
+ def _runner():
+ asyncio.run(_ws_subscribe_and_collect(ws_url, topic, ready, received, stop))
+
+ t = threading.Thread(target=_runner, daemon=True)
+ t.start()
+ assert ready.wait(timeout=5)
+
+ # Publish from account B using a 12-digit access key.
+ client_b = boto3.client(
+ "iot-data",
+ endpoint_url=ENDPOINT,
+ aws_access_key_id="222222222222",
+ aws_secret_access_key="x",
+ region_name="us-east-1",
+ config=Config(retries={"mode": "standard"}),
+ )
+ client_b.publish(topic=topic, payload=b"from-b")
+
+ # Give the broker time to (not) deliver.
+ time.sleep(1.5)
+ stop.set()
+ t.join(timeout=2)
+
+ assert received == [], (
+ "Subscriber in account A should not have received a publish from account B "
+ f"(got {received!r})"
+ )
+
+
+def test_iot_ws_same_account_publish_delivers(iot_data_client):
+ """Positive case: a subscriber in account A DOES receive a publish from account A.
+
+ Validates that topic prefixing correctly scopes delivery within the same
+ account — the counterpart to the negative isolation test above.
+ """
+ import boto3
+ from botocore.config import Config
+
+ topic = _unique("same-acct/sensor")
+ parsed = urlparse(ENDPOINT)
+ ws_host = parsed.hostname or "localhost"
+ ws_port = parsed.port or 4566
+ account = "333333333333"
+ cred = quote(f"{account}/20240101/us-east-1/iotdevicegateway/aws4_request")
+ ws_url = (
+ f"ws://prefix-ats.iot.us-east-1.{ws_host}:{ws_port}/mqtt"
+ f"?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential={cred}"
+ )
+
+ ready = threading.Event()
+ stop = threading.Event()
+ received: list = []
+
+ def _runner():
+ asyncio.run(_ws_subscribe_and_collect(ws_url, topic, ready, received, stop))
+
+ t = threading.Thread(target=_runner, daemon=True)
+ t.start()
+ assert ready.wait(timeout=5)
+
+ # Publish from the SAME account.
+ client_a = boto3.client(
+ "iot-data",
+ endpoint_url=ENDPOINT,
+ aws_access_key_id=account,
+ aws_secret_access_key="x",
+ region_name="us-east-1",
+ config=Config(retries={"mode": "standard"}),
+ )
+ payload = b"hello-from-same-account"
+ client_a.publish(topic=topic, payload=payload)
+
+ deadline = time.time() + 5
+ while time.time() < deadline and not received:
+ time.sleep(0.05)
+ stop.set()
+ t.join(timeout=2)
+
+ assert received, "Subscriber should have received the publish from the same account"
+ delivered_topic, delivered_payload = received[0]
+ assert delivered_topic == topic
+ assert delivered_payload == payload
diff --git a/tests/test_iot_lwt.py b/tests/test_iot_lwt.py
new file mode 100644
index 00000000..9e4cd82f
--- /dev/null
+++ b/tests/test_iot_lwt.py
@@ -0,0 +1,300 @@
+"""Unit tests for Last Will and Testament (LWT) support in iot_broker.py."""
+
+import asyncio
+import struct
+
+from ministack.services.iot import (
+ PKT_CONNECT,
+ PKT_DISCONNECT,
+ _WSSession,
+ _encode_string,
+ broker_reset as reset,
+ broker_subscribe as subscribe,
+)
+
+
+def _build_connect_body(
+ client_id="test",
+ will_flag=False,
+ will_qos=0,
+ will_retain=False,
+ will_topic="",
+ will_message=b"",
+):
+ """Build a CONNECT packet body (variable header + payload)."""
+ body = bytearray()
+ # Protocol Name
+ body += _encode_string("MQTT")
+ # Protocol Level (4 for MQTT 3.1.1)
+ body.append(4)
+ # Connect Flags
+ flags = 0
+ if will_flag:
+ flags |= 0x04
+ flags |= (will_qos & 0x03) << 3
+ if will_retain:
+ flags |= 0x20
+ body.append(flags)
+ # Keep Alive (60 seconds)
+ body += struct.pack("!H", 60)
+ # Payload: Client ID
+ body += _encode_string(client_id)
+ # Will Topic + Will Message (if Will Flag set)
+ if will_flag:
+ body += _encode_string(will_topic)
+ msg = will_message if isinstance(will_message, bytes) else will_message.encode()
+ body += struct.pack("!H", len(msg)) + msg
+ return bytes(body)
+
+
+def _mock_send():
+ sent = []
+
+ async def send(msg):
+ sent.append(msg)
+
+ return send, sent
+
+
+def test_will_fields_parsed_from_connect():
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body = _build_connect_body(
+ client_id="device1",
+ will_flag=True,
+ will_qos=1,
+ will_retain=True,
+ will_topic="devices/device1/status",
+ will_message=b"offline",
+ )
+ result = await session.handle_packet(PKT_CONNECT, 0, body)
+ assert result is True
+ assert session._will_topic == "devices/device1/status"
+ assert session._will_message == b"offline"
+ assert session._will_qos == 1
+ assert session._will_retain is True
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_no_will_when_flag_not_set():
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body = _build_connect_body(client_id="device2", will_flag=False)
+ await session.handle_packet(PKT_CONNECT, 0, body)
+ assert session._will_topic is None
+ assert session._will_message is None
+ assert session._will_qos == 0
+ assert session._will_retain is False
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_graceful_disconnect_does_not_publish_will():
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body = _build_connect_body(
+ client_id="device3",
+ will_flag=True,
+ will_qos=0,
+ will_retain=False,
+ will_topic="devices/device3/status",
+ will_message=b"offline",
+ )
+ await session.handle_packet(PKT_CONNECT, 0, body)
+
+ received = []
+
+ async def on_msg(topic, payload, qos):
+ received.append((topic, payload, qos))
+
+ await subscribe("123456789012", "devices/device3/status", on_msg)
+
+ # Graceful disconnect
+ result = await session.handle_packet(PKT_DISCONNECT, 0, b"")
+ assert result is False
+ assert session._graceful_disconnect is True
+ await session.cleanup()
+ assert len(received) == 0
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_ungraceful_disconnect_publishes_will():
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body = _build_connect_body(
+ client_id="device4",
+ will_flag=True,
+ will_qos=1,
+ will_retain=False,
+ will_topic="devices/device4/status",
+ will_message=b"gone",
+ )
+ await session.handle_packet(PKT_CONNECT, 0, body)
+
+ received = []
+
+ async def on_msg(topic, payload, qos):
+ received.append((topic, payload, qos))
+
+ # Subscribe at QoS 1 so effective QoS = min(publish_qos=1, granted_qos=1) = 1
+ await subscribe("123456789012", "devices/device4/status", on_msg, granted_qos=1)
+
+ # Ungraceful disconnect (no DISCONNECT packet)
+ await session.cleanup()
+ assert len(received) == 1
+ assert received[0] == ("devices/device4/status", b"gone", 1)
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_will_retain_stores_retained_message():
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body = _build_connect_body(
+ client_id="device5",
+ will_flag=True,
+ will_qos=0,
+ will_retain=True,
+ will_topic="devices/device5/status",
+ will_message=b"dead",
+ )
+ await session.handle_packet(PKT_CONNECT, 0, body)
+ # Ungraceful disconnect publishes Will with retain
+ await session.cleanup()
+
+ # New subscriber should get the retained message
+ received = []
+
+ async def on_msg(topic, payload, qos):
+ received.append((topic, payload, qos))
+
+ await subscribe("123456789012", "devices/device5/status", on_msg)
+ assert len(received) == 1
+ assert received[0] == ("devices/device5/status", b"dead", 0)
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_reconnect_replaces_will_fields():
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body1 = _build_connect_body(
+ client_id="device6",
+ will_flag=True,
+ will_qos=0,
+ will_retain=False,
+ will_topic="old/topic",
+ will_message=b"old",
+ )
+ await session.handle_packet(PKT_CONNECT, 0, body1)
+ assert session._will_topic == "old/topic"
+
+ # Reconnect with new Will
+ body2 = _build_connect_body(
+ client_id="device6",
+ will_flag=True,
+ will_qos=1,
+ will_retain=True,
+ will_topic="new/topic",
+ will_message=b"new",
+ )
+ await session.handle_packet(PKT_CONNECT, 0, body2)
+ assert session._will_topic == "new/topic"
+ assert session._will_message == b"new"
+ assert session._will_qos == 1
+ assert session._will_retain is True
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_reconnect_clears_graceful_disconnect_flag():
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body = _build_connect_body(client_id="device7", will_flag=False)
+ await session.handle_packet(PKT_CONNECT, 0, body)
+
+ # Graceful disconnect
+ await session.handle_packet(PKT_DISCONNECT, 0, b"")
+ assert session._graceful_disconnect is True
+
+ # Reconnect resets the flag
+ await session.handle_packet(PKT_CONNECT, 0, body)
+ assert session._graceful_disconnect is False
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_reconnect_without_will_clears_previous_will():
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ # First connect with Will
+ body1 = _build_connect_body(
+ client_id="device8",
+ will_flag=True,
+ will_qos=1,
+ will_retain=True,
+ will_topic="presence/device8",
+ will_message=b"offline",
+ )
+ await session.handle_packet(PKT_CONNECT, 0, body1)
+ assert session._will_topic == "presence/device8"
+
+ # Reconnect without Will
+ body2 = _build_connect_body(client_id="device8", will_flag=False)
+ await session.handle_packet(PKT_CONNECT, 0, body2)
+ assert session._will_topic is None
+ assert session._will_message is None
+
+ # Ungraceful disconnect should NOT publish anything
+ received = []
+
+ async def on_msg(topic, payload, qos):
+ received.append((topic, payload, qos))
+
+ await subscribe("123456789012", "presence/device8", on_msg)
+ await session.cleanup()
+ assert len(received) == 0
+
+ asyncio.run(_run())
+ reset()
diff --git a/tests/test_iot_persistent_sessions.py b/tests/test_iot_persistent_sessions.py
new file mode 100644
index 00000000..0a394eef
--- /dev/null
+++ b/tests/test_iot_persistent_sessions.py
@@ -0,0 +1,473 @@
+"""Unit tests for persistent sessions (cleanSession flag) in iot_broker.py."""
+
+import asyncio
+import struct
+
+from ministack.services.iot import (
+ PKT_CONNECT,
+ PKT_CONNACK,
+ PKT_DISCONNECT,
+ PKT_PUBLISH,
+ PKT_SUBSCRIBE,
+ _WSSession,
+ _encode_string,
+ _persistent_sessions,
+ broker_publish as publish,
+ broker_reset as reset,
+ broker_subscribe as subscribe,
+)
+
+
+def _build_connect_body(
+ client_id="test",
+ clean_session=True,
+ will_flag=False,
+ will_qos=0,
+ will_retain=False,
+ will_topic="",
+ will_message=b"",
+):
+ """Build a CONNECT packet body (variable header + payload)."""
+ body = bytearray()
+ # Protocol Name
+ body += _encode_string("MQTT")
+ # Protocol Level (4 for MQTT 3.1.1)
+ body.append(4)
+ # Connect Flags
+ flags = 0
+ if clean_session:
+ flags |= 0x02
+ if will_flag:
+ flags |= 0x04
+ flags |= (will_qos & 0x03) << 3
+ if will_retain:
+ flags |= 0x20
+ body.append(flags)
+ # Keep Alive (60 seconds)
+ body += struct.pack("!H", 60)
+ # Payload: Client ID
+ body += _encode_string(client_id)
+ # Will Topic + Will Message (if Will Flag set)
+ if will_flag:
+ body += _encode_string(will_topic)
+ msg = will_message if isinstance(will_message, bytes) else will_message.encode()
+ body += struct.pack("!H", len(msg)) + msg
+ return bytes(body)
+
+
+def _build_subscribe_body(packet_id, topics_qos):
+ """Build a SUBSCRIBE packet body. topics_qos is list of (topic, qos)."""
+ body = struct.pack("!H", packet_id)
+ for topic, qos in topics_qos:
+ body += _encode_string(topic)
+ body += bytes([qos])
+ return body
+
+
+def _mock_send():
+ sent = []
+
+ async def send(msg):
+ sent.append(msg)
+
+ return send, sent
+
+
+def _parse_connack(sent_messages):
+ """Extract sessionPresent flag from CONNACK in sent messages."""
+ for msg in sent_messages:
+ data = msg.get("bytes")
+ if data and len(data) >= 4:
+ pkt_type = (data[0] >> 4) & 0x0F
+ if pkt_type == PKT_CONNACK:
+ # CONNACK: fixed header (1 byte) + remaining length (1 byte) + flags (1 byte) + return code (1 byte)
+ session_present = bool(data[2] & 0x01)
+ return_code = data[3]
+ return session_present, return_code
+ return None, None
+
+
+def test_clean_session_1_sends_session_present_0():
+ """cleanSession=1 always sends sessionPresent=0."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body = _build_connect_body(client_id="client1", clean_session=True)
+ await session.handle_packet(PKT_CONNECT, 0, body)
+
+ session_present, return_code = _parse_connack(sent)
+ assert session_present is False
+ assert return_code == 0
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_clean_session_0_no_prior_session_sends_session_present_0():
+ """cleanSession=0 with no prior session sends sessionPresent=0."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ body = _build_connect_body(client_id="client1", clean_session=False)
+ await session.handle_packet(PKT_CONNECT, 0, body)
+
+ session_present, return_code = _parse_connack(sent)
+ assert session_present is False
+ assert return_code == 0
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_persistent_session_subscribe_disconnect_reconnect_restores():
+ """Connect with cleanSession=0 → subscribe → disconnect → reconnect → sessionPresent=1 and subscriptions restored."""
+ reset()
+
+ async def _run():
+ # First connection: cleanSession=0, subscribe to a topic
+ send1, sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+
+ connect_body = _build_connect_body(client_id="device1", clean_session=False)
+ await session1.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ # Subscribe to "sensor/temp"
+ sub_body = _build_subscribe_body(1, [("sensor/temp", 1)])
+ await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
+
+ # Disconnect (graceful)
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+
+ # Second connection: cleanSession=0, same client_id
+ send2, sent2 = _mock_send()
+ session2 = _WSSession(send2, "123456789012")
+
+ await session2.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ session_present, return_code = _parse_connack(sent2)
+ assert session_present is True
+ assert return_code == 0
+
+ # Verify subscriptions are restored by publishing a message
+ received = []
+
+ # The session should already be subscribed, so publish should deliver
+ await publish("123456789012", "sensor/temp", b"25C", qos=1)
+
+ # Check that session2 received the message
+ # The message should be in sent2 as a PUBLISH packet
+ publish_found = False
+ for msg in sent2:
+ data = msg.get("bytes")
+ if data and ((data[0] >> 4) & 0x0F) == PKT_PUBLISH:
+ publish_found = True
+ break
+ assert publish_found, "Restored subscription should receive published messages"
+
+ await session2.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_clean_session_1_discards_prior_state():
+ """cleanSession=1 discards any prior persistent session state."""
+ reset()
+
+ async def _run():
+ # First connection: cleanSession=0, subscribe
+ send1, sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+
+ connect_body_persistent = _build_connect_body(client_id="device2", clean_session=False)
+ await session1.handle_packet(PKT_CONNECT, 0, connect_body_persistent)
+
+ sub_body = _build_subscribe_body(1, [("alerts/#", 1)])
+ await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
+
+ # Disconnect
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+
+ # Verify persistent session exists
+ assert ("123456789012", "device2") in _persistent_sessions
+
+ # Second connection: cleanSession=1 — should discard prior state
+ send2, sent2 = _mock_send()
+ session2 = _WSSession(send2, "123456789012")
+
+ connect_body_clean = _build_connect_body(client_id="device2", clean_session=True)
+ await session2.handle_packet(PKT_CONNECT, 0, connect_body_clean)
+
+ session_present, return_code = _parse_connack(sent2)
+ assert session_present is False
+ assert return_code == 0
+
+ # Verify persistent session was discarded
+ assert ("123456789012", "device2") not in _persistent_sessions
+
+ # Publish to the old subscription topic — should NOT be delivered
+ await publish("123456789012", "alerts/fire", b"alarm", qos=1)
+
+ publish_found = False
+ for msg in sent2:
+ data = msg.get("bytes")
+ if data and ((data[0] >> 4) & 0x0F) == PKT_PUBLISH:
+ publish_found = True
+ break
+ assert not publish_found, "cleanSession=1 should not restore prior subscriptions"
+
+ await session2.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_offline_qos1_messages_queued_and_delivered_on_reconnect():
+ """Persistent session disconnects; QoS 1 messages published; reconnect delivers queued messages."""
+ reset()
+
+ async def _run():
+ # First connection: cleanSession=0, subscribe
+ send1, sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+
+ connect_body = _build_connect_body(client_id="device3", clean_session=False)
+ await session1.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ sub_body = _build_subscribe_body(1, [("data/stream", 1)])
+ await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
+
+ # Disconnect
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+
+ # Publish QoS 1 messages while client is offline
+ await publish("123456789012", "data/stream", b"msg1", qos=1)
+ await publish("123456789012", "data/stream", b"msg2", qos=1)
+ await publish("123456789012", "data/stream", b"msg3", qos=1)
+
+ # Verify messages are queued
+ ps = _persistent_sessions.get(("123456789012", "device3"))
+ assert ps is not None
+ assert len(ps.queued_messages) == 3
+
+ # Reconnect with cleanSession=0
+ send2, sent2 = _mock_send()
+ session2 = _WSSession(send2, "123456789012")
+
+ await session2.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ session_present, _ = _parse_connack(sent2)
+ assert session_present is True
+
+ # Verify queued messages were delivered
+ publish_messages = []
+ for msg in sent2:
+ data = msg.get("bytes")
+ if data and ((data[0] >> 4) & 0x0F) == PKT_PUBLISH:
+ publish_messages.append(data)
+
+ assert len(publish_messages) == 3, f"Expected 3 queued messages delivered, got {len(publish_messages)}"
+
+ # Verify queue is now empty
+ assert len(ps.queued_messages) == 0
+
+ await session2.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_qos0_messages_not_queued_for_offline_sessions():
+ """QoS 0 messages should NOT be queued for offline persistent sessions."""
+ reset()
+
+ async def _run():
+ # First connection: cleanSession=0, subscribe
+ send1, sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+
+ connect_body = _build_connect_body(client_id="device4", clean_session=False)
+ await session1.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ sub_body = _build_subscribe_body(1, [("events/log", 1)])
+ await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
+
+ # Disconnect
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+
+ # Publish QoS 0 messages while client is offline
+ await publish("123456789012", "events/log", b"info1", qos=0)
+ await publish("123456789012", "events/log", b"info2", qos=0)
+
+ # Verify no messages queued (QoS 0 not queued)
+ ps = _persistent_sessions.get(("123456789012", "device4"))
+ assert ps is not None
+ assert len(ps.queued_messages) == 0
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_queue_bounded_to_1000_messages():
+ """Queue should be bounded to 1000 messages, dropping oldest on overflow."""
+ reset()
+
+ async def _run():
+ # First connection: cleanSession=0, subscribe
+ send1, sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+
+ connect_body = _build_connect_body(client_id="device5", clean_session=False)
+ await session1.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ sub_body = _build_subscribe_body(1, [("bulk/data", 1)])
+ await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
+
+ # Disconnect
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+
+ # Publish 1050 QoS 1 messages while client is offline
+ for i in range(1050):
+ await publish("123456789012", "bulk/data", f"msg{i}".encode(), qos=1)
+
+ # Verify queue is bounded to 1000
+ ps = _persistent_sessions.get(("123456789012", "device5"))
+ assert ps is not None
+ assert len(ps.queued_messages) == 1000
+
+ # Verify oldest messages were dropped (first 50 should be gone)
+ first_topic, first_payload, first_qos = ps.queued_messages[0]
+ assert first_payload == b"msg50"
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_expired_session_not_restored():
+ """An expired persistent session should not be restored."""
+ reset()
+
+ async def _run():
+ import time
+
+ # First connection: cleanSession=0, subscribe
+ send1, sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+
+ connect_body = _build_connect_body(client_id="device6", clean_session=False)
+ await session1.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ sub_body = _build_subscribe_body(1, [("temp/data", 1)])
+ await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
+
+ # Disconnect
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+
+ # Manually expire the session by setting created_at far in the past
+ ps = _persistent_sessions.get(("123456789012", "device6"))
+ assert ps is not None
+ ps.created_at = time.time() - 7200 # 2 hours ago (default expiry is 1 hour)
+
+ # Reconnect with cleanSession=0
+ send2, sent2 = _mock_send()
+ session2 = _WSSession(send2, "123456789012")
+
+ await session2.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ session_present, return_code = _parse_connack(sent2)
+ assert session_present is False # Expired session not restored
+ assert return_code == 0
+
+ await session2.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_wildcard_subscription_persisted_and_restored():
+ """Wildcard subscriptions should be persisted and restored correctly."""
+ reset()
+
+ async def _run():
+ # First connection: cleanSession=0, subscribe with wildcard
+ send1, sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+
+ connect_body = _build_connect_body(client_id="device7", clean_session=False)
+ await session1.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ sub_body = _build_subscribe_body(1, [("sensors/+/temp", 1)])
+ await session1.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
+
+ # Disconnect
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+
+ # Reconnect
+ send2, sent2 = _mock_send()
+ session2 = _WSSession(send2, "123456789012")
+
+ await session2.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ session_present, _ = _parse_connack(sent2)
+ assert session_present is True
+
+ # Publish to a topic matching the wildcard
+ await publish("123456789012", "sensors/room1/temp", b"22C", qos=1)
+
+ publish_found = False
+ for msg in sent2:
+ data = msg.get("bytes")
+ if data and ((data[0] >> 4) & 0x0F) == PKT_PUBLISH:
+ publish_found = True
+ break
+ assert publish_found, "Restored wildcard subscription should receive matching messages"
+
+ await session2.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_different_accounts_sessions_isolated():
+ """Persistent sessions are scoped by (account_id, client_id)."""
+ reset()
+
+ async def _run():
+ # Account A: connect, subscribe, disconnect
+ send_a, sent_a = _mock_send()
+ session_a = _WSSession(send_a, "account_A")
+
+ connect_body = _build_connect_body(client_id="shared_id", clean_session=False)
+ await session_a.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ sub_body = _build_subscribe_body(1, [("topic/a", 1)])
+ await session_a.handle_packet(PKT_SUBSCRIBE, 0x02, sub_body)
+ await session_a.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session_a.cleanup()
+
+ # Account B: connect with same client_id — should NOT see account A's session
+ send_b, sent_b = _mock_send()
+ session_b = _WSSession(send_b, "account_B")
+
+ await session_b.handle_packet(PKT_CONNECT, 0, connect_body)
+
+ session_present, _ = _parse_connack(sent_b)
+ assert session_present is False # No prior session for account_B
+
+ await session_b.cleanup()
+
+ asyncio.run(_run())
+ reset()
diff --git a/tests/test_iot_qos1.py b/tests/test_iot_qos1.py
new file mode 100644
index 00000000..b8bff051
--- /dev/null
+++ b/tests/test_iot_qos1.py
@@ -0,0 +1,631 @@
+"""Unit tests for QoS 1 end-to-end delivery in iot_broker.py.
+
+Covers tasks 18.1 (granted QoS per subscription), 18.2 (QoS 1 delivery with
+packet ID tracking), and 18.3 (PUBACK handling and retransmission).
+"""
+
+import asyncio
+import struct
+
+from ministack.services.iot import (
+ PKT_CONNECT,
+ PKT_PUBACK,
+ PKT_PUBLISH,
+ PKT_SUBSCRIBE,
+ _InFlightMessage,
+ _RETRANSMIT_INTERVAL_SECONDS,
+ _Subscription,
+ _WSSession,
+ _encode_remaining_length,
+ _encode_string,
+ _make_puback,
+ _make_suback,
+ broker_publish as publish,
+ broker_reset as reset,
+ broker_subscribe as subscribe,
+)
+
+
+def _build_connect_body(client_id="test", clean_session=True):
+ """Build a minimal CONNECT packet body."""
+ body = bytearray()
+ body += _encode_string("MQTT")
+ body.append(4) # Protocol Level
+ flags = 0x02 if clean_session else 0x00
+ body.append(flags)
+ body += struct.pack("!H", 60) # Keep Alive
+ body += _encode_string(client_id)
+ return bytes(body)
+
+
+def _build_subscribe_body(packet_id: int, topics: list[tuple[str, int]]):
+ """Build a SUBSCRIBE packet body with topic filters and requested QoS."""
+ body = struct.pack("!H", packet_id)
+ for topic, qos in topics:
+ body += _encode_string(topic)
+ body += bytes([qos])
+ return body
+
+
+def _mock_send():
+ sent = []
+
+ async def send(msg):
+ sent.append(msg)
+
+ return send, sent
+
+
+def _extract_publish_frames(sent_messages):
+ """Extract PUBLISH frames from sent WebSocket messages, returning (topic, payload, qos, packet_id, dup)."""
+ results = []
+ for msg in sent_messages:
+ data = msg.get("bytes")
+ if data is None:
+ continue
+ if not data:
+ continue
+ first = data[0]
+ pkt_type = (first >> 4) & 0x0F
+ if pkt_type != 3: # Not PUBLISH
+ continue
+ qos = (first >> 1) & 0x03
+ dup = bool(first & 0x08)
+ # Decode remaining length
+ offset = 1
+ multiplier = 1
+ remaining = 0
+ while True:
+ b = data[offset]
+ offset += 1
+ remaining += (b & 0x7F) * multiplier
+ if b & 0x80 == 0:
+ break
+ multiplier *= 128
+ # Read topic
+ topic_len = struct.unpack_from("!H", data, offset)[0]
+ offset += 2
+ topic = data[offset:offset + topic_len].decode("utf-8")
+ offset += topic_len
+ # Read packet ID if QoS > 0
+ packet_id = None
+ if qos > 0:
+ packet_id = struct.unpack_from("!H", data, offset)[0]
+ offset += 2
+ payload = data[offset:]
+ results.append((topic, payload, qos, packet_id, dup))
+ return results
+
+
+# ---------------------------------------------------------------------------
+# Task 18.1: Track granted QoS per subscription
+# ---------------------------------------------------------------------------
+
+
+def test_subscription_has_granted_qos_field():
+ """_Subscription stores granted_qos."""
+ async def deliver(t, p, q):
+ pass
+
+ sub = _Subscription("acct/topic", "acct", deliver, granted_qos=1)
+ assert sub.granted_qos == 1
+
+ sub0 = _Subscription("acct/topic", "acct", deliver, granted_qos=0)
+ assert sub0.granted_qos == 0
+
+
+def test_subscribe_handler_caps_qos_at_1():
+ """PKT_SUBSCRIBE grants min(requested, 1) — QoS 2 is capped to 1."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("sub-client"))
+
+ # Subscribe with QoS 0, 1, and 2
+ body = _build_subscribe_body(1, [
+ ("topic/a", 0),
+ ("topic/b", 1),
+ ("topic/c", 2), # Should be capped to 1
+ ])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+
+ # Find SUBACK in sent messages
+ suback_frames = [m for m in sent if m.get("bytes") and (m["bytes"][0] >> 4) == 9]
+ assert len(suback_frames) == 1
+ suback_data = suback_frames[0]["bytes"]
+ # SUBACK: fixed header (1 byte) + remaining length (1 byte) + packet_id (2 bytes) + return codes
+ offset = 1
+ # Decode remaining length
+ multiplier = 1
+ remaining = 0
+ while True:
+ b = suback_data[offset]
+ offset += 1
+ remaining += (b & 0x7F) * multiplier
+ if b & 0x80 == 0:
+ break
+ multiplier *= 128
+ # Skip packet ID
+ offset += 2
+ # Return codes
+ return_codes = list(suback_data[offset:])
+ assert return_codes == [0, 1, 1] # QoS 2 capped to 1
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_subscribe_stores_granted_qos_on_session():
+ """Session tracks granted QoS per subscription ID."""
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("qos-track"))
+
+ body = _build_subscribe_body(1, [("sensor/temp", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+
+ # Session should have one subscription with granted_qos=1
+ assert len(session._sub_ids) == 1
+ sid = session._sub_ids[0]
+ assert session._sub_granted_qos[sid] == 1
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+# ---------------------------------------------------------------------------
+# Task 18.2: QoS 1 delivery with packet ID tracking
+# ---------------------------------------------------------------------------
+
+
+def test_qos1_publish_delivers_with_packet_id():
+ """QoS 1 publish to QoS 1 subscriber delivers at QoS 1 with packet ID."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("qos1-sub"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/qos1", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+
+ # Clear sent to isolate publish frames
+ sent.clear()
+
+ # Publish at QoS 1 from external source
+ await publish("123456789012", "test/qos1", b"hello-qos1", qos=1)
+
+ # Check delivered message
+ publishes = _extract_publish_frames(sent)
+ assert len(publishes) == 1
+ topic, payload, qos, packet_id, dup = publishes[0]
+ assert topic == "test/qos1"
+ assert payload == b"hello-qos1"
+ assert qos == 1
+ assert packet_id is not None
+ assert packet_id >= 1
+ assert dup is False
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_qos0_publish_to_qos1_subscriber_delivers_at_qos0():
+ """QoS 0 publish to QoS 1 subscriber delivers at QoS 0 (effective = min)."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("qos-min"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/minqos", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish at QoS 0
+ await publish("123456789012", "test/minqos", b"qos0-msg", qos=0)
+
+ publishes = _extract_publish_frames(sent)
+ assert len(publishes) == 1
+ topic, payload, qos, packet_id, dup = publishes[0]
+ assert qos == 0
+ assert packet_id is None # No packet ID for QoS 0
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_qos1_publish_to_qos0_subscriber_delivers_at_qos0():
+ """QoS 1 publish to QoS 0 subscriber delivers at QoS 0 (effective = min)."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("qos0-sub"))
+
+ # Subscribe at QoS 0
+ body = _build_subscribe_body(1, [("test/downgrade", 0)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish at QoS 1
+ await publish("123456789012", "test/downgrade", b"downgraded", qos=1)
+
+ publishes = _extract_publish_frames(sent)
+ assert len(publishes) == 1
+ topic, payload, qos, packet_id, dup = publishes[0]
+ assert qos == 0
+ assert packet_id is None
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_qos1_delivery_tracks_in_flight():
+ """QoS 1 delivery stores message in _in_flight dict."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("inflight"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/inflight", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish at QoS 1
+ await publish("123456789012", "test/inflight", b"tracked", qos=1)
+
+ # Should have one in-flight message
+ assert len(session._in_flight) == 1
+ pid = list(session._in_flight.keys())[0]
+ msg = session._in_flight[pid]
+ assert msg.topic == "test/inflight"
+ assert msg.payload == b"tracked"
+ assert msg.retransmit_count == 0
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_packet_ids_are_monotonically_increasing():
+ """Packet IDs increment monotonically."""
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+
+ ids = [session._alloc_packet_id() for _ in range(5)]
+ assert ids == [1, 2, 3, 4, 5]
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_packet_ids_wrap_at_65535():
+ """Packet IDs wrap from 65535 back to 1."""
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+ session._next_pid = 65535
+
+ pid1 = session._alloc_packet_id()
+ pid2 = session._alloc_packet_id()
+ assert pid1 == 65535
+ assert pid2 == 1 # Wraps back to 1
+
+ asyncio.run(_run())
+ reset()
+
+
+# ---------------------------------------------------------------------------
+# Task 18.3: PUBACK handling and retransmission
+# ---------------------------------------------------------------------------
+
+
+def test_puback_removes_from_in_flight():
+ """PUBACK with matching packet ID removes message from _in_flight."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("puback-test"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/puback", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish at QoS 1
+ await publish("123456789012", "test/puback", b"ack-me", qos=1)
+
+ assert len(session._in_flight) == 1
+ pid = list(session._in_flight.keys())[0]
+
+ # Send PUBACK
+ puback_body = struct.pack("!H", pid)
+ result = await session.handle_packet(PKT_PUBACK, 0, puback_body)
+ assert result is True
+ assert len(session._in_flight) == 0
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_puback_unknown_packet_id_is_ignored():
+ """PUBACK for unknown packet ID does not crash."""
+ reset()
+
+ async def _run():
+ send, _ = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("puback-unknown"))
+
+ # Send PUBACK for non-existent packet ID
+ puback_body = struct.pack("!H", 999)
+ result = await session.handle_packet(PKT_PUBACK, 0, puback_body)
+ assert result is True
+ assert len(session._in_flight) == 0
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_retransmit_task_started_on_qos1_delivery():
+ """Retransmit background task is started when QoS 1 message is delivered."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("retransmit"))
+
+ assert session._retransmit_task is None
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/retransmit", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish at QoS 1
+ await publish("123456789012", "test/retransmit", b"retry-me", qos=1)
+
+ # Retransmit task should be started
+ assert session._retransmit_task is not None
+ assert not session._retransmit_task.done()
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_cleanup_cancels_retransmit_task():
+ """cleanup() cancels the retransmit background task."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("cleanup-rt"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/cleanup", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish at QoS 1 to start retransmit task
+ await publish("123456789012", "test/cleanup", b"clean", qos=1)
+ task = session._retransmit_task
+ assert task is not None
+
+ await session.cleanup()
+ assert session._retransmit_task is None
+ assert task.done() or task.cancelled()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_cleanup_clears_in_flight():
+ """cleanup() clears the _in_flight dict."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("cleanup-if"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/clear", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish at QoS 1
+ await publish("123456789012", "test/clear", b"clear-me", qos=1)
+ assert len(session._in_flight) == 1
+
+ await session.cleanup()
+ assert len(session._in_flight) == 0
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_retransmit_sends_dup_flag():
+ """Retransmission sends PUBLISH with DUP flag set."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("dup-test"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/dup", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish at QoS 1
+ await publish("123456789012", "test/dup", b"dup-payload", qos=1)
+
+ # Verify initial publish has DUP=False
+ publishes = _extract_publish_frames(sent)
+ assert len(publishes) == 1
+ assert publishes[0][4] is False # dup flag
+
+ # Manually trigger retransmission by manipulating sent_at
+ pid = list(session._in_flight.keys())[0]
+ msg = session._in_flight[pid]
+ # Set sent_at far in the past to trigger retransmit
+ msg.sent_at = 0
+
+ sent.clear()
+
+ # Run one iteration of retransmit logic manually
+ import asyncio as _asyncio
+ now = _asyncio.get_event_loop().time()
+ for p, m in list(session._in_flight.items()):
+ if now - m.sent_at >= _RETRANSMIT_INTERVAL_SECONDS:
+ m.retransmit_count += 1
+ m.sent_at = now
+ from ministack.services.iot import _make_publish
+ await session.send_bytes(
+ _make_publish(m.topic, m.payload, qos=1, packet_id=p, dup=True)
+ )
+
+ # Verify retransmitted publish has DUP=True
+ publishes = _extract_publish_frames(sent)
+ assert len(publishes) == 1
+ topic, payload, qos, packet_id, dup = publishes[0]
+ assert topic == "test/dup"
+ assert payload == b"dup-payload"
+ assert qos == 1
+ assert packet_id == pid
+ assert dup is True
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_in_flight_message_fields():
+ """_InFlightMessage stores all required fields."""
+ reset()
+
+ async def _run():
+ msg = _InFlightMessage(packet_id=42, topic="sensor/data", payload=b"temp=22")
+ assert msg.packet_id == 42
+ assert msg.topic == "sensor/data"
+ assert msg.payload == b"temp=22"
+ assert msg.sent_at > 0
+ assert msg.retransmit_count == 0
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_multiple_qos1_messages_get_unique_packet_ids():
+ """Multiple QoS 1 deliveries get unique, incrementing packet IDs."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("multi-pid"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/multi", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish 3 messages at QoS 1
+ await publish("123456789012", "test/multi", b"msg1", qos=1)
+ await publish("123456789012", "test/multi", b"msg2", qos=1)
+ await publish("123456789012", "test/multi", b"msg3", qos=1)
+
+ publishes = _extract_publish_frames(sent)
+ assert len(publishes) == 3
+ pids = [p[3] for p in publishes]
+ # All unique
+ assert len(set(pids)) == 3
+ # Monotonically increasing
+ assert pids == sorted(pids)
+
+ # All tracked in-flight
+ assert len(session._in_flight) == 3
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_puback_for_first_of_multiple_in_flight():
+ """PUBACK removes only the specific packet ID from in-flight."""
+ reset()
+
+ async def _run():
+ send, sent = _mock_send()
+ session = _WSSession(send, "123456789012")
+ await session.handle_packet(PKT_CONNECT, 0, _build_connect_body("selective-ack"))
+
+ # Subscribe at QoS 1
+ body = _build_subscribe_body(1, [("test/selective", 1)])
+ await session.handle_packet(PKT_SUBSCRIBE, 0x02, body)
+ sent.clear()
+
+ # Publish 3 messages
+ await publish("123456789012", "test/selective", b"a", qos=1)
+ await publish("123456789012", "test/selective", b"b", qos=1)
+ await publish("123456789012", "test/selective", b"c", qos=1)
+
+ assert len(session._in_flight) == 3
+ pids = sorted(session._in_flight.keys())
+
+ # ACK the middle one
+ puback_body = struct.pack("!H", pids[1])
+ await session.handle_packet(PKT_PUBACK, 0, puback_body)
+
+ assert len(session._in_flight) == 2
+ assert pids[1] not in session._in_flight
+ assert pids[0] in session._in_flight
+ assert pids[2] in session._in_flight
+
+ await session.cleanup()
+
+ asyncio.run(_run())
+ reset()