Skip to main content

marionette/
lib.rs

1//! Minimal scripted MQTT v5 "broker" for protocol edge cases that a real
2//! broker will never produce. Examples are unsolicited packets, missing
3//! CONNACKs, sockets that stop reading and unusual CONNACK properties.
4//!
5//! This is not a conforming broker: each test scripts the exact packets to
6//! read and write. Packets are encoded/decoded with `finmqtt-core`, so tests
7//! can construct and inspect them with the regular packet types.
8
9#![allow(
10    clippy::expect_used,
11    clippy::panic,
12    reason = "this is a test helper crate"
13)]
14
15use std::io::{self, ErrorKind};
16use std::time::Duration;
17
18use finmqtt_core::codec::{GrowBuffer, PacketReader};
19use finmqtt_core::packet::{Ack, Body, Connack, Measured, Packet, ReasonCode, Suback};
20use finmqtt_core::property::{AckProperties, ConnackPropertiesBuf, Property, SubackProperties};
21use finmqtt_core::wire::{FixedHeader, PacketId, PacketType};
22use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
23use tokio::net::{TcpListener, TcpStream};
24use tokio::time::timeout;
25
26/// Default deadline for blocking-style helpers ([`Broker::accept`],
27/// [`Conn::read_packet`]).
28const DEADLINE: Duration = Duration::from_secs(10);
29
30/// A TCP listener that hands out scripted MQTT connections.
31#[derive(Debug)]
32pub struct Broker {
33    listener: TcpListener,
34}
35
36impl Broker {
37    /// Binds to an ephemeral IPv6 port.
38    ///
39    /// Listening on `[::]` accepts IPv6 clients and, on the usual dual-stack
40    /// configuration, IPv4-mapped clients (e.g. `127.0.0.1`) too. On a rare
41    /// IPv6-only host, clients simply connect over IPv6.
42    ///
43    /// # Panics
44    ///
45    /// Panics if binding fails.
46    pub async fn bind() -> Self {
47        let listener = TcpListener::bind("[::]:0")
48            .await
49            .expect("failed to bind fake broker");
50        Self { listener }
51    }
52
53    /// The TCP port the fake broker is listening on.
54    ///
55    /// # Panics
56    ///
57    /// Panics if the listener's local address cannot be queried.
58    #[must_use]
59    pub fn port(&self) -> u16 {
60        self.listener
61            .local_addr()
62            .expect("failed to get local addr")
63            .port()
64    }
65
66    /// The loopback host a client should connect to, matching the bound
67    /// address family. Pair it with [`port`](Self::port) so test code never
68    /// has to assume IPv4 or dual-stack.
69    #[must_use]
70    pub fn host(&self) -> &'static str {
71        if self
72            .listener
73            .local_addr()
74            .map_or(true, |addr| addr.is_ipv6())
75        {
76            "::1"
77        } else {
78            "127.0.0.1"
79        }
80    }
81
82    /// Accepts the next client connection.
83    ///
84    /// # Panics
85    ///
86    /// Panics if no client connects within 10 s.
87    pub async fn accept(&self) -> Conn {
88        self.try_accept(DEADLINE)
89            .await
90            .expect("timed out waiting for a client connection")
91    }
92
93    /// Accepts the next client connection, returning `None` if no client
94    /// connects within `dur`.
95    ///
96    /// # Panics
97    ///
98    /// Panics on listener I/O errors.
99    pub async fn try_accept(&self, dur: Duration) -> Option<Conn> {
100        match timeout(dur, self.listener.accept()).await {
101            Ok(Ok((stream, _addr))) => Some(Conn {
102                stream,
103                reader: PacketReader::try_with_capacity(8 * 1024)
104                    .expect("allocate the read buffer"),
105            }),
106            Ok(Err(e)) => panic!("fake broker accept failed: {e}"),
107            Err(_elapsed) => None,
108        }
109    }
110}
111
112/// One scripted broker-side connection.
113#[derive(Debug)]
114pub struct Conn {
115    stream: TcpStream,
116    reader: PacketReader<GrowBuffer>,
117}
118
119/// A packet received from the client: fixed header plus body bytes.
120///
121/// Use [`RecvPacket::decode`] to view it as a [`Packet`].
122#[derive(Debug)]
123pub struct RecvPacket {
124    /// The fixed header of the packet.
125    pub header: FixedHeader,
126    /// The bytes after the fixed header.
127    pub body: Vec<u8>,
128}
129
130impl RecvPacket {
131    /// Decodes the packet, panicking on malformed data.
132    ///
133    /// # Panics
134    ///
135    /// Panics if the body cannot be decoded for the header's packet type.
136    #[must_use]
137    pub fn decode(&self) -> Packet<'_> {
138        Packet::decode(self.header, &self.body)
139            .unwrap_or_else(|e| panic!("client sent malformed {:?}: {e:?}", self.header))
140    }
141
142    /// The packet type from the fixed header.
143    #[must_use]
144    pub const fn packet_type(&self) -> PacketType {
145        self.header.packet_type
146    }
147}
148
149impl Conn {
150    /// Reads the next packet from the client.
151    ///
152    /// # Panics
153    ///
154    /// Panics if no packet arrives within 10 s or the connection closes.
155    pub async fn read_packet(&mut self) -> RecvPacket {
156        let result = timeout(DEADLINE, self.read_packet_or_eof())
157            .await
158            .expect("timed out waiting for a packet from the client");
159        result.expect("client closed the connection while a packet was expected")
160    }
161
162    /// Reads the next packet, returning `None` on timeout or if the client
163    /// closed the connection cleanly.
164    ///
165    /// # Panics
166    ///
167    /// Panics on I/O errors or if the connection drops mid-packet.
168    pub async fn try_read_packet(&mut self, dur: Duration) -> Option<RecvPacket> {
169        timeout(dur, self.read_packet_or_eof())
170            .await
171            .unwrap_or_default()
172    }
173
174    /// Reads one packet. Returns `None` on a clean EOF before the next packet
175    /// starts.
176    async fn read_packet_or_eof(&mut self) -> Option<RecvPacket> {
177        let mut chunk = [0u8; 1024];
178        loop {
179            match self.reader.peek() {
180                Ok(Some(frame)) => {
181                    let header = frame.header();
182                    let body = self.reader.body(&frame).to_vec();
183                    self.reader.consume(frame);
184                    return Some(RecvPacket { header, body });
185                }
186                Ok(None) => {}
187                Err(e) => panic!("client sent a malformed packet header: {e:?}"),
188            }
189            match self.stream.read(&mut chunk).await {
190                Ok(0) => {
191                    assert!(
192                        self.reader.buffered_len() == 0,
193                        "connection dropped mid packet"
194                    );
195                    return None;
196                }
197                Ok(n) => {
198                    self.reader
199                        .feed(
200                            chunk
201                                .get(..n)
202                                .expect("read returns at most the buffer length"),
203                        )
204                        .expect("fake broker cannot buffer the bytes it read");
205                }
206                Err(e) if e.kind() == ErrorKind::UnexpectedEof => return None,
207                Err(e) => panic!("fake broker read failed: {e}"),
208            }
209        }
210    }
211
212    /// Encodes and writes a packet to the client.
213    ///
214    /// # Panics
215    ///
216    /// Panics if encoding or the socket write fails.
217    pub async fn write_packet<P: Body + Sync + ?Sized>(&mut self, pkt: &P) {
218        let mut buf = Vec::new();
219        Measured::new(pkt)
220            .expect("packet too large to encode")
221            .encode(&mut buf)
222            .expect("failed to encode packet");
223        self.write_raw(&buf).await;
224    }
225
226    /// Writes raw bytes to the client, bypassing packet encoding.
227    ///
228    /// Useful for hand-crafted or deliberately malformed wire data, e.g. a
229    /// fixed header that announces a body which is never sent.
230    ///
231    /// # Panics
232    ///
233    /// Panics if the socket write fails.
234    pub async fn write_raw(&mut self, bytes: &[u8]) {
235        self.try_write_raw(bytes)
236            .await
237            .expect("fake broker write failed");
238    }
239
240    /// Writes raw bytes to the client, returning any socket error instead of
241    /// panicking.
242    ///
243    /// Use this when the client is expected to apply backpressure or close
244    /// the connection, so the write failing (or never returning) is part of
245    /// what the test observes.
246    ///
247    /// # Errors
248    ///
249    /// Returns the underlying I/O error if the socket write fails.
250    pub async fn try_write_raw(&mut self, bytes: &[u8]) -> io::Result<()> {
251        self.stream.write_all(bytes).await
252    }
253
254    /// Reads the next packet and asserts it is a CONNECT.
255    ///
256    /// # Panics
257    ///
258    /// Panics if the next packet is not a CONNECT.
259    pub async fn expect_connect(&mut self) -> RecvPacket {
260        let pkt = self.read_packet().await;
261        assert_eq!(
262            pkt.packet_type(),
263            PacketType::Connect,
264            "expected CONNECT as the first packet"
265        );
266        pkt
267    }
268
269    /// Sends a successful CONNACK with `props`.
270    ///
271    /// # Panics
272    ///
273    /// Panics if a property is not valid for CONNACK.
274    pub async fn send_connack(&mut self, session_present: bool, props: &[Property<'_>]) {
275        let buf = ConnackPropertiesBuf::try_from(props).expect("invalid CONNACK property");
276        self.write_packet(&Packet::Connack(Connack {
277            session_present,
278            reason_code: ReasonCode::Success,
279            properties: buf.as_properties(),
280        }))
281        .await;
282    }
283
284    /// Performs the broker side of the connection handshake: reads CONNECT,
285    /// replies with a successful CONNACK (`session_present = false`) that
286    /// contains `props`.
287    pub async fn handshake(&mut self, props: &[Property<'_>]) {
288        self.expect_connect().await;
289        self.send_connack(false, props).await;
290    }
291
292    /// Acknowledges a `QoS` 1 PUBLISH with a successful PUBACK.
293    pub async fn send_puback(&mut self, packet_id: PacketId) {
294        self.write_packet(&Packet::Puback(Ack {
295            packet_id,
296            reason_code: ReasonCode::Success,
297            properties: AckProperties::EMPTY,
298        }))
299        .await;
300    }
301
302    /// Acknowledges a SUBSCRIBE with one reason code per requested filter.
303    pub async fn send_suback(&mut self, packet_id: PacketId, reason_codes: &[ReasonCode]) {
304        self.write_packet(&Packet::Suback(Suback {
305            packet_id,
306            properties: SubackProperties::EMPTY,
307            reason_codes,
308        }))
309        .await;
310    }
311
312    /// Reads packets until a PUBLISH arrives, transparently answering
313    /// PINGREQ with PINGRESP. Returns the PUBLISH packet.
314    ///
315    /// # Panics
316    ///
317    /// Panics if a packet other than PUBLISH or PINGREQ arrives, or if no
318    /// PUBLISH arrives within 10 s.
319    pub async fn expect_publish(&mut self) -> RecvPacket {
320        self.expect_packet(PacketType::Publish).await
321    }
322
323    /// Reads packets until a SUBSCRIBE arrives, transparently answering
324    /// PINGREQ with PINGRESP. Returns the SUBSCRIBE packet.
325    ///
326    /// # Panics
327    ///
328    /// Panics if a packet other than SUBSCRIBE or PINGREQ arrives, or if no
329    /// SUBSCRIBE arrives within 10 s.
330    pub async fn expect_subscribe(&mut self) -> RecvPacket {
331        self.expect_packet(PacketType::Subscribe).await
332    }
333
334    /// Reads packets until one of type `want` arrives, transparently
335    /// answering PINGREQ with PINGRESP.
336    ///
337    /// # Panics
338    ///
339    /// Panics if a packet other than `want` or PINGREQ arrives, or if no
340    /// matching packet arrives within 10 s.
341    async fn expect_packet(&mut self, want: PacketType) -> RecvPacket {
342        loop {
343            let pkt = self.read_packet().await;
344            let got = pkt.packet_type();
345            if got == want {
346                return pkt;
347            }
348            match got {
349                PacketType::Pingreq => self.write_packet(&Packet::Pingresp).await,
350                other @ (PacketType::Connect
351                | PacketType::Connack
352                | PacketType::Publish
353                | PacketType::Puback
354                | PacketType::Pubrec
355                | PacketType::Pubrel
356                | PacketType::Pubcomp
357                | PacketType::Subscribe
358                | PacketType::Suback
359                | PacketType::Unsubscribe
360                | PacketType::Unsuback
361                | PacketType::Pingresp
362                | PacketType::Disconnect
363                | PacketType::Auth) => panic!("expected {want:?}, got {other:?}"),
364            }
365        }
366    }
367}