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): refuse deleting things, certificates, policies and thing types still in use (#2144)
iot-rocketea6ed1c0fb79
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 977af966..038ac19f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **IoT — deleting things, certificates, policies and thing types still in use** — `DeleteThing` detached a thing's certificates and deleted it, and `DeleteCertificate` refused only an `ACTIVE` certificate. Now `DeleteThing` refuses a thing with a certificate attached, `DeleteCertificate` refuses a certificate with things attached and, without `forceDelete`, one with policies attached (`forceDelete` detaches them), `DeletePolicy` refuses a policy with non-default versions and `DeleteThingType` one that things still use, all with AWS's messages. Contributed by @iot-rocket.- **IoT — `RegisterCertificate` under an inactive CA** — a certificate issued by a CA that is not `ACTIVE` registered anyway; it is now refused with `CertificateStateException`, with or without `caCertificatePem`. An unregistered CA and a CA that did not issue the certificate are refused with AWS's codes and messages. Contributed by @iot-rocket.- **IoT — rule SQL `principal()` and `traceid()`** — both resolved to Undefined; `principal()` now returns the client certificate id for mTLS, the caller's `GetCallerIdentity` `UserId` for HTTP Publish and SigV4 WebSocket sessions (also their lifecycle events' `principalIdentifier`) and the rule role's session for a republish, and `traceid()` returns a per-message id that the errorAction document carries as `cloudwatchTraceId`. Contributed by @iot-rocket.### Addeddiff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 98c0abf1..528c6cf5 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -13118,13 +13118,11 @@ def _iot_thing_import(identifier):def _iot_thing_delete(physical_id, props):- thing = _iot._things.get(physical_id)- if thing is None:+ if physical_id not in _iot._things:return- if any(p.rsplit("/", 1)[-1] in _iot._certificates for p in thing.get("principals", [])):- raise ValueError(- f"Cannot delete. Thing {physical_id} is still attached to one or more principals")- _iot._delete_thing(physical_id)+ resp = _iot._delete_thing(physical_id)+ if resp[0] >= 400:+ raise ValueError(json.loads(resp[2])["message"])def _iot_certificate_attrs(cert_id):@@ -13201,16 +13199,9 @@ def _iot_certificate_delete(physical_id, props):returnif cert["status"] == "ACTIVE":_iot_certificate_status(physical_id, "INACTIVE")- arn = cert["certificateArn"]- # The service refuses DeleteCertificate while things are attached, then- # while policies are, in that order.- if any(_iot._thing_name_from_arn(t) in _iot._things for t in cert.get("attachedThings", [])):- raise ValueError(f"Things must be detached before deletion (arn: {arn})")- if _iot._policies_attached_to(arn):- raise ValueError(f"Certificate policies must be detached before deletion (arn: {arn})")resp = _iot._handle_certificate("DELETE", f"/certificates/{physical_id}", b"", {})if resp[0] >= 400:- raise ValueError(f"AWS::IoT::Certificate delete failed: {resp[2]!r}")+ raise ValueError(json.loads(resp[2])["message"])def _iot_thing_principal_attachment_call(method, thing, principal, thing_principal_type=None):diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex e6bd8625..ac300616 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -1385,12 +1385,12 @@ 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+ if any(p.rsplit("/", 1)[-1] in _certificates for p in thing.get("principals", [])):+ return error_response_json(+ "InvalidRequestException",+ f"Cannot delete. Thing {name} is still attached to one or more principals",+ 400,+ )_thing_events("DELETED", thing, thing.get("thingTypeName"))# Remove from groupsfor gname in list(thing.get("thingGroupNames", [])):@@ -1547,6 +1547,12 @@ def _delete_thing_type(name: str) -> tuple:"ThingType must be deprecated for at least 5 minutes before deletion",400,)+ if any(thing.get("thingTypeName") == name for thing in _things.values()):+ return error_response_json(+ "InvalidRequestException",+ f"Can not delete thing type {name} with things associated with it",+ 400,+ )del _thing_types[name]_thing_type_event("DELETED", t)return json_response({})@@ -2439,9 +2445,27 @@ def _handle_certificate(method: str, path: str, body: bytes, qp: dict) -> tuple:if record["status"] == "ACTIVE":return error_response_json("CertificateStateException",- "Certificate is ACTIVE; deactivate before deletion",+ f"Certificate must be deactivated (not ACTIVE) before deletion. Id: {cert_id}",406,)+ # Attached things refuse even forceDelete; attached policies only+ # refuse without it, and forceDelete detaches them.+ arn = record["certificateArn"]+ if any(_thing_name_from_arn(t) in _things for t in record.get("attachedThings", [])):+ return error_response_json(+ "DeleteConflictException",+ f"Things must be detached before deletion (arn: {arn})",+ 409,+ )+ policies = _policies_attached_to(arn)+ if policies and not _qp_bool(qp, "forceDelete"):+ return error_response_json(+ "DeleteConflictException",+ f"Certificate policies must be detached before deletion (arn: {arn})",+ 409,+ )+ for policy in policies:+ _change_policy_target(policy["policyName"], arn, attach=False)del _certificates[cert_id]return json_response({})return error_response_json(@@ -2873,10 +2897,17 @@ def _delete_policy(name: str) -> tuple:p = _policies.get(name)if p is None:return _error_not_found("Policy", name)+ if len(p["versions"]) > 1:+ return error_response_json(+ "DeleteConflictException",+ f"The policy cannot be deleted as multiple versions of the policy exist (name={name}). "+ "Use DeletePolicyVersion action to delete all non-default versions of the policy and retry.",+ 409,+ )if p.get("targets"):return error_response_json("DeleteConflictException",- "Policy is attached; detach it before deletion",+ f"The policy cannot be deleted as the policy is attached to one or more principals (name={name})",409,)del _policies[name]diff --git a/tests/test_iot.py b/tests/test_iot.pyindex 718e0b2e..16e70e1f 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -684,6 +684,24 @@ def test_iot_delete_thing_type_active_rejected(iot_client):iot_client.delete_thing_type(thingTypeName=name)+def test_iot_delete_thing_type_refused_while_a_thing_uses_it(iot_client):+ """A deprecated thing type that a thing still uses is refused."""+ type_name, thing = _unique("type"), _unique("thing")+ iot_client.create_thing_type(thingTypeName=type_name)+ iot_client.create_thing(thingName=thing, thingTypeName=type_name)+ iot_client.deprecate_thing_type(thingTypeName=type_name)+ with pytest.raises(ClientError) as ei:+ iot_client.delete_thing_type(thingTypeName=type_name)+ err = ei.value.response+ assert (err["ResponseMetadata"]["HTTPStatusCode"], err["Error"]["Code"], err["Error"]["Message"]) == (+ 400, "InvalidRequestException", f"Can not delete thing type {type_name} with things associated with it")+ assert iot_client.describe_thing_type(thingTypeName=type_name)["thingTypeName"] == type_name++ iot_client.update_thing(thingName=thing, removeThingType=True)+ iot_client.delete_thing_type(thingTypeName=type_name)+ iot_client.delete_thing(thingName=thing)++# ---------------------------------------------------------------------------# ThingGroup CRUD + membership# ---------------------------------------------------------------------------@@ -937,6 +955,43 @@ def test_iot_delete_active_certificate_rejected(iot_client):iot_client.delete_certificate(certificateId=cert_id)+def test_iot_delete_certificate_refused_while_attached(iot_client):+ """ACTIVE is refused first, then attached things even when forced, then policies unless forced."""+ pytest.importorskip("cryptography")+ thing, policy = _unique("thing"), _unique("policy")+ iot_client.create_thing(thingName=thing)+ iot_client.create_policy(policyName=policy, policyDocument=_POLICY_DOC)+ cert = iot_client.create_keys_and_certificate(setAsActive=True)+ cert_id, arn = cert["certificateId"], cert["certificateArn"]+ iot_client.attach_thing_principal(thingName=thing, principal=arn)+ iot_client.attach_policy(policyName=policy, target=arn)++ def refusal(**kwargs):+ with pytest.raises(ClientError) as ei:+ iot_client.delete_certificate(certificateId=cert_id, **kwargs)+ err = ei.value.response+ return err["ResponseMetadata"]["HTTPStatusCode"], err["Error"]["Code"], err["Error"]["Message"]++ active = (406, "CertificateStateException",+ f"Certificate must be deactivated (not ACTIVE) before deletion. Id: {cert_id}")+ things = (409, "DeleteConflictException", f"Things must be detached before deletion (arn: {arn})")+ policies = (409, "DeleteConflictException", f"Certificate policies must be detached before deletion (arn: {arn})")+ assert refusal() == refusal(forceDelete=True) == active+ for status in ("INACTIVE", "REVOKED"):+ iot_client.update_certificate(certificateId=cert_id, newStatus=status)+ assert refusal() == refusal(forceDelete=True) == things+ iot_client.detach_thing_principal(thingName=thing, principal=arn)+ assert refusal() == policies+ assert iot_client.list_targets_for_policy(policyName=policy)["targets"] == [arn]++ iot_client.delete_certificate(certificateId=cert_id, forceDelete=True)+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.describe_certificate(certificateId=cert_id)+ assert iot_client.list_targets_for_policy(policyName=policy)["targets"] == []+ iot_client.delete_policy(policyName=policy)+ iot_client.delete_thing(thingName=thing)++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.@@ -993,6 +1048,31 @@ def test_iot_attach_detach_thing_principal(iot_client):iot_client.delete_thing(thingName=name)+def test_iot_delete_thing_refused_while_a_principal_is_attached(iot_client):+ """A thing with a certificate attached is refused whatever the certificate's status."""+ pytest.importorskip("cryptography")+ name = _unique("thing")+ iot_client.create_thing(thingName=name)+ cert = iot_client.create_keys_and_certificate(setAsActive=True)+ cert_id, arn = cert["certificateId"], cert["certificateArn"]+ iot_client.attach_thing_principal(thingName=name, principal=arn)+ for status in ("ACTIVE", "INACTIVE", "REVOKED"):+ iot_client.update_certificate(certificateId=cert_id, newStatus=status)+ with pytest.raises(ClientError) as ei:+ iot_client.delete_thing(thingName=name)+ err = ei.value.response+ assert (err["ResponseMetadata"]["HTTPStatusCode"], err["Error"]["Code"], err["Error"]["Message"]) == (+ 400, "InvalidRequestException", f"Cannot delete. Thing {name} is still attached to one or more principals")+ assert iot_client.list_thing_principals(thingName=name)["principals"] == [arn]+ assert iot_client.list_principal_things(principal=arn)["things"] == [name]++ iot_client.detach_thing_principal(thingName=name, principal=arn)+ iot_client.delete_thing(thingName=name)+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.describe_thing(thingName=name)+ iot_client.delete_certificate(certificateId=cert_id)++def test_iot_thing_arn_tail_parser_requires_iot_thing_scope():from ministack.core.responses import (get_account_id,@@ -1108,6 +1188,37 @@ def test_iot_attach_detach_policy(iot_client):iot_client.delete_certificate(certificateId=cert["certificateId"])+def test_iot_delete_policy_refused_while_versioned_or_attached(iot_client):+ """A non-default version is refused before an attachment."""+ pytest.importorskip("cryptography")+ name = _unique("policy")+ iot_client.create_policy(policyName=name, policyDocument=_POLICY_DOC)+ iot_client.create_policy_version(policyName=name, policyDocument=json.dumps({+ "Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "iot:Subscribe", "Resource": "*"}]}))+ cert = iot_client.create_keys_and_certificate(setAsActive=False)+ iot_client.attach_policy(policyName=name, target=cert["certificateArn"])++ def refusal():+ with pytest.raises(ClientError) as ei:+ iot_client.delete_policy(policyName=name)+ err = ei.value.response+ assert (err["ResponseMetadata"]["HTTPStatusCode"], err["Error"]["Code"]) == (409, "DeleteConflictException")+ return err["Error"]["Message"]++ assert refusal() == (+ f"The policy cannot be deleted as multiple versions of the policy exist (name={name}). "+ "Use DeletePolicyVersion action to delete all non-default versions of the policy and retry.")+ iot_client.delete_policy_version(policyName=name, policyVersionId="2")+ assert refusal() == (+ f"The policy cannot be deleted as the policy is attached to one or more principals (name={name})")++ iot_client.detach_policy(policyName=name, target=cert["certificateArn"])+ iot_client.delete_policy(policyName=name)+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.get_policy(policyName=name)+ iot_client.delete_certificate(certificateId=cert["certificateId"])++# ---------------------------------------------------------------------------# Certificates: register-no-CA + legacy principal-policy family# ---------------------------------------------------------------------------