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): deliver a client's own messages despite MQTT 5 No Local (#2406)
iot-rocket09950db8c658
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 66f50dcc..4b1fd5ce 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **IoT — MQTT 5 No Local follows AWS IoT** — a subscription with No Local kept the client's own messages from it; AWS IoT Core ignores that option and delivers them, and so does the broker now. Contributed by @iot-rocket.- **CloudFront — a viewer-request function that leaves the query string alone no longer re-encodes it** — any function that returned the request it was given counted as a query-string rewrite, so the origin got the query rebuilt from the parsed parameters instead of as the viewer sent it: a bare key gained an `=` (`?flag` became `?flag=`). The query string is now rebuilt only when the function's returned `querystring` differs from the one in its event. Contributed by @jeffreyheller.- **API Gateway — an HTTP API's responses carry `apigw-requestid`, not a REST API's request ids** — a response from an HTTP API's route got `x-amzn-requestid` and `x-amz-request-id`; an HTTP API names its request id `apigw-requestid`, 16 base64 characters, which it now sends instead. REST APIs keep `x-amzn-requestid`. Contributed by @jeffreyheller.- **Lambda — publishing on create or code update leaves `$LATEST` unpublished** — `CreateFunction` and `UpdateFunctionCode` with `Publish: true` overwrote `$LATEST`'s `Version` with the new version number. `ListVersionsByFunction` then listed that number twice and no `$LATEST`, `GetFunctionConfiguration` without a qualifier reported it, and invoking `$LATEST` set `AWS_LAMBDA_FUNCTION_VERSION` to it. `$LATEST` now stays `$LATEST`, as on AWS; the create and update responses are unchanged.diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex a76fb8eb..1366397c 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -8797,9 +8797,9 @@ def delete_thing_shadow(thing_name: str, shadow_name: str) -> tuple:## MQTT 5 support is deliberately partial: enough that a real SDK connects,# subscribes, publishes, receives and disconnects cleanly. Implemented are-# property blocks on every packet that carries one, all four fields of the-# subscription-options byte (QoS, No Local, Retain As Published, Retain-# Handling), v5 reason codes on CONNACK/SUBACK/PUBACK/UNSUBACK/DISCONNECT, an+# property blocks on every packet that carries one, the subscription-options+# byte (QoS, Retain As Published, Retain Handling; No Local is ignored, as+# AWS IoT does), v5 reason codes on CONNACK/SUBACK/PUBACK/UNSUBACK/DISCONNECT, an# assigned client identifier, message expiry, and pass-through of the# PUBLISH properties a subscriber may echo back. Out of scope, and advertised# as unavailable in CONNACK where the protocol has a flag for it: shared@@ -8930,7 +8930,6 @@ class _Subscription:"deliver","granted_qos","client_id",- "no_local","retain_as_published",)@@ -8942,7 +8941,6 @@ class _Subscription:deliver: Callable[[str, bytes, int], Awaitable[None]],granted_qos: int = 0,client_id: str | None = None,- no_local: bool = False,retain_as_published: bool = False,):self.subscription_id = uuid.uuid4().hex@@ -8951,14 +8949,11 @@ class _Subscription:self.region = regionself.deliver = deliverself.granted_qos = granted_qos- # Owning MQTT client, when there is one. iot_data's HTTP publishes and- # in-process subscribers have no client identity, which is what No- # Local compares against — a subscriber with no identity can never be- # the publisher.+ # Owning MQTT client, when there is one; in-process subscribers have+ # no client identity.self.client_id = client_id# MQTT 5 subscription options (§3.8.3.1). Retain Handling is consumed# at subscribe time and so is not kept here.- self.no_local = no_localself.retain_as_published = retain_as_publisheddef __hash__(self) -> int:@@ -10090,11 +10085,10 @@ async def broker_publish(``properties`` is an encoded MQTT 5 property block forwarded verbatim tov5 subscribers (empty for a 3.1.1 publisher or an HTTP publish).- ``client_id`` names the publishing MQTT client, which is what a No Local- subscription is defined against (§3.8.3.1): that subscriber does not want- its own messages back. A publish with no client identity — iot_data's HTTP- Publish, a rule, an in-process caller — matches no subscriber's identity- and so is delivered to all of them.+ ``client_id`` names the publishing MQTT client, what the rule SQL+ ``clientid()`` returns. Every matching subscriber gets the message, the+ publisher included, also when its subscription asked for No Local: AWS+ IoT ignores that option.``principal`` is who published the message, what the rule SQL``principal()`` returns; rules also see a fresh trace id per message.@@ -10134,8 +10128,6 @@ async def broker_publish(for sub in subs:if sub.account_id != account_id or sub.region != region:continue- if sub.no_local and client_id is not None and sub.client_id == client_id:- continueif _subscription_matches(_unscope_topic(sub.account_id, sub.region, sub.filter_prefixed), topic):@@ -10218,24 +10210,22 @@ async def broker_subscribe(callback: Callable[[str, bytes, int], Awaitable[None]],granted_qos: int = 0,client_id: str | None = None,- no_local: bool = False,retain_as_published: bool = False,retain_handling: int = RETAIN_HANDLING_SEND_ALWAYS,) -> str:"""Register a subscriber and hand it any matching retained message.- The last four arguments are the MQTT 5 subscription options (§3.8.3.1);+ The last two arguments are MQTT 5 subscription options (§3.8.3.1);their defaults are what an MQTT 3.1.1 SUBSCRIBE means, so an existingcaller keeps its behaviour. ``retain_handling`` is acted on here andnowhere else — it only decides whether this call replays retained- messages — while No Local and Retain As Published are stored on the- subscription because they apply to every later delivery.+ messages — while Retain As Published is stored on the subscription+ because it applies to every later delivery."""filter_prefixed = _scoped_topic(account_id, region, topic_filter)sub = _Subscription(filter_prefixed, account_id, region, callback, granted_qos,- client_id=client_id, no_local=no_local,- retain_as_published=retain_as_published,+ client_id=client_id, retain_as_published=retain_as_published,)async with _broker_lock:existing_subscribers = _subscriptions.setdefault(filter_prefixed, set())@@ -10459,9 +10449,9 @@ RC5_TOPIC_NAME_INVALID = 0x90# Layout of the MQTT 5 SUBSCRIBE options byte (§3.8.3.1). MQTT 3.1.1 sends a# bare QoS byte with the upper bits reserved zero, so the same masks read both-# and a 3.1.1 subscription comes out with every option off.+# and a 3.1.1 subscription comes out with every option off. Bit 2, No Local,+# is not read: AWS IoT delivers a client's own messages to it regardless.SUB_OPT_QOS_MASK = 0x03-SUB_OPT_NO_LOCAL = 0x04SUB_OPT_RETAIN_AS_PUBLISHED = 0x08SUB_OPT_RETAIN_HANDLING_SHIFT = 4SUB_OPT_RETAIN_HANDLING_MASK = 0x03@@ -11551,7 +11541,6 @@ class _WSSession:self.deliver_to_client,granted_qos,client_id=self._client_id or None,- no_local=bool(subscription_options & SUB_OPT_NO_LOCAL),retain_as_published=bool(subscription_options & SUB_OPT_RETAIN_AS_PUBLISHED),diff --git a/tests/conftest.py b/tests/conftest.pyindex 9f26bcce..b4041bd4 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -442,7 +442,7 @@ _SERIAL_TESTS = {"tests/test_iot_data.py::test_mqtt5_property_block_truncated_at_the_packet_end_is_refused","tests/test_iot_data.py::test_mqtt5_malformed_connect_is_refused_with_a_connack_reason_code","tests/test_iot_data.py::test_mqtt5_property_block_longer_than_127_bytes_round_trips",- "tests/test_iot_data.py::test_mqtt5_no_local_withholds_a_publisher_its_own_message",+ "tests/test_iot_data.py::test_mqtt5_no_local_still_delivers_a_publisher_its_own_message","tests/test_iot_data.py::test_mqtt5_retain_as_published_keeps_the_publishers_retain_flag","tests/test_iot_data.py::test_mqtt5_retain_handling_2_suppresses_the_retained_replay","tests/test_iot_data.py::test_mqtt5_retain_handling_1_replays_only_for_a_new_subscription",diff --git a/tests/test_iot_data.py b/tests/test_iot_data.pyindex 3097f863..830d2b1c 100644--- a/tests/test_iot_data.py+++ b/tests/test_iot_data.py@@ -3676,8 +3676,8 @@ def test_mqtt5_property_block_longer_than_127_bytes_round_trips():assert [p for p in props if p[0] == PROP_USER_PROPERTY] == user_properties-def test_mqtt5_no_local_withholds_a_publisher_its_own_message():- """No Local is defined against the publishing client, not the connection."""+def test_mqtt5_no_local_still_delivers_a_publisher_its_own_message():+ """AWS IoT ignores No Local: the subscriber gets its own message and everyone else's."""topic = _unique("options/nolocal")async def scenario():@@ -3692,19 +3692,21 @@ def test_mqtt5_no_local_withholds_a_publisher_its_own_message():_make_publish(topic, b"mine", qos=1, packet_id=7,protocol_level=MQTT_5))- # The next packet, not the next PUBACK: a self-delivery would- # arrive ahead of the acknowledgement and be skipped past.- own_reply = await subscriber.packet(timeout=5.0)+ # The own message and the PUBACK, in either order.+ own = sorted([await subscriber.packet(timeout=5.0), await subscriber.packet(timeout=5.0)])async with _connect(MQTT_5) as (other, _c2):await other.send(_make_publish(topic, b"theirs", protocol_level=MQTT_5))_flags, delivered = await subscriber.await_packet(PKT_PUBLISH)- return own_reply, delivered+ return own, delivered- (pkt_type, _flags, puback), delivered = _run(scenario())- assert pkt_type == PKT_PUBACK, "the publisher's own message must not come back"+ ((pub_type, pub_flags, mine), (ack_type, _ack_flags, puback)), delivered = _run(scenario())+ assert (pub_type, ack_type) == (PKT_PUBLISH, PKT_PUBACK)+ # Delivered at the subscription's QoS 0.+ assert pub_flags & 0x06 == 0+ assert _parse_publish(mine, MQTT_5)[:2] == (topic, b"mine")assert puback == b"\x00\x07\x00\x00", "packet id 7, Success, no properties"assert _parse_publish(delivered, MQTT_5)[1] == b"theirs"