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(cloudformation): provision AWS::IoT::CACertificate (#1539)
iot-rocket2947bedd9cb0
diff --git a/README.md b/README.mdindex 04ca4b45..df035e7b 100644--- a/README.md+++ b/README.md@@ -508,6 +508,7 @@ subnet = ec2.create_subnet(| `AWS::Cognito::UserPoolResourceServer` | Identifier | — || `AWS::Cognito::IdentityPool` | Pool ID | — || `AWS::Cognito::UserPoolDomain` | Domain | — |+| `AWS::IoT::CACertificate` | Certificate id | Arn, Id || `AWS::ECR::Repository` | Repo name | Arn, RepositoryUri || `AWS::IAM::ManagedPolicy` | Policy ARN | — || `AWS::KMS::Key` | Key ID | Arn, KeyId |diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 7724fe84..4cea4808 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -6787,6 +6787,93 @@ def _iot_provisioning_template_delete(physical_id, props):_iot._delete_provisioning_template(physical_id)+def _iot_ca_certificate_apply(ca_id, props):+ """Bring an existing CA registration to the template's declared state."""+ resp = _iot._handle_ca_certificate(+ "PUT", f"/cacertificate/{ca_id}", b"", {+ "newStatus": props.get("Status", "INACTIVE"),+ "newAutoRegistrationStatus":+ "ENABLE" if props.get("AutoRegistrationStatus") == "ENABLE" else "DISABLE",+ },+ )+ if resp[0] >= 400:+ raise ValueError(f"AWS::IoT::CACertificate update failed: {resp[2]!r}")+ if props.get("CertificateMode"):+ if props["CertificateMode"] not in ("DEFAULT", "SNI_ONLY"):+ raise ValueError(+ "AWS::IoT::CACertificate CertificateMode must be one of ['DEFAULT', 'SNI_ONLY']"+ )+ # Deliberate simplification: real CloudFormation documents CertificateMode+ # as update-requires-replacement (UpdateCACertificate has no mode member),+ # so the mode is written on the record directly instead. Omitting it on an+ # update keeps the old mode, where real CFN would revert to DEFAULT by+ # replacing the certificate.+ _iot._ca_certificates[ca_id]["certificateMode"] = props["CertificateMode"]+ return ca_id, {"Arn": _iot._ca_cert_arn(ca_id), "Id": ca_id}+++def _iot_ca_certificate_create(logical_id, props, stack_name):+ pem = props.get("CACertificatePem")+ if not pem:+ raise ValueError("AWS::IoT::CACertificate requires CACertificatePem")+ payload = {+ "caCertificate": pem,+ "verificationCertificate": props.get("VerificationCertificatePem"),+ "certificateMode": props.get("CertificateMode"),+ }+ resp = _iot._register_ca_certificate(+ {k: v for k, v in payload.items() if v is not None},+ {+ "setAsActive": "true" if props.get("Status", "INACTIVE") == "ACTIVE" else "false",+ "allowAutoRegistration": "true" if props.get("AutoRegistrationStatus") == "ENABLE" else "false",+ },+ )+ if resp[0] == 409:+ # The certificate id is derived from the PEM, so re-registering the+ # same PEM answers ResourceAlreadyExists. CloudFormation's create must+ # be idempotent — a rollback replay re-enters create — so adopt the+ # existing registration and bring it to the declared state instead of+ # failing the stack. Tradeoff: a CA the user registered out of band+ # under the same PEM is adopted too (and mutated/deleted with the+ # stack from here on) — an accepted simplification.+ return _iot_ca_certificate_apply(json.loads(resp[2])["resourceId"], props)+ if resp[0] >= 400:+ raise ValueError(f"AWS::IoT::CACertificate create failed: {resp[2]!r}")+ ca_id = json.loads(resp[2])["certificateId"]+ return ca_id, {"Arn": _iot._ca_cert_arn(ca_id), "Id": ca_id}+++def _iot_ca_certificate_update(physical_id, old_props, new_props, stack_name):+ """Apply Status/AutoRegistrationStatus/CertificateMode in place.++ The physical id is derived from the certificate content, so a changed+ ``CACertificatePem`` cannot be an in-place update — and silently replacing+ the CA would orphan every device certificate registered under the old one.+ The update fails loudly instead, the way a custom-named replacement is+ refused.+ """+ if new_props.get("CACertificatePem") != old_props.get("CACertificatePem"):+ raise ValueError(+ "AWS::IoT::CACertificate cannot update CACertificatePem in place: "+ "the certificate id is derived from the PEM. Declare a new "+ "CACertificate resource for the new PEM and remove this one."+ )+ return _iot_ca_certificate_apply(physical_id, new_props)+++def _iot_ca_certificate_delete(physical_id, props):+ if physical_id not in _iot._ca_certificates:+ return+ # An ACTIVE CA refuses deletion (CertificateStateException) — deactivate+ # first, and delete through the API path rather than a raw pop so the+ # registry stays consistent with what DeleteCACertificate enforces.+ if _iot._ca_certificates[physical_id].get("status") == "ACTIVE":+ _iot._handle_ca_certificate(+ "PUT", f"/cacertificate/{physical_id}", b"", {"newStatus": "INACTIVE"}+ )+ _iot._handle_ca_certificate("DELETE", f"/cacertificate/{physical_id}", b"", {})++def _cognito_identity_pool_role_attachment_create(logical_id, props, stack_name):iid = props.get("IdentityPoolId")if not iid:@@ -7111,6 +7198,11 @@ _RESOURCE_HANDLERS = {"update_with_logical_id": True,"delete": _iot_provisioning_template_delete,},+ "AWS::IoT::CACertificate": {+ "create": _iot_ca_certificate_create,+ "update": _iot_ca_certificate_update,+ "delete": _iot_ca_certificate_delete,+ },"AWS::Cognito::IdentityPoolRoleAttachment": {"create": _cognito_identity_pool_role_attachment_create,"delete": _cognito_identity_pool_role_attachment_delete,diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex b1a07be9..faa774d0 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -1598,16 +1598,24 @@ def _handle_registration_code(method: str) -> tuple:def _register_ca_certificate(payload: dict, qp: dict) -> tuple:"""``POST /cacertificate`` (``RegisterCACertificate``).- Body members per the botocore model: ``caCertificate`` (required) and+ Body members per the botocore model: ``caCertificate`` (required),``verificationCertificate`` (accepted; the registration-code CN handshake- is not enforced locally). ``setAsActive`` / ``allowAutoRegistration`` ride- as query-string booleans, as on AWS.+ is not enforced locally) and ``certificateMode`` (``DEFAULT`` when+ omitted, as on AWS). ``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)+ certificate_mode = payload.get("certificateMode") or "DEFAULT"+ if certificate_mode not in ("DEFAULT", "SNI_ONLY"):+ return error_response_json(+ "InvalidRequestException",+ "certificateMode must be one of ['DEFAULT', 'SNI_ONLY']",+ 400,+ )try:ca_id = get_certificate_id(ca_pem)except Exception as e:@@ -1626,6 +1634,7 @@ def _register_ca_certificate(payload: dict, qp: dict) -> tuple:"certificatePem": ca_pem, # verbatim"status": "ACTIVE" if set_active else "INACTIVE","autoRegistrationStatus": "ENABLE" if allow_auto else "DISABLE",+ "certificateMode": certificate_mode,"creationDate": _now_epoch(),"ownedBy": get_account_id(),}@@ -1672,6 +1681,9 @@ def _handle_ca_certificate(method: str, path: str, body: bytes, qp: dict) -> tup"status": record["status"],"certificatePem": record["certificatePem"],"autoRegistrationStatus": record["autoRegistrationStatus"],+ # .get: a record restored from a snapshot taken before the+ # field existed carries no mode; AWS's default stands in.+ "certificateMode": record.get("certificateMode", "DEFAULT"),"ownedBy": record["ownedBy"],"creationDate": record.get("creationDate"),}@@ -1708,9 +1720,11 @@ def _handle_ca_certificate(method: str, path: str, body: bytes, qp: dict) -> tupreturn json_response({})if method == "DELETE":if record["status"] == "ACTIVE":+ # Wording verified against real AWS (live probe 2026-08-26).return error_response_json("CertificateStateException",- "CA certificate is ACTIVE; deactivate before deletion",+ "CA Certificate must be deactivated (not ACTIVE) before "+ f"deletion. Id: {ca_id}",406,)del _ca_certificates[ca_id]diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 88d5ee6a..e32503c1 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -799,6 +799,154 @@ def test_cfn_iot_provisioning_template_generated_name(cfn, iot_client):iot_client.describe_provisioning_template(templateName=name)+def test_cfn_iot_ca_certificate_lifecycle(cfn, iot_client):+ """AWS::IoT::CACertificate provisions onto the real CA registry instead of+ rolling the stack back: create registers the PEM (readable back through+ DescribeCACertificate), a status change is applied in place under the same+ PEM-derived physical id, and delete deactivates first — an ACTIVE CA+ refuses deletion — before removing the registration."""+ pytest.importorskip("cryptography")+ from ministack.core.x509_utils import generate_ca++ ca_pem, _ca_key = generate_ca(common_name="cfn-test-ca")++ def template(status):+ return json.dumps({+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {"CA": {"Type": "AWS::IoT::CACertificate", "Properties": {+ "CACertificatePem": ca_pem,+ "Status": status,+ "AutoRegistrationStatus": "ENABLE",+ "CertificateMode": "SNI_ONLY",+ }}},+ "Outputs": {+ "CaRef": {"Value": {"Ref": "CA"}},+ "CaArn": {"Value": {"Fn::GetAtt": ["CA", "Arn"]}},+ "CaId": {"Value": {"Fn::GetAtt": ["CA", "Id"]}},+ },+ })++ cfn.create_stack(StackName="cfn-iot-ca", TemplateBody=template("ACTIVE"))+ stack = _wait_stack(cfn, "cfn-iot-ca")+ assert stack["StackStatus"] == "CREATE_COMPLETE"++ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}+ ca_id = outputs["CaId"]+ assert outputs["CaRef"] == ca_id+ assert outputs["CaArn"].endswith(":cacert/" + ca_id)++ # Readable back through the CA registry's own API, with every declared+ # property applied.+ desc = iot_client.describe_ca_certificate(certificateId=ca_id)[+ "certificateDescription"]+ assert desc["certificatePem"] == ca_pem+ assert desc["status"] == "ACTIVE"+ assert desc["autoRegistrationStatus"] == "ENABLE"+ assert desc["certificateMode"] == "SNI_ONLY"++ # A status change is applied in place: same physical id, no replacement.+ cfn.update_stack(StackName="cfn-iot-ca", TemplateBody=template("INACTIVE"))+ stack = _wait_stack(cfn, "cfn-iot-ca")+ assert stack["StackStatus"] == "UPDATE_COMPLETE"+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}+ assert outputs["CaId"] == ca_id+ desc = iot_client.describe_ca_certificate(certificateId=ca_id)[+ "certificateDescription"]+ assert desc["status"] == "INACTIVE"++ # Reactivate, then delete the stack: an ACTIVE CA refuses DeleteCACertificate,+ # so the provisioner must deactivate before deleting.+ cfn.update_stack(StackName="cfn-iot-ca", TemplateBody=template("ACTIVE"))+ assert _wait_stack(cfn, "cfn-iot-ca")["StackStatus"] == "UPDATE_COMPLETE"++ cfn.delete_stack(StackName="cfn-iot-ca")+ _wait_stack(cfn, "cfn-iot-ca")+ with pytest.raises(ClientError) as ei:+ iot_client.describe_ca_certificate(certificateId=ca_id)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_cfn_iot_ca_certificate_adopts_existing_registration(cfn, iot_client):+ """A CA already registered out of band answers ResourceAlreadyExists when+ the stack's create re-registers the PEM (the certificate id is derived+ from it). Create adopts that registration under the same id and brings it+ to the declared state instead of failing the stack — the same idempotent+ path a rollback replay of create takes. The adopted CA is owned by the+ stack from then on, so it goes away with the stack."""+ pytest.importorskip("cryptography")+ from ministack.core.x509_utils import generate_ca++ ca_pem, _ca_key = generate_ca(common_name="cfn-adopt-ca")+ # Registered out of band: INACTIVE, auto-registration DISABLE.+ pre_id = iot_client.register_ca_certificate(caCertificate=ca_pem)["certificateId"]++ template = json.dumps({+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {"CA": {"Type": "AWS::IoT::CACertificate", "Properties": {+ "CACertificatePem": ca_pem,+ "Status": "ACTIVE",+ "AutoRegistrationStatus": "ENABLE",+ }}},+ "Outputs": {"CaId": {"Value": {"Fn::GetAtt": ["CA", "Id"]}}},+ })+ cfn.create_stack(StackName="cfn-iot-ca-adopt", TemplateBody=template)+ stack = _wait_stack(cfn, "cfn-iot-ca-adopt")+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}+ assert outputs["CaId"] == pre_id++ # Adopted and brought to the declared state, not re-registered.+ desc = iot_client.describe_ca_certificate(certificateId=pre_id)[+ "certificateDescription"]+ assert desc["status"] == "ACTIVE"+ assert desc["autoRegistrationStatus"] == "ENABLE"++ cfn.delete_stack(StackName="cfn-iot-ca-adopt")+ _wait_stack(cfn, "cfn-iot-ca-adopt")+ with pytest.raises(ClientError) as ei:+ iot_client.describe_ca_certificate(certificateId=pre_id)+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_cfn_iot_ca_certificate_pem_change_refused(cfn, iot_client):+ """CACertificatePem is the physical identity — the certificate id derives+ from it — so an update that changes the PEM fails loudly and rolls back+ instead of silently replacing the CA (which would orphan every device+ certificate registered under the old one). The original registration+ survives untouched."""+ pytest.importorskip("cryptography")+ from ministack.core.x509_utils import generate_ca++ pem_a, _key_a = generate_ca(common_name="cfn-ca-pem-a")+ pem_b, _key_b = generate_ca(common_name="cfn-ca-pem-b")++ def template(pem):+ return json.dumps({+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {"CA": {"Type": "AWS::IoT::CACertificate", "Properties": {+ "CACertificatePem": pem,+ "Status": "INACTIVE",+ }}},+ "Outputs": {"CaId": {"Value": {"Fn::GetAtt": ["CA", "Id"]}}},+ })++ cfn.create_stack(StackName="cfn-iot-ca-pem", TemplateBody=template(pem_a))+ stack = _wait_stack(cfn, "cfn-iot-ca-pem")+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ ca_id = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}["CaId"]++ cfn.update_stack(StackName="cfn-iot-ca-pem", TemplateBody=template(pem_b))+ stack = _wait_stack(cfn, "cfn-iot-ca-pem")+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"++ desc = iot_client.describe_ca_certificate(certificateId=ca_id)[+ "certificateDescription"]+ assert desc["certificatePem"] == pem_a++ cfn.delete_stack(StackName="cfn-iot-ca-pem")+ _wait_stack(cfn, "cfn-iot-ca-pem")++def test_cfn_lambda_layer_version_permission(cfn, lam):"""AWS::Lambda::LayerVersionPermission attaches a statement to the reallayer version's policy, readable via GetLayerVersionPolicy. (#1345, item 5)"""diff --git a/tests/test_iot.py b/tests/test_iot.pyindex 76621f96..87413e58 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -5220,6 +5220,34 @@ def test_iot_register_ca_certificate_duplicate_conflict(iot_client):iot_client.delete_ca_certificate(certificateId=ca_id)+def test_iot_register_ca_certificate_mode_round_trip(iot_client):+ ca_pem, _leaf = _generate_ca_and_leaf()++ # An invalid mode is rejected up front — nothing is registered.+ with pytest.raises(ClientError) as ei:+ iot_client.register_ca_certificate(+ caCertificate=ca_pem, certificateMode="BOGUS"+ )+ assert ei.value.response["Error"]["Code"] == "InvalidRequestException"++ ca_id = iot_client.register_ca_certificate(+ caCertificate=ca_pem, certificateMode="SNI_ONLY"+ )["certificateId"]+ desc = iot_client.describe_ca_certificate(certificateId=ca_id)[+ "certificateDescription"+ ]+ assert desc["certificateMode"] == "SNI_ONLY"+ iot_client.delete_ca_certificate(certificateId=ca_id)++ # An omitted mode reports AWS's default.+ ca_id = iot_client.register_ca_certificate(caCertificate=ca_pem)["certificateId"]+ desc = iot_client.describe_ca_certificate(certificateId=ca_id)[+ "certificateDescription"+ ]+ assert desc["certificateMode"] == "DEFAULT"+ 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