Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(iot): auto-register under an SNI_ONLY CA when the device sends SNI (#2005)
iot-rocket57cda4a86768
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9e80a209..14d25bac 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **IoT — just-in-time registration under a CA in `SNI_ONLY` mode** — a device certificate signed by a CA registered with `certificateMode` `SNI_ONLY` and auto-registration enabled was refused on its first mTLS connect, so only `DEFAULT` CAs auto-registered. Such a CA now registers the certificate `PENDING_ACTIVATION` and publishes the registered event when the device's TLS ClientHello names the account's endpoint (its DescribeEndpoint prefix in any region) or a host the gateway serves (`localhost`, a compose service name, `MINISTACK_HOST`), and does nothing without a server name. Under a `DEFAULT` CA, a server name with another account's endpoint prefix or a name the gateway does not serve (`mqtt.example.com`) no longer auto-registers, as on AWS. Contributed by @iot-rocket.+- **IoT — `RegisterCertificate` links the CA that signed the certificate** — a certificate registered without `caCertificatePem` carried no `caCertificateId`, even when a registered ACTIVE CA had signed it, so `DescribeCertificate` named no CA and `ListCertificatesByCA` left it out. It is now linked to that CA, as AWS does; when several registered CAs share a subject, the signature decides. Contributed by @iot-rocket.- **IoT — a CONTINUOUS job runs again for a thing that rejoins its target group** — executions were kept one per thing and job, so a thing that finished the job, left the group and was added back never got another execution. Joining a target group now queues the next execution number when the thing's newest execution is finished, leaving the group moves a QUEUED execution to `REMOVED`, both publish `jobs/notify(-next)`, the `notify-next` execution leaves out `thingName` and an empty `statusDetails`, and `ListJobExecutionsForThing`, `DescribeJobExecution` with `executionNumber` and `jobProcessDetails` include the earlier executions, as AWS does. Contributed by @iot-rocket.- **IoT — a `#` region no longer widens topic filters** — a WebSocket session whose credential names `#` as its region received every message published under that region, whatever its filter, because filters were matched with the account and region prefix in front of them. Contributed by @iot-rocket.diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex e4c2afde..a8031c75 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -69,6 +69,7 @@ import sslimport structimport timeimport uuid+import weakreffrom datetime import datetime, timezonefrom typing import Awaitable, Callable@@ -84,6 +85,7 @@ from ministack.core.responses import (new_uuid,request_scope,)+from ministack.core.router import _host_served_by_stackfrom ministack.core.x509_utils import (certificate_is_signed_by,generate_ca,@@ -645,6 +647,11 @@ _RETIRED_ENDPOINT_TYPES = {}+def _endpoint_prefix(account_id: str) -> str:+ """The account's endpoint host prefix: the first 14 hex chars of SHA-256(account_id)."""+ return hashlib.sha256(account_id.encode("utf-8")).hexdigest()[:14]++def _describe_endpoint(qp: dict) -> tuple:"""Return a per-account endpoint hostname.@@ -655,7 +662,7 @@ def _describe_endpoint(qp: dict) -> tuple:"""endpoint_type = qp.get("endpointType", "iot:Data-ATS")account_id = get_account_id()- prefix = hashlib.sha256(account_id.encode("utf-8")).hexdigest()[:14]+ prefix = _endpoint_prefix(account_id)region = get_region()if endpoint_type in _RETIRED_ENDPOINT_TYPES:@@ -8192,6 +8199,9 @@ _mtls_sessions: set[asyncio.StreamWriter] = set()# Digests of the trust anchors already loaded into the live TLS context;# emptied whenever a context is built, since a fresh one starts with none._mtls_loaded_anchors: set[str] = set()+# The server name (SNI) each handshake's ClientHello carried, by its TLS+# object; just-in-time registration depends on it (see _mtls_server_name_reaches).+_mtls_server_names: weakref.WeakKeyDictionary[ssl.SSLObject, str] = weakref.WeakKeyDictionary()import importlib.util as _importlib_util@@ -8358,10 +8368,14 @@ def _mtls_on_client_hello(restart, and ``sni_callback`` is the only hook that runs late enough to seethe current registry yet early enough to matter. It runs on everyhandshake, including those carrying no server name — which is what a- device dialling the broker by IP sends. An exception here aborts the- handshake with an internal-error alert, so nothing is allowed to escape.+ device dialling the broker by IP sends. It is also the only place the+ server side sees that name, so it records whether one was sent. An+ exception here aborts the handshake with an internal-error alert, so+ nothing is allowed to escape."""try:+ if server_name:+ _mtls_server_names[ssl_object] = server_name_mtls_refresh_trust_anchors(ctx)except Exception:_mtls_logger.warning("IoT mTLS: trust-anchor refresh failed", exc_info=True)@@ -8574,30 +8588,69 @@ def _mtls_resolve_identity(der: bytes | None) -> tuple[str, str] | None:return None-def _mtls_auto_registering_ca(account_id: str, region: str, ca_id: str | None) -> dict | None:- """The CA record when it would auto-register a device certificate now."""+def _mtls_server_name_reaches(server_name: str, account_id: str) -> bool:+ """Whether a device that sent ``server_name`` as its SNI dialled ``account_id``'s endpoint.++ On AWS the endpoint prefix names the account: ``<prefix>-ats.iot.<region>...``+ reaches it whichever region the name carries, while another account's+ prefix, or any name that is not an IoT endpoint (``example.com``,+ ``ministack``), auto-registers nothing, whatever the CA mode. Here a name+ of a shape DescribeEndpoint hands out (``<prefix>-ats.iot.`` or+ ``<prefix>.credentials.iot.``, under any suffix) counts only with this+ account's prefix, and any other name counts when the gateway serves it+ (``_host_served_by_stack``: ``localhost``, a compose service name,+ ``MINISTACK_HOST``, any two-label alias, so ``example.com`` too), since+ those are the names devices dial an emulator by.+ """+ name = server_name.lower().rstrip(".")+ first, _, rest = name.partition(".")+ if first.endswith("-ats") and rest.startswith("iot."):+ prefix = first[: -len("-ats")]+ elif rest.startswith("credentials.iot."):+ prefix = first+ else:+ prefix = None+ if prefix is not None and prefix != _endpoint_prefix(account_id):+ return False+ return _host_served_by_stack(name)+++def _mtls_auto_registering_ca(+ account_id: str, region: str, ca_id: str | None, server_name: str | None = None+) -> dict | None:+ """The CA record when it would auto-register a device certificate now.++ Without a server name (SNI) only a CA in DEFAULT mode does. With one, a+ CA in either mode does when the name reaches the CA's account.+ """ca = _ca_certificates.get_scoped(account_id, region, ca_id) if ca_id else Noneif (isinstance(ca, dict)and ca.get("status") == "ACTIVE"and ca.get("autoRegistrationStatus") == "ENABLE"- and ca.get("certificateMode", "DEFAULT") == "DEFAULT"+ and (+ ca.get("certificateMode", "DEFAULT") == "DEFAULT"+ if server_name is None+ else _mtls_server_name_reaches(server_name, account_id)+ )):return careturn None-def _mtls_auto_registering_signers(cert_pem: str) -> list[tuple[str, str, str]]:+def _mtls_auto_registering_signers(+ cert_pem: str, server_name: str | None = None+) -> list[tuple[str, str, str]]:"""Every (account_id, region, ca_id) of an auto-registering CA that signed ``cert_pem``."""return [(account_id, region, ca_id)for (account_id, region, ca_id), ca in list(_ca_certificates._data.items())- if _mtls_auto_registering_ca(account_id, region, ca_id) is not None+ if _mtls_auto_registering_ca(account_id, region, ca_id, server_name) is not Noneand certificate_is_signed_by(cert_pem, ca.get("certificatePem") or "")]-async def _mtls_auto_register(der: bytes, peername) -> bool:+async def _mtls_auto_register(der: bytes, peername, server_name: str | None = None) -> bool:"""Just-in-time registration for a presented certificate that no scopeholds ACTIVE. True when it applied, and the caller closes without aCONNACK; False leaves the refusal to ``_mtls_refuse``.@@ -8606,7 +8659,8 @@ async def _mtls_auto_register(der: bytes, peername) -> bool:auto-registering CA that signed it. A certificate alreadyPENDING_ACTIVATION under such a CA only publishes the event again. AWSdoes both on every such connect, and nothing for an INACTIVE certificate- or a CA with auto-registration disabled.+ or a CA with auto-registration disabled. Which CAs qualify depends on+ the server name the device sent, if any (``_mtls_auto_registering_ca``)."""cert_id = hashlib.sha256(der).hexdigest()held = _mtls_active_registrations(cert_id, status=None)@@ -8616,14 +8670,14 @@ async def _mtls_auto_register(der: bytes, peername) -> bool:account_id, region, record = held[0]if record.get("status") != "PENDING_ACTIVATION":return False- if _mtls_auto_registering_ca(account_id, region, record.get("caCertificateId")) is None:+ if _mtls_auto_registering_ca(account_id, region, record.get("caCertificateId"), server_name) is None:return Falseregistration_timestamp = str(int(record["creationDate"] * 1000))else:cert_pem = ssl.DER_cert_to_PEM_cert(der)# One signature check per auto-registering CA, off the broker's loop:# a device retrying with a refused certificate must not stall it.- signers = await asyncio.to_thread(_mtls_auto_registering_signers, cert_pem)+ signers = await asyncio.to_thread(_mtls_auto_registering_signers, cert_pem, server_name)# The same CA registered in several scopes cannot be attributed, for# the same reason an ambiguous ACTIVE certificate is refused.if len(signers) != 1:@@ -8750,7 +8804,7 @@ async def _mtls_serve_conn(reader: asyncio.StreamReader, writer: asyncio.StreamWpacket = await _mtls_first_packet(reader)protocol_level = _connect_protocol_level(packet) if packet else Noneif protocol_level is not None and await _mtls_auto_register(- der, writer.get_extra_info("peername")+ der, writer.get_extra_info("peername"), _mtls_server_names.get(ssl_object)):returnawait _mtls_refuse(writer, hashlib.sha256(der).hexdigest(), protocol_level)diff --git a/tests/conftest.py b/tests/conftest.pyindex 3d0329cf..30b5c2b5 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -322,6 +322,7 @@ _SERIAL_TESTS = {"tests/test_iot_data.py::test_mtls_registered_ca_chain_connects","tests/test_iot_data.py::test_mtls_jitr_certificate_is_listed_by_its_ca","tests/test_iot_data.py::test_mtls_jitr_auto_registers_an_unknown_cert_without_connack",+ "tests/test_iot_data.py::test_mtls_jitr_under_an_sni_only_ca_needs_sni","tests/test_iot_data.py::test_mtls_account_scoped_delivery","tests/test_iot_data.py::test_mtls_garbage_bytes_dropped","tests/test_iot_data.py::test_mtls_duplicate_client_id_evicts_first_connection",diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 2805b35d..f94e1ec7 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -1398,6 +1398,46 @@ def test_cfn_iot_ca_certificate_registration_config_and_mode_immutability(cfn, i_wait_stack(cfn, "cfn-iot-ca-regcfg")+def test_cfn_iot_sni_only_ca_certificate_auto_registers_with_sni():+ """A CACertificate declared with CertificateMode SNI_ONLY and+ AutoRegistrationStatus ENABLE (how a CDK app declares a JITR CA without a+ verification certificate) is stored as RegisterCACertificate stores it, and+ just-in-time registration under it runs for a device that sent a server+ name (SNI) and not for one that did not. In-process, so no MQTT listener is needed."""+ pytest.importorskip("cryptography")+ import asyncio+ import ssl++ from ministack.core.x509_utils import generate_ca, get_certificate_id, sign_leaf_certificate+ from ministack.services import iot as iot_module++ ca_pem, ca_key = generate_ca(common_name="cfn-jitr-sni-ca")+ leaf_pem = sign_leaf_certificate(ca_pem, ca_key, common_name="cfn-jitr-sni-device")[0]+ cert_id = get_certificate_id(leaf_pem)+ der = ssl.PEM_cert_to_DER_cert(leaf_pem)+ peer = ("192.0.2.10", 50000)+ handler = _RESOURCE_HANDLERS["AWS::IoT::CACertificate"]+ props = {"CACertificatePem": ca_pem, "Status": "ACTIVE",+ "AutoRegistrationStatus": "ENABLE", "CertificateMode": "SNI_ONLY"}+ ca_id, _attrs = handler["create"]("CA", props, "cfn-jitr-sni")++ async def _connects():+ return (await iot_module._mtls_auto_register(der, peer),+ await iot_module._mtls_auto_register(der, peer, "localhost"))++ try:+ ca = iot_module._ca_certificates[ca_id]+ assert (ca["status"], ca["autoRegistrationStatus"], ca["certificateMode"]) == (+ "ACTIVE", "ENABLE", "SNI_ONLY")+ assert asyncio.run(_connects()) == (False, True)+ record = iot_module._certificates[cert_id]+ assert record["status"] == "PENDING_ACTIVATION"+ assert record["caCertificateId"] == ca_id+ finally:+ iot_module._certificates.pop(cert_id, None)+ handler["delete"](ca_id, props)++def test_cfn_iot_ca_certificate_pem_change_refused(cfn, iot_client):"""CACertificatePem is the physical identity — the certificate id derivesfrom it — so an update that changes the PEM fails loudly and rolls backdiff --git a/tests/test_iot.py b/tests/test_iot.pyindex 89f0966e..b552916c 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -5792,13 +5792,18 @@ def _jitr_registration_code(iot_module) -> str:async def _jitr_scope_with_ca(iot_module, ca_pem: str, verification_pem: str, received: list, allow_auto=True) -> str:- """Pin the JITR test scope, register ``ca_pem`` ACTIVE and collect every- registered event into ``received``. Returns the CA id."""+ """Pin the JITR test scope, register ``ca_pem`` ACTIVE (in SNI_ONLY mode+ when ``verification_pem`` is None) and collect every registered event into+ ``received``. Returns the CA id."""_jitr_registration_code(iot_module)qp = {"setAsActive": "true"}if allow_auto:qp["allowAutoRegistration"] = "true"- body = {"caCertificate": ca_pem, "verificationCertificate": verification_pem}+ body = {"caCertificate": ca_pem}+ if verification_pem is None:+ body["certificateMode"] = "SNI_ONLY"+ else:+ body["verificationCertificate"] = verification_pemstatus, _, body = await iot_module.handle_request("POST", "/cacertificate", {}, json.dumps(body).encode(), qp)@@ -5925,6 +5930,110 @@ def test_iot_jitr_auto_registration_on_connect(monkeypatch):assert second["certificateRegistrationTimestamp"] == str(int(record["creationDate"] * 1000))+def test_iot_jitr_under_an_sni_only_ca_needs_sni():+ """A CA in SNI_ONLY mode auto-registers only on a connect whose ClientHello+ named the account's endpoint, as on AWS: the account's endpoint prefix+ counts in any region (and so do the names the gateway serves), while no+ server name, an unrelated one or another account's prefix creates+ nothing. A certificate already PENDING_ACTIVATION gets a repeat event only+ with SNI. A DEFAULT CA auto-registers nothing for an unrelated name+ either, but still does for a compose service name."""+ import ssl++ from ministack.services import iot as iot_module++ code = _jitr_registration_code(iot_module)+ ca_pem, _verification_pem, leaf_pem = _generate_ca_and_leaf(code)+ def_ca_pem, def_verification_pem, def_leaf_pem = _generate_ca_and_leaf(code)+ cert_id = iot_module.get_certificate_id(leaf_pem)+ der = ssl.PEM_cert_to_DER_cert(leaf_pem)+ peer = ("192.0.2.10", 50000)+ prefix = iot_module._endpoint_prefix(_JITR_ACCOUNT)+ other_prefix = iot_module._endpoint_prefix("111111111111")+ received: list = []++ async def _run():+ ca_id = await _jitr_scope_with_ca(iot_module, ca_pem, None, received)+ await _jitr_scope_with_ca(iot_module, def_ca_pem, def_verification_pem, [])+ for server_name in (+ None,+ "mqtt.example.com",+ f"{other_prefix}-ats.iot.{_TEST_REGION}.amazonaws.com",+ f"{other_prefix}-ats.iot.{_TEST_REGION}.localhost",+ f"{other_prefix}.credentials.iot.{_TEST_REGION}.localhost",+ ):+ assert not await iot_module._mtls_auto_register(der, peer, server_name)+ assert cert_id not in iot_module._certificates+ def_der = ssl.PEM_cert_to_DER_cert(def_leaf_pem)+ assert not await iot_module._mtls_auto_register(def_der, peer, "mqtt.example.com")+ assert iot_module.get_certificate_id(def_leaf_pem) not in iot_module._certificates+ assert await iot_module._mtls_auto_register(def_der, peer, "ministack")++ other_region = f"{prefix.upper()}-ats.iot.us-east-1.amazonaws.com"+ assert await iot_module._mtls_auto_register(der, peer, other_region)+ record = iot_module._certificates[cert_id]+ assert record["status"] == "PENDING_ACTIVATION"+ assert record["caCertificateId"] == ca_id+ assert not await iot_module._mtls_auto_register(der, peer)+ assert await iot_module._mtls_auto_register(der, peer, "localhost")+ return ca_id++ try:+ ca_id = asyncio.run(_run())+ finally:+ iot_module.reset()+ iot_module.broker_reset()++ topic = f"$aws/events/certificates/registered/{ca_id}"+ events = [event for t, event in received if t == topic]+ assert [event["certificateId"] for event in events] == [cert_id] * 2+ assert events[0]["certificateRegistrationTimestamp"] is None+ assert isinstance(events[1]["certificateRegistrationTimestamp"], str)+++def test_iot_jitr_sni_only_ca_in_two_accounts_registers_where_the_name_points():+ """The same SNI_ONLY CA registered in two accounts: an endpoint name picks+ the account it names, while a name both accounts are served under+ (``localhost``) is ambiguous and registers nothing."""+ import ssl++ from ministack.core.responses import set_request_account_id, set_request_region+ from ministack.services import iot as iot_module++ ca_pem, _verification_pem, leaf_pem = _generate_ca_and_leaf("unused")+ cert_id = iot_module.get_certificate_id(leaf_pem)+ der = ssl.PEM_cert_to_DER_cert(leaf_pem)+ peer = ("192.0.2.10", 50000)+ accounts = ("111111111111", "222222222222")++ async def _run():+ for account in accounts:+ set_request_account_id(account)+ set_request_region(_TEST_REGION)+ status, _, _body = await iot_module.handle_request(+ "POST", "/cacertificate", {},+ json.dumps({"caCertificate": ca_pem, "certificateMode": "SNI_ONLY"}).encode(),+ {"setAsActive": "true", "allowAutoRegistration": "true"},+ )+ assert status == 200+ assert not await iot_module._mtls_auto_register(der, peer, "localhost")+ prefix = iot_module._endpoint_prefix(accounts[1])+ name = f"{prefix}-ats.iot.{_TEST_REGION}.localhost"+ assert await iot_module._mtls_auto_register(der, peer, name)+ return [+ iot_module._certificates.get_scoped(account, _TEST_REGION, cert_id)+ for account in accounts+ ]++ try:+ first, second = asyncio.run(_run())+ finally:+ iot_module.reset()+ iot_module.broker_reset()+ assert first is None+ assert second["status"] == "PENDING_ACTIVATION"++# ----------------------------------------------------------------------# Registry events ($aws/events/...) gated by UpdateEventConfigurations# ----------------------------------------------------------------------diff --git a/tests/test_iot_data.py b/tests/test_iot_data.pyindex 30241341..d201aa44 100644--- a/tests/test_iot_data.py+++ b/tests/test_iot_data.py@@ -3150,10 +3150,18 @@ def _client_context(broker: _Broker, cert_pem: str | None, key_pem: str | None,return ctx-def _mtls_connect(broker: _Broker, cert_pem, key_pem, tmp_path, timeout: float = 10.0):- """Open a TLS socket to the listener, verifying the broker's chain."""+def _mtls_connect(+ broker: _Broker, cert_pem, key_pem, tmp_path, timeout: float = 10.0,+ server_name: str | None = "localhost",+):+ """Open a TLS socket to the listener, verifying the broker's chain. Another+ ``server_name`` is sent as the SNI without checking it against the+ certificate; None sends no SNI, as when dialling by IP."""ctx = _client_context(broker, cert_pem, key_pem, tmp_path)raw = socket.create_connection(("127.0.0.1", broker.mqtt_port), timeout=timeout)+ if server_name != "localhost":+ ctx.check_hostname = False+ return ctx.wrap_socket(raw, server_hostname=server_name)# `server_hostname` is checked against the certificate's SANs, so this also# pins that the broker certificate carries a usable `localhost` name.return ctx.wrap_socket(raw, server_hostname="localhost")@@ -3719,6 +3727,48 @@ def test_mtls_jitr_auto_registers_an_unknown_cert_without_connack(broker, tmp_paiot.delete_ca_certificate(certificateId=ca_id)+def test_mtls_jitr_under_an_sni_only_ca_needs_sni(broker, tmp_path):+ """A CA in SNI_ONLY mode auto-registers a device only when its ClientHello+ carries a server name that reaches the endpoint, as on AWS. Without one,+ or with an unrelated one, the certificate stays unknown and is refused+ like any other unknown certificate (CONNACK 5)."""+ from ministack.core.x509_utils import generate_ca, get_certificate_id, sign_leaf_certificate++ iot = broker.client("iot")+ ca_pem, ca_key = generate_ca(common_name=_unique("jitr-sni-ca"))+ ca_id = iot.register_ca_certificate(+ caCertificate=ca_pem, certificateMode="SNI_ONLY",+ setAsActive=True, allowAutoRegistration=True,+ )["certificateId"]+ leaf_pem, leaf_key, _public = sign_leaf_certificate(ca_pem, ca_key, common_name="jitr-sni-device")+ cert_id = get_certificate_id(leaf_pem)+ try:+ for server_name in (None, "mqtt.example.com"):+ peer = _Peer(_mtls_connect(broker, leaf_pem, leaf_key, tmp_path, server_name=server_name))+ try:+ _assert_connack(peer.connect(_unique("jitr-no-sni")), return_code=5)+ finally:+ peer.close()+ with pytest.raises(ClientError) as exc:+ iot.describe_certificate(certificateId=cert_id)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"++ assert _refused_below_mqtt(+ broker, leaf_pem, leaf_key, tmp_path, _unique("jitr-sni")+ ), "connect with SNI got a CONNACK"+ desc = iot.describe_certificate(certificateId=cert_id)["certificateDescription"]+ assert desc["status"] == "PENDING_ACTIVATION"+ assert desc["caCertificateId"] == ca_id+ finally:+ try:+ iot.update_certificate(certificateId=cert_id, newStatus="INACTIVE")+ iot.delete_certificate(certificateId=cert_id, forceDelete=True)+ except ClientError:+ pass+ iot.update_ca_certificate(certificateId=ca_id, newStatus="INACTIVE")+ iot.delete_ca_certificate(certificateId=ca_id)++def test_mtls_account_scoped_delivery(broker, tmp_path):"""The client certificate decides the tenant: a device whose certificate isowned by 111111111111 sees that account's traffic and nobody else's."""