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): honour the MQTT 5 message expiry interval (#2188)
iot-rocket8d3843c0c6d1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 171e7885..bac084c2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **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.- **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.- **CloudFormation — AppSync data sources and resolvers keep their configuration** — `AWS::AppSync::DataSource` dropped `Description`, `HttpConfig` and `EventBridgeConfig` and stored `DynamoDBConfig` and `LambdaConfig` in the template's PascalCase, and `AWS::AppSync::Resolver` dropped `Kind`, `Runtime`, `Code`, `PipelineConfig` and `MaxBatchSize`, so a DynamoDB resolver from a stack answered `null` and an `APPSYNC_JS` resolver never ran; both now go through `CreateDataSource` and `CreateResolver` and read back as on AWS, and a new data source `Name` or resolver `TypeName` or `FieldName` is reported as a replacement. `GetDataSource` and `GetResolver` leave out a description, service role or mapping template that was never set, a DynamoDB data source reports `useCallerCredentials` and `versioned`, an EventBridge one keeps `eventBridgeConfig`, and a resolver reports `maxBatchSize`. Contributed by @iot-rocket.diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex 550257b3..3e044c5a 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -218,7 +218,7 @@ _retained: dict[str, "_RetainedMessage"] = {}class _RetainedMessage:- __slots__ = ("payload", "properties", "qos", "topic", "ts")+ __slots__ = ("expires_at", "payload", "properties", "qos", "topic", "ts")def __init__(self, topic: str, payload: bytes, qos: int, properties: bytes = b"",ts: float | None = None):@@ -229,6 +229,11 @@ class _RetainedMessage:# a message published by a 3.1.1 client.self.properties = propertiesself.ts = time.time() if ts is None else ts+ self.expires_at = _message_expires_at(properties, self.ts)++ def expired(self, now: float) -> bool:+ """Whether the message's MQTT 5 expiry interval has run out."""+ return self.expires_at is not None and now >= self.expires_atdef _broker_get_state() -> dict:@@ -8388,10 +8393,10 @@ def delete_thing_shadow(thing_name: str, shadow_name: str) -> tuple:# 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-# assigned client identifier, 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 subscriptions, topic-# aliases, message expiry, flow control (receive maximum), subscription+# 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+# subscriptions, topic aliases, flow control (receive maximum), subscription# identifiers, and request/response semantics beyond forwarding the# properties untouched. Properties this broker does not model are parsed and# ignored, never echoed back.@@ -8443,7 +8448,8 @@ class _PersistentSessionState:session_identifier: str | None = None,):self.subscriptions: list[str] = subscriptions- self.queued_messages: list[tuple[str, bytes, int]] = []+ # (topic, payload, qos, PUBLISH properties, time the broker received it)+ self.queued_messages: list[tuple[str, bytes, int, bytes, float]] = []self.created_at: float = created_at# Seconds this session outlives its connection, as the client asked# for it in the MQTT 5 Session Expiry Interval. None means the client@@ -9663,17 +9669,18 @@ async def broker_publish(returnscoped = _scoped_topic(account_id, region, topic)+ received_at = time.time()if retain:if not payload:_retained.pop(scoped, None)else:- _retained[scoped] = _RetainedMessage(scoped, payload, qos, properties)+ _retained[scoped] = _RetainedMessage(scoped, payload, qos, properties, received_at)async with _broker_lock:subs = [s for sset in _subscriptions.values() for s in sset]- token = _delivery_properties.set(properties)+ token = _delivery_properties.set(_aged_properties(properties, received_at, received_at) or b"")try:for sub in subs:if sub.account_id != account_id or sub.region != region:@@ -9714,7 +9721,7 @@ async def broker_publish(continuefor filt in ps.subscriptions:if _subscription_matches(filt, topic):- ps.queued_messages.append((topic, payload, qos))+ ps.queued_messages.append((topic, payload, qos, properties, received_at))if len(ps.queued_messages) > _MAX_QUEUED_MESSAGES:ps.queued_messages = ps.queued_messages[-_MAX_QUEUED_MESSAGES:]break@@ -9806,7 +9813,10 @@ async def broker_subscribe(retained_to_send = []for r in retained_to_send:- token = _delivery_properties.set(r.properties)+ properties = _aged_properties(r.properties, r.ts)+ if properties is None:+ continue+ token = _delivery_properties.set(properties)# §3.3.1.3: a message sent because a subscription was established# carries RETAIN 1 whatever the subscription's Retain As Published# says — that flag is how the client tells this apart from live@@ -9836,13 +9846,21 @@ async def broker_unsubscribe(subscription_id: str) -> None:def broker_get_retained(account_id: str, region: str, topic: str) -> "_RetainedMessage | None":- """The retained message stored for ``topic``, or None."""- return _retained.get(_scoped_topic(account_id, region, topic))+ """The retained message stored for ``topic``, or None; an expired one is dropped here."""+ scoped = _scoped_topic(account_id, region, topic)+ msg = _retained.get(scoped)+ if msg is not None and msg.expired(time.time()):+ _retained.pop(scoped, None)+ return None+ return msgdef broker_list_retained(account_id: str, region: str) -> list[tuple[str, "_RetainedMessage"]]:"""``(topic, message)`` for every retained message here, most recently stored first."""prefix = f"{account_id}/{region}/"+ now = time.time()+ for key in [k for k, m in _retained.items() if k.startswith(prefix) and m.expired(now)]:+ del _retained[key]found = [(k[len(prefix):], m) for k, m in _retained.items() if k.startswith(prefix)]found.sort(key=lambda item: item[1].ts, reverse=True)return found@@ -10062,7 +10080,8 @@ _PROPERTY_TYPES: dict[int, str] = {PROP_SHARED_SUBSCRIPTION_AVAILABLE: "byte",}-# PUBLISH properties handed on to subscribers unchanged. §3.3.2.3 requires a+# PUBLISH properties handed on to subscribers unchanged, except the expiry+# interval, which loses the time the message waited. §3.3.2.3 requires a# server to forward these, and a request/response client depends on getting# its own response topic and correlation data back. Everything else a# publisher sends (topic alias, subscription identifier, anything this broker@@ -10076,6 +10095,9 @@ _FORWARDED_PUBLISH_PROPERTIES = frozenset({PROP_USER_PROPERTY,})+# AWS IoT Core counts a Message Expiry Interval of 0 as 1 and caps it at seven days.+_MESSAGE_EXPIRY_MAX = 604800+# MQTT 5 PUBLISH properties ride a contextvar rather than the subscriber# callback signature. ``deliver(topic, payload, qos)`` is the broker's# extension point — iot_data, persistent-session replay and tests all supply@@ -10289,6 +10311,40 @@ def _forwardable_publish_properties(props: list[tuple[int, object]]) -> bytes:return _encode_properties(kept)+def _expiry_interval(props: list[tuple[int, object]]) -> int | None:+ """The Message Expiry Interval among decoded PUBLISH properties, as AWS IoT Core bounds it."""+ interval = _property_value(props, PROP_MESSAGE_EXPIRY_INTERVAL, None)+ if interval is None:+ return None+ return min(max(int(interval), 1), _MESSAGE_EXPIRY_MAX) # type: ignore[arg-type]+++def _message_expires_at(properties: bytes, received_at: float) -> float | None:+ """When a message with this PUBLISH property block expires, or None if it never does."""+ if not properties:+ return None+ interval = _expiry_interval(_decode_properties(properties, 0)[0])+ return None if interval is None else received_at + interval+++def _aged_properties(properties: bytes, received_at: float, now: float | None = None) -> bytes | None:+ """``properties`` with the expiry interval lowered to the whole seconds left, None once expired."""+ if not properties:+ return properties+ props, _ = _decode_properties(properties, 0)+ interval = _expiry_interval(props)+ if interval is None:+ return properties+ left = received_at + interval - (time.time() if now is None else now)+ if left <= 0:+ return None+ # A started second counts as spent: 60 goes out as 59, and 999 ms left as 0.+ seconds = math.ceil(left) - 1+ return _encode_properties(+ [(i, seconds if i == PROP_MESSAGE_EXPIRY_INTERVAL else v) for i, v in props]+ )++def _make_connack(return_code: int = 0,session_present: bool = False,@@ -10871,8 +10927,15 @@ class _WSSession:)queued = existing_ps.queued_messages[:]existing_ps.queued_messages.clear()- for q_topic, q_payload, q_qos in queued:- await self.deliver_to_client(q_topic, q_payload, q_qos)+ for q_topic, q_payload, q_qos, q_properties, q_received_at in queued:+ properties = _aged_properties(q_properties, q_received_at)+ if properties is None:+ continue+ token = _delivery_properties.set(properties)+ try:+ await self.deliver_to_client(q_topic, q_payload, q_qos)+ finally:+ _delivery_properties.reset(token)await self._publish_connected()return Trueelse:diff --git a/ministack/services/iot_data.py b/ministack/services/iot_data.pyindex f5fc8a04..b842495c 100644--- a/ministack/services/iot_data.py+++ b/ministack/services/iot_data.py@@ -53,8 +53,6 @@ _HTTP_RESTRICTED_TOPIC_RE = re.compile(# Publish's x-amz-mqtt5-payload-format-indicator values and the byte each one stands for._PAYLOAD_FORMAT_INDICATORS = {"UNSPECIFIED_BYTES": 0, "UTF8_DATA": 1}-# The broker's message expiry limit (seven days); longer intervals are capped.-_MAX_MESSAGE_EXPIRY = 604800def _validate_topic(topic: str) -> tuple | None:@@ -279,7 +277,7 @@ def _publish_properties(headers: dict, qp: dict) -> tuple[bytes, tuple | None]:seconds = int(expiry) if expiry.isascii() and expiry.isdigit() else -1if not 0 <= seconds < 2**32:return invalid("Message expiry interval must be an unsigned 4-byte integer")- props.append((_iot_module.PROP_MESSAGE_EXPIRY_INTERVAL, min(seconds, _MAX_MESSAGE_EXPIRY)))+ props.append((_iot_module.PROP_MESSAGE_EXPIRY_INTERVAL, seconds))response_topic = qp.get("responseTopic")if response_topic:if "+" in response_topic or "#" in response_topic:diff --git a/tests/test_iot.py b/tests/test_iot.pyindex 7686aee8..642a5143 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -4620,7 +4620,7 @@ def test_iot_broker_persistent_sessions_are_region_isolated():west_state = _persistent_sessions[(account_id, "us-west-2", client_id)]- assert east_state.queued_messages == [+ assert [m[:3] for m in east_state.queued_messages] == [("events/one", b"east-only", 1)]assert west_state.queued_messages == []@@ -5417,7 +5417,7 @@ def test_queue_bounded_to_1000_messages():assert len(ps.queued_messages) == 1000# Verify oldest messages were dropped (first 50 should be gone)- first_topic, first_payload, first_qos = ps.queued_messages[0]+ first_topic, first_payload, first_qos = ps.queued_messages[0][:3]assert first_payload == b"msg50"asyncio.run(_run())diff --git a/tests/test_iot_data.py b/tests/test_iot_data.pyindex dbecd2cb..7133a1bf 100644--- a/tests/test_iot_data.py+++ b/tests/test_iot_data.py@@ -2453,6 +2453,9 @@ SUB_OPT_RETAIN_HANDLING_NEVER = 0x20PROP_PAYLOAD_FORMAT_INDICATOR = 0x01+PROP_MESSAGE_EXPIRY_INTERVAL = 0x02++PROP_CONTENT_TYPE = 0x03@@ -2517,7 +2520,7 @@ def _enc_props(props: list[tuple[int, object]]) -> bytes:body.append(int(value)) # type: ignore[arg-type]elif ident in (PROP_TOPIC_ALIAS_MAXIMUM,):body += struct.pack("!H", int(value)) # type: ignore[arg-type]- elif ident in (PROP_SESSION_EXPIRY_INTERVAL,):+ elif ident in (PROP_MESSAGE_EXPIRY_INTERVAL, PROP_SESSION_EXPIRY_INTERVAL):body += struct.pack("!I", int(value)) # type: ignore[arg-type]elif ident in (PROP_CORRELATION_DATA,):body += struct.pack("!H", len(value)) + value # type: ignore[arg-type]@@ -2905,7 +2908,7 @@ def test_http_publish_forwards_mqtt5_properties(iot_data_client):full, edges, none = _run(scenario())assert full == [(PROP_PAYLOAD_FORMAT_INDICATOR, 1),- (0x02, 60),+ (0x02, 59),(PROP_RESPONSE_TOPIC, f"{topic}/reply"),(PROP_CORRELATION_DATA, b"\x00\x01req-7"),(PROP_CONTENT_TYPE, "application/json"),@@ -2916,7 +2919,7 @@ def test_http_publish_forwards_mqtt5_properties(iot_data_client):]assert edges == [(PROP_PAYLOAD_FORMAT_INDICATOR, 0),- (0x02, 604800),+ (0x02, 604799),(PROP_CORRELATION_DATA, b"req-7"),]assert none == []@@ -3374,6 +3377,102 @@ def test_mqtt5_retain_handling_1_replays_only_for_a_new_subscription():assert repeat_type == PKT_SUBACK, "the subscription already existed"+def test_mqtt5_message_expiry_counts_down_on_delivery():+ """A subscriber gets the expiry interval less the started second; 0 counts as 1, the cap is 604800."""+ topic = _unique("v5/expiry/live")+ intervals = [60, 1, 0, 604801, 0xFFFFFFFF]++ async def scenario():+ async with _connect(MQTT_5) as (sub, _c1):+ await sub.send(_make_subscribe(1, topic, protocol_level=MQTT_5))+ await sub.await_packet(PKT_SUBACK)+ async with _connect(MQTT_5) as (pub, _c2):+ delivered = []+ for interval in intervals:+ await pub.send(+ _make_publish(topic, b"m", protocol_level=MQTT_5,+ properties=[(PROP_MESSAGE_EXPIRY_INTERVAL, interval)])+ )+ _flags, body = await sub.await_packet(PKT_PUBLISH)+ delivered.append(_prop(_parse_publish(body, MQTT_5)[2], PROP_MESSAGE_EXPIRY_INTERVAL))+ return delivered++ assert _run(scenario()) == [59, 0, 0, 604799, 604799]+++def test_mqtt5_expired_retained_message_is_no_longer_served(iot_data_client):+ """Once its expiry interval has passed, a retained message reaches neither a new subscriber nor iot-data."""+ short, kept = _unique("v5/expiry/short"), _unique("v5/expiry/kept")++ async def scenario():+ async with _connect(MQTT_5) as (pub, _c1):+ for packet_id, (topic, interval) in enumerate(((short, 1), (kept, 60)), start=1):+ await pub.send(+ _make_publish(topic, b"stored", qos=1, packet_id=packet_id,+ protocol_level=MQTT_5, retain=True,+ properties=[(PROP_MESSAGE_EXPIRY_INTERVAL, interval)])+ )+ await pub.await_packet(PKT_PUBACK)+ before = await asyncio.to_thread(iot_data_client.get_retained_message, topic=short)+ await asyncio.sleep(1.2)+ async with _connect(MQTT_5) as (sub, _c2):+ await sub.send(_make_subscribe(1, short, protocol_level=MQTT_5))+ first_type, _flags, _body = await sub.packet()+ await sub.send(_make_subscribe(2, kept, protocol_level=MQTT_5))+ flags, body = await sub.await_packet(PKT_PUBLISH)+ return before, first_type, _parse_publish(body, MQTT_5, qos=(flags >> 1) & 0x03)[2]++ before, first_type, kept_props = _run(scenario())+ assert before["payload"] == b"stored"+ assert first_type == PKT_SUBACK, "the expired message is not replayed"+ assert 50 <= _prop(kept_props, PROP_MESSAGE_EXPIRY_INTERVAL) <= 58, "lowered by the time it waited"+ with pytest.raises(ClientError) as exc:+ iot_data_client.get_retained_message(topic=short)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+ pages = iot_data_client.get_paginator("list_retained_messages").paginate()+ listed = {t["topic"] for page in pages for t in page["retainedTopics"]}+ assert kept in listed and short not in listed+++def test_mqtt5_queued_message_expires_while_the_session_is_offline():+ """A resumed session gets only the queued messages still inside their interval, properties lowered."""+ client_id, base = _unique("queue-expiry"), _unique("v5/expiry/queued")+ session = {"clean_start": False, "properties": [(PROP_SESSION_EXPIRY_INTERVAL, 300)]}++ async def scenario():+ async with _connect(MQTT_5, client_id=client_id, **session) as (sub, _c1):+ await sub.send(_make_subscribe(1, f"{base}/#", qos=1, protocol_level=MQTT_5))+ await sub.await_packet(PKT_SUBACK)+ await sub.send(_make_disconnect(MQTT_5))+ await asyncio.sleep(0.5)+ async with _connect(MQTT_5) as (pub, _c2):+ for packet_id, (leaf, interval) in enumerate((("short", 1), ("long", 60), ("none", None)), start=1):+ props = [] if interval is None else [(PROP_MESSAGE_EXPIRY_INTERVAL, interval)]+ await pub.send(+ _make_publish(f"{base}/{leaf}", b"q", qos=1, packet_id=packet_id,+ protocol_level=MQTT_5, properties=props)+ )+ await pub.await_packet(PKT_PUBACK)+ await asyncio.sleep(1.2)+ delivered = {}+ async with _connect(MQTT_5, client_id=client_id, **session) as (back, connack):+ try:+ while True:+ flags, body = await back.await_packet(PKT_PUBLISH, timeout=1.0)+ topic, _payload, props = _parse_publish(body, MQTT_5, qos=(flags >> 1) & 0x03)+ delivered[topic.rsplit("/", 1)[1]] = _prop(props, PROP_MESSAGE_EXPIRY_INTERVAL, "absent")+ except asyncio.TimeoutError:+ pass+ await back.send(_make_disconnect(MQTT_5))+ return connack, delivered++ connack, delivered = _run(scenario())+ assert connack[0] & 0x01 == 1, "the session was resumed"+ assert set(delivered) == {"long", "none"}+ assert 50 <= delivered["long"] <= 58+ assert delivered["none"] == "absent"++def _make_connect_with_will(client_id: str,will_topic: str,