Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(iot): CA-certificate registry and registration events (#1397)
iot-rocket7e825854f594
diff --git a/ministack/core/x509_utils.py b/ministack/core/x509_utils.pyindex 766ea594..c6ed8b62 100644--- a/ministack/core/x509_utils.py+++ b/ministack/core/x509_utils.py@@ -28,6 +28,7 @@ logger = logging.getLogger("x509_utils")try:from cryptography import x509+ from cryptography.exceptions import InvalidSignaturefrom cryptography.hazmat.primitives import hashes, serializationfrom cryptography.hazmat.primitives.asymmetric import ec, rsafrom cryptography.x509.oid import NameOID@@ -213,6 +214,41 @@ def sign_leaf_certificate(return cert_pem, private_pem, public_pem+def certificate_is_signed_by(cert_pem: str, ca_cert_pem: str) -> bool:+ """Return True when ``cert_pem`` carries a valid signature from ``ca_cert_pem``.++ The issuer/subject distinguished names are compared first — cheap, and the+ only discriminator when several CAs share a subject — and then the+ signature itself is verified against the CA's public key.++ This answers "did this CA issue this certificate", not "is this chain+ trusted right now": validity dates, basic constraints and revocation are+ deliberately not considered, matching what AWS IoT's ``RegisterCertificate``+ needs to know about ``caCertificatePem``.++ Args:+ cert_pem: The leaf certificate in PEM format.+ ca_cert_pem: The claimed issuing CA certificate in PEM format.++ Returns:+ True if the CA's key signed the leaf, False otherwise (including+ unparseable input and unsupported signature algorithms).+ """+ _require_crypto()+ try:+ cert = x509.load_pem_x509_certificate(cert_pem.encode("utf-8"))+ ca_cert = x509.load_pem_x509_certificate(ca_cert_pem.encode("utf-8"))+ except Exception:+ return False+ if cert.issuer != ca_cert.subject:+ return False+ try:+ cert.verify_directly_issued_by(ca_cert)+ except (InvalidSignature, ValueError, TypeError):+ return False+ return True++def get_certificate_id(cert_pem: str) -> str:"""Return a stable 64-char hex identifier for a certificate.diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex 45c6b0d2..5b0afc9c 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -9,6 +9,11 @@ Implements the JSON/REST APIs under ``iot.{region}.amazonaws.com``:- Certificates: ``CreateKeysAndCertificate``, ``RegisterCertificate``,``RegisterCertificateWithoutCA``, ``UpdateCertificate``,``DeleteCertificate``, ``AttachThingPrincipal`` / ``DetachThingPrincipal``+ - CA certificates + JITR: ``GetRegistrationCode`` / ``DeleteRegistrationCode``,+ ``RegisterCACertificate``, ``DescribeCACertificate``, ``UpdateCACertificate``,+ ``ListCACertificates``, ``DeleteCACertificate``; registering a device+ certificate under a CA with auto-registration enabled publishes the AWS+ JITR event to ``$aws/events/certificates/registered/{caCertificateId}``- Policies: ``CreatePolicy``, ``CreatePolicyVersion``, ``AttachPolicy``,``DetachPolicy``, etc., plus the deprecated principal-policy family(``AttachPrincipalPolicy`` / ``DetachPrincipalPolicy`` /@@ -61,6 +66,7 @@ from ministack.core.responses import (request_scope,)from ministack.core.x509_utils import (+ certificate_is_signed_by,generate_ca,get_certificate_id,sign_leaf_certificate,@@ -88,6 +94,10 @@ _topic_rules: AccountRegionScopedDict = AccountRegionScopedDict()_shadows: AccountRegionScopedDict = AccountRegionScopedDict()# Fleet-indexing configuration, one entry per account+region._indexing_config: AccountRegionScopedDict = AccountRegionScopedDict()+# CA-certificate registry (RegisterCACertificate & friends): caCertificateId -> record+_ca_certificates: AccountRegionScopedDict = AccountRegionScopedDict()+# JITR registration code — a single "code" key per account/region+_registration_codes: AccountRegionScopedDict = AccountRegionScopedDict()# Local CA state — lazily generated on first use, persisted across restarts.import threading@@ -178,6 +188,8 @@ def get_state() -> dict:"topic_rules": copy.deepcopy(_topic_rules),"shadows": copy.deepcopy(_shadows),"indexing_config": copy.deepcopy(_indexing_config),+ "ca_certificates": copy.deepcopy(_ca_certificates),+ "registration_codes": copy.deepcopy(_registration_codes),"ca": {"ca_cert_pem": _ca_cert_pem, "ca_key_pem": _ca_key_pem}if _ca_cert_pem and _ca_key_pemelse {},@@ -197,6 +209,8 @@ def restore_state(data: dict | None) -> None:_topic_rules.update(data.get("topic_rules", {}))_shadows.update(data.get("shadows", {}))_indexing_config.update(data.get("indexing_config", {}))+ _ca_certificates.update(data.get("ca_certificates", {}))+ _registration_codes.update(data.get("registration_codes", {}))ca_data = data.get("ca")if ca_data:cert = ca_data.get("ca_cert_pem")@@ -223,6 +237,8 @@ def reset() -> None:# gets no warning._warned_sql_funcs.clear()_indexing_config.clear()+ _ca_certificates.clear()+ _registration_codes.clear()with _CA_LOCK:_ca_cert_pem = None_ca_key_pem = None@@ -284,6 +300,10 @@ def _cert_arn(certificate_id: str) -> str:return f"arn:aws:iot:{get_region()}:{get_account_id()}:cert/{certificate_id}"+def _ca_cert_arn(certificate_id: str) -> str:+ return f"arn:aws:iot:{get_region()}:{get_account_id()}:cacert/{certificate_id}"++def _policy_arn(name: str) -> str:return f"arn:aws:iot:{get_region()}:{get_account_id()}:policy/{name}"@@ -397,9 +417,20 @@ async def handle_request(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)+ return await _register_certificate(_parse_body(body), qp)if path == "/certificate/register-no-ca" and method == "POST":- return _register_certificate(_parse_body(body), qp, without_ca=True)+ return await _register_certificate(_parse_body(body), qp, without_ca=True)++ # CA certificates + JITR registration code+ if path == "/registrationcode" and method in ("GET", "DELETE"):+ return _handle_registration_code(method)+ if path == "/cacertificate" and method == "POST":+ return _register_ca_certificate(_parse_body(body), qp)+ if path == "/cacertificates" and method == "GET":+ return _list_ca_certificates(qp)+ if path.startswith("/cacertificate/") and method in ("GET", "PUT", "DELETE"):+ return _handle_ca_certificate(method, path, body, qp)+if path == "/certificates" and method == "GET":return _list_certificates(qp)if path.startswith("/certificates/") and method in ("GET", "PUT", "DELETE"):@@ -989,19 +1020,21 @@ def _create_keys_and_certificate(qp: dict) -> tuple:})-def _certificate_already_exists(cert_id: str) -> tuple:+def _certificate_already_exists(cert_id: str, arn: str | None = None) -> tuple:"""409 for a duplicate PEM, carrying ``resourceId``/``resourceArn`` the way- real AWS's ``ResourceAlreadyExistsException`` does — both register variants- answer identically."""+ real AWS's ``ResourceAlreadyExistsException`` does — all register variants+ (device certs and CA certs) answer identically."""return error_response_json("ResourceAlreadyExistsException",f"The certificate with id {cert_id} already exists.",409,- extra={"resourceId": cert_id, "resourceArn": _cert_arn(cert_id)},+ extra={"resourceId": cert_id, "resourceArn": arn or _cert_arn(cert_id)},)-def _register_certificate(payload: dict, qp: dict, *, without_ca: bool = False) -> tuple:+async def _register_certificate(+ payload: dict, qp: dict, *, without_ca: bool = False+) -> tuple:"""Register a certificate that was issued elsewhere (no re-signing).Serves both ``RegisterCertificate`` (``POST /certificate/register``) and@@ -1011,6 +1044,14 @@ def _register_certificate(payload: dict, qp: dict, *, without_ca: bool = False)JSON body kept as a fallback for raw callers. The no-CA variant carries noCA reference and takes its status from the plain ``status`` body fieldonly — it has no deprecated ``setAsActive``.++ ``caCertificatePem`` must name a CA registered via+ ``RegisterCACertificate`` in this account/region that really signed the+ leaf; anything else is a ``CertificateValidationException``. When that CA's+ ``autoRegistrationStatus`` is ``ENABLE``, the AWS JITR lifecycle event is+ published to ``$aws/events/certificates/registered/{caCertificateId}`` so+ just-in-time-registration Lambdas subscribed via topic rules fire exactly+ as on AWS."""cert_pem = payload.get("certificatePem") or qp.get("certificatePem")if not cert_pem:@@ -1025,12 +1066,43 @@ def _register_certificate(payload: dict, qp: dict, *, without_ca: bool = False)ca_pem = None if without_ca else payload.get("caCertificatePem")try:cert_id = get_certificate_id(cert_pem)+ ca_id = get_certificate_id(ca_pem) if ca_pem else Noneexcept Exception as e:return error_response_json("CertificateValidationException",f"Invalid certificate PEM: {e}",400,)+ # caCertificatePem is a claim about who signed the leaf, and the whole JITR+ # flow keys off it: the event topic, and with it the provisioning template a+ # JITR Lambda picks, is chosen by caCertificateId. An unchecked claim lets a+ # certificate signed by CA-X register as CA-Y's and provision the wrong+ # fleet, so the claim is verified the way AWS does before anything is+ # stored — the CA has to be registered in this account/region, and it has to+ # be the certificate that actually signed the leaf.+ ca = None+ if ca_id is not None:+ ca = _ca_certificates.get(ca_id)+ if ca is None:+ return error_response_json(+ "CertificateValidationException",+ (+ f"The CA certificate {ca_id} is not registered in this "+ "account and region. Register it with RegisterCACertificate, "+ "or use RegisterCertificateWithoutCA."+ ),+ 400,+ )+ if not certificate_is_signed_by(cert_pem, ca_pem):+ return error_response_json(+ "CertificateValidationException",+ (+ f"The certificate was not signed by CA {ca_id}. "+ "caCertificatePem must be the CA certificate that issued "+ "certificatePem."+ ),+ 400,+ )if cert_id in _certificates:return _certificate_already_exists(cert_id)record = {@@ -1040,11 +1112,48 @@ def _register_certificate(payload: dict, qp: dict, *, without_ca: bool = False)"status": status or ("ACTIVE" if set_active else "INACTIVE"),"creationDate": _now_epoch(),"ownedBy": get_account_id(),- "caCertificateId": get_certificate_id(ca_pem) if ca_pem else None,+ "caCertificateId": ca_id,"attachedThings": [],"attachedPolicies": [],}_certificates[cert_id] = record++ # JITR: the registered-certificate lifecycle event, fired when the+ # referenced CA is ACTIVE and has auto-registration enabled — AWS+ # auto-registers nothing under an INACTIVE CA. certificateStatus echoes+ # the requested register status; real connect-triggered auto-registration+ # carries PENDING_ACTIVATION, but here registration is always explicit —+ # there is no mTLS first-connect path to auto-register from.+ if (+ ca+ and ca.get("status") == "ACTIVE"+ and ca.get("autoRegistrationStatus") == "ENABLE"+ ):+ now_ms = int(time.time() * 1000)+ event = {+ "certificateId": cert_id,+ "caCertificateId": ca_id,+ "timestamp": now_ms,+ "certificateStatus": record["status"],+ "awsAccountId": get_account_id(),+ "certificateRegistrationTimestamp": str(now_ms),+ }+ try:+ await broker_publish(+ get_account_id(),+ get_region(),+ f"$aws/events/certificates/registered/{ca_id}",+ json.dumps(event).encode("utf-8"),+ qos=0,+ )+ except Exception:+ # The certificate is already registered at this point, so a broker+ # failure must not turn a successful registration into a 500 — the+ # iot-data publish path guards the same call the same way.+ logger.warning(+ "JITR registered-event publish failed for CA %s", ca_id, exc_info=True+ )+return json_response({"certificateArn": record["certificateArn"],"certificateId": cert_id,@@ -1074,6 +1183,140 @@ def _handle_certificate(method: str, path: str, body: bytes, qp: dict) -> tuple:record = _certificates.get(cert_id)if record is None:return _error_not_found("Certificate", cert_id)+ if method == "GET":+ description = {+ "certificateArn": record["certificateArn"],+ "certificateId": record["certificateId"],+ "status": record["status"],+ "certificatePem": record["certificatePem"],+ "ownedBy": record["ownedBy"],+ "creationDate": record.get("creationDate"),+ }+ # Present only for CA-signed registrations, so JITR consumers can+ # resolve the signing CA (per the CertificateDescription model).+ if record.get("caCertificateId"):+ description["caCertificateId"] = record["caCertificateId"]+ return json_response({"certificateDescription": description})+ 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",+ 406,+ )+ del _certificates[cert_id]+ return json_response({})+ return error_response_json(+ "InvalidRequestException", f"Unsupported method: {method}", 400+ )+++# ---------------------------------------------------------------------------+# CA-certificate registry + JITR registration code+# ---------------------------------------------------------------------------+++def _handle_registration_code(method: str) -> tuple:+ """``GET|DELETE /registrationcode`` — ``GetRegistrationCode`` /+ ``DeleteRegistrationCode``.++ The code is minted once per account/region (a random SHA-256 hex string,+ AWS-shaped), persisted, and returned unchanged on every subsequent GET.+ DELETE discards it; the next GET mints a fresh one.+ """+ if method == "GET":+ code = _registration_codes.get("code")+ if not code:+ code = hashlib.sha256(os.urandom(32)).hexdigest()+ _registration_codes["code"] = code+ return json_response({"registrationCode": code})+ # DELETE+ _registration_codes.pop("code", None)+ return json_response({})+++def _register_ca_certificate(payload: dict, qp: dict) -> tuple:+ """``POST /cacertificate`` (``RegisterCACertificate``).++ Body members per the botocore model: ``caCertificate`` (required) and+ ``verificationCertificate`` (accepted; the registration-code CN handshake+ is not enforced locally). ``setAsActive`` / ``allowAutoRegistration`` ride+ as query-string booleans, as on AWS.+ """+ ca_pem = payload.get("caCertificate")+ if not ca_pem:+ return error_response_json(+ "InvalidRequestException", "caCertificate is required", 400+ )+ try:+ ca_id = get_certificate_id(ca_pem)+ except Exception as e:+ return error_response_json(+ "CertificateValidationException",+ f"Invalid CA certificate PEM: {e}",+ 400,+ )+ if ca_id in _ca_certificates:+ return _certificate_already_exists(ca_id, _ca_cert_arn(ca_id))+ set_active = _qp_bool(qp, "setAsActive")+ allow_auto = _qp_bool(qp, "allowAutoRegistration")+ record = {+ "certificateId": ca_id,+ "certificateArn": _ca_cert_arn(ca_id),+ "certificatePem": ca_pem, # verbatim+ "status": "ACTIVE" if set_active else "INACTIVE",+ "autoRegistrationStatus": "ENABLE" if allow_auto else "DISABLE",+ "creationDate": _now_epoch(),+ "ownedBy": get_account_id(),+ }+ _ca_certificates[ca_id] = record+ return json_response({+ "certificateArn": record["certificateArn"],+ "certificateId": ca_id,+ })+++def _list_ca_certificates(qp: dict) -> tuple:+ """``GET /cacertificates`` (``ListCACertificates``)."""+ return json_response({+ "certificates": [+ {+ "certificateArn": c["certificateArn"],+ "certificateId": c["certificateId"],+ "status": c["status"],+ "creationDate": c.get("creationDate"),+ }+ for c in _ca_certificates.values()+ ]+ })+++def _handle_ca_certificate(method: str, path: str, body: bytes, qp: dict) -> tuple:+ """``GET|PUT|DELETE /cacertificate/{caCertificateId}`` —+ ``DescribeCACertificate`` / ``UpdateCACertificate`` /+ ``DeleteCACertificate``.+ """+ ca_id = path[len("/cacertificate/"):]+ if not ca_id or "/" in ca_id:+ return error_response_json(+ "InvalidRequestException", "Invalid CA certificate path", 400+ )+ record = _ca_certificates.get(ca_id)+ if record is None:+ return _error_not_found("CACertificate", ca_id)if method == "GET":return json_response({"certificateDescription": {@@ -1081,31 +1324,49 @@ def _handle_certificate(method: str, path: str, body: bytes, qp: dict) -> tuple:"certificateId": record["certificateId"],"status": record["status"],"certificatePem": record["certificatePem"],+ "autoRegistrationStatus": record["autoRegistrationStatus"],"ownedBy": record["ownedBy"],"creationDate": record.get("creationDate"),}})if method == "PUT":+ # newStatus / newAutoRegistrationStatus are query-string params per the+ # botocore model; both are optional and independently applied. The body+ # is read as a fallback, as UpdateCertificate does — otherwise a raw+ # caller that puts them in the JSON body gets a 200 that applied+ # nothing.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:+ new_auto = (+ payload.get("newAutoRegistrationStatus")+ or qp.get("newAutoRegistrationStatus")+ )+ if new_status is not None and new_status not in ("ACTIVE", "INACTIVE"):return error_response_json("InvalidRequestException",- f"newStatus must be one of {sorted(valid)}",+ "newStatus must be one of ['ACTIVE', 'INACTIVE']",400,)- record["status"] = new_status- _certificates[cert_id] = record+ if new_auto is not None and new_auto not in ("ENABLE", "DISABLE"):+ return error_response_json(+ "InvalidRequestException",+ "newAutoRegistrationStatus must be one of ['DISABLE', 'ENABLE']",+ 400,+ )+ if new_status is not None:+ record["status"] = new_status+ if new_auto is not None:+ record["autoRegistrationStatus"] = new_auto+ _ca_certificates[ca_id] = recordreturn json_response({})if method == "DELETE":if record["status"] == "ACTIVE":return error_response_json("CertificateStateException",- "Certificate is ACTIVE; deactivate before deletion",- 409,+ "CA certificate is ACTIVE; deactivate before deletion",+ 406,)- del _certificates[cert_id]+ del _ca_certificates[ca_id]return json_response({})return error_response_json("InvalidRequestException", f"Unsupported method: {method}", 400diff --git a/tests/conftest.py b/tests/conftest.pyindex b1b0ac6e..33817023 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -150,6 +150,11 @@ _SERIAL_TESTS = {"tests/test_lambda.py::test_lambda_recursive_loop_allow_lets_the_chain_through","tests/test_lambda.py::test_lambda_recursive_loop_drop_is_recursive_invocation_exception","tests/test_lambda.py::test_lambda_nested_invoke_below_limit_is_unaffected",+ # DeleteRegistrationCode discards the one code the account/region holds, and+ # the test asserts the next GetRegistrationCode mints a different one — a+ # parallel worker calling GetRegistrationCode either side of the delete sees+ # the code change under it. Same account-global mutation class as above.+ "tests/test_iot.py::test_iot_registration_code_stable_until_deleted",}diff --git a/tests/test_iot.py b/tests/test_iot.pyindex 87800504..70915dac 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -331,6 +331,9 @@ def test_iot_delete_active_certificate_rejected(iot_client):with pytest.raises(ClientError) as ei:iot_client.delete_certificate(certificateId=cert_id)assert ei.value.response["Error"]["Code"] == "CertificateStateException"+ # 406 per the service model — the same status the CA-certificate delete+ # answers with for the same exception.+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 406iot_client.update_certificate(certificateId=cert_id, newStatus="INACTIVE")iot_client.delete_certificate(certificateId=cert_id)@@ -1433,6 +1436,8 @@ def test_iot_control_plane_identity_stores_are_region_scoped():iot_module._policies,iot_module._topic_rules,iot_module._shadows,+ iot_module._ca_certificates,+ iot_module._registration_codes,)assert all(isinstance(store, AccountRegionScopedDict) for store in stores)@@ -4356,6 +4361,187 @@ def test_ddb_attribute_value_mapping():assert _ddb_attribute_value({"a": 1}) == {"S": '{"a": 1}'}assert _ddb_attribute_value([1, 2]) == {"S": "[1, 2]"}assert _ddb_attribute_value("x") == {"S": "x"}+# ---------------------------------------------------------------------------+# CA-certificate registry + JITR (registration code, RegisterCACertificate+# and friends, and the $aws/events/certificates/registered/{caId} event)+# ---------------------------------------------------------------------------+++def _generate_ca_and_leaves(count: int = 1) -> tuple[str, list[str]]:+ """A fresh CA PEM and ``count`` leaf certificate PEMs signed by it.++ Leaves have to be signed by the CA they are registered under —+ ``RegisterCertificate`` verifies the ``caCertificatePem`` claim — so a test+ that needs two device certificates under one CA must take them from the+ same CA key, not from two independent ``_generate_ca_and_leaf`` calls.+ """+ pytest.importorskip("cryptography")+ from ministack.core.x509_utils import generate_ca, sign_leaf_certificate++ ca_pem, ca_key_pem = generate_ca(common_name=_unique("jitr-test-ca"))+ leaves = [+ sign_leaf_certificate(+ ca_cert_pem=ca_pem,+ ca_key_pem=ca_key_pem,+ common_name=_unique("jitr-device"),+ )[0]+ for _ in range(count)+ ]+ return ca_pem, leaves+++def _generate_ca_and_leaf() -> tuple[str, str]:+ """A fresh CA PEM and a leaf certificate PEM signed by it."""+ ca_pem, leaves = _generate_ca_and_leaves()+ return ca_pem, leaves[0]+++def test_iot_registration_code_stable_until_deleted(iot_client):+ code = iot_client.get_registration_code()["registrationCode"]+ assert len(code) == 64+ int(code, 16) # sha256 hex+ # Stable across calls.+ assert iot_client.get_registration_code()["registrationCode"] == code+ # DELETE discards it; the next GET mints a fresh one.+ iot_client.delete_registration_code()+ fresh = iot_client.get_registration_code()["registrationCode"]+ assert len(fresh) == 64+ assert fresh != code+++def test_iot_ca_certificate_lifecycle(iot_client):+ ca_pem, _leaf = _generate_ca_and_leaf()+ resp = iot_client.register_ca_certificate(+ caCertificate=ca_pem, setAsActive=True, allowAutoRegistration=True+ )+ ca_id = resp["certificateId"]+ assert resp["certificateArn"].endswith(":cacert/" + ca_id)++ desc = iot_client.describe_ca_certificate(certificateId=ca_id)[+ "certificateDescription"+ ]+ assert desc["certificatePem"] == ca_pem # verbatim+ assert desc["certificateId"] == ca_id+ assert desc["status"] == "ACTIVE"+ assert desc["autoRegistrationStatus"] == "ENABLE"+ assert desc["creationDate"]++ listing = iot_client.list_ca_certificates()["certificates"]+ entry = next(c for c in listing if c["certificateId"] == ca_id)+ assert entry["certificateArn"].endswith(":cacert/" + ca_id)+ assert entry["status"] == "ACTIVE"++ # ACTIVE CAs cannot be deleted — 406 per the service model.+ with pytest.raises(ClientError) as ei:+ iot_client.delete_ca_certificate(certificateId=ca_id)+ assert ei.value.response["Error"]["Code"] == "CertificateStateException"+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 406++ iot_client.update_ca_certificate(+ certificateId=ca_id,+ newStatus="INACTIVE",+ newAutoRegistrationStatus="DISABLE",+ )+ desc = iot_client.describe_ca_certificate(certificateId=ca_id)[+ "certificateDescription"+ ]+ assert desc["status"] == "INACTIVE"+ assert desc["autoRegistrationStatus"] == "DISABLE"++ iot_client.delete_ca_certificate(certificateId=ca_id)+ with pytest.raises(ClientError) as ei:+ iot_client.describe_ca_certificate(certificateId=ca_id)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_iot_register_ca_certificate_duplicate_conflict(iot_client):+ ca_pem, _leaf = _generate_ca_and_leaf()+ ca_id = iot_client.register_ca_certificate(caCertificate=ca_pem)["certificateId"]+ with pytest.raises(ClientError) as ei:+ iot_client.register_ca_certificate(caCertificate=ca_pem)+ err = ei.value.response+ assert err["Error"]["Code"] == "ResourceAlreadyExistsException"+ assert err["resourceId"] == ca_id+ assert err["resourceArn"].endswith(":cacert/" + ca_id)+ iot_client.delete_ca_certificate(certificateId=ca_id)+++def test_iot_jitr_registered_event_published_when_auto_registration_enabled():+ """Register a CA with auto-registration ENABLE, subscribe on+ ``$aws/events/certificates/registered/#``, register a device cert under+ that CA — the JITR lifecycle event arrives with certificateId ++ caCertificateId and DescribeCertificate resolves the signing CA.++ Runs in-process against the module broker (the WS route to the live+ server needs ``*.localhost`` DNS this environment lacks), following the+ broker-helper pattern above.+ """+ from ministack.core.responses import (+ set_request_account_id,+ set_request_region,+ )+ from ministack.services import iot as iot_module++ ca_pem, leaf_pem = _generate_ca_and_leaf()+ account_id = "123456789012"+ received: list = []++ async def _run():+ set_request_account_id(account_id)+ set_request_region(_TEST_REGION)++ status, _, body = await iot_module.handle_request(+ "POST",+ "/cacertificate",+ {},+ json.dumps({"caCertificate": ca_pem}).encode(),+ {"setAsActive": "true", "allowAutoRegistration": "true"},+ )+ assert status == 200+ ca_id = json.loads(body)["certificateId"]++ async def _collect(topic, payload, qos):+ received.append((topic, payload, qos))++ await iot_module.broker_subscribe(+ account_id,+ _TEST_REGION,+ "$aws/events/certificates/registered/#",+ _collect,+ )++ status, _, body = await iot_module.handle_request(+ "POST",+ "/certificate/register",+ {},+ json.dumps({+ "certificatePem": leaf_pem,+ "caCertificatePem": ca_pem,+ "status": "PENDING_ACTIVATION",+ }).encode(),+ {},+ )+ assert status == 200+ cert_id = json.loads(body)["certificateId"]++ assert len(received) == 1+ topic, payload, _qos = received[0]+ assert topic == f"$aws/events/certificates/registered/{ca_id}"+ event = json.loads(payload)+ assert event["certificateId"] == cert_id+ assert event["caCertificateId"] == ca_id+ assert event["certificateStatus"] == "PENDING_ACTIVATION"+ assert event["awsAccountId"] == account_id+ assert isinstance(event["timestamp"], int)+ assert event["certificateRegistrationTimestamp"] == str(event["timestamp"])++ # A JITR Lambda resolves the signing CA via DescribeCertificate.+ status, _, body = await iot_module.handle_request(+ "GET", f"/certificates/{cert_id}", {}, b"", {}+ )+ assert status == 200+ assert (+ json.loads(body)["certificateDescription"]["caCertificateId"] == ca_id# ----------------------------------------------------------------------@@ -4486,6 +4672,67 @@ def test_shadow_mqtt_update_reported_in_sync_emits_no_delta():try:asyncio.run(_run())+ finally:+ iot_module.reset()+ iot_module.broker_reset()+++def test_iot_jitr_no_event_when_auto_registration_disabled():+ """A CA registered without ``allowAutoRegistration`` links the device cert+ (``caCertificateId``) but publishes no registered event."""+ from ministack.core.responses import (+ set_request_account_id,+ set_request_region,+ )+ from ministack.services import iot as iot_module++ ca_pem, leaf_pem = _generate_ca_and_leaf()+ account_id = "123456789012"+ received: list = []++ async def _run():+ set_request_account_id(account_id)+ set_request_region(_TEST_REGION)++ status, _, body = await iot_module.handle_request(+ "POST",+ "/cacertificate",+ {},+ json.dumps({"caCertificate": ca_pem}).encode(),+ {"setAsActive": "true"},+ )+ assert status == 200+ ca_id = json.loads(body)["certificateId"]++ async def _collect(topic, payload, qos):+ received.append((topic, payload, qos))++ await iot_module.broker_subscribe(+ account_id,+ _TEST_REGION,+ "$aws/events/certificates/registered/#",+ _collect,+ )++ status, _, body = await iot_module.handle_request(+ "POST",+ "/certificate/register",+ {},+ json.dumps({+ "certificatePem": leaf_pem,+ "caCertificatePem": ca_pem,+ }).encode(),+ {},+ )+ assert status == 200+ cert_id = json.loads(body)["certificateId"]+ assert received == []++ status, _, body = await iot_module.handle_request(+ "GET", f"/certificates/{cert_id}", {}, b"", {}+ )+ assert (+ json.loads(body)["certificateDescription"]["caCertificateId"] == ca_idassert len(frames["$aws/things/dev2/shadow/update/accepted"]) == 1assert "$aws/things/dev2/shadow/update/delta" not in framesassert len(frames["$aws/things/dev2/shadow/update/documents"]) == 1@@ -4528,6 +4775,378 @@ def test_shadow_mqtt_update_rejections():try:asyncio.run(_run())+ finally:+ iot_module.reset()+ iot_module.broker_reset()+++def test_iot_register_certificate_under_ca_links_ca_certificate_id(iot_client):+ """The headline JITR flow over the wire: register a CA, register a device+ certificate under it, and DescribeCertificate resolves the signing CA —+ through the router, botocore serialization and all."""+ ca_pem, leaf_pem = _generate_ca_and_leaf()+ ca_id = iot_client.register_ca_certificate(+ caCertificate=ca_pem, setAsActive=True, allowAutoRegistration=True+ )["certificateId"]+ try:+ cert_id = iot_client.register_certificate(+ certificatePem=leaf_pem,+ caCertificatePem=ca_pem,+ status="PENDING_ACTIVATION",+ )["certificateId"]+ desc = iot_client.describe_certificate(certificateId=cert_id)[+ "certificateDescription"+ ]+ assert desc["caCertificateId"] == ca_id+ assert desc["status"] == "PENDING_ACTIVATION"+ iot_client.delete_certificate(certificateId=cert_id)+ finally:+ iot_client.update_ca_certificate(certificateId=ca_id, newStatus="INACTIVE")+ iot_client.delete_ca_certificate(certificateId=ca_id)+++def test_iot_register_certificate_rejects_an_unregistered_ca(iot_client):+ """``caCertificatePem`` naming a CA that was never registered is a+ ``CertificateValidationException``, and nothing is stored — otherwise the+ CA id is whatever the caller sent and DescribeCertificate points at a CA+ that does not exist."""+ from ministack.core.x509_utils import get_certificate_id++ ca_pem, leaf_pem = _generate_ca_and_leaf()+ with pytest.raises(ClientError) as ei:+ iot_client.register_certificate(+ certificatePem=leaf_pem, caCertificatePem=ca_pem+ )+ assert ei.value.response["Error"]["Code"] == "CertificateValidationException"+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400++ with pytest.raises(ClientError) as ei:+ iot_client.describe_certificate(certificateId=get_certificate_id(leaf_pem))+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_iot_register_certificate_rejects_a_leaf_from_another_ca(iot_client):+ """Both CAs are registered, so the only thing separating them is the+ signature: a leaf signed by CA-X may not register under CA-Y. Without the+ check the JITR event fires on CA-Y's topic and a JITR Lambda that picks+ provisioning templates by ``caCertificateId`` provisions the wrong fleet.+ The same leaf under its real CA still registers."""+ from ministack.core.x509_utils import get_certificate_id++ ca_x_pem, leaf_pem = _generate_ca_and_leaf()+ ca_y_pem, _leaf_y = _generate_ca_and_leaf()+ ca_x_id = iot_client.register_ca_certificate(+ caCertificate=ca_x_pem, setAsActive=True, allowAutoRegistration=True+ )["certificateId"]+ ca_y_id = iot_client.register_ca_certificate(+ caCertificate=ca_y_pem, setAsActive=True, allowAutoRegistration=True+ )["certificateId"]+ try:+ with pytest.raises(ClientError) as ei:+ iot_client.register_certificate(+ certificatePem=leaf_pem, caCertificatePem=ca_y_pem+ )+ assert ei.value.response["Error"]["Code"] == "CertificateValidationException"+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+ with pytest.raises(ClientError):+ iot_client.describe_certificate(certificateId=get_certificate_id(leaf_pem))++ # Same leaf, its actual issuer — accepted, and linked to that CA.+ cert_id = iot_client.register_certificate(+ certificatePem=leaf_pem, caCertificatePem=ca_x_pem+ )["certificateId"]+ desc = iot_client.describe_certificate(certificateId=cert_id)[+ "certificateDescription"+ ]+ assert desc["caCertificateId"] == ca_x_id+ iot_client.delete_certificate(certificateId=cert_id)+ finally:+ for ca_id in (ca_x_id, ca_y_id):+ iot_client.update_ca_certificate(certificateId=ca_id, newStatus="INACTIVE")+ iot_client.delete_ca_certificate(certificateId=ca_id)+++def test_iot_jitr_no_event_for_a_certificate_from_another_ca():+ """The rejection happens before anything is published, so no JITR consumer+ ever sees an event attributing a foreign certificate to its CA."""+ from ministack.core.responses import (+ set_request_account_id,+ set_request_region,+ )+ from ministack.services import iot as iot_module++ _ca_x_pem, leaf_pem = _generate_ca_and_leaf()+ ca_y_pem, _leaf_y = _generate_ca_and_leaf()+ account_id = "123456789012"+ received: list = []++ async def _run():+ set_request_account_id(account_id)+ set_request_region(_TEST_REGION)++ status, _, _body = await iot_module.handle_request(+ "POST",+ "/cacertificate",+ {},+ json.dumps({"caCertificate": ca_y_pem}).encode(),+ {"setAsActive": "true", "allowAutoRegistration": "true"},+ )+ assert status == 200++ async def _collect(topic, payload, qos):+ received.append((topic, payload, qos))++ await iot_module.broker_subscribe(+ account_id,+ _TEST_REGION,+ "$aws/events/certificates/registered/#",+ _collect,+ )++ status, _, body = await iot_module.handle_request(+ "POST",+ "/certificate/register",+ {},+ json.dumps(+ {"certificatePem": leaf_pem, "caCertificatePem": ca_y_pem}+ ).encode(),+ {},+ )+ assert status == 400+ assert json.loads(body)["__type"] == "CertificateValidationException"+ assert received == []++ try:+ asyncio.run(_run())+ finally:+ iot_module.reset()+ iot_module.broker_reset()+++def test_iot_update_ca_certificate_applies_a_body_only_status(iot_client):+ """newStatus / newAutoRegistrationStatus are modeled in the query string,+ but a raw caller that sends them in the JSON body must not get a 200 that+ changed nothing — UpdateCertificate accepts either, and so does this."""+ import os+ import urllib.request++ ca_pem, _leaf = _generate_ca_and_leaf()+ ca_id = iot_client.register_ca_certificate(caCertificate=ca_pem)["certificateId"]+ try:+ assert (+ iot_client.describe_ca_certificate(certificateId=ca_id)[+ "certificateDescription"+ ]["status"]+ == "INACTIVE"+ )+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ req = urllib.request.Request(+ f"{endpoint}/cacertificate/{ca_id}",+ data=json.dumps(+ {"newStatus": "ACTIVE", "newAutoRegistrationStatus": "ENABLE"}+ ).encode(),+ method="PUT",+ headers={+ # The CA registry is account+region scoped, so the credential+ # scope has to name the same region the boto3 client signs with.+ "Authorization": (+ "AWS4-HMAC-SHA256 Credential=test/0/us-east-1/iot/aws4_request"+ ),+ "Content-Type": "application/json",+ },+ )+ with urllib.request.urlopen(req, timeout=5) as resp:+ assert resp.status == 200+ desc = iot_client.describe_ca_certificate(certificateId=ca_id)[+ "certificateDescription"+ ]+ assert desc["status"] == "ACTIVE"+ assert desc["autoRegistrationStatus"] == "ENABLE"+ finally:+ iot_client.update_ca_certificate(certificateId=ca_id, newStatus="INACTIVE")+ iot_client.delete_ca_certificate(certificateId=ca_id)+++def test_iot_jitr_event_requires_an_active_ca():+ """Auto-registration is gated on the CA's own status: an INACTIVE CA with+ allowAutoRegistration publishes nothing (AWS registers nothing under one),+ and activating the same CA starts the events flowing."""+ from ministack.core.responses import (+ set_request_account_id,+ set_request_region,+ )+ from ministack.services import iot as iot_module++ ca_pem, (leaf_pem, leaf_pem2) = _generate_ca_and_leaves(2)+ account_id = "123456789012"+ received: list = []++ async def _run():+ set_request_account_id(account_id)+ set_request_region(_TEST_REGION)++ # INACTIVE (no setAsActive) but auto-registration ENABLE.+ status, _, body = await iot_module.handle_request(+ "POST",+ "/cacertificate",+ {},+ json.dumps({"caCertificate": ca_pem}).encode(),+ {"allowAutoRegistration": "true"},+ )+ assert status == 200+ ca_id = json.loads(body)["certificateId"]++ async def _collect(topic, payload, qos):+ received.append((topic, payload, qos))++ await iot_module.broker_subscribe(+ account_id,+ _TEST_REGION,+ "$aws/events/certificates/registered/#",+ _collect,+ )++ status, _, _body = await iot_module.handle_request(+ "POST",+ "/certificate/register",+ {},+ json.dumps(+ {"certificatePem": leaf_pem, "caCertificatePem": ca_pem}+ ).encode(),+ {},+ )+ assert status == 200+ assert received == []++ # Activate the CA — the very next registration fires.+ status, _, _body = await iot_module.handle_request(+ "PUT", f"/cacertificate/{ca_id}", {}, b"", {"newStatus": "ACTIVE"}+ )+ assert status == 200++ status, _, body = await iot_module.handle_request(+ "POST",+ "/certificate/register",+ {},+ json.dumps(+ {"certificatePem": leaf_pem2, "caCertificatePem": ca_pem}+ ).encode(),+ {},+ )+ assert status == 200+ cert_id2 = json.loads(body)["certificateId"]++ assert len(received) == 1+ topic, payload, _qos = received[0]+ assert topic == f"$aws/events/certificates/registered/{ca_id}"+ assert json.loads(payload)["certificateId"] == cert_id2++ try:+ asyncio.run(_run())+ finally:+ iot_module.reset()+ iot_module.broker_reset()+++def test_iot_jitr_registration_survives_a_broker_failure(monkeypatch):+ """The certificate is committed before the event is published, so a broker+ that raises must not turn a successful registration into a 500."""+ from ministack.core.responses import (+ set_request_account_id,+ set_request_region,+ )+ from ministack.services import iot as iot_module++ ca_pem, leaf_pem = _generate_ca_and_leaf()+ account_id = "123456789012"++ async def _boom(*_args, **_kwargs):+ raise RuntimeError("broker down")++ async def _run():+ set_request_account_id(account_id)+ set_request_region(_TEST_REGION)++ status, _, _body = await iot_module.handle_request(+ "POST",+ "/cacertificate",+ {},+ json.dumps({"caCertificate": ca_pem}).encode(),+ {"setAsActive": "true", "allowAutoRegistration": "true"},+ )+ assert status == 200++ monkeypatch.setattr(iot_module, "broker_publish", _boom)+ status, _, body = await iot_module.handle_request(+ "POST",+ "/certificate/register",+ {},+ json.dumps(+ {"certificatePem": leaf_pem, "caCertificatePem": ca_pem}+ ).encode(),+ {},+ )+ assert status == 200+ cert_id = json.loads(body)["certificateId"]++ status, _, body = await iot_module.handle_request(+ "GET", f"/certificates/{cert_id}", {}, b"", {}+ )+ assert status == 200+ assert json.loads(body)["certificateDescription"]["certificateId"] == cert_id++ try:+ asyncio.run(_run())+ finally:+ iot_module.reset()+ iot_module.broker_reset()+++def test_iot_update_ca_certificate_rejects_invalid_enum_values(iot_client):+ """The two update fields validate their enums with a 400.++ boto3 already refuses bad values client-side, so the branch is only+ reachable over raw HTTP - which is exactly how a non-SDK caller would+ hit it.+ """+ import os+ import urllib.error+ import urllib.request++ ca_pem, _leaf = _generate_ca_and_leaf()+ ca_id = iot_client.register_ca_certificate(caCertificate=ca_pem)["certificateId"]+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")+ try:+ for payload, wanted in (+ ({"newStatus": "BOGUS"}, "newStatus"),+ ({"newAutoRegistrationStatus": "MAYBE"}, "newAutoRegistrationStatus"),+ ):+ req = urllib.request.Request(+ f"{endpoint}/cacertificate/{ca_id}",+ data=json.dumps(payload).encode(),+ method="PUT",+ headers={+ "Authorization": (+ "AWS4-HMAC-SHA256 Credential=test/0/us-east-1/iot/aws4_request"+ ),+ "Content-Type": "application/json",+ },+ )+ try:+ urllib.request.urlopen(req, timeout=5)+ pytest.fail(f"expected HTTP 400 for {payload}")+ except urllib.error.HTTPError as e:+ assert e.code == 400+ assert wanted in e.read().decode()+ # The invalid updates changed nothing: a freshly registered CA stays+ # INACTIVE with auto-registration DISABLE.+ desc = iot_client.describe_ca_certificate(certificateId=ca_id)[+ "certificateDescription"+ ]+ assert desc["status"] == "INACTIVE"+ assert desc["autoRegistrationStatus"] == "DISABLE"+ finally:+ iot_client.delete_ca_certificate(certificateId=ca_id)assert len(rejected) == 2assert rejected[0]["code"] == 400assert "clientToken" not in rejected[0]diff --git a/tests/test_iot_data.py b/tests/test_iot_data.pyindex 000bc4ba..d55e8512 100644--- a/tests/test_iot_data.py+++ b/tests/test_iot_data.py@@ -1112,6 +1112,55 @@ def test_iot_rule_sns_action_publishes_to_topic(iot_client, iot_data_client, snsiot_client.delete_topic_rule(ruleName=rule)+def test_iot_jitr_registration_event_drives_a_topic_rule(iot_client, lam, sqs):+ """The JITR lifecycle event is a real broker publish, so a topic rule on+ ``$aws/events/certificates/registered/{caId}`` hands it to a Lambda — the+ shape a just-in-time-registration stack actually deploys.++ The rule names this test's CA id rather than the ``+`` wildcard: the+ account's registered-certificate topics are shared, so a wildcard rule+ living for the length of this test also catches the registrations other+ tests make on other xdist workers, and ``_poll_sink`` would return+ whichever event landed first."""+ pytest.importorskip("cryptography")+ from ministack.core.x509_utils import generate_ca, sign_leaf_certificate++ ca_pem, ca_key_pem = generate_ca(common_name=_unique("jitr-rule-ca"))+ leaf_pem, _priv, _pub = sign_leaf_certificate(+ ca_cert_pem=ca_pem,+ ca_key_pem=ca_key_pem,+ common_name=_unique("jitr-rule-device"),+ )++ sink = sqs.create_queue(QueueName=_unique("jitr-sink"))["QueueUrl"]+ fn_arn = _make_sink_lambda(lam, sink)+ rule = _unique("jitr").replace("-", "_")+ ca_id = iot_client.register_ca_certificate(+ caCertificate=ca_pem, setAsActive=True, allowAutoRegistration=True+ )["certificateId"]+ iot_client.create_topic_rule(+ ruleName=rule,+ topicRulePayload={+ "sql": f"SELECT * FROM '$aws/events/certificates/registered/{ca_id}'",+ "actions": [{"lambda": {"functionArn": fn_arn}}],+ },+ )+ try:+ cert_id = iot_client.register_certificate(+ certificatePem=leaf_pem,+ caCertificatePem=ca_pem,+ status="PENDING_ACTIVATION",+ )["certificateId"]+ event = _poll_sink(sqs, sink)+ assert event is not None, "no JITR event reached the rule's Lambda"+ assert event["certificateId"] == cert_id+ assert event["caCertificateId"] == ca_id+ assert event["certificateStatus"] == "PENDING_ACTIVATION"+ iot_client.delete_certificate(certificateId=cert_id)+ finally:+ iot_client.delete_topic_rule(ruleName=rule)+ iot_client.update_ca_certificate(certificateId=ca_id, newStatus="INACTIVE")+ iot_client.delete_ca_certificate(certificateId=ca_id)# ---------------------------------------------------------------------------# Topic-rule `sqs` action (publish → rule → SQS queue)# ---------------------------------------------------------------------------diff --git a/tests/test_persistence.py b/tests/test_persistence.pyindex 62d964a4..69edb208 100644--- a/tests/test_persistence.py+++ b/tests/test_persistence.py@@ -2471,6 +2471,67 @@ def test_eventbridge_legacy_account_scoped_targets_restore_to_rule_region():set_request_region(original_region)+# ── iot._ca_certificates + iot._registration_codes ────────────────────++def test_iot_ca_registry_and_registration_code_survive_warm_boot():+ """`RegisterCACertificate` writes `_ca_certificates` and+ `GetRegistrationCode` writes `_registration_codes`. If either dict is+ dropped from get_state()/restore_state(), registered JITR CAs and the+ account registration code silently vanish on restart.++ The warm boot is spelled out rather than taken from `_round_trip_dict` so+ the state is also checked *between* reset() and restore_state(): a dict+ missing from reset() survives the round trip untouched, which would satisfy+ an after-restore assertion alone while restore_state never restored+ anything."""+ mod = _get_module("iot")+ mod.reset()+ ca_id = "c" * 64+ ca_arn = f"arn:aws:iot:us-east-1:000000000000:cacert/{ca_id}"+ try:+ mod._ca_certificates[ca_id] = {+ "certificateId": ca_id,+ "certificateArn": ca_arn,+ "certificatePem": (+ "-----BEGIN CERTIFICATE-----\nAA==\n-----END CERTIFICATE-----\n"+ ),+ "status": "ACTIVE",+ "autoRegistrationStatus": "ENABLE",+ "creationDate": 1700000000,+ }+ mod._registration_codes["code"] = "d" * 64++ persistence.save_state("iot", mod.get_state())+ mod.reset()+ assert mod._ca_certificates.get(ca_id) is None, (+ "_ca_certificates survived reset() — the CA registry must be "+ "cleared there, or a restart leaks the previous run's CAs."+ )+ assert mod._registration_codes.get("code") is None, (+ "_registration_codes survived reset() — the registration code must "+ "be cleared there."+ )+ loaded = persistence.load_state("iot")+ assert loaded is not None, (+ "persistence.load_state('iot') returned None — state file was not "+ "written by save_state()."+ )+ mod.restore_state(loaded)++ restored = mod._ca_certificates.get(ca_id)+ assert restored is not None, (+ "_ca_certificates lost across save_state → load_state — the CA "+ "registry must be in both get_state and restore_state."+ )+ assert restored["certificateArn"] == ca_arn+ assert restored["autoRegistrationStatus"] == "ENABLE"+ assert mod._registration_codes.get("code") == "d" * 64, (+ "_registration_codes lost across save_state → load_state."+ )+ finally:+ mod.reset()++# ── Import-order regression for the ECS NameError trap ───────────────def test_ecs_module_reload_with_persisted_attributes_does_not_namerror():