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): answer deletes of unknown IoT resources with 200 and check use in CloudFormation deletes (#2189)
iot-rocket83508c687a85
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bac084c2..c31fac5b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **IoT — deletes of unknown resources and `DeleteThing` `expectedVersion`** — `DeleteThing`, `DeleteThingType`, `DeleteThingGroup`, `RemoveThingFromThingGroup` with an unknown group and `DetachPolicy` with an unknown policy answered `ResourceNotFoundException`, and `DeleteThing` ignored `expectedVersion`; they now answer 200 as AWS does, and `DeleteThing` refuses a wrong `expectedVersion` with `VersionConflictException` before the attached-principal check. Contributed by @iot-rocket.+- **CloudFormation — IoT policy and thing type deletes check what still uses them** — a stack delete removed an `AWS::IoT::Policy` or `AWS::IoT::ThingType` directly, even while a certificate outside the stack had the policy attached or a thing used the type; the policy delete now removes the non-default versions and then calls `DeletePolicy`, the thing type delete deprecates the type and then calls `DeleteThingType`, so a resource still in use fails its delete with the service's message and the stack ends in `DELETE_FAILED`, as on AWS. Contributed by @iot-rocket.- **IoT — MQTT 5 message expiry** — the broker forwarded the Message Expiry Interval unchanged and never expired a message; a subscriber now receives the seconds left (60 arrives as 59, 0 counts as 1, intervals above seven days are capped at 604800), an expired retained message is no longer replayed to new subscribers or returned by `GetRetainedMessage` and `ListRetainedMessages`, and a QoS 1 message queued for an offline persistent session is dropped once it expires (the queue also keeps the MQTT 5 properties now). Contributed by @iot-rocket.- **IoT — HTTP `Publish` keeps the MQTT 5 properties and a literal `%` in the topic** — `Publish` ignored `userProperties`, `payloadFormatIndicator`, `contentType`, `responseTopic`, `correlationData` and `messageExpiry`, so MQTT 5 subscribers got none of them and `GetRetainedMessage` returned no `userProperties`; they now reach subscribers and the retained message, and invalid values are refused with AWS's `InvalidRequestException` messages. `Publish`, `GetRetainedMessage` and the `AUTH=true` topic ARN decoded the topic a second time, so `p%41q` became `pAq`; the topic is now kept as sent. `/_ministack/reset` kept messages retained over MQTT when no iot-data call had loaded that module; it now clears them. Contributed by @iot-rocket.- **IoT Core — MQTT 5 PUBACK reports Success without subscribers** — a QoS 1 PUBLISH that no subscriber matched (including a topic only a rule reads, Basic Ingest and a retained publish) was acknowledged with reason code `0x10` No matching subscribers; it now gets `0x00` Success, as AWS IoT answers over both MQTT over TLS and MQTT over WebSocket. Contributed by @iot-rocket.diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 2f1b4f34..61fbaa6f 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -13432,11 +13432,24 @@ def _iot_thing_type_import(identifier):return identifier["ThingTypeName"], _iot_thing_type_attrs(identifier["ThingTypeName"])-def _iot_thing_type_delete(physical_id, props):+def _iot_thing_type_remove(physical_id, props):+ """Drop the record without the delete checks, for a replacement that reuses the generated name."""_iot._thing_types.pop(physical_id, None)_iot._tags.pop(_iot._thing_type_arn(physical_id), None)+def _iot_thing_type_delete(physical_id, props):+ """Deprecate the thing type, then delete it; a type a thing still uses fails the delete and stays deprecated."""+ record = _iot._thing_types.get(physical_id)+ if record is None:+ return+ if not record["thingTypeMetadata"].get("deprecated"):+ _iot._deprecate_thing_type(physical_id, {"undoDeprecate": False})+ resp = _iot._delete_thing_type(physical_id)+ if resp[0] >= 400:+ raise ValueError(json.loads(resp[2])["message"])++def _iot_thing_type_update(physical_id, old_props, new_props, stack_name,logical_id=None):"""Update a thing type in place, keeping its id, its ARN and its creation@@ -13463,7 +13476,7 @@ def _iot_thing_type_update(physical_id, old_props, new_props, stack_name,if replaced is not None:return replacedif _requires_replacement("AWS::IoT::ThingType", old_props, new_props):- _iot_thing_type_delete(physical_id, old_props)+ _iot_thing_type_remove(physical_id, old_props)return _iot_thing_type_create(logical_id or physical_id, new_props, stack_name)stored = record.setdefault("thingTypeProperties", {})@@ -13619,8 +13632,16 @@ def _iot_policy_import(identifier):def _iot_policy_delete(physical_id, props):- _iot._policies.pop(physical_id, None)- _iot._tags.pop(_iot._policy_arn(physical_id), None)+ """Delete the non-default versions, then the policy; a policy still attached fails the delete."""+ policy = _iot._policies.get(physical_id)+ if policy is None:+ return+ for version_id, version in list(policy["versions"].items()):+ if not version["isDefaultVersion"]:+ _iot._delete_policy_version(physical_id, version_id)+ resp = _iot._delete_policy(physical_id)+ if resp[0] >= 400:+ raise ValueError(json.loads(resp[2])["message"])def _iot_provisioning_template_body(props):diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex 3e044c5a..6974290f 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -1313,7 +1313,7 @@ def _handle_thing(method: str, path: str, body: bytes, qp: dict) -> tuple:if method == "PATCH":return _update_thing(name, _parse_body(body))if method == "DELETE":- return _delete_thing(name)+ return _delete_thing(name, qp.get("expectedVersion"))return error_response_json("InvalidRequestException", f"Unsupported method: {method}", 400)@@ -1439,10 +1439,17 @@ def _update_thing(name: str, payload: dict) -> tuple:return json_response({})-def _delete_thing(name: str) -> tuple:+def _delete_thing(name: str, expected_version=None) -> tuple:+ """DeleteThing; an unknown name answers 200 like a completed delete."""thing = _things.get(name)if thing is None:- return _error_not_found("Thing", name)+ return json_response({})+ if expected_version not in (None, "") and str(expected_version) != str(thing.get("version", 1)):+ return error_response_json(+ "VersionConflictException",+ f"The version for thing {name} does not match the expected version.",+ 409,+ )if any(p.rsplit("/", 1)[-1] in _certificates for p in thing.get("principals", [])):return error_response_json("InvalidRequestException",@@ -1602,7 +1609,7 @@ def _deprecate_thing_type(name: str, payload: dict) -> tuple:def _delete_thing_type(name: str) -> tuple:t = _thing_types.get(name)if t is None:- return _error_not_found("ThingType", name)+ return json_response({})if not t["thingTypeMetadata"].get("deprecated"):return error_response_json("InvalidRequestException",@@ -1815,7 +1822,7 @@ def _update_thing_group(name: str, payload: dict) -> tuple:def _delete_thing_group(name: str) -> tuple:g = _thing_groups.get(name)if g is None:- return _error_not_found("ThingGroup", name)+ return json_response({})if any((c.get("thingGroupMetadata") or {}).get("parentGroupName") == name for c in _thing_groups.values()):return error_response_json("InvalidRequestException",@@ -1873,10 +1880,11 @@ async def _remove_thing_from_group(payload: dict) -> tuple:tname = payload.get("thingName")group = _thing_groups.get(gname) if gname else Nonething = _things.get(tname) if tname else None- if group is None:- return _error_not_found("ThingGroup", gname or "")if thing is None:return _error_not_found("Thing", tname or "")+ if group is None:+ # Only a named group that does not exist answers 200; a group ARN is not resolved.+ return json_response({}) if gname else _error_not_found("ThingGroup", "")prev_next = jobs_first_pending_job_id(tname)left = tname in group.get("things", [])if left:@@ -3739,6 +3747,9 @@ def _handle_target_policy(method: str, path: str, body: bytes, qp: dict) -> tuplreturn error_response_json("InvalidRequestException", f"Unsupported method: {method}", 400)+ # DetachPolicy of an unknown policy succeeds; DetachPrincipalPolicy refuses it.+ if method != "PUT" and name not in _policies:+ return json_response({})return _change_policy_target(name, _parse_body(body).get("target"), attach=method == "PUT")diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex f38458fa..4d80e47d 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -1357,6 +1357,53 @@ def test_cfn_iot_policy_rename_replaces_the_policy(cfn, iot_client):_wait_stack(cfn, "cfn-iot-pol-ren")+def test_cfn_iot_policy_delete_removes_versions_and_keeps_an_attached_policy(cfn, iot_client):+ """A stack delete removes non-default policy versions; a policy still attached fails its delete until detached."""+ pytest.importorskip("cryptography")+ uid = _uuid_mod.uuid4().hex[:8]+ stack, attached, free = f"cfn-iot-pol-del-{uid}", f"cfn-pol-att-{uid}", f"cfn-pol-free-{uid}"++ def template(action):+ doc = {"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": action, "Resource": "*"}]}+ return json.dumps({"Resources": {+ "Attached": {"Type": "AWS::IoT::Policy", "Properties": {"PolicyName": attached, "PolicyDocument": doc}},+ "Free": {"Type": "AWS::IoT::Policy", "Properties": {"PolicyName": free, "PolicyDocument": doc}},+ }})++ cert = iot_client.create_keys_and_certificate(setAsActive=False)+ outside_doc = json.dumps({"Version": "2012-10-17", "Statement": [+ {"Effect": "Deny", "Action": "iot:Connect", "Resource": "*"}]})+ cfn.create_stack(StackName=stack, TemplateBody=template("iot:Connect"))+ try:+ assert _wait_stack(cfn, stack)["StackStatus"] == "CREATE_COMPLETE"+ cfn.update_stack(StackName=stack, TemplateBody=template("iot:Publish"))+ assert _wait_stack(cfn, stack)["StackStatus"] == "UPDATE_COMPLETE"+ for name in (attached, free):+ iot_client.create_policy_version(policyName=name, policyDocument=outside_doc, setAsDefault=False)+ assert len(iot_client.list_policy_versions(policyName=name)["policyVersions"]) == 3+ iot_client.attach_policy(policyName=attached, target=cert["certificateArn"])++ cfn.delete_stack(StackName=stack)+ assert _wait_stack(cfn, stack)["StackStatus"] == "DELETE_FAILED"+ assert _cfn_iot_failure(cfn, stack, "Attached", "DELETE_FAILED") == (+ "The policy cannot be deleted as the policy is attached to one or more principals "+ f"(name={attached})")+ versions = iot_client.list_policy_versions(policyName=attached)["policyVersions"]+ assert [(v["versionId"], v["isDefaultVersion"]) for v in versions] == [("2", True)]+ assert iot_client.list_targets_for_policy(policyName=attached)["targets"] == [cert["certificateArn"]]+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.get_policy(policyName=free)++ iot_client.detach_policy(policyName=attached, target=cert["certificateArn"])+ cfn.delete_stack(StackName=stack)+ assert _wait_stack(cfn, stack)["StackStatus"] == "DELETE_COMPLETE"+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.get_policy(policyName=attached)+ finally:+ iot_client.delete_certificate(certificateId=cert["certificateId"], forceDelete=True)+ _delete_cfn_test_stack(cfn, stack)++def _cfn_provisioning_template_body(marker="one"):# The IoT control plane refuses a body without an AWS::IoT::Certificate# resource, so every stack body carries one; `marker` varies the body so a@@ -8765,6 +8812,38 @@ def test_cfn_iot_thing_type_rename_replaces_it(cfn, iot_client):_delete_cfn_test_stack(cfn, stack_name)+def test_cfn_iot_thing_type_delete_deprecates_and_keeps_a_type_in_use(cfn, iot_client):+ """A stack delete deprecates then deletes a thing type; one a thing still uses fails and stays deprecated."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack, used, free, thing = (f"cfn-iot-tt-del-{uid}", f"cfn-tt-used-{uid}",+ f"cfn-tt-free-{uid}", f"cfn-tt-thing-{uid}")+ cfn.create_stack(StackName=stack, TemplateBody=json.dumps({"Resources": {+ "Used": {"Type": "AWS::IoT::ThingType", "Properties": {"ThingTypeName": used}},+ "Free": {"Type": "AWS::IoT::ThingType", "Properties": {"ThingTypeName": free}},+ }}))+ try:+ assert _wait_stack(cfn, stack)["StackStatus"] == "CREATE_COMPLETE"+ iot_client.create_thing(thingName=thing, thingTypeName=used)++ cfn.delete_stack(StackName=stack)+ assert _wait_stack(cfn, stack)["StackStatus"] == "DELETE_FAILED"+ assert _cfn_iot_failure(cfn, stack, "Used", "DELETE_FAILED") == (+ f"Can not delete thing type {used} with things associated with it")+ assert iot_client.describe_thing_type(thingTypeName=used)["thingTypeMetadata"]["deprecated"] is True+ assert iot_client.describe_thing(thingName=thing)["thingTypeName"] == used+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.describe_thing_type(thingTypeName=free)++ iot_client.update_thing(thingName=thing, removeThingType=True)+ cfn.delete_stack(StackName=stack)+ assert _wait_stack(cfn, stack)["StackStatus"] == "DELETE_COMPLETE"+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.describe_thing_type(thingTypeName=used)+ finally:+ iot_client.delete_thing(thingName=thing)+ _delete_cfn_test_stack(cfn, stack)++def test_cfn_apigateway_account_update_removes_a_dropped_role():"""CloudWatchRoleArn is No interruption. The create handler only everwrote a declared role, so a template that dropped the property left thediff --git a/tests/test_iot.py b/tests/test_iot.pyindex 642a5143..f0d4b6e1 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -702,6 +702,12 @@ def test_iot_delete_thing_type_refused_while_a_thing_uses_it(iot_client):iot_client.delete_thing(thingName=thing)++def test_iot_delete_thing_type_of_an_unknown_name_succeeds(iot_client):+ """DeleteThingType answers 200 for a name that does not exist."""+ resp = iot_client.delete_thing_type(thingTypeName=_unique("type"))+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200+# ---------------------------------------------------------------------------# ThingGroup CRUD + membership# ---------------------------------------------------------------------------@@ -826,6 +832,12 @@ def test_iot_delete_thing_group_with_child_groups_is_refused(iot_client):iot_client.delete_thing_group(thingGroupName=parent)+def test_iot_delete_thing_group_of_an_unknown_name_succeeds(iot_client):+ """DeleteThingGroup answers 200 for a name that does not exist."""+ resp = iot_client.delete_thing_group(thingGroupName=_unique("group"))+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200++def test_iot_thing_group_membership(iot_client):gname = _unique("group")tname = _unique("thing")@@ -844,6 +856,24 @@ def test_iot_thing_group_membership(iot_client):iot_client.delete_thing_group(thingGroupName=gname)+def test_iot_remove_thing_from_an_unknown_thing_group_succeeds(iot_client):+ """An unknown group name answers 200; an unknown thing, or no group name at all, is refused."""+ tname, gname = _unique("thing"), _unique("group")+ iot_client.create_thing(thingName=tname)+ resp = iot_client.remove_thing_from_thing_group(thingGroupName=_unique("group"), thingName=tname)+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.remove_thing_from_thing_group(thingGroupName=_unique("group"), thingName=_unique("thing"))+ group_arn = iot_client.create_thing_group(thingGroupName=gname)["thingGroupArn"]+ iot_client.add_thing_to_thing_group(thingGroupName=gname, thingName=tname)+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.remove_thing_from_thing_group(thingGroupArn=group_arn, thingName=tname)+ assert tname in iot_client.list_things_in_thing_group(thingGroupName=gname)["things"]+ iot_client.remove_thing_from_thing_group(thingGroupName=gname, thingName=tname)+ iot_client.delete_thing_group(thingGroupName=gname)+ iot_client.delete_thing(thingName=tname)++def test_iot_list_thing_groups_for_thing(iot_client):tname = _unique("thing")g1 = _unique("group")@@ -1390,6 +1420,39 @@ def test_iot_delete_thing_refused_while_a_principal_is_attached(iot_client):iot_client.delete_certificate(certificateId=cert_id)+def test_iot_delete_thing_of_an_unknown_name_succeeds(iot_client):+ """DeleteThing answers 200 for a name that does not exist, also with expectedVersion."""+ name = _unique("thing")+ for params in ({}, {"expectedVersion": 1}, {"expectedVersion": 7}):+ resp = iot_client.delete_thing(thingName=name, **params)+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.describe_thing(thingName=name)+++def test_iot_delete_thing_checks_expected_version(iot_client):+ """A wrong expectedVersion is refused before the attached-principal check; the current one deletes."""+ pytest.importorskip("cryptography")+ name = _unique("thing")+ iot_client.create_thing(thingName=name)+ cert = iot_client.create_keys_and_certificate(setAsActive=False)+ iot_client.attach_thing_principal(thingName=name, principal=cert["certificateArn"])+ with pytest.raises(ClientError) as ei:+ iot_client.delete_thing(thingName=name, expectedVersion=2)+ err = ei.value.response+ assert (err["ResponseMetadata"]["HTTPStatusCode"], err["Error"]["Code"], err["Error"]["Message"]) == (+ 409, "VersionConflictException", f"The version for thing {name} does not match the expected version.")+ with pytest.raises(ClientError) as ei:+ iot_client.delete_thing(thingName=name, expectedVersion=1)+ assert ei.value.response["Error"]["Code"] == "InvalidRequestException"++ iot_client.detach_thing_principal(thingName=name, principal=cert["certificateArn"])+ iot_client.delete_thing(thingName=name, expectedVersion=1)+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.describe_thing(thingName=name)+ iot_client.delete_certificate(certificateId=cert["certificateId"])++def test_iot_thing_arn_tail_parser_requires_iot_thing_scope():from ministack.core.responses import (get_account_id,@@ -1809,6 +1872,22 @@ def test_iot_legacy_principal_policy_unknown_policy_404(iot_client):policyName=_unique("nope"), principal="arn:aws:iot:cert/none")assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_iot_detach_policy_of_an_unknown_policy_succeeds(iot_client):+ """DetachPolicy succeeds for an unknown policy; AttachPolicy and DetachPrincipalPolicy refuse it."""+ pytest.importorskip("cryptography")+ name = _unique("policy")+ cert = iot_client.create_keys_and_certificate(setAsActive=False)+ arn = cert["certificateArn"]+ for target in (arn, arn.rsplit("/", 1)[0] + "/" + "ab" * 32):+ resp = iot_client.detach_policy(policyName=name, target=target)+ assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.detach_principal_policy(policyName=name, principal=arn)+ with pytest.raises(iot_client.exceptions.ResourceNotFoundException):+ iot_client.attach_policy(policyName=name, target=arn)+ iot_client.delete_certificate(certificateId=cert["certificateId"])# ---------------------------------------------------------------------------