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): unsubscribe only the topic filters the packet names (#1379)
iot-rocketd11bae300baa
diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex f10e5264..602997f0 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -3002,9 +3002,39 @@ class _WSSession:if pkt_type == PKT_UNSUBSCRIBE:packet_id = struct.unpack_from("!H", body, 0)[0]- for sid in list(self._sub_ids):- await broker_unsubscribe(sid)- self._sub_ids.clear()+ off = 2+ filters = []+ while off < len(body):+ try:+ topic_filter, off = _read_string(body, off)+ except ValueError:+ _broker_logger.warning(+ "IoT broker: UNSUBSCRIBE payload truncated after %d "+ "topic filter(s), dropping the remainder",+ len(filters),+ )+ break+ filters.append(topic_filter)++ # MQTT 3.1.1 §3.10.4: each filter is compared character-by-character+ # with the session's subscriptions, and one that matches none of them+ # is simply skipped — a wildcard filter goes only by its own text, not+ # by the topics it happened to match. `_sub_filters` keeps the filter+ # as it arrived on the wire, so the comparison happens before topic+ # prefixing, in the same form SUBSCRIBE stored it.+ for topic_filter in filters:+ removed = [+ sid+ for sid, stored in self._sub_filters.items()+ if stored == topic_filter+ ]+ for sid in removed:+ await broker_unsubscribe(sid)+ self._sub_filters.pop(sid, None)+ self._sub_granted_qos.pop(sid, None)+ self._sub_ids[:] = [+ sid for sid in self._sub_ids if sid not in removed+ ]await self.send_bytes(_make_unsuback(packet_id))return Truediff --git a/tests/test_iot.py b/tests/test_iot.pyindex f1ff11b1..e52a2c89 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -1112,6 +1112,8 @@ from ministack.services.iot import (PKT_PUBACK,PKT_PUBLISH,PKT_SUBSCRIBE,+ PKT_UNSUBACK,+ PKT_UNSUBSCRIBE,_encode_remaining_length,_encode_string,_InFlightMessage,@@ -1616,6 +1618,14 @@ def _build_subscribe_body(packet_id, topics_qos):return body+def _build_unsubscribe_body(packet_id, topic_filters):+ """Build an UNSUBSCRIBE packet body. topic_filters is a list of filters."""+ body = struct.pack("!H", packet_id)+ for topic_filter in topic_filters:+ body += _encode_string(topic_filter)+ return body++def _mock_send():"""Return (async send-callable, captured-message list)."""sent = []@@ -1626,6 +1636,16 @@ def _mock_send():return send, sent+def _unsuback_packet_ids(sent_messages):+ """Return the packet ID of every UNSUBACK in sent messages."""+ ids = []+ for msg in sent_messages:+ data = msg.get("bytes")+ if data and len(data) >= 4 and (data[0] >> 4) & 0x0F == PKT_UNSUBACK:+ ids.append(struct.unpack_from("!H", data, 2)[0])+ return ids++def _parse_connack(sent_messages):"""Extract (sessionPresent, return_code) from a CONNACK in sent messages."""for msg in sent_messages:@@ -2419,6 +2439,158 @@ def test_subscribe_stores_granted_qos_on_session():reset()+# ----------------------------------------------------------------------+# Broker — UNSUBSCRIBE+# ----------------------------------------------------------------------+++async def _connect_and_subscribe(client_id, topics, clean_session=True):+ """CONNECT a session and SUBSCRIBE it at QoS 0 to every topic filter."""+ send, sent = _mock_send()+ session = _WSSession(send, "123456789012")+ await session.handle_packet(+ PKT_CONNECT, 0, _build_connect_body(client_id, clean_session=clean_session)+ )+ await session.handle_packet(+ PKT_SUBSCRIBE, 0x02, _build_subscribe_body(1, [(t, 0) for t in topics])+ )+ sent.clear()+ return session, sent+++def test_unsubscribe_removes_only_the_named_filters():+ """The filters named in the packet go; every other subscription stays."""+ reset()++ async def _run():+ session, sent = await _connect_and_subscribe(+ "unsub-one", ["sensor/a", "sensor/b", "sensor/c"]+ )++ await session.handle_packet(+ PKT_UNSUBSCRIBE, 0x02, _build_unsubscribe_body(7, ["sensor/b"])+ )+ assert _unsuback_packet_ids(sent) == [7]++ sent.clear()+ for topic in ("sensor/a", "sensor/b", "sensor/c"):+ await publish("123456789012", topic, topic.encode())++ delivered = [topic for topic, _payload, _qos, _pid, _dup in _extract_publish_frames(sent)]+ assert delivered == ["sensor/a", "sensor/c"]++ await session.cleanup()++ asyncio.run(_run())+ reset()+++def test_unsubscribe_of_filter_never_subscribed_is_a_no_op():+ """An unmatched filter changes nothing and is still acknowledged."""+ reset()++ async def _run():+ session, sent = await _connect_and_subscribe("unsub-unknown", ["sensor/a"])++ await session.handle_packet(+ PKT_UNSUBSCRIBE, 0x02, _build_unsubscribe_body(11, ["sensor/never"])+ )+ # MQTT 3.1.1 UNSUBACK carries no reason codes, so the acknowledgement+ # looks the same whether or not a subscription existed.+ assert _unsuback_packet_ids(sent) == [11]++ sent.clear()+ await publish("123456789012", "sensor/a", b"still-here")++ assert _extract_publish_frames(sent) == [("sensor/a", b"still-here", 0, None, False)]++ await session.cleanup()++ asyncio.run(_run())+ reset()+++def test_unsubscribe_of_every_filter_stops_delivery():+ """Naming all the session's filters leaves it with no subscriptions."""+ reset()++ async def _run():+ session, sent = await _connect_and_subscribe(+ "unsub-all", ["sensor/a", "sensor/b"]+ )++ await session.handle_packet(+ PKT_UNSUBSCRIBE, 0x02, _build_unsubscribe_body(3, ["sensor/a", "sensor/b"])+ )+ assert _unsuback_packet_ids(sent) == [3]+ assert session._sub_ids == []+ assert session._sub_filters == {}+ assert session._sub_granted_qos == {}++ sent.clear()+ await publish("123456789012", "sensor/a", b"gone")+ await publish("123456789012", "sensor/b", b"gone")++ assert _extract_publish_frames(sent) == []++ await session.cleanup()++ asyncio.run(_run())+ reset()+++def test_unsubscribe_matches_a_wildcard_filter_by_its_own_text():+ """A wildcard subscription goes by its filter string, not what it matched."""+ reset()++ async def _run():+ session, sent = await _connect_and_subscribe("unsub-wildcard", ["sensor/#"])++ # `sensor/temp` is a topic the wildcard delivers, not a filter the+ # session holds — it must leave the subscription untouched.+ await session.handle_packet(+ PKT_UNSUBSCRIBE, 0x02, _build_unsubscribe_body(1, ["sensor/temp"])+ )+ sent.clear()+ await publish("123456789012", "sensor/temp", b"matched")+ assert len(_extract_publish_frames(sent)) == 1++ await session.handle_packet(+ PKT_UNSUBSCRIBE, 0x02, _build_unsubscribe_body(2, ["sensor/#"])+ )+ sent.clear()+ await publish("123456789012", "sensor/temp", b"unmatched")+ assert _extract_publish_frames(sent) == []++ await session.cleanup()++ asyncio.run(_run())+ reset()+++def test_unsubscribe_drops_the_filter_from_a_preserved_session():+ """An unsubscribed filter must not come back with a cleanSession=0 resume."""+ reset()++ async def _run():+ client_id = "unsub-persistent"+ session, _sent = await _connect_and_subscribe(+ client_id, ["sensor/a", "sensor/b"], clean_session=False+ )++ await session.handle_packet(+ PKT_UNSUBSCRIBE, 0x02, _build_unsubscribe_body(1, ["sensor/a"])+ )+ await session.handle_packet(PKT_DISCONNECT, 0, b"")+ await session.cleanup()++ preserved = _persistent_sessions[("123456789012", _TEST_REGION, client_id)]+ assert preserved.subscriptions == ["sensor/b"]++ asyncio.run(_run())+ reset()++# ---------------------------------------------------------------------------# Task 18.2: QoS 1 delivery with packet ID tracking# ---------------------------------------------------------------------------diff --git a/tests/test_iot_data.py b/tests/test_iot_data.pyindex 63285209..2c2b7c20 100644--- a/tests/test_iot_data.py+++ b/tests/test_iot_data.py@@ -182,22 +182,29 @@ def _parse_packet(buf: bytes) -> tuple[int, int, bytes, int] | None:return (first >> 4) & 0x0F, first & 0x0F, buf[header_end:total], total+def _make_unsubscribe(packet_id: int, topics: list[str]) -> bytes:+ body = struct.pack("!H", packet_id) + b"".join(_enc_str(t) for t in topics)+ return bytes([0xA2]) + _enc_remaining(len(body)) + body+++def _record_publish(msg, received: list) -> int | None:+ """Append any PUBLISH frame in ``msg`` to ``received``; return its packet type."""+ buf = msg if isinstance(msg, (bytes, bytearray)) else msg.encode("latin-1")+ parsed = _parse_packet(bytes(buf))+ if not parsed:+ return None+ ptype, _flags, body, _ = parsed+ if ptype == 3: # PUBLISH+ topic_len = struct.unpack_from("!H", body, 0)[0]+ delivered_topic = body[2:2 + topic_len].decode("utf-8")+ payload = body[2 + topic_len:]+ received.append((delivered_topic, payload))+ return ptype++async def _ws_subscribe_and_collect(ws_url: str, topic: str, ready_event: threading.Event, received: list, stop: threading.Event):- def _record_publish(msg) -> int | None:- buf = msg if isinstance(msg, (bytes, bytearray)) else msg.encode("latin-1")- parsed = _parse_packet(bytes(buf))- if not parsed:- return None- ptype, _flags, body, _ = parsed- if ptype == 3: # PUBLISH- topic_len = struct.unpack_from("!H", body, 0)[0]- delivered_topic = body[2:2 + topic_len].decode("utf-8")- payload = body[2 + topic_len:]- received.append((delivered_topic, payload))- return ptype-async with websockets.connect(ws_url, subprotocols=["mqtt"]) as ws:await ws.send(_make_connect("test-client"))# Wait for CONNACK@@ -207,7 +214,7 @@ async def _ws_subscribe_and_collect(# Retained PUBLISH frames may precede SUBACK in the in-process broker.while True:msg = await asyncio.wait_for(ws.recv(), timeout=2.0)- if _record_publish(msg) == 9: # SUBACK+ if _record_publish(msg, received) == 9: # SUBACKbreakready_event.set()@@ -218,7 +225,78 @@ async def _ws_subscribe_and_collect(msg = await asyncio.wait_for(ws.recv(), timeout=0.5)except asyncio.TimeoutError:continue- _record_publish(msg)+ _record_publish(msg, received)+++async def _ws_unsubscribe_one_and_collect(+ ws_url: str,+ topics: list[str],+ drop: str,+ ready_event: threading.Event,+ received: list,+ stop: threading.Event,+):+ """Subscribe to every topic in ``topics``, then UNSUBSCRIBE from ``drop``."""+ async with websockets.connect(ws_url, subprotocols=["mqtt"]) as ws:+ await ws.send(_make_connect("unsub-client"))+ await asyncio.wait_for(ws.recv(), timeout=2.0)+ for packet_id, topic in enumerate(topics, start=1):+ await ws.send(_make_subscribe(packet_id=packet_id, topic=topic, qos=0))+ while True:+ msg = await asyncio.wait_for(ws.recv(), timeout=2.0)+ if _record_publish(msg, received) == 9: # SUBACK+ break++ await ws.send(_make_unsubscribe(packet_id=len(topics) + 1, topics=[drop]))+ while True:+ msg = await asyncio.wait_for(ws.recv(), timeout=2.0)+ if _record_publish(msg, received) == 11: # UNSUBACK+ break+ ready_event.set()++ end_at = time.time() + 5+ while not stop.is_set() and time.time() < end_at:+ try:+ msg = await asyncio.wait_for(ws.recv(), timeout=0.5)+ except asyncio.TimeoutError:+ continue+ _record_publish(msg, received)+++def test_iot_ws_unsubscribe_keeps_the_other_subscriptions(iot_data_client):+ """UNSUBSCRIBE over the real WebSocket bridge drops only the named filter."""+ kept = _unique("unsub/kept")+ dropped = _unique("unsub/dropped")+ parsed = urlparse(ENDPOINT)+ ws_host = parsed.hostname or "localhost"+ ws_port = parsed.port or 4566+ ws_url = f"ws://prefix-ats.iot.us-east-1.{ws_host}:{ws_port}/mqtt"++ ready = threading.Event()+ stop = threading.Event()+ received: list = []++ t = threading.Thread(+ target=lambda: asyncio.run(_ws_unsubscribe_one_and_collect(+ ws_url, [kept, dropped], dropped, ready, received, stop+ )),+ daemon=True,+ )+ t.start()+ assert ready.wait(timeout=5), "WebSocket subscriber did not become ready"++ iot_data_client.publish(topic=dropped, payload=b"should-not-arrive")+ iot_data_client.publish(topic=kept, payload=b"should-arrive")++ deadline = time.time() + 5+ while time.time() < deadline and not received:+ time.sleep(0.05)+ # Give a message on the unsubscribed topic every chance to show up late.+ time.sleep(0.6)+ stop.set()+ t.join(timeout=2)++ assert received == [(kept, b"should-arrive")]def test_iot_lambda_publishes_browser_subscribes_e2e(iot_data_client):