Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(iot): MQTT 5.0 support negotiated per connection (#1398)

iot-rocketfdba3ea2136d
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 5b0afc9c..cbe04ff3 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -136,12 +136,16 @@ _retained: dict[str, "_RetainedMessage"] = {}
class _RetainedMessage:
- __slots__ = ("payload", "qos", "topic", "ts")
+ __slots__ = ("payload", "properties", "qos", "topic", "ts")
- def __init__(self, topic: str, payload: bytes, qos: int):
+ def __init__(self, topic: str, payload: bytes, qos: int, properties: bytes = b""):
self.topic = topic
self.payload = payload
self.qos = qos
+ # Encoded MQTT 5 property block forwarded to v5 subscribers, empty for
+ # a message published by a 3.1.1 client. Runtime only: properties are
+ # not part of the persisted retained-message state.
+ self.properties = properties
self.ts = time.time()
@@ -3381,12 +3385,12 @@ def delete_thing_shadow(thing_name: str, shadow_name: str) -> tuple:
# ===========================================================================
-# MQTT Broker — embedded MQTT 3.1.1 broker logic over WebSocket
+# MQTT Broker — embedded MQTT 3.1.1 + 5.0 broker logic over WebSocket
# ===========================================================================
#
-# The broker owns a small in-process pub/sub registry plus an MQTT 3.1.1
-# framing layer used between the broker and WebSocket clients (per the AWS
-# WS-MQTT subprotocol).
+# The broker owns a small in-process pub/sub registry plus an MQTT framing
+# layer used between the broker and WebSocket clients (per the AWS WS-MQTT
+# subprotocol).
#
# Architecture (mirrors Transfer Family's shared SFTP listener):
# Client → WebSocket (gateway port) → Bridge → in-memory pub/sub
@@ -3395,6 +3399,37 @@ def delete_thing_shadow(thing_name: str, shadow_name: str) -> tuple:
# PUBLISH/SUBSCRIBE topic seen on the wire is internally prefixed with the
# caller's account_id and region before it hits the registry, and the prefix
# is stripped on outbound delivery.
+#
+# Protocol version
+# ----------------
+# The CONNECT packet's protocol level picks the wire format for the rest of
+# the connection: 4 selects MQTT 3.1.1, 5 selects MQTT 5.0, anything else is
+# refused with a 3.1.1 CONNACK carrying return code 0x01 (unacceptable
+# protocol version) so the client sees a diagnosable answer instead of a
+# mis-framed one. The level is per connection and per session — a 3.1.1
+# publisher and a 5.0 subscriber talk to each other through the same
+# registry, each seeing its own framing.
+#
+# 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
+# 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
+# identifiers, and request/response semantics beyond forwarding the
+# properties untouched. Properties this broker does not model are parsed and
+# ignored, never echoed back.
+#
+# Two further limits are worth naming because the protocol has no flag to
+# advertise them. A stored session keeps its topic filters but not the
+# subscription options they arrived with, so a resumed subscription comes back
+# at the defaults. And Session Expiry Interval is honoured as an interval —
+# 0 means do not persist, 0xFFFFFFFF means never expire — but only when a
+# session is looked at, on reconnect or when a QoS 1 message hunts for offline
+# sessions to queue for; nothing reaps expired sessions on a timer.
_broker_logger = logging.getLogger("iot_broker")
@@ -3408,29 +3443,64 @@ _persistent_sessions: dict[tuple[str, str, str], "_PersistentSessionState"] = {}
_broker_lock = asyncio.Lock()
_SESSION_EXPIRY_SECONDS: int = int(os.environ.get("IOT_SESSION_EXPIRY_SECONDS", "3600"))
+# MQTT 5 §3.1.2.11.2: 0xFFFFFFFF means the session never expires.
+_SESSION_EXPIRY_NEVER = 0xFFFFFFFF
_MAX_QUEUED_MESSAGES = 1000
class _PersistentSessionState:
- __slots__ = ("subscriptions", "queued_messages", "created_at")
+ __slots__ = ("subscriptions", "queued_messages", "created_at", "expiry_interval")
- def __init__(self, subscriptions: list[str], created_at: float):
+ def __init__(
+ self,
+ subscriptions: list[str],
+ created_at: float,
+ expiry_interval: int | None = None,
+ ):
self.subscriptions: list[str] = subscriptions
self.queued_messages: list[tuple[str, bytes, int]] = []
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
+ # named no interval (every 3.1.1 client, and a v5 client that omitted
+ # the property), so the module-wide default applies.
+ self.expiry_interval: int | None = expiry_interval
def _is_session_expired(session_state: _PersistentSessionState) -> bool:
- return (time.time() - session_state.created_at) > _SESSION_EXPIRY_SECONDS
+ """Whether a stored session has outlived its expiry interval.
+
+ Evaluated on access — when a client reconnects and when a QoS 1 message
+ looks for offline sessions to queue for — not by a timer. An expired
+ session is therefore never resumed and never queued for, but its entry
+ survives in ``_persistent_sessions`` until something touches that key or
+ the broker is reset. Reaping on a schedule would need a timer this broker
+ deliberately does not run.
+ """
+ interval = session_state.expiry_interval
+ if interval is None:
+ interval = _SESSION_EXPIRY_SECONDS
+ if interval >= _SESSION_EXPIRY_NEVER:
+ return False
+ return (time.time() - session_state.created_at) > interval
class _InFlightMessage:
- __slots__ = ("packet_id", "topic", "payload", "sent_at", "retransmit_count")
+ __slots__ = (
+ "packet_id", "topic", "payload", "properties", "retain", "sent_at",
+ "retransmit_count",
+ )
- def __init__(self, packet_id: int, topic: str, payload: bytes):
+ def __init__(self, packet_id: int, topic: str, payload: bytes, properties: bytes = b"",
+ retain: bool = False):
self.packet_id = packet_id
self.topic = topic
self.payload = payload
+ # Encoded MQTT 5 property block and the RETAIN flag the first attempt
+ # went out with, so a retransmit repeats the original packet rather
+ # than a stripped or reflagged one.
+ self.properties = properties
+ self.retain = retain
self.sent_at = asyncio.get_event_loop().time()
self.retransmit_count = 0
@@ -3438,6 +3508,15 @@ class _InFlightMessage:
_RETRANSMIT_INTERVAL_SECONDS = int(os.environ.get("IOT_RETRANSMIT_SECONDS", "10"))
+# MQTT 5 Retain Handling (§3.8.3.1), the one subscription option that is spent
+# at subscribe time: send retained messages on every SUBSCRIBE, send them only
+# when this subscription is new, or never send them. 0 is also what a 3.1.1
+# SUBSCRIBE means, since it has no options byte.
+RETAIN_HANDLING_SEND_ALWAYS = 0
+RETAIN_HANDLING_SEND_IF_NEW = 1
+RETAIN_HANDLING_SEND_NEVER = 2
+
+
class _Subscription:
__slots__ = (
"subscription_id",
@@ -3446,6 +3525,9 @@ class _Subscription:
"region",
"deliver",
"granted_qos",
+ "client_id",
+ "no_local",
+ "retain_as_published",
)
def __init__(
@@ -3455,6 +3537,9 @@ class _Subscription:
region: str,
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
self.filter_prefixed = filter_prefixed
@@ -3462,6 +3547,15 @@ class _Subscription:
self.region = region
self.deliver = deliver
self.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.
+ 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_local
+ self.retain_as_published = retain_as_published
def __hash__(self) -> int:
return hash(self.subscription_id)
@@ -4095,8 +4189,24 @@ async def broker_publish(
payload: bytes,
qos: int = 0,
retain: bool = False,
+ properties: bytes = b"",
client_id: str | None = None,
-) -> None:
+) -> int:
+ """Deliver a message to every matching subscriber.
+
+ ``properties`` is an encoded MQTT 5 property block forwarded verbatim to
+ v5 subscribers (empty for a 3.1.1 publisher or an HTTP publish). Returns
+ how many recipients the message reached — subscribers delivered to plus
+ offline persistent sessions it was queued for — which is what an MQTT 5
+ PUBACK reports as Success versus No matching subscribers.
+
+ ``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.
+ """
+ delivered = 0
# Basic Ingest: a publish to `$aws/rules/<ruleName>` is delivered straight
# to that rule's actions and bypasses pub/sub delivery entirely.
if topic.startswith(_BASIC_INGEST_PREFIX):
@@ -4112,7 +4222,7 @@ async def broker_publish(
remainder[1] if len(remainder) > 1 else "",
client_id,
)
- return
+ return delivered
scoped = _scoped_topic(account_id, region, topic)
@@ -4120,24 +4230,39 @@ async def broker_publish(
if not payload:
_retained.pop(scoped, None)
else:
- _retained[scoped] = _RetainedMessage(scoped, payload, qos)
+ _retained[scoped] = _RetainedMessage(scoped, payload, qos, properties)
async with _broker_lock:
subs = [s for sset in _subscriptions.values() for s in sset]
- for sub in subs:
- if sub.account_id != account_id or sub.region != region:
- continue
- if _topic_matches(sub.filter_prefixed, scoped):
- try:
- effective_qos = min(qos, sub.granted_qos)
- await sub.deliver(
- _unscope_topic(sub.account_id, sub.region, scoped),
- payload,
- effective_qos,
+ token = _delivery_properties.set(properties)
+ try:
+ 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:
+ continue
+ if _topic_matches(sub.filter_prefixed, scoped):
+ # Retain As Published forwards the publisher's flag; without
+ # it the flag is cleared, so a subscriber can tell a live
+ # message from a retained one (§3.3.1.3).
+ retain_token = _delivery_retain.set(
+ retain if sub.retain_as_published else False
)
- except Exception:
- _broker_logger.exception("IoT broker: subscriber %s delivery failed", sub.subscription_id)
+ try:
+ effective_qos = min(qos, sub.granted_qos)
+ await sub.deliver(
+ _unscope_topic(sub.account_id, sub.region, scoped),
+ payload,
+ effective_qos,
+ )
+ delivered += 1
+ except Exception:
+ _broker_logger.exception("IoT broker: subscriber %s delivery failed", sub.subscription_id)
+ finally:
+ _delivery_retain.reset(retain_token)
+ finally:
+ _delivery_properties.reset(token)
if qos >= 1:
for key, ps in list(_persistent_sessions.items()):
@@ -4154,9 +4279,11 @@ async def broker_publish(
ps.queued_messages.append((topic, payload, qos))
if len(ps.queued_messages) > _MAX_QUEUED_MESSAGES:
ps.queued_messages = ps.queued_messages[-_MAX_QUEUED_MESSAGES:]
+ delivered += 1
break
await _evaluate_topic_rules(account_id, region, topic, payload, client_id)
+ return delivered
# Shadow-over-MQTT bridge — AFTER delivery and rule evaluation, so rules
# matching `$aws/things/+/shadow/update` fire on the request, and the
@@ -4186,15 +4313,40 @@ async def broker_subscribe(
topic_filter: str,
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);
+ their defaults are what an MQTT 3.1.1 SUBSCRIBE means, so an existing
+ caller keeps its behaviour. ``retain_handling`` is acted on here and
+ nowhere 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.
+ """
filter_prefixed = _scoped_topic(account_id, region, topic_filter)
sub = _Subscription(
- filter_prefixed, account_id, region, callback, granted_qos
+ filter_prefixed, account_id, region, callback, granted_qos,
+ client_id=client_id, no_local=no_local,
+ retain_as_published=retain_as_published,
)
async with _broker_lock:
- _subscriptions.setdefault(filter_prefixed, set()).add(sub)
+ existing_subscribers = _subscriptions.setdefault(filter_prefixed, set())
+ # "Existing" is per client: whether *this* client already held the
+ # filter, which is what Retain Handling 1 asks about. A subscriber
+ # with no client identity has no subscription to re-establish.
+ already_subscribed = client_id is not None and any(
+ s.client_id == client_id for s in existing_subscribers
+ )
+ existing_subscribers.add(sub)
+ send_retained = retain_handling == RETAIN_HANDLING_SEND_ALWAYS or (
+ retain_handling == RETAIN_HANDLING_SEND_IF_NEW and not already_subscribed
+ )
has_wildcard = "+" in topic_filter or "#" in topic_filter
- if not has_wildcard:
+ if send_retained and not has_wildcard:
scope_prefix = f"{account_id}/{region}/"
retained_to_send = [
r
@@ -4206,12 +4358,21 @@ async def broker_subscribe(
retained_to_send = []
for r in retained_to_send:
+ token = _delivery_properties.set(r.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
+ # traffic on the same topic.
+ retain_token = _delivery_retain.set(True)
try:
await sub.deliver(
_unscope_topic(account_id, region, r.topic), r.payload, r.qos
)
except Exception:
_broker_logger.exception("IoT broker: retained-message delivery failed")
+ finally:
+ _delivery_retain.reset(retain_token)
+ _delivery_properties.reset(token)
return sub.subscription_id
@@ -4255,6 +4416,13 @@ async def _force_disconnect_duplicate(
existing = _connected_clients.get(key)
if existing is not None:
_broker_logger.info("IoT broker: duplicate client_id=%s, forcing old connection closed", client_id)
+ if existing.protocol_version == MQTT_5:
+ # An MQTT 5 client is told why it lost the connection; 3.1.1 has
+ # no server-initiated DISCONNECT, so it just sees the close.
+ try:
+ await existing.send_bytes(_make_disconnect(RC5_SESSION_TAKEN_OVER))
+ except Exception:
+ pass
try:
await existing._send({"type": "websocket.close", "code": 1000})
except Exception:
@@ -4264,7 +4432,7 @@ async def _force_disconnect_duplicate(
# ---------------------------------------------------------------------------
-# MQTT 3.1.1 frame codec
+# MQTT 3.1.1 / 5.0 frame codec
# ---------------------------------------------------------------------------
PKT_CONNECT = 1
@@ -4279,6 +4447,128 @@ PKT_PINGREQ = 12
PKT_PINGRESP = 13
PKT_DISCONNECT = 14
+# Protocol levels carried by the CONNECT variable header.
+MQTT_311 = 4
+MQTT_5 = 5
+
+# MQTT 3.1.1 CONNACK return codes (§3.2.2.3).
+CONNACK_311_ACCEPTED = 0x00
+CONNACK_311_UNACCEPTABLE_PROTOCOL_VERSION = 0x01
+
+# MQTT 5 reason codes, only the ones this broker produces (§2.4). Success and
+# Normal disconnection share the value 0x00.
+RC5_SUCCESS = 0x00
+RC5_NO_MATCHING_SUBSCRIBERS = 0x10
+RC5_NO_SUBSCRIPTION_EXISTED = 0x11
+RC5_MALFORMED_PACKET = 0x81
+RC5_SESSION_TAKEN_OVER = 0x8E
+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.
+SUB_OPT_QOS_MASK = 0x03
+SUB_OPT_NO_LOCAL = 0x04
+SUB_OPT_RETAIN_AS_PUBLISHED = 0x08
+SUB_OPT_RETAIN_HANDLING_SHIFT = 4
+SUB_OPT_RETAIN_HANDLING_MASK = 0x03
+
+# MQTT 5 property identifiers (§2.2.2.2).
+PROP_PAYLOAD_FORMAT_INDICATOR = 0x01
+PROP_MESSAGE_EXPIRY_INTERVAL = 0x02
+PROP_CONTENT_TYPE = 0x03
+PROP_RESPONSE_TOPIC = 0x08
+PROP_CORRELATION_DATA = 0x09
+PROP_SUBSCRIPTION_IDENTIFIER = 0x0B
+PROP_SESSION_EXPIRY_INTERVAL = 0x11
+PROP_ASSIGNED_CLIENT_IDENTIFIER = 0x12
+PROP_SERVER_KEEP_ALIVE = 0x13
+PROP_AUTHENTICATION_METHOD = 0x15
+PROP_AUTHENTICATION_DATA = 0x16
+PROP_REQUEST_PROBLEM_INFORMATION = 0x17
+PROP_WILL_DELAY_INTERVAL = 0x18
+PROP_REQUEST_RESPONSE_INFORMATION = 0x19
+PROP_RESPONSE_INFORMATION = 0x1A
+PROP_SERVER_REFERENCE = 0x1C
+PROP_REASON_STRING = 0x1F
+PROP_RECEIVE_MAXIMUM = 0x21
+PROP_TOPIC_ALIAS_MAXIMUM = 0x22
+PROP_TOPIC_ALIAS = 0x23
+PROP_MAXIMUM_QOS = 0x24
+PROP_RETAIN_AVAILABLE = 0x25
+PROP_USER_PROPERTY = 0x26
+PROP_MAXIMUM_PACKET_SIZE = 0x27
+PROP_WILDCARD_SUBSCRIPTION_AVAILABLE = 0x28
+PROP_SUBSCRIPTION_IDENTIFIER_AVAILABLE = 0x29
+PROP_SHARED_SUBSCRIPTION_AVAILABLE = 0x2A
+
+# Wire type of every property identifier the protocol defines: "byte",
+# "u16", "u32", "vbi" (variable byte integer), "str", "bin" and "pair" (a
+# UTF-8 string pair). The table is complete even for properties the broker
+# has no use for, because knowing a property's *width* is what lets the
+# parser step over it — see _decode_properties.
+_PROPERTY_TYPES: dict[int, str] = {
+ PROP_PAYLOAD_FORMAT_INDICATOR: "byte",
+ PROP_MESSAGE_EXPIRY_INTERVAL: "u32",
+ PROP_CONTENT_TYPE: "str",
+ PROP_RESPONSE_TOPIC: "str",
+ PROP_CORRELATION_DATA: "bin",
+ PROP_SUBSCRIPTION_IDENTIFIER: "vbi",
+ PROP_SESSION_EXPIRY_INTERVAL: "u32",
+ PROP_ASSIGNED_CLIENT_IDENTIFIER: "str",
+ PROP_SERVER_KEEP_ALIVE: "u16",
+ PROP_AUTHENTICATION_METHOD: "str",
+ PROP_AUTHENTICATION_DATA: "bin",
+ PROP_REQUEST_PROBLEM_INFORMATION: "byte",
+ PROP_WILL_DELAY_INTERVAL: "u32",
+ PROP_REQUEST_RESPONSE_INFORMATION: "byte",
+ PROP_RESPONSE_INFORMATION: "str",
+ PROP_SERVER_REFERENCE: "str",
+ PROP_REASON_STRING: "str",
+ PROP_RECEIVE_MAXIMUM: "u16",
+ PROP_TOPIC_ALIAS_MAXIMUM: "u16",
+ PROP_TOPIC_ALIAS: "u16",
+ PROP_MAXIMUM_QOS: "byte",
+ PROP_RETAIN_AVAILABLE: "byte",
+ PROP_USER_PROPERTY: "pair",
+ PROP_MAXIMUM_PACKET_SIZE: "u32",
+ PROP_WILDCARD_SUBSCRIPTION_AVAILABLE: "byte",
+ PROP_SUBSCRIPTION_IDENTIFIER_AVAILABLE: "byte",
+ PROP_SHARED_SUBSCRIPTION_AVAILABLE: "byte",
+}
+
+# PUBLISH properties handed on to subscribers unchanged. §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
+# does not model) is dropped rather than echoed.
+_FORWARDED_PUBLISH_PROPERTIES = frozenset({
+ PROP_PAYLOAD_FORMAT_INDICATOR,
+ PROP_MESSAGE_EXPIRY_INTERVAL,
+ PROP_CONTENT_TYPE,
+ PROP_RESPONSE_TOPIC,
+ PROP_CORRELATION_DATA,
+ PROP_USER_PROPERTY,
+})
+
+# 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
+# their own three-argument callbacks — and only an MQTT 5 session has any use
+# for properties. broker_publish sets this around each delivery; every other
+# caller sees the empty default and sends an empty property block.
+_delivery_properties: contextvars.ContextVar[bytes] = contextvars.ContextVar(
+ "_iot_delivery_properties", default=b""
+)
+
+# The RETAIN flag one delivery goes out with, carried the same way and for the
+# same reason. It is resolved per subscriber rather than per message, because
+# Retain As Published makes it a property of the subscription: two subscribers
+# to one publish can legitimately see different flags.
+_delivery_retain: contextvars.ContextVar[bool] = contextvars.ContextVar(
+ "_iot_delivery_retain", default=False
+)
+
def _encode_remaining_length(n: int) -> bytes:
out = bytearray()
@@ -4325,35 +4615,187 @@ def _encode_string(s: str) -> bytes:
return struct.pack("!H", len(raw)) + raw
-def _make_connack(return_code: int = 0, session_present: bool = False) -> bytes:
+def _read_binary(buf: bytes, offset: int) -> tuple[bytes, int]:
+ if offset + 2 > len(buf):
+ raise ValueError("Truncated binary length")
+ n = struct.unpack_from("!H", buf, offset)[0]
+ offset += 2
+ if offset + n > len(buf):
+ raise ValueError("Truncated binary body")
+ return buf[offset:offset + n], offset + n
+
+
+def _encode_binary(b: bytes) -> bytes:
+ return struct.pack("!H", len(b)) + b
+
+
+def _decode_properties(buf: bytes, offset: int) -> tuple[list[tuple[int, object]], int]:
+ """Read one MQTT 5 property block, returning (properties, new_offset).
+
+ Properties keep wire order and duplicates (User Property is allowed to
+ repeat), so the result is a list of ``(identifier, value)`` rather than a
+ dict. A property whose identifier is not in ``_PROPERTY_TYPES`` cannot be
+ stepped over — its width is unknown — so parsing stops there and the
+ remainder of the block is skipped wholesale. The block's own length is
+ always honoured, which keeps the packet parse in sync either way.
+
+ Values are read out of a slice that ends where the block's declared length
+ ends, never out of the whole packet. A property whose value runs past that
+ point raises ``ValueError`` like the sibling field readers, instead of
+ quietly consuming the field that follows the block (a PUBLISH payload, a
+ will topic) or walking off the end of the packet.
+ """
+ length, offset = _decode_remaining_length(buf, offset)
+ end = offset + length
+ if end > len(buf):
+ raise ValueError("Truncated property block")
+ block = buf[offset:end]
+ props: list[tuple[int, object]] = []
+ pos = 0
+ while pos < len(block):
+ identifier = block[pos]
+ pos += 1
+ kind = _PROPERTY_TYPES.get(identifier)
+ if kind is None:
+ _broker_logger.warning(
+ "IoT broker: unknown MQTT 5 property 0x%02X — skipping rest of block",
+ identifier,
+ )
+ break
+ if kind == "byte":
+ if pos + 1 > len(block):
+ raise ValueError("Truncated property value")
+ value: object = block[pos]
+ pos += 1
+ elif kind == "u16":
+ if pos + 2 > len(block):
+ raise ValueError("Truncated property value")
+ value = struct.unpack_from("!H", block, pos)[0]
+ pos += 2
+ elif kind == "u32":
+ if pos + 4 > len(block):
+ raise ValueError("Truncated property value")
+ value = struct.unpack_from("!I", block, pos)[0]
+ pos += 4
+ elif kind == "vbi":
+ value, pos = _decode_remaining_length(block, pos)
+ elif kind == "str":
+ value, pos = _read_string(block, pos)
+ elif kind == "bin":
+ value, pos = _read_binary(block, pos)
+ else: # pair
+ name, pos = _read_string(block, pos)
+ pair_value, pos = _read_string(block, pos)
+ value = (name, pair_value)
+ props.append((identifier, value))
+ return props, end
+
+
+def _encode_properties(props: list[tuple[int, object]] | None) -> bytes:
+ """Encode a property list, length prefix included. Empty block is ``b'\\x00'``."""
+ body = bytearray()
+ for identifier, value in props or []:
+ kind = _PROPERTY_TYPES[identifier]
+ body.append(identifier)
+ if kind == "byte":
+ body.append(int(value)) # type: ignore[arg-type]
+ elif kind == "u16":
+ body += struct.pack("!H", int(value)) # type: ignore[arg-type]
+ elif kind == "u32":
+ body += struct.pack("!I", int(value)) # type: ignore[arg-type]
+ elif kind == "vbi":
+ body += _encode_remaining_length(int(value)) # type: ignore[arg-type]
+ elif kind == "str":
+ body += _encode_string(str(value))
+ elif kind == "bin":
+ body += _encode_binary(bytes(value)) # type: ignore[arg-type]
+ else: # pair
+ name, pair_value = value # type: ignore[misc]
+ body += _encode_string(name) + _encode_string(pair_value)
+ return _encode_remaining_length(len(body)) + bytes(body)
+
+
+def _property_value(props: list[tuple[int, object]], identifier: int, default: object) -> object:
+ for prop_id, value in props:
+ if prop_id == identifier:
+ return value
+ return default
+
+
+def _forwardable_publish_properties(props: list[tuple[int, object]]) -> bytes:
+ """Encoded property block a subscriber receives for an incoming PUBLISH."""
+ kept = [p for p in props if p[0] in _FORWARDED_PUBLISH_PROPERTIES]
+ if not kept:
+ return b""
+ return _encode_properties(kept)
+
+
+def _make_connack(
+ return_code: int = 0,
+ session_present: bool = False,
+ protocol_version: int = MQTT_311,
+ properties: list[tuple[int, object]] | None = None,
+) -> bytes:
flags = 1 if session_present else 0
body = bytes([flags, return_code])
+ if protocol_version == MQTT_5:
+ body += _encode_properties(properties)
return bytes([PKT_CONNACK << 4]) + _encode_remaining_length(len(body)) + body
def _make_publish(topic: str, payload: bytes, qos: int = 0, packet_id: int | None = None,
- retain: bool = False, dup: bool = False) -> bytes:
+ retain: bool = False, dup: bool = False,
+ properties: bytes | None = None) -> bytes:
+ """Build a PUBLISH. ``properties`` is an already-encoded MQTT 5 property
+ block; ``None`` means MQTT 3.1.1, which has no such field."""
fixed = (PKT_PUBLISH << 4) | (qos << 1) | (0x08 if dup else 0) | (0x01 if retain else 0)
body = _encode_string(topic)
if qos > 0:
if packet_id is None:
packet_id = 1
body += struct.pack("!H", packet_id)
+ if properties is not None:
+ body += properties or b"\x00"
body += payload
return bytes([fixed]) + _encode_remaining_length(len(body)) + body
-def _make_puback(packet_id: int) -> bytes:
- return bytes([PKT_PUBACK << 4]) + bytes([2]) + struct.pack("!H", packet_id)
+def _make_puback(packet_id: int, reason_code: int | None = None,
+ properties: list[tuple[int, object]] | None = None) -> bytes:
+ """Build a PUBACK. ``reason_code`` is MQTT 5 only; ``None`` yields the
+ bare 3.1.1 packet."""
+ body = struct.pack("!H", packet_id)
+ if reason_code is not None:
+ body += bytes([reason_code]) + _encode_properties(properties)
+ return bytes([PKT_PUBACK << 4]) + _encode_remaining_length(len(body)) + body
-def _make_suback(packet_id: int, granted_qos: list[int]) -> bytes:
- body = struct.pack("!H", packet_id) + bytes(granted_qos)
+def _make_suback(packet_id: int, granted_qos: list[int],
+ protocol_version: int = MQTT_311,
+ properties: list[tuple[int, object]] | None = None) -> bytes:
+ body = struct.pack("!H", packet_id)
+ if protocol_version == MQTT_5:
+ body += _encode_properties(properties)
+ body += bytes(granted_qos)
return bytes([PKT_SUBACK << 4]) + _encode_remaining_length(len(body)) + body
-def _make_unsuback(packet_id: int) -> bytes:
- return bytes([PKT_UNSUBACK << 4]) + bytes([2]) + struct.pack("!H", packet_id)
+def _make_unsuback(packet_id: int, reason_codes: list[int] | None = None,
+ properties: list[tuple[int, object]] | None = None) -> bytes:
+ """Build an UNSUBACK. ``reason_codes`` is MQTT 5 only — 3.1.1's UNSUBACK
+ carries the packet identifier and nothing else."""
+ body = struct.pack("!H", packet_id)
+ if reason_codes is not None:
+ body += _encode_properties(properties) + bytes(reason_codes)
+ return bytes([PKT_UNSUBACK << 4]) + _encode_remaining_length(len(body)) + body
+
+
+def _make_disconnect(reason_code: int,
+ properties: list[tuple[int, object]] | None = None) -> bytes:
+ """Build a server-initiated MQTT 5 DISCONNECT. 3.1.1 has no such packet —
+ a 3.1.1 server just closes the transport."""
+ body = bytes([reason_code]) + _encode_properties(properties)
+ return bytes([PKT_DISCONNECT << 4]) + _encode_remaining_length(len(body)) + body
def _make_pingresp() -> bytes:
@@ -4381,13 +4823,21 @@ class _WSSession:
self._next_pid = 1
self._send_lock = asyncio.Lock()
self._client_id: str = ""
- self._clean_session: bool = True
+ # Negotiated in CONNECT; every packet built for this session is framed
+ # for this version.
+ self.protocol_version: int = MQTT_311
+ # 3.1.1 derives both from one flag; MQTT 5 splits them into Clean
+ # Start (resume or not) and Session Expiry Interval (keep or not).
+ self._resume_session: bool = False
+ self._persist_session: bool = False
+ self._session_expiry_interval: int | None = None
self._in_flight: dict[int, _InFlightMessage] = {}
self._retransmit_task: asyncio.Task | None = None
self._will_topic: str | None = None
self._will_message: bytes | None = None
self._will_qos: int = 0
self._will_retain: bool = False
+ self._will_properties: bytes = b""
self._graceful_disconnect: bool = False
def _alloc_packet_id(self) -> int:
@@ -4409,7 +4859,11 @@ class _WSSession:
msg.retransmit_count += 1
msg.sent_at = now
await self.send_bytes(
- _make_publish(msg.topic, msg.payload, qos=1, packet_id=pid, dup=True)
+ _make_publish(
+ msg.topic, msg.payload, qos=1, packet_id=pid, dup=True,
+ retain=msg.retain,
+ properties=self._publish_properties(msg.properties),
+ )
)
except asyncio.CancelledError:
pass
@@ -4418,13 +4872,32 @@ class _WSSession:
async with self._send_lock:
await self._send({"type": "websocket.send", "bytes": b})
+ def _publish_properties(self, properties: bytes) -> bytes | None:
+ """Property block for an outbound PUBLISH, or None on a 3.1.1 session.
+
+ This is where cross-version delivery is resolved: a 3.1.1 subscriber
+ never sees the field, and a v5 subscriber always gets one — empty when
+ the publisher was 3.1.1 or sent nothing forwardable.
+ """
+ if self.protocol_version != MQTT_5:
+ return None
+ return properties or b"\x00"
+
async def deliver_to_client(self, topic: str, payload: bytes, qos: int) -> None:
+ properties = _delivery_properties.get()
+ retain = _delivery_retain.get()
if qos == 0:
- await self.send_bytes(_make_publish(topic, payload, qos=0))
+ await self.send_bytes(
+ _make_publish(topic, payload, qos=0, retain=retain,
+ properties=self._publish_properties(properties))
+ )
else:
pid = self._alloc_packet_id()
- self._in_flight[pid] = _InFlightMessage(pid, topic, payload)
- await self.send_bytes(_make_publish(topic, payload, qos=1, packet_id=pid))
+ self._in_flight[pid] = _InFlightMessage(pid, topic, payload, properties, retain)
+ await self.send_bytes(
+ _make_publish(topic, payload, qos=1, packet_id=pid, retain=retain,
+ properties=self._publish_properties(properties))
+ )
self._ensure_retransmit_timer()
def _take_packet(self) -> tuple[int, int, bytes] | None:
@@ -4446,13 +4919,124 @@ class _WSSession:
flags = first & 0x0F
return pkt_type, flags, body
+ def _connack_properties(self, assigned_client_id: str | None) -> list[tuple[int, object]]:
+ """CONNACK properties for an MQTT 5 session.
+
+ The three "available" flags set to 0 are the protocol's own way of
+ telling a client not to use a feature this broker does not implement,
+ which is why advertising them beats staying silent (their defaults all
+ mean "available"). Topic Alias Maximum 0 does the same for aliases.
+ """
+ props: list[tuple[int, object]] = []
+ if assigned_client_id:
+ props.append((PROP_ASSIGNED_CLIENT_IDENTIFIER, assigned_client_id))
+ props += [
+ (PROP_MAXIMUM_QOS, 1),
+ (PROP_RETAIN_AVAILABLE, 1),
+ (PROP_MAXIMUM_PACKET_SIZE, _max_frame_buffer_bytes()),
+ (PROP_TOPIC_ALIAS_MAXIMUM, 0),
+ (PROP_WILDCARD_SUBSCRIPTION_AVAILABLE, 1),
+ (PROP_SUBSCRIPTION_IDENTIFIER_AVAILABLE, 0),
+ (PROP_SHARED_SUBSCRIPTION_AVAILABLE, 0),
+ ]
+ return props
+
+ async def _send_connack(
+ self, session_present: bool = False, assigned_client_id: str | None = None
+ ) -> None:
+ """Accept the connection, framed for the negotiated protocol version."""
+ if self.protocol_version == MQTT_5:
+ await self.send_bytes(
+ _make_connack(
+ return_code=RC5_SUCCESS,
+ session_present=session_present,
+ protocol_version=MQTT_5,
+ properties=self._connack_properties(assigned_client_id),
+ )
+ )
+ else:
+ await self.send_bytes(
+ _make_connack(
+ return_code=CONNACK_311_ACCEPTED, session_present=session_present
+ )
+ )
+
+ async def _reject_malformed_packet(self, pkt_type: int, exc: Exception) -> None:
+ """Answer a packet this broker could not parse, then let the caller close.
+
+ MQTT 5 §4.13.1 requires a server that detects a Malformed Packet to
+ close the connection, and to say why first: in a CONNACK when the
+ CONNECT itself is what failed and no CONNACK has gone out yet, in a
+ DISCONNECT once the connection is established. Both carry reason code
+ 0x81. MQTT 3.1.1 has no CONNACK return code for a malformed packet and
+ no server-sent DISCONNECT at all, so there the connection just closes,
+ which is what §4.8 prescribes.
+ """
+ _broker_logger.warning(
+ "IoT broker: malformed MQTT packet (type %d) — closing connection: %s",
+ pkt_type,
+ exc,
+ )
+ if self.protocol_version != MQTT_5:
+ return
+ packet = (
+ _make_connack(return_code=RC5_MALFORMED_PACKET, protocol_version=MQTT_5)
+ if pkt_type == PKT_CONNECT
+ else _make_disconnect(RC5_MALFORMED_PACKET)
+ )
+ try:
+ await self.send_bytes(packet)
+ except Exception:
+ # The transport is going away regardless; a client that already
+ # hung up must not turn into an unhandled error here.
+ _broker_logger.debug(
+ "IoT broker: malformed-packet reason code not delivered", exc_info=True
+ )
+
async def handle_packet(self, pkt_type: int, flags: int, body: bytes) -> bool:
+ """Dispatch one packet. Returns False when the connection must close.
+
+ Every field reader in this codec raises on truncation rather than
+ reading past its own bounds, so a packet the client mis-framed lands
+ here as an exception instead of as silently wrong values. Catching it
+ at the one dispatch point is what turns it into the protocol's own
+ answer — a reason code and a close — for any transport driving this
+ session, rather than an exception the caller has to know about.
+ """
+ try:
+ return await self._dispatch_packet(pkt_type, flags, body)
+ except (ValueError, IndexError, struct.error) as exc:
+ await self._reject_malformed_packet(pkt_type, exc)
+ return False
+
+ async def _dispatch_packet(self, pkt_type: int, flags: int, body: bytes) -> bool:
if pkt_type == PKT_CONNECT:
off = 0
_proto_name, off = _read_string(body, off)
- off += 1 # Protocol Level
if off >= len(body):
- await self.send_bytes(_make_connack(return_code=0))
+ await self.send_bytes(_make_connack(return_code=CONNACK_311_ACCEPTED))
+ return True
+ protocol_level = body[off]
+ off += 1
+ if protocol_level not in (MQTT_311, MQTT_5):
+ # The client asked for a version this broker cannot frame, so
+ # the refusal goes out in the 3.1.1 shape: it is the one form
+ # whose second body byte every MQTT decoder reads as a return
+ # code, which turns an otherwise silent decode failure into a
+ # diagnosable "unacceptable protocol version".
+ _broker_logger.warning(
+ "IoT broker: CONNECT with unsupported protocol level %d refused",
+ protocol_level,
+ )
+ await self.send_bytes(
+ _make_connack(return_code=CONNACK_311_UNACCEPTABLE_PROTOCOL_VERSION)
+ )
+ return False
+ self.protocol_version = protocol_level
+ is_v5 = protocol_level == MQTT_5
+
+ if off >= len(body):
+ await self._send_connack()
return True
connect_flags = body[off]
off += 1
@@ -4461,19 +5045,46 @@ class _WSSession:
will_flag = bool(connect_flags & 0x04)
will_qos = (connect_flags >> 3) & 0x03
will_retain = bool(connect_flags & 0x20)
- clean_session = bool(connect_flags & 0x02)
+ # Bit 1 is Clean Session in 3.1.1 and Clean Start in MQTT 5.
+ clean_start = bool(connect_flags & 0x02)
+
+ session_expiry = 0
+ if is_v5:
+ connect_props, off = _decode_properties(body, off)
+ session_expiry = int(
+ _property_value(connect_props, PROP_SESSION_EXPIRY_INTERVAL, 0)
+ )
- self._clean_session = clean_session
+ # 3.1.1 ties resumption and retention to the one flag. MQTT 5
+ # separates them: Clean Start decides whether an existing session
+ # is picked up, Session Expiry Interval whether this one outlives
+ # the connection and for how long.
+ self._resume_session = not clean_start
+ self._persist_session = session_expiry > 0 if is_v5 else not clean_start
+ # The interval the client asked for, kept so a stored session
+ # expires on the client's terms rather than on the module-wide
+ # default. A 3.1.1 client names no interval and gets the default.
+ self._session_expiry_interval = session_expiry if is_v5 else None
if off < len(body):
client_id, off = _read_string(body, off)
else:
client_id = ""
+ assigned_client_id = None
if not client_id:
client_id = uuid.uuid4().hex
+ # MQTT 5 requires the server to hand back the identifier it
+ # made up; a 3.1.1 client is never told and cannot ask.
+ assigned_client_id = client_id
self._client_id = client_id
if will_flag:
+ will_props: list[tuple[int, object]] = []
+ if is_v5:
+ # Will properties precede the will topic. Will Delay
+ # Interval is parsed and ignored — the will goes out as
+ # soon as the connection drops.
+ will_props, off = _decode_properties(body, off)
if off < len(body):
will_topic, off = _read_string(body, off)
else:
@@ -4489,11 +5100,13 @@ class _WSSession:
self._will_message = will_message
self._will_qos = will_qos
self._will_retain = will_retain
+ self._will_properties = _forwardable_publish_properties(will_props)
else:
self._will_topic = None
self._will_message = None
self._will_qos = 0
self._will_retain = False
+ self._will_properties = b""
self._graceful_disconnect = False
await _force_disconnect_duplicate(
@@ -4506,24 +5119,31 @@ class _WSSession:
session_key = (self.account_id, self.region, self._client_id)
session_present = False
- if clean_session:
+ if not self._resume_session:
_persistent_sessions.pop(session_key, None)
else:
existing_ps = _persistent_sessions.get(session_key)
if existing_ps is not None and not _is_session_expired(existing_ps):
session_present = True
for topic_filter in existing_ps.subscriptions:
+ # A stored session keeps its topic filters, not the
+ # subscription options they were made with: those live
+ # on the connection that sent them, so a resumed
+ # subscription comes back with the defaults.
sid = await broker_subscribe(
self.account_id,
self.region,
topic_filter,
self.deliver_to_client,
1,
+ client_id=self._client_id or None,
)
self._sub_ids.append(sid)
self._sub_filters[sid] = topic_filter
self._sub_granted_qos[sid] = 1
- await self.send_bytes(_make_connack(return_code=0, session_present=True))
+ await self._send_connack(
+ session_present=True, assigned_client_id=assigned_client_id
+ )
queued = existing_ps.queued_messages[:]
existing_ps.queued_messages.clear()
for q_topic, q_payload, q_qos in queued:
@@ -4531,10 +5151,14 @@ class _WSSession:
return True
else:
_persistent_sessions[session_key] = _PersistentSessionState(
- subscriptions=[], created_at=time.time()
+ subscriptions=[],
+ created_at=time.time(),
+ expiry_interval=self._session_expiry_interval,
)
- await self.send_bytes(_make_connack(return_code=0, session_present=session_present))
+ await self._send_connack(
+ session_present=session_present, assigned_client_id=assigned_client_id
+ )
return True
if pkt_type == PKT_PUBLISH:
@@ -4547,32 +5171,56 @@ class _WSSession:
return True
packet_id = struct.unpack_from("!H", body, off)[0]
off += 2
+ properties = b""
+ if self.protocol_version == MQTT_5:
+ publish_props, off = _decode_properties(body, off)
+ properties = _forwardable_publish_properties(publish_props)
if not _validate_publish_topic(topic):
_broker_logger.warning("IoT broker: PUBLISH rejected — invalid topic: %r", topic)
+ if self.protocol_version == MQTT_5:
+ await self.send_bytes(_make_disconnect(RC5_TOPIC_NAME_INVALID))
return False
payload = body[off:]
- await broker_publish(
+ delivered = await broker_publish(
self.account_id,
self.region,
topic,
payload,
qos=qos,
retain=retain,
- client_id=self._client_id,
+ properties=properties,
+ client_id=self._client_id or None,
)
if qos == 1 and packet_id is not None:
- await self.send_bytes(_make_puback(packet_id))
+ if self.protocol_version == MQTT_5:
+ reason = RC5_SUCCESS if delivered else RC5_NO_MATCHING_SUBSCRIBERS
+ await self.send_bytes(_make_puback(packet_id, reason_code=reason))
+ else:
+ await self.send_bytes(_make_puback(packet_id))
return True
if pkt_type == PKT_SUBSCRIBE:
packet_id = struct.unpack_from("!H", body, 0)[0]
off = 2
+ if self.protocol_version == MQTT_5:
+ # Subscription Identifier lives here; the broker advertises it
+ # as unavailable in CONNACK and ignores it if sent anyway.
+ _subscribe_props, off = _decode_properties(body, off)
granted = []
while off < len(body):
topic, off = _read_string(body, off)
- req_qos = body[off]
+ # MQTT 5 replaces 3.1.1's bare QoS byte with a subscription
+ # options byte: the low two bits are the QoS, the rest are No
+ # Local, Retain As Published and Retain Handling. In 3.1.1 the
+ # upper bits are reserved zero, so reading the same byte the
+ # same way leaves every option off.
+ if off >= len(body):
+ raise ValueError("SUBSCRIBE topic filter without options byte")
+ subscription_options = body[off]
off += 1
- granted_qos = min(req_qos, 1)
+ granted_qos = min(subscription_options & SUB_OPT_QOS_MASK, 1)
+ # A granted QoS doubles as an MQTT 5 SUBACK reason code: 0x00
+ # and 0x01 mean the same thing in both versions.
granted.append(granted_qos)
sid = await broker_subscribe(
self.account_id,
@@ -4580,14 +5228,26 @@ class _WSSession:
topic,
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
+ ),
+ retain_handling=(
+ subscription_options >> SUB_OPT_RETAIN_HANDLING_SHIFT
+ ) & SUB_OPT_RETAIN_HANDLING_MASK,
)
self._sub_ids.append(sid)
self._sub_filters[sid] = topic
self._sub_granted_qos[sid] = granted_qos
- await self.send_bytes(_make_suback(packet_id, granted))
+ await self.send_bytes(
+ _make_suback(packet_id, granted, protocol_version=self.protocol_version)
+ )
return True
if pkt_type == PKT_PUBACK:
+ # MQTT 5 appends a reason code and properties after the packet
+ # identifier; nothing here acts on either.
if len(body) >= 2:
packet_id = struct.unpack_from("!H", body, 0)[0]
self._in_flight.pop(packet_id, None)
@@ -4596,6 +5256,10 @@ class _WSSession:
if pkt_type == PKT_UNSUBSCRIBE:
packet_id = struct.unpack_from("!H", body, 0)[0]
off = 2
+ if self.protocol_version == MQTT_5:
+ # 5.0 puts a property block between the packet identifier and
+ # the topic filters; none of the defined ones apply to a server.
+ _unsubscribe_props, off = _decode_properties(body, off)
filters = []
while off < len(body):
try:
@@ -4609,12 +5273,14 @@ class _WSSession:
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.
+ # MQTT 3.1.1 §3.10.4 (5.0 §3.10.4 is the same rule): 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.
+ reason_codes = []
for topic_filter in filters:
removed = [
sid
@@ -4628,7 +5294,19 @@ class _WSSession:
self._sub_ids[:] = [
sid for sid in self._sub_ids if sid not in removed
]
- await self.send_bytes(_make_unsuback(packet_id))
+ # MQTT 5.0 §3.11.3: the reason code says what this filter's
+ # removal actually did, so it is read off the removal itself
+ # rather than off a snapshot taken before it. A filter repeated
+ # inside one packet is therefore Success once and then No
+ # subscription existed, which is what the session now holds.
+ reason_codes.append(
+ RC5_SUCCESS if removed else RC5_NO_SUBSCRIPTION_EXISTED
+ )
+ if self.protocol_version == MQTT_5:
+ await self.send_bytes(_make_unsuback(packet_id, reason_codes))
+ else:
+ # 3.1.1's UNSUBACK is the packet identifier and nothing else.
+ await self.send_bytes(_make_unsuback(packet_id))
return True
if pkt_type == PKT_PINGREQ:
@@ -4637,6 +5315,11 @@ class _WSSession:
if pkt_type == PKT_DISCONNECT:
self._graceful_disconnect = True
+ if self.protocol_version == MQTT_5 and body:
+ # 0x04 "Disconnect with Will Message" is the one reason code
+ # that asks for the will to be published anyway.
+ if body[0] == 0x04:
+ self._graceful_disconnect = False
return False
return True
@@ -4658,9 +5341,21 @@ class _WSSession:
self._will_message or b"",
qos=self._will_qos,
retain=self._will_retain,
+ properties=self._will_properties,
)
- if not self._clean_session and self._client_id:
- self._preserve_session()
+ if self._client_id:
+ if self._persist_session:
+ self._preserve_session()
+ else:
+ # A connection can resume a stored session and still not
+ # persist one: MQTT 5 splits the two, so Clean Start 0 with no
+ # Session Expiry Interval picks the session up and then ends
+ # it. Without this the entry outlives every such connection,
+ # queueing QoS 1 messages nobody will collect and reporting
+ # session_present=1 to a client that asked for a clean one.
+ _persistent_sessions.pop(
+ (self.account_id, self.region, self._client_id), None
+ )
for sid in self._sub_ids:
await broker_unsubscribe(sid)
self._sub_ids.clear()
@@ -4676,9 +5371,12 @@ class _WSSession:
if existing is not None:
existing.subscriptions = unprefixed_filters
existing.created_at = time.time()
+ existing.expiry_interval = self._session_expiry_interval
else:
_persistent_sessions[session_key] = _PersistentSessionState(
- subscriptions=unprefixed_filters, created_at=time.time()
+ subscriptions=unprefixed_filters,
+ created_at=time.time(),
+ expiry_interval=self._session_expiry_interval,
)
diff --git a/tests/test_iot.py b/tests/test_iot.py
index 67d68358..511c989f 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -1363,15 +1363,20 @@ from ministack.services.iot import (
PKT_DISCONNECT,
PKT_PUBACK,
PKT_PUBLISH,
+ PKT_SUBACK,
PKT_SUBSCRIBE,
PKT_UNSUBACK,
PKT_UNSUBSCRIBE,
+ _decode_properties,
+ _decode_remaining_length,
_encode_remaining_length,
_encode_string,
_InFlightMessage,
_make_puback,
_make_suback,
_persistent_sessions,
+ _property_value,
+ _read_string,
broker_publish,
broker_subscribe,
)
@@ -2607,6 +2612,233 @@ def test_different_accounts_sessions_isolated():
reset()
+# ----------------------------------------------------------------------
+# Broker — MQTT 5.0. These drive the session object directly, so they need
+# neither a running server nor the websockets package; the wire-level suite
+# that needs both lives in test_iot_mqtt5.py.
+# ----------------------------------------------------------------------
+
+PROP_SESSION_EXPIRY_INTERVAL = 0x11
+PROP_MAXIMUM_QOS = 0x24
+PROP_USER_PROPERTY = 0x26
+
+
+def _mqtt_packet(pkt_type, flags, body):
+ """Wrap a packet body in its fixed header."""
+ return bytes([(pkt_type << 4) | flags]) + _encode_remaining_length(len(body)) + body
+
+
+def _build_mqtt5_connect_body(client_id="v5-client", clean_start=True, session_expiry=None):
+ """Build an MQTT 5 CONNECT body: like the 3.1.1 one plus a property block."""
+ props = b""
+ if session_expiry is not None:
+ props = bytes([PROP_SESSION_EXPIRY_INTERVAL]) + struct.pack("!I", session_expiry)
+ body = bytearray()
+ body += _encode_string("MQTT")
+ body.append(5) # Protocol Level
+ body.append(0x02 if clean_start else 0x00) # Clean Start
+ body += struct.pack("!H", 60) # Keep Alive
+ body += _encode_remaining_length(len(props)) + props
+ body += _encode_string(client_id)
+ return bytes(body)
+
+
+def _build_mqtt5_subscribe_body(packet_id, topic, options):
+ """Build an MQTT 5 SUBSCRIBE body: property block, then filter + options."""
+ return (
+ struct.pack("!H", packet_id)
+ + b"\x00"
+ + _encode_string(topic)
+ + bytes([options])
+ )
+
+
+def _build_mqtt5_publish_body(topic, payload, qos=0, packet_id=None, properties=b"\x00"):
+ body = _encode_string(topic)
+ if qos:
+ body += struct.pack("!H", packet_id or 1)
+ return body + properties + payload
+
+
+def _mqtt5_user_property(name, value):
+ """An encoded property block holding one User Property."""
+ body = bytes([PROP_USER_PROPERTY]) + _encode_string(name) + _encode_string(value)
+ return _encode_remaining_length(len(body)) + body
+
+
+def _parse_mqtt5_publish(packet):
+ """Return (topic, payload, properties) from a PUBLISH the broker sent."""
+ qos = (packet[0] >> 1) & 0x03
+ _remaining, off = _decode_remaining_length(packet, 1)
+ topic, off = _read_string(packet, off)
+ if qos:
+ off += 2
+ props, off = _decode_properties(packet, off)
+ return topic, packet[off:], props
+
+
+def test_mqtt5_session_round_trips_over_a_plain_byte_stream():
+ """Version negotiation lives in the session, not in the WebSocket layer.
+
+ The session object is driven here the way a raw TCP listener drives it —
+ bytes appended to its buffer, packets taken off by its own framing — with
+ every packet split at an offset that lands inside the new property fields,
+ which is where a framing mistake would show up first.
+ """
+ reset()
+ topic = "stream/topic"
+
+ async def _run():
+ sent = []
+
+ async def _stream_send(message):
+ if message.get("type") == "websocket.send":
+ sent.append(message["bytes"])
+
+ session = _WSSession(_stream_send, "123456789012")
+
+ async def feed(packet, chunk):
+ for start in range(0, len(packet), chunk):
+ session._buffer.extend(packet[start:start + chunk])
+ while True:
+ parsed = session._take_packet()
+ if parsed is None:
+ break
+ await session.handle_packet(*parsed)
+
+ await feed(
+ _mqtt_packet(PKT_CONNECT, 0, _build_mqtt5_connect_body("stream-client")), 3
+ )
+ await feed(
+ _mqtt_packet(PKT_SUBSCRIBE, 0x02, _build_mqtt5_subscribe_body(1, topic, 0x01)),
+ 5,
+ )
+ await feed(
+ _mqtt_packet(
+ PKT_PUBLISH,
+ 0x02,
+ _build_mqtt5_publish_body(
+ topic, b"over-tcp", qos=1, packet_id=9,
+ properties=_mqtt5_user_property("via", "stream"),
+ ),
+ ),
+ 4,
+ )
+ await session.cleanup()
+ return sent
+
+ sent = asyncio.run(_run())
+ assert len(sent) == 4, "CONNACK, SUBACK, the delivered PUBLISH, then PUBACK"
+ connack, suback, publish, puback = sent
+ assert connack[:2] == bytes([0x20, len(connack) - 2])
+ assert connack[3] == 0x00, "reason code Success"
+ connack_props, _end = _decode_properties(connack, 4)
+ assert _property_value(connack_props, PROP_MAXIMUM_QOS, None) == 1
+ assert suback[0] >> 4 == PKT_SUBACK
+ assert publish[0] >> 4 == PKT_PUBLISH
+ assert (publish[0] >> 1) & 0x03 == 1, "delivered at the granted QoS"
+ delivered_topic, payload, props = _parse_mqtt5_publish(publish)
+ assert (delivered_topic, payload) == (topic, b"over-tcp")
+ assert _property_value(props, PROP_USER_PROPERTY, None) == ("via", "stream")
+ assert puback == bytes([0x40, 0x04, 0x00, 0x09, 0x00, 0x00])
+ reset()
+
+
+def test_mqtt5_session_expiry_is_read_as_an_interval_not_a_flag():
+ """Session Expiry Interval says how long the session lives, not whether.
+
+ The session below asks for 60 seconds, so it is restored a second later
+ and gone a minute later. Treated as a yes/no flag it would instead have
+ fallen back to the module-wide hour and been restored both times.
+ """
+ reset()
+ key = ("123456789012", _TEST_REGION, "expiring")
+ connect = _build_mqtt5_connect_body(
+ "expiring", clean_start=False, session_expiry=60
+ )
+
+ async def _run():
+ send1, _sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+ await session1.handle_packet(PKT_CONNECT, 0, connect)
+ await session1.handle_packet(
+ PKT_SUBSCRIBE, 0x02, _build_mqtt5_subscribe_body(1, "temp/data", 0x01)
+ )
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+
+ assert _persistent_sessions[key].expiry_interval == 60
+
+ send2, sent2 = _mock_send()
+ session2 = _WSSession(send2, "123456789012")
+ await session2.handle_packet(PKT_CONNECT, 0, connect)
+ assert _parse_connack(sent2) == (True, 0), "still inside the interval"
+ await session2.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session2.cleanup()
+
+ # Spend the interval the client asked for, which is still well inside
+ # the module-wide default.
+ _persistent_sessions[key].created_at = time.time() - 61
+
+ send3, sent3 = _mock_send()
+ session3 = _WSSession(send3, "123456789012")
+ await session3.handle_packet(PKT_CONNECT, 0, connect)
+ assert _parse_connack(sent3) == (False, 0), "the interval is spent"
+ await session3.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_mqtt5_resumed_session_without_an_expiry_interval_is_discarded():
+ """Clean Start 0 and no Session Expiry Interval: resume one, leave none.
+
+ MQTT 5 splits resumption from retention, so this connection legitimately
+ picks a stored session up and legitimately must not leave one behind.
+ Nothing used to remove it — the entry outlived every such connection,
+ queueing QoS 1 messages nobody would collect and answering the next
+ CONNECT with session_present=1.
+ """
+ reset()
+ key = ("123456789012", _TEST_REGION, "transient")
+
+ async def _run():
+ # A first connection that does persist, so there is one to resume.
+ send1, _sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+ await session1.handle_packet(
+ PKT_CONNECT,
+ 0,
+ _build_mqtt5_connect_body(
+ "transient", clean_start=False, session_expiry=3600
+ ),
+ )
+ await session1.handle_packet(
+ PKT_SUBSCRIBE, 0x02, _build_mqtt5_subscribe_body(1, "temp/data", 0x01)
+ )
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+ assert key in _persistent_sessions
+
+ resume_only = _build_mqtt5_connect_body("transient", clean_start=False)
+ send2, sent2 = _mock_send()
+ session2 = _WSSession(send2, "123456789012")
+ await session2.handle_packet(PKT_CONNECT, 0, resume_only)
+ assert _parse_connack(sent2) == (True, 0), "Clean Start 0 still resumes"
+ await session2.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session2.cleanup()
+ assert key not in _persistent_sessions
+
+ send3, sent3 = _mock_send()
+ session3 = _WSSession(send3, "123456789012")
+ await session3.handle_packet(PKT_CONNECT, 0, resume_only)
+ assert _parse_connack(sent3) == (False, 0), "and the next client is told so"
+ await session3.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
# ----------------------------------------------------------------------
# Broker — QoS 1 + retransmits
# ----------------------------------------------------------------------
diff --git a/tests/test_iot_mqtt5.py b/tests/test_iot_mqtt5.py
new file mode 100644
index 00000000..4e741e9e
--- /dev/null
+++ b/tests/test_iot_mqtt5.py
@@ -0,0 +1,1023 @@
+"""Integration tests for MQTT 5.0 support in the embedded IoT broker.
+
+The broker negotiates its wire format from the CONNECT packet's protocol
+level, so these tests drive it with hand-built packets of both versions over
+the MQTT-over-WebSocket endpoint: a 5.0 client must get property blocks,
+subscription options and reason codes, a 3.1.1 client must keep getting the
+exact bytes it got before, and a message must cross between the two.
+
+No MQTT client library is involved — the packets are assembled here, in the
+same stdlib style as ``test_iot_data.py``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import struct
+import uuid
+from urllib.parse import urlparse
+
+import pytest
+from conftest import patch_endpoint_dns
+
+pytest.importorskip("websockets")
+
+import websockets # noqa: E402
+
+ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+
+MQTT_311 = 4
+MQTT_5 = 5
+
+PKT_CONNACK = 2
+PKT_PUBLISH = 3
+PKT_PUBACK = 4
+PKT_SUBACK = 9
+PKT_UNSUBACK = 11
+PKT_DISCONNECT = 14
+
+RC5_MALFORMED_PACKET = 0x81
+
+SUB_OPT_NO_LOCAL = 0x04
+SUB_OPT_RETAIN_AS_PUBLISHED = 0x08
+SUB_OPT_RETAIN_HANDLING_IF_NEW = 0x10
+SUB_OPT_RETAIN_HANDLING_NEVER = 0x20
+
+PROP_PAYLOAD_FORMAT_INDICATOR = 0x01
+PROP_CONTENT_TYPE = 0x03
+PROP_RESPONSE_TOPIC = 0x08
+PROP_CORRELATION_DATA = 0x09
+PROP_SESSION_EXPIRY_INTERVAL = 0x11
+PROP_ASSIGNED_CLIENT_IDENTIFIER = 0x12
+PROP_TOPIC_ALIAS_MAXIMUM = 0x22
+PROP_MAXIMUM_QOS = 0x24
+PROP_RETAIN_AVAILABLE = 0x25
+PROP_USER_PROPERTY = 0x26
+PROP_SHARED_SUBSCRIPTION_AVAILABLE = 0x2A
+
+
+def _unique(prefix: str) -> str:
+ return f"{prefix}-{uuid.uuid4().hex[:8]}"
+
+
+def _ws_url(region: str = "us-east-1") -> str:
+ parsed = urlparse(ENDPOINT)
+ host = parsed.hostname or "localhost"
+ port = parsed.port or 4566
+ return f"ws://prefix-ats.iot.{region}.{host}:{port}/mqtt"
+
+
+# ---------------------------------------------------------------------------
+# Minimal MQTT 3.1.1 / 5.0 codec for the test client
+# ---------------------------------------------------------------------------
+
+
+def _enc_remaining(n: int) -> bytes:
+ out = bytearray()
+ while True:
+ b = n & 0x7F
+ n >>= 7
+ if n > 0:
+ b |= 0x80
+ out.append(b)
+ if n == 0:
+ return bytes(out)
+
+
+def _dec_remaining(buf: bytes, off: int) -> tuple[int, int]:
+ multiplier = 1
+ value = 0
+ while True:
+ b = buf[off]
+ off += 1
+ value += (b & 0x7F) * multiplier
+ if b & 0x80 == 0:
+ return value, off
+ multiplier *= 128
+
+
+def _enc_str(s: str) -> bytes:
+ raw = s.encode("utf-8")
+ return struct.pack("!H", len(raw)) + raw
+
+
+def _dec_str(buf: bytes, off: int) -> tuple[str, int]:
+ n = struct.unpack_from("!H", buf, off)[0]
+ off += 2
+ return buf[off:off + n].decode("utf-8"), off + n
+
+
+def _enc_props(props: list[tuple[int, object]]) -> bytes:
+ """Encode a property block, length prefix included."""
+ body = bytearray()
+ for ident, value in props:
+ body.append(ident)
+ if ident in (PROP_PAYLOAD_FORMAT_INDICATOR,):
+ 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,):
+ 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]
+ elif ident == PROP_USER_PROPERTY:
+ name, pair_value = value # type: ignore[misc]
+ body += _enc_str(name) + _enc_str(pair_value)
+ else:
+ body += _enc_str(str(value))
+ return _enc_remaining(len(body)) + bytes(body)
+
+
+def _dec_props(buf: bytes, off: int) -> tuple[list[tuple[int, object]], int]:
+ """Decode a property block, covering every property the broker emits."""
+ length, off = _dec_remaining(buf, off)
+ end = off + length
+ props: list[tuple[int, object]] = []
+ while off < end:
+ ident = buf[off]
+ off += 1
+ if ident in (0x01, 0x17, 0x19, 0x24, 0x25, 0x28, 0x29, 0x2A):
+ props.append((ident, buf[off]))
+ off += 1
+ elif ident in (0x13, 0x21, 0x22, 0x23):
+ props.append((ident, struct.unpack_from("!H", buf, off)[0]))
+ off += 2
+ elif ident in (0x02, 0x11, 0x18, 0x27):
+ props.append((ident, struct.unpack_from("!I", buf, off)[0]))
+ off += 4
+ elif ident in (0x09, 0x16):
+ n = struct.unpack_from("!H", buf, off)[0]
+ off += 2
+ props.append((ident, buf[off:off + n]))
+ off += n
+ elif ident == PROP_USER_PROPERTY:
+ name, off = _dec_str(buf, off)
+ value, off = _dec_str(buf, off)
+ props.append((ident, (name, value)))
+ else:
+ value, off = _dec_str(buf, off)
+ props.append((ident, value))
+ return props, end
+
+
+def _prop(props: list[tuple[int, object]], ident: int, default: object = None) -> object:
+ for prop_id, value in props:
+ if prop_id == ident:
+ return value
+ return default
+
+
+def _make_connect(
+ client_id: str,
+ protocol_level: int = MQTT_311,
+ clean_start: bool = True,
+ properties: list[tuple[int, object]] | None = None,
+ protocol_name: str = "MQTT",
+ raw_properties: bytes | None = None,
+) -> bytes:
+ body = (
+ _enc_str(protocol_name)
+ + bytes([protocol_level])
+ + bytes([0x02 if clean_start else 0x00])
+ + struct.pack("!H", 60)
+ )
+ if protocol_level == MQTT_5:
+ body += raw_properties if raw_properties is not None else _enc_props(properties or [])
+ body += _enc_str(client_id)
+ return bytes([0x10]) + _enc_remaining(len(body)) + body
+
+
+def _make_subscribe(
+ packet_id: int,
+ topic: str,
+ qos: int = 0,
+ protocol_level: int = MQTT_311,
+ options: int | None = None,
+) -> bytes:
+ body = struct.pack("!H", packet_id)
+ if protocol_level == MQTT_5:
+ body += _enc_props([])
+ body += _enc_str(topic) + bytes([qos if options is None else options])
+ return bytes([0x82]) + _enc_remaining(len(body)) + body
+
+
+def _make_unsubscribe(
+ packet_id: int, topics: list[str], protocol_level: int = MQTT_311
+) -> bytes:
+ body = struct.pack("!H", packet_id)
+ if protocol_level == MQTT_5:
+ body += _enc_props([])
+ body += b"".join(_enc_str(topic) for topic in topics)
+ return bytes([0xA2]) + _enc_remaining(len(body)) + body
+
+
+def _make_publish(
+ topic: str,
+ payload: bytes,
+ qos: int = 0,
+ packet_id: int | None = None,
+ protocol_level: int = MQTT_311,
+ properties: list[tuple[int, object]] | None = None,
+ retain: bool = False,
+ raw_properties: bytes | None = None,
+) -> bytes:
+ """Build a PUBLISH. ``raw_properties`` replaces the encoded property block
+ verbatim, which is how the malformed-packet tests get a block the encoder
+ would never produce."""
+ body = _enc_str(topic)
+ if qos > 0:
+ body += struct.pack("!H", packet_id or 1)
+ if protocol_level == MQTT_5:
+ body += raw_properties if raw_properties is not None else _enc_props(properties or [])
+ body += payload
+ fixed = 0x30 | (qos << 1) | (0x01 if retain else 0)
+ return bytes([fixed]) + _enc_remaining(len(body)) + body
+
+
+def _make_disconnect(protocol_level: int = MQTT_311, reason_code: int = 0x00) -> bytes:
+ if protocol_level == MQTT_5:
+ body = bytes([reason_code]) + _enc_props([])
+ return bytes([0xE0]) + _enc_remaining(len(body)) + body
+ return bytes([0xE0, 0x00])
+
+
+def _parse_publish(body: bytes, protocol_level: int, qos: int = 0) -> tuple[str, bytes, list]:
+ topic, off = _dec_str(body, 0)
+ if qos > 0:
+ off += 2
+ props: list[tuple[int, object]] = []
+ if protocol_level == MQTT_5:
+ props, off = _dec_props(body, off)
+ return topic, body[off:], props
+
+
+class _Client:
+ """One MQTT connection over the broker's WebSocket endpoint."""
+
+ def __init__(self, ws, protocol_level: int):
+ self._ws = ws
+ self.protocol_level = protocol_level
+ self._buffer = bytearray()
+
+ async def send(self, packet: bytes) -> None:
+ await self._ws.send(packet)
+
+ async def packet(self, timeout: float = 5.0) -> tuple[int, int, bytes]:
+ """Return the next (type, flags, body); raises on timeout."""
+ while True:
+ parsed = self._take()
+ if parsed is not None:
+ return parsed
+ frame = await asyncio.wait_for(self._ws.recv(), timeout=timeout)
+ if isinstance(frame, str):
+ frame = frame.encode("latin-1")
+ self._buffer.extend(frame)
+
+ def _take(self) -> tuple[int, int, bytes] | None:
+ if len(self._buffer) < 2:
+ return None
+ remaining, header_end = _dec_remaining(bytes(self._buffer), 1)
+ total = header_end + remaining
+ if len(self._buffer) < total:
+ return None
+ first = self._buffer[0]
+ body = bytes(self._buffer[header_end:total])
+ del self._buffer[:total]
+ return (first >> 4) & 0x0F, first & 0x0F, body
+
+ async def await_packet(self, pkt_type: int, timeout: float = 5.0) -> tuple[int, bytes]:
+ """Skip packets until ``pkt_type`` arrives (a retained PUBLISH may
+ precede a SUBACK), returning its (flags, body)."""
+ deadline = asyncio.get_event_loop().time() + timeout
+ while True:
+ left = deadline - asyncio.get_event_loop().time()
+ ptype, flags, body = await self.packet(timeout=max(left, 0.1))
+ if ptype == pkt_type:
+ return flags, body
+
+
+class _connect:
+ """Async context manager yielding a connected ``_Client``."""
+
+ def __init__(self, protocol_level: int = MQTT_311, client_id: str | None = None,
+ region: str = "us-east-1", **connect_kwargs):
+ self._protocol_level = protocol_level
+ self._client_id = _unique("cli") if client_id is None else client_id
+ self._region = region
+ self._connect_kwargs = connect_kwargs
+ self._dns = None
+ self._ws_cm = None
+
+ async def __aenter__(self) -> tuple[_Client, bytes]:
+ self._dns = patch_endpoint_dns()
+ self._dns.__enter__()
+ self._ws_cm = websockets.connect(_ws_url(self._region), subprotocols=["mqtt"])
+ ws = await self._ws_cm.__aenter__()
+ client = _Client(ws, self._protocol_level)
+ await client.send(
+ _make_connect(
+ self._client_id,
+ protocol_level=self._protocol_level,
+ **self._connect_kwargs,
+ )
+ )
+ _flags, connack = await client.await_packet(PKT_CONNACK)
+ return client, connack
+
+ async def __aexit__(self, *exc) -> None:
+ try:
+ await self._ws_cm.__aexit__(*exc)
+ finally:
+ self._dns.__exit__(None, None, None)
+
+
+def _run(coro):
+ return asyncio.run(asyncio.wait_for(coro, timeout=30))
+
+
+# ---------------------------------------------------------------------------
+# Version negotiation
+# ---------------------------------------------------------------------------
+
+
+def test_mqtt5_connect_is_accepted_with_properties():
+ """A 5.0 CONNECT gets a 5.0 CONNACK: reason code 0 plus a property block."""
+
+ async def scenario():
+ async with _connect(MQTT_5) as (_client, connack):
+ return connack
+
+ connack = _run(scenario())
+ assert connack[0] == 0x00, "session present must be clear for a fresh session"
+ assert connack[1] == 0x00, "reason code Success"
+ props, end = _dec_props(connack, 2)
+ assert end == len(connack)
+ assert props, "a 5.0 CONNACK must carry a property block"
+ assert _prop(props, PROP_MAXIMUM_QOS) == 1
+ assert _prop(props, PROP_RETAIN_AVAILABLE) == 1
+ # Features this broker does not implement are advertised as unavailable
+ # rather than left at their permissive defaults.
+ assert _prop(props, PROP_SHARED_SUBSCRIPTION_AVAILABLE) == 0
+ assert _prop(props, PROP_TOPIC_ALIAS_MAXIMUM) == 0
+
+
+def test_mqtt311_connack_is_byte_identical():
+ """The 3.1.1 CONNACK is still exactly the four bytes it always was."""
+
+ async def scenario():
+ async with _connect(MQTT_311) as (client, connack):
+ return bytes([0x20]) + _enc_remaining(len(connack)) + connack
+
+ assert _run(scenario()) == b"\x20\x02\x00\x00"
+
+
+def test_unsupported_protocol_level_is_refused():
+ """Protocol level 3 (MQTT 3.1) gets CONNACK 0x01, not a mis-framed reply."""
+
+ async def scenario():
+ with patch_endpoint_dns():
+ async with websockets.connect(_ws_url(), subprotocols=["mqtt"]) as ws:
+ client = _Client(ws, MQTT_311)
+ await client.send(
+ _make_connect("legacy", protocol_level=3, protocol_name="MQIsdp")
+ )
+ _flags, body = await client.await_packet(PKT_CONNACK)
+ return body
+
+ body = _run(scenario())
+ assert body == b"\x00\x01", "session present 0, return code 0x01"
+
+
+def test_mqtt5_empty_client_id_gets_assigned_identifier():
+ """An empty client id is accepted and the generated one is handed back."""
+
+ async def scenario():
+ async with _connect(MQTT_5, client_id="") as (_client, connack):
+ return connack
+
+ connack = _run(scenario())
+ props, _end = _dec_props(connack, 2)
+ assigned = _prop(props, PROP_ASSIGNED_CLIENT_IDENTIFIER)
+ assert isinstance(assigned, str) and assigned
+
+
+def test_mqtt5_unknown_property_is_ignored():
+ """A property the broker does not model does not derail the CONNECT parse."""
+
+ async def scenario():
+ # 0x7F is not a defined identifier; the parser must skip the rest of
+ # the block and still find the client id behind it.
+ async with _connect(MQTT_5, properties=[(0x7F, "whatever")]) as (_c, connack):
+ return connack
+
+ connack = _run(scenario())
+ assert connack[1] == 0x00
+
+
+# ---------------------------------------------------------------------------
+# Subscribe / publish
+# ---------------------------------------------------------------------------
+
+
+def test_mqtt5_subscribe_options_byte_gets_v5_suback():
+ """The 5.0 options byte is read for its QoS bits; SUBACK carries properties."""
+
+ async def scenario():
+ async with _connect(MQTT_5) as (client, _connack):
+ # QoS 1 in bits 0-1, No Local set in bit 2, Retain Handling 1 in
+ # bits 4-5 — only the QoS bits are modelled.
+ await client.send(
+ _make_subscribe(
+ 1, _unique("opts/topic"), protocol_level=MQTT_5, options=0x15
+ )
+ )
+ _flags, body = await client.await_packet(PKT_SUBACK)
+ return body
+
+ body = _run(scenario())
+ assert struct.unpack_from("!H", body, 0)[0] == 1
+ props, off = _dec_props(body, 2)
+ assert props == []
+ assert body[off:] == bytes([0x01]), "reason code Granted QoS 1"
+
+
+def test_mqtt5_publish_round_trip_forwards_properties():
+ """A 5.0 publisher reaches a 5.0 subscriber, properties included."""
+ topic = _unique("v5/round/trip")
+ payload = b"v5-telemetry"
+ sent_props = [
+ (PROP_PAYLOAD_FORMAT_INDICATOR, 1),
+ (PROP_CONTENT_TYPE, "application/json"),
+ (PROP_RESPONSE_TOPIC, f"{topic}/reply"),
+ (PROP_CORRELATION_DATA, b"\x01\x02\x03"),
+ (PROP_USER_PROPERTY, ("tenant", "acme")),
+ ]
+
+ async def scenario():
+ async with _connect(MQTT_5) as (sub, _c1):
+ await sub.send(_make_subscribe(1, topic, protocol_level=MQTT_5, options=0x00))
+ await sub.await_packet(PKT_SUBACK)
+ async with _connect(MQTT_5) as (pub, _c2):
+ await pub.send(
+ _make_publish(topic, payload, protocol_level=MQTT_5,
+ properties=sent_props)
+ )
+ _flags, body = await sub.await_packet(PKT_PUBLISH)
+ return body
+
+ body = _run(scenario())
+ delivered_topic, delivered_payload, props = _parse_publish(body, MQTT_5)
+ assert delivered_topic == topic
+ assert delivered_payload == payload
+ assert _prop(props, PROP_CONTENT_TYPE) == "application/json"
+ assert _prop(props, PROP_RESPONSE_TOPIC) == f"{topic}/reply"
+ assert _prop(props, PROP_CORRELATION_DATA) == b"\x01\x02\x03"
+ assert _prop(props, PROP_USER_PROPERTY) == ("tenant", "acme")
+
+
+def test_mqtt311_publisher_reaches_mqtt5_subscriber():
+ """Cross-version delivery: the 5.0 subscriber gets an empty property block."""
+ topic = _unique("cross/311to5")
+
+ async def scenario():
+ async with _connect(MQTT_5) as (sub, _c1):
+ await sub.send(_make_subscribe(1, topic, protocol_level=MQTT_5, options=0x00))
+ await sub.await_packet(PKT_SUBACK)
+ async with _connect(MQTT_311) as (pub, _c2):
+ await pub.send(_make_publish(topic, b"from-311"))
+ _flags, body = await sub.await_packet(PKT_PUBLISH)
+ return body
+
+ body = _run(scenario())
+ delivered_topic, payload, props = _parse_publish(body, MQTT_5)
+ assert delivered_topic == topic
+ assert payload == b"from-311"
+ assert props == []
+
+
+def test_mqtt5_publisher_reaches_mqtt311_subscriber():
+ """The 3.1.1 subscriber sees no property field at all — its packet is unchanged."""
+ topic = _unique("cross/5to311")
+
+ async def scenario():
+ async with _connect(MQTT_311) as (sub, _c1):
+ await sub.send(_make_subscribe(1, topic, qos=0))
+ await sub.await_packet(PKT_SUBACK)
+ async with _connect(MQTT_5) as (pub, _c2):
+ await pub.send(
+ _make_publish(
+ topic, b"from-v5", protocol_level=MQTT_5,
+ properties=[(PROP_USER_PROPERTY, ("tenant", "acme"))],
+ )
+ )
+ _flags, body = await sub.await_packet(PKT_PUBLISH)
+ return body
+
+ body = _run(scenario())
+ delivered_topic, payload, _props = _parse_publish(body, MQTT_311)
+ assert delivered_topic == topic
+ assert payload == b"from-v5", "no property block may be spliced in front"
+
+
+def test_mqtt5_qos1_puback_carries_reason_code():
+ """QoS 1 PUBACK reports Success with a subscriber, No matching subscribers without."""
+ topic = _unique("v5/qos1")
+
+ async def scenario():
+ async with _connect(MQTT_5) as (pub, _c1):
+ await pub.send(
+ _make_publish(topic, b"nobody-home", qos=1, packet_id=7,
+ protocol_level=MQTT_5)
+ )
+ _flags, lonely = await pub.await_packet(PKT_PUBACK)
+ async with _connect(MQTT_5) as (sub, _c2):
+ await sub.send(
+ _make_subscribe(1, topic, protocol_level=MQTT_5, options=0x01)
+ )
+ await sub.await_packet(PKT_SUBACK)
+ await pub.send(
+ _make_publish(topic, b"delivered", qos=1, packet_id=8,
+ protocol_level=MQTT_5)
+ )
+ _flags, matched = await pub.await_packet(PKT_PUBACK)
+ return lonely, matched
+
+ lonely, matched = _run(scenario())
+ assert lonely == b"\x00\x07\x10\x00", "packet id 7, No matching subscribers, no properties"
+ assert matched == b"\x00\x08\x00\x00", "packet id 8, Success, no properties"
+
+
+def test_mqtt311_qos1_puback_stays_two_bytes():
+ """The 3.1.1 PUBACK gains neither a reason code nor properties."""
+ topic = _unique("v311/qos1")
+
+ async def scenario():
+ async with _connect(MQTT_311) as (pub, _c1):
+ await pub.send(_make_publish(topic, b"x", qos=1, packet_id=3))
+ _flags, body = await pub.await_packet(PKT_PUBACK)
+ return body
+
+ assert _run(scenario()) == b"\x00\x03"
+
+
+def test_mqtt5_unsuback_reason_codes_follow_the_actual_removal():
+ """A 5.0 UNSUBACK reports one reason code per topic filter, and each one is
+ read off what the removal actually did: Success (0x00) for a filter the
+ session held, No subscription existed (0x11) for one it never had.
+
+ The same scenario pins the removal itself, because the reason codes alone
+ cannot tell an honest per-filter unsubscribe from an unsubscribe-everything
+ loop that answers per filter. The filter the packet does not name has to
+ keep delivering — the 3.1.1 rule of ``test_unsubscribe_removes_only_the_
+ named_filters`` in ``test_iot.py``, seen here through the 5.0 path.
+ """
+ kept = _unique("v5/unsub/kept")
+ dropped = _unique("v5/unsub/dropped")
+ unknown = _unique("v5/unsub/never")
+
+ async def scenario():
+ async with _connect(MQTT_5) as (sub, _c1):
+ for packet_id, topic in enumerate((kept, dropped), start=1):
+ await sub.send(
+ _make_subscribe(packet_id, topic, protocol_level=MQTT_5, options=0x00)
+ )
+ await sub.await_packet(PKT_SUBACK)
+
+ await sub.send(
+ _make_unsubscribe(3, [dropped, unknown], protocol_level=MQTT_5)
+ )
+ _flags, unsuback = await sub.await_packet(PKT_UNSUBACK)
+
+ async with _connect(MQTT_5) as (pub, _c2):
+ # The unsubscribed topic goes first, so a delivery that should
+ # not happen is the *first* PUBLISH to arrive rather than a
+ # timing question.
+ await pub.send(
+ _make_publish(dropped, b"should-not-arrive", protocol_level=MQTT_5)
+ )
+ await pub.send(
+ _make_publish(kept, b"should-arrive", protocol_level=MQTT_5)
+ )
+ _flags, delivered = await sub.await_packet(PKT_PUBLISH)
+ try:
+ extra = await sub.packet(timeout=0.5)
+ except (asyncio.TimeoutError, TimeoutError):
+ extra = None
+ return unsuback, delivered, extra
+
+ unsuback, delivered, extra = _run(scenario())
+
+ assert struct.unpack_from("!H", unsuback, 0)[0] == 3
+ props, off = _dec_props(unsuback, 2)
+ assert props == []
+ assert unsuback[off:] == bytes([0x00, 0x11]), (
+ "Success for the held filter, No subscription existed for the unknown one"
+ )
+
+ delivered_topic, payload, _props = _parse_publish(delivered, MQTT_5)
+ assert (delivered_topic, payload) == (kept, b"should-arrive")
+ assert extra is None, "no further packet — the unsubscribed topic stays silent"
+
+
+def test_mqtt311_unsuback_stays_two_bytes():
+ """The 3.1.1 UNSUBACK gains neither a property block nor reason codes."""
+ topic = _unique("v311/unsub")
+
+ async def scenario():
+ async with _connect(MQTT_311) as (client, _connack):
+ await client.send(_make_subscribe(1, topic, qos=0))
+ await client.await_packet(PKT_SUBACK)
+ await client.send(_make_unsubscribe(4, [topic, _unique("v311/never")]))
+ _flags, body = await client.await_packet(PKT_UNSUBACK)
+ return body
+
+ assert _run(scenario()) == b"\x00\x04"
+
+
+def test_mqtt5_disconnect_with_reason_code_closes_cleanly():
+ """A 5.0 DISCONNECT carrying a reason code and properties ends the session."""
+
+ async def scenario():
+ async with _connect(MQTT_5) as (client, _connack):
+ await client.send(_make_disconnect(MQTT_5, reason_code=0x00))
+ try:
+ await client.packet(timeout=5.0)
+ except websockets.exceptions.ConnectionClosed:
+ return "closed"
+ return "still open"
+
+ assert _run(scenario()) == "closed"
+
+
+# ---------------------------------------------------------------------------
+# Malformed packets
+# ---------------------------------------------------------------------------
+
+
+def test_mqtt5_property_value_running_past_the_block_is_refused():
+ """A property whose value is missing gets a reason code, not a bleed-over.
+
+ The block below declares one byte and holds only the Payload Format
+ Indicator's identifier: its value would have to come from the byte after
+ the block, which is the first byte of the payload. Reading it there costs
+ nothing at parse time and shows up as a subscriber receiving a property
+ the publisher never sent, on a payload with its first byte eaten — so the
+ subscriber here is what proves the block boundary held.
+ """
+ topic = _unique("malformed/bleed")
+
+ async def scenario():
+ async with _connect(MQTT_5) as (subscriber, _connack):
+ await subscriber.send(_make_subscribe(1, topic, protocol_level=MQTT_5))
+ await subscriber.await_packet(PKT_SUBACK)
+
+ async with _connect(MQTT_5) as (publisher, _c2):
+ await publisher.send(
+ _make_publish(
+ topic, b"bleed", protocol_level=MQTT_5,
+ raw_properties=bytes([0x01, PROP_PAYLOAD_FORMAT_INDICATOR]),
+ )
+ )
+ pkt_type, _flags, disconnect = await publisher.packet(timeout=5.0)
+
+ async with _connect(MQTT_5) as (other, _c3):
+ await other.send(
+ _make_publish(topic, b"clean", protocol_level=MQTT_5)
+ )
+ _flags, delivered = await subscriber.await_packet(PKT_PUBLISH)
+
+ return pkt_type, disconnect, delivered
+
+ pkt_type, disconnect, delivered = _run(scenario())
+ assert pkt_type == PKT_DISCONNECT, "a v5 client is told why it is being cut off"
+ assert disconnect[0] == RC5_MALFORMED_PACKET
+ delivered_topic, payload, props = _parse_publish(delivered, MQTT_5)
+ assert (delivered_topic, payload) == (topic, b"clean"), (
+ "the malformed publish must not have been delivered at all"
+ )
+ assert _prop(props, PROP_PAYLOAD_FORMAT_INDICATOR) is None
+
+
+def test_mqtt5_property_block_truncated_at_the_packet_end_is_refused():
+ """The same truncation with nothing after it: the read runs off the packet.
+
+ With no payload behind the block there is no byte to borrow, so this is
+ the shape that used to raise out of the parser and take the connection
+ down with no packet sent — the client saw only a closed socket.
+ """
+ topic = _unique("malformed/end")
+
+ async def scenario():
+ async with _connect(MQTT_5) as (client, _connack):
+ await client.send(
+ _make_publish(
+ topic, b"", protocol_level=MQTT_5,
+ raw_properties=bytes([0x01, PROP_PAYLOAD_FORMAT_INDICATOR]),
+ )
+ )
+ pkt_type, _flags, body = await client.packet(timeout=5.0)
+ return pkt_type, body
+
+ pkt_type, body = _run(scenario())
+ assert pkt_type == PKT_DISCONNECT
+ assert body[0] == RC5_MALFORMED_PACKET
+
+
+def test_mqtt5_malformed_connect_is_refused_with_a_connack_reason_code():
+ """Before a CONNACK there is no DISCONNECT to send, so the CONNACK carries it.
+
+ MQTT 5 §4.13.1 lets the server answer a malformed CONNECT with a CONNACK
+ reason code and close; a DISCONNECT would be the one packet the client
+ cannot be sent yet.
+ """
+
+ async def scenario():
+ with patch_endpoint_dns():
+ async with websockets.connect(_ws_url(), subprotocols=["mqtt"]) as ws:
+ client = _Client(ws, MQTT_5)
+ await client.send(
+ _make_connect(
+ "malformed-connect", protocol_level=MQTT_5,
+ # Session Expiry Interval is four bytes wide; two are
+ # given, and the client id follows the block.
+ raw_properties=bytes(
+ [0x03, PROP_SESSION_EXPIRY_INTERVAL, 0x00, 0x00]
+ ),
+ )
+ )
+ pkt_type, _flags, body = await client.packet(timeout=5.0)
+ return pkt_type, body
+
+ pkt_type, body = _run(scenario())
+ assert pkt_type == PKT_CONNACK
+ assert body[0] == 0x00, "session present clear"
+ assert body[1] == RC5_MALFORMED_PACKET
+
+
+def test_mqtt5_property_block_longer_than_127_bytes_round_trips():
+ """A block over 127 bytes needs the two-byte varint length on both sides."""
+ topic = _unique("props/varint")
+ user_properties = [
+ (PROP_USER_PROPERTY, (f"key-{i:02d}", f"value-{i:02d}")) for i in range(10)
+ ]
+
+ async def scenario():
+ async with _connect(MQTT_5) as (subscriber, _connack):
+ await subscriber.send(_make_subscribe(1, topic, protocol_level=MQTT_5))
+ await subscriber.await_packet(PKT_SUBACK)
+ async with _connect(MQTT_5) as (publisher, _c2):
+ sent = _make_publish(
+ topic, b"long-props", protocol_level=MQTT_5,
+ properties=user_properties,
+ )
+ await publisher.send(sent)
+ _flags, delivered = await subscriber.await_packet(PKT_PUBLISH)
+ return delivered
+
+ delivered = _run(scenario())
+ _topic, off = _dec_str(delivered, 0)
+ assert delivered[off] & 0x80, (
+ "the property length must have spilled into a second varint byte"
+ )
+ delivered_topic, payload, props = _parse_publish(delivered, MQTT_5)
+ assert (delivered_topic, payload) == (topic, b"long-props")
+ assert [p for p in props if p[0] == PROP_USER_PROPERTY] == user_properties
+
+
+# ---------------------------------------------------------------------------
+# Subscription options
+# ---------------------------------------------------------------------------
+
+
+def test_mqtt5_no_local_withholds_a_publisher_its_own_message():
+ """No Local is defined against the publishing client, not the connection."""
+ topic = _unique("options/nolocal")
+
+ async def scenario():
+ async with _connect(MQTT_5) as (subscriber, _connack):
+ await subscriber.send(
+ _make_subscribe(1, topic, protocol_level=MQTT_5,
+ options=SUB_OPT_NO_LOCAL)
+ )
+ await subscriber.await_packet(PKT_SUBACK)
+
+ await subscriber.send(
+ _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)
+
+ 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
+
+ (pkt_type, _flags, puback), delivered = _run(scenario())
+ assert pkt_type == PKT_PUBACK, "the publisher's own message must not come back"
+ assert puback == b"\x00\x07\x10\x00", (
+ "No matching subscribers: the only subscription was the publisher's own"
+ )
+ assert _parse_publish(delivered, MQTT_5)[1] == b"theirs"
+
+
+def test_mqtt5_retain_as_published_keeps_the_publishers_retain_flag():
+ """Two subscribers, one option apart, see different RETAIN bits."""
+ topic = _unique("options/rap")
+
+ async def scenario():
+ async with _connect(MQTT_5) as (keeps_flag, _c1):
+ await keeps_flag.send(
+ _make_subscribe(1, topic, protocol_level=MQTT_5,
+ options=SUB_OPT_RETAIN_AS_PUBLISHED)
+ )
+ await keeps_flag.await_packet(PKT_SUBACK)
+ async with _connect(MQTT_5) as (clears_flag, _c2):
+ await clears_flag.send(_make_subscribe(1, topic, protocol_level=MQTT_5))
+ await clears_flag.await_packet(PKT_SUBACK)
+ async with _connect(MQTT_5) as (publisher, _c3):
+ await publisher.send(
+ _make_publish(topic, b"sticky", protocol_level=MQTT_5,
+ retain=True)
+ )
+ kept, _body = await keeps_flag.await_packet(PKT_PUBLISH)
+ cleared, _body2 = await clears_flag.await_packet(PKT_PUBLISH)
+ return kept, cleared
+
+ kept, cleared = _run(scenario())
+ assert kept & 0x01 == 1, "Retain As Published forwards the flag as sent"
+ assert cleared & 0x01 == 0, "without it the flag is cleared"
+
+
+def test_mqtt5_retain_handling_2_suppresses_the_retained_replay():
+ """Retain Handling 2 means: subscribe me, but keep the retained message."""
+ topic = _unique("options/rh2")
+
+ async def scenario():
+ async with _connect(MQTT_5) as (publisher, _c1):
+ await publisher.send(
+ _make_publish(topic, b"stored", qos=1, packet_id=3,
+ protocol_level=MQTT_5, retain=True)
+ )
+ await publisher.await_packet(PKT_PUBACK)
+ async with _connect(MQTT_5) as (subscriber, _c2):
+ await subscriber.send(
+ _make_subscribe(1, topic, protocol_level=MQTT_5,
+ options=SUB_OPT_RETAIN_HANDLING_NEVER)
+ )
+ pkt_type, _flags, _body = await subscriber.packet(timeout=5.0)
+ return pkt_type
+
+ assert _run(scenario()) == PKT_SUBACK, (
+ "the retained PUBLISH precedes the SUBACK, so a SUBACK first means none was sent"
+ )
+
+
+def test_mqtt5_retain_handling_1_replays_only_for_a_new_subscription():
+ """Retain Handling 1 replays on the first SUBSCRIBE and not on a repeat."""
+ topic = _unique("options/rh1")
+
+ async def scenario():
+ async with _connect(MQTT_5) as (publisher, _c1):
+ await publisher.send(
+ _make_publish(topic, b"stored", qos=1, packet_id=3,
+ protocol_level=MQTT_5, retain=True)
+ )
+ await publisher.await_packet(PKT_PUBACK)
+ async with _connect(MQTT_5) as (subscriber, _c2):
+ options = SUB_OPT_RETAIN_HANDLING_IF_NEW
+ await subscriber.send(
+ _make_subscribe(1, topic, protocol_level=MQTT_5, options=options)
+ )
+ first = await subscriber.packet(timeout=5.0)
+ await subscriber.await_packet(PKT_SUBACK)
+ await subscriber.send(
+ _make_subscribe(2, topic, protocol_level=MQTT_5, options=options)
+ )
+ repeat = await subscriber.packet(timeout=5.0)
+ return first, repeat
+
+ (first_type, first_flags, first_body), (repeat_type, _f, _b) = _run(scenario())
+ assert first_type == PKT_PUBLISH
+ # A retained message keeps the QoS it was published at, so the packet
+ # identifier's two bytes are there to be stepped over.
+ first_qos = (first_flags >> 1) & 0x03
+ assert _parse_publish(first_body, MQTT_5, qos=first_qos)[1] == b"stored"
+ assert first_flags & 0x01 == 1, (
+ "a message sent because a subscription was established carries RETAIN 1"
+ )
+ assert repeat_type == PKT_SUBACK, "the subscription already existed"
+
+
+# ---------------------------------------------------------------------------
+# Will (Last Will and Testament) with MQTT 5 properties
+# ---------------------------------------------------------------------------
+
+
+def _make_connect_with_will(
+ client_id: str,
+ will_topic: str,
+ will_payload: bytes,
+ will_properties: list[tuple[int, object]] | None = None,
+ raw_will_properties: bytes | None = None,
+ will_qos: int = 0,
+ will_retain: bool = False,
+) -> bytes:
+ """A v5 CONNECT carrying a will.
+
+ Kept separate from ``_make_connect`` so the will-free packets the rest of
+ the file builds stay byte-identical. In a v5 CONNECT the will *property
+ block precedes the will topic*, so a defect in its parsing corrupts the
+ offset of everything after it — which is exactly what these tests pin.
+ """
+ flags = 0x02 | 0x04 | (will_qos << 3) | (0x20 if will_retain else 0)
+ body = (
+ _enc_str("MQTT")
+ + bytes([MQTT_5])
+ + bytes([flags])
+ + struct.pack("!H", 60)
+ + _enc_props([]) # connect properties
+ + _enc_str(client_id)
+ )
+ body += (
+ raw_will_properties
+ if raw_will_properties is not None
+ else _enc_props(will_properties or [])
+ )
+ body += _enc_str(will_topic)
+ body += struct.pack("!H", len(will_payload)) + will_payload
+ return bytes([0x10]) + _enc_remaining(len(body)) + body
+
+
+def test_mqtt5_will_with_properties_fires_on_transport_drop():
+ """An ungraceful drop publishes the will, forwardable properties intact."""
+ topic = f"wills/{_unique('t')}"
+
+ async def scenario():
+ async with _connect(MQTT_5) as (sub, _connack):
+ await sub.send(_make_subscribe(1, topic, protocol_level=MQTT_5))
+ await sub.await_packet(PKT_SUBACK)
+
+ with patch_endpoint_dns():
+ ws = await websockets.connect(_ws_url(), subprotocols=["mqtt"])
+ doomed = _Client(ws, MQTT_5)
+ await doomed.send(
+ _make_connect_with_will(
+ _unique("doomed"),
+ topic,
+ b"gone",
+ will_properties=[
+ (PROP_CONTENT_TYPE, "text/plain"),
+ (PROP_USER_PROPERTY, ("cause", "test")),
+ ],
+ )
+ )
+ _flags, connack = await doomed.await_packet(PKT_CONNACK)
+ assert connack[1] == 0x00, "will CONNECT must be accepted"
+ # Close the transport without an MQTT DISCONNECT: ungraceful,
+ # so the will must go out.
+ await ws.close()
+
+ _flags, body = await sub.await_packet(PKT_PUBLISH, timeout=10)
+ return _parse_publish(body, MQTT_5)
+
+ got_topic, payload, props = _run(scenario())
+ assert got_topic == topic
+ assert payload == b"gone"
+ assert _prop(props, PROP_CONTENT_TYPE) == "text/plain"
+ user_props = [value for ident, value in props if ident == PROP_USER_PROPERTY]
+ assert ("cause", "test") in user_props
+
+
+def test_mqtt5_malformed_will_properties_answer_connack_0x81():
+ """A truncated will-property block is a malformed CONNECT.
+
+ The block below claims four bytes but holds a Content Type whose UTF-8
+ length points past the end — un-flagged, the parser would read the will
+ topic out of the middle of a property. v5 answers CONNACK ``0x81``.
+ """
+
+ async def scenario():
+ with patch_endpoint_dns():
+ async with websockets.connect(_ws_url(), subprotocols=["mqtt"]) as ws:
+ client = _Client(ws, MQTT_5)
+ await client.send(
+ _make_connect_with_will(
+ _unique("mal"),
+ "wills/never",
+ b"x",
+ raw_will_properties=bytes(
+ [0x04, PROP_CONTENT_TYPE, 0x00, 0x09, 0x41]
+ ),
+ )
+ )
+ pkt_type, _flags, body = await client.packet(timeout=5.0)
+ return pkt_type, body
+
+ pkt_type, body = _run(scenario())
+ assert pkt_type == PKT_CONNACK
+ assert body[1] == RC5_MALFORMED_PACKET