Skip to main content

rtmp_runtime/
handshake.rs

1//! RTMP handshake — C0/C1/C2 and S0/S1/S2 (Adobe RTMP 1.0 §5.2).
2//!
3//! See `private/specs-verified/rtmp/rtmp-runtime/rtmp.md` §2 (Handshake) for the wire layout:
4//! C0/S0 (§5.2.2), C1/S1 (§5.2.3), C2/S2 (§5.2.4), and the handshake sequence
5//! diagram (§5.2.5).
6//!
7//! # Scope: simple handshake only
8//!
9//! This module implements only the **simple** (plain) handshake described by
10//! §5.2 itself: C0/C1/C2 and S0/S1/S2 carry no HMAC-SHA256 digest and no
11//! "complex handshake" key-exchange scheme (that scheme is an Adobe Flash
12//! Media Server addition, not part of the RTMP 1.0 spec text transcribed in
13//! `private/specs-verified/rtmp/rtmp-runtime/rtmp.md`). This is sufficient for interoperating with real-world
14//! publishers such as ffmpeg and OBS Studio, which fall back to (or always
15//! use) the simple handshake for `rtmp://` publish. Complex-handshake support
16//! is out of scope for this crate.
17//!
18//! # No wall clock in the sans-IO core
19//!
20//! This crate has no socket or clock of its own (see the crate-root sans-IO
21//! contract doc). `time` in S1 and `time2` in S2 are therefore not read from
22//! a real clock: [`Handshake::new`] uses `0` for both and a fixed,
23//! non-cryptographic filler pattern for S1's random bytes (see
24//! [`default_random_fill`]); [`Handshake::with_time_and_random`] lets a
25//! caller supply real values instead. Per §5.2.3/§5.2.4 neither field is
26//! required to be meaningful (the spec itself calls the bandwidth estimate
27//! they enable "unlikely to be useful"), and no `rand`-style dependency is
28//! pulled in to generate them.
29
30use broadcast_common::len::need_in;
31use broadcast_common::{Parse, Serialize};
32
33use crate::RtmpError;
34
35type Result<T> = core::result::Result<T, RtmpError>;
36
37/// RTMP version this handshake implements/advertises (§5.2.2): `3`.
38pub const RTMP_VERSION: u8 = 3;
39
40/// Wire length in bytes of C1/S1 and C2/S2 (§5.2.3/§5.2.4): `1536`.
41pub const HANDSHAKE_PACKET_LEN: usize = 1536;
42
43/// Wire length in bytes of C0/S0 (§5.2.2): `1`.
44const VERSION_LEN: usize = 1;
45/// Byte width of the `time`/`zero`/`time2` fields.
46const FIELD_LEN: usize = 4;
47/// Byte width of the `random bytes`/`random echo` field:
48/// `HANDSHAKE_PACKET_LEN` minus two 4-byte fields.
49const RANDOM_LEN: usize = HANDSHAKE_PACKET_LEN - FIELD_LEN - FIELD_LEN;
50
51/// C0 (client→server) or S0 (server→client): the 1-byte RTMP version
52/// (§5.2.2).
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct Version(pub u8);
55
56impl<'a> Parse<'a> for Version {
57    type Error = RtmpError;
58
59    fn parse(bytes: &'a [u8]) -> Result<Self> {
60        need_in(bytes, VERSION_LEN, "C0/S0 version")?;
61        Ok(Version(bytes[0]))
62    }
63}
64
65impl Serialize for Version {
66    type Error = RtmpError;
67
68    fn serialized_len(&self) -> usize {
69        VERSION_LEN
70    }
71
72    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
73        need_in(buf, VERSION_LEN, "C0/S0 version output")?;
74        buf[0] = self.0;
75        Ok(VERSION_LEN)
76    }
77}
78
79/// C1 (client→server) or S1 (server→client): the 1536-byte time/zero/random
80/// handshake packet (§5.2.3).
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct HandshakePacket {
83    /// `time` — timestamp epoch for this endpoint's future chunks. May be 0
84    /// or arbitrary (§5.2.3).
85    pub time: u32,
86    /// `zero` — MUST be all zeros on the wire (§5.2.3).
87    pub zero: u32,
88    /// `random bytes` — arbitrary data distinguishing this handshake from
89    /// the peer's; no cryptographic randomness required (§5.2.3).
90    pub random: [u8; RANDOM_LEN],
91}
92
93impl<'a> Parse<'a> for HandshakePacket {
94    type Error = RtmpError;
95
96    fn parse(bytes: &'a [u8]) -> Result<Self> {
97        need_in(bytes, HANDSHAKE_PACKET_LEN, "C1/S1")?;
98        let time = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
99        let zero = u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
100        let mut random = [0u8; RANDOM_LEN];
101        random.copy_from_slice(&bytes[2 * FIELD_LEN..HANDSHAKE_PACKET_LEN]);
102        Ok(HandshakePacket { time, zero, random })
103    }
104}
105
106impl Serialize for HandshakePacket {
107    type Error = RtmpError;
108
109    fn serialized_len(&self) -> usize {
110        HANDSHAKE_PACKET_LEN
111    }
112
113    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
114        need_in(buf, HANDSHAKE_PACKET_LEN, "C1/S1 output")?;
115        buf[0..FIELD_LEN].copy_from_slice(&self.time.to_be_bytes());
116        buf[FIELD_LEN..2 * FIELD_LEN].copy_from_slice(&self.zero.to_be_bytes());
117        buf[2 * FIELD_LEN..HANDSHAKE_PACKET_LEN].copy_from_slice(&self.random);
118        Ok(HANDSHAKE_PACKET_LEN)
119    }
120}
121
122/// C2 (client→server) or S2 (server→client): the 1536-byte near-echo packet
123/// (§5.2.4).
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub struct EchoPacket {
126    /// `time` — MUST equal the peer's S1 `time` (for C2) or C1 `time` (for
127    /// S2) (§5.2.4).
128    pub time: u32,
129    /// `time2` — MUST be the timestamp at which the peer's previous packet
130    /// (S1 or C1) was read (§5.2.4).
131    pub time2: u32,
132    /// `random echo` — MUST equal the peer's S1/C1 `random bytes`, verbatim
133    /// (§5.2.4).
134    pub random_echo: [u8; RANDOM_LEN],
135}
136
137impl<'a> Parse<'a> for EchoPacket {
138    type Error = RtmpError;
139
140    fn parse(bytes: &'a [u8]) -> Result<Self> {
141        need_in(bytes, HANDSHAKE_PACKET_LEN, "C2/S2")?;
142        let time = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
143        let time2 = u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
144        let mut random_echo = [0u8; RANDOM_LEN];
145        random_echo.copy_from_slice(&bytes[2 * FIELD_LEN..HANDSHAKE_PACKET_LEN]);
146        Ok(EchoPacket {
147            time,
148            time2,
149            random_echo,
150        })
151    }
152}
153
154impl Serialize for EchoPacket {
155    type Error = RtmpError;
156
157    fn serialized_len(&self) -> usize {
158        HANDSHAKE_PACKET_LEN
159    }
160
161    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
162        need_in(buf, HANDSHAKE_PACKET_LEN, "C2/S2 output")?;
163        buf[0..FIELD_LEN].copy_from_slice(&self.time.to_be_bytes());
164        buf[FIELD_LEN..2 * FIELD_LEN].copy_from_slice(&self.time2.to_be_bytes());
165        buf[2 * FIELD_LEN..HANDSHAKE_PACKET_LEN].copy_from_slice(&self.random_echo);
166        Ok(HANDSHAKE_PACKET_LEN)
167    }
168}
169
170/// A fixed, non-cryptographic 1528-byte fill pattern for a server's own S1
171/// `random bytes` when the caller has no specific bytes to supply. Per
172/// §5.2.3 the field only needs to "distinguish this handshake from the
173/// peer's" — no cryptographic randomness is required, so a deterministic
174/// repeating byte pattern is spec-conformant and keeps this crate free of a
175/// `rand`-style dependency.
176#[must_use]
177pub fn default_random_fill() -> [u8; RANDOM_LEN] {
178    let mut random = [0u8; RANDOM_LEN];
179    for (i, b) in random.iter_mut().enumerate() {
180        *b = (i & 0xFF) as u8;
181    }
182    random
183}
184
185/// Server-side handshake driver state (§5.2.5's Uninitialized → Version Sent
186/// → Ack Sent → Handshake Done, collapsed to the three states this driver
187/// actually distinguishes).
188#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189enum HandshakeState {
190    /// Awaiting C0+C1 from the client (spec's "Uninitialized").
191    WaitC0C1,
192    /// S0+S1+S2 sent; awaiting C2 from the client (spec's "Version
193    /// Sent"/"Ack Sent" collapsed into one wait).
194    WaitC2,
195    /// C2 received; handshake complete (spec's "Handshake Done").
196    Done,
197}
198
199/// Sans-IO server-side RTMP handshake driver (§5.2, simple handshake only —
200/// see the module doc).
201///
202/// Drive it by feeding inbound bytes to [`read`](Self::read); it returns any
203/// outbound reply bytes, how many input bytes it consumed, and whether the
204/// handshake is now complete. It never touches a socket or clock itself.
205#[derive(Debug)]
206pub struct Handshake {
207    state: HandshakeState,
208    /// Written into our own S1 `time` field.
209    local_time: u32,
210    /// Written into our own S1 `random bytes` field.
211    local_random: [u8; RANDOM_LEN],
212    /// Written into our own S2 `time2` field (see the module doc: this core
213    /// has no wall clock, so this is caller-supplied or `0`, not a real
214    /// read-timestamp).
215    read_time: u32,
216}
217
218impl Default for Handshake {
219    fn default() -> Self {
220        Self::new()
221    }
222}
223
224impl Handshake {
225    /// A new server-side handshake in the initial (`WaitC0C1`) state, using
226    /// `0` for S1's `time`/S2's `time2` and [`default_random_fill`] for S1's
227    /// random bytes. Use [`with_time_and_random`](Self::with_time_and_random)
228    /// to supply real values instead.
229    #[must_use]
230    pub fn new() -> Self {
231        Self::with_time_and_random(0, default_random_fill(), 0)
232    }
233
234    /// A new server-side handshake with caller-supplied S1 `time`, S1
235    /// `random bytes`, and S2 `time2` values.
236    #[must_use]
237    pub fn with_time_and_random(
238        local_time: u32,
239        local_random: [u8; RANDOM_LEN],
240        read_time: u32,
241    ) -> Self {
242        Self {
243            state: HandshakeState::WaitC0C1,
244            local_time,
245            local_random,
246            read_time,
247        }
248    }
249
250    /// True once C2 has been received and the handshake is complete.
251    #[must_use]
252    pub fn is_done(&self) -> bool {
253        self.state == HandshakeState::Done
254    }
255
256    /// Feed inbound bytes to the handshake driver.
257    ///
258    /// - In `WaitC0C1`, requires a full C0(1)+C1(1536) = 1537 bytes at the
259    ///   front of `input`; on success returns the S0+S1+S2 reply
260    ///   (1+1536+1536 = 3073 bytes), consumes 1537 input bytes, and advances
261    ///   to `WaitC2`.
262    /// - In `WaitC2`, requires a full C2(1536) bytes; on success returns no
263    ///   reply bytes, consumes 1536 input bytes, and advances to `Done`.
264    /// - In `Done`, is a no-op: returns no reply, consumes 0 bytes, and
265    ///   reports done.
266    ///
267    /// Returns `(reply_bytes, consumed, done)`.
268    ///
269    /// # Errors
270    /// [`RtmpError::BufferTooShort`] if `input` does not yet hold a full
271    /// C0+C1 (`WaitC0C1`) or C2 (`WaitC2`). This driver does not buffer
272    /// partial input itself — callers should re-invoke `read` once more
273    /// bytes have arrived.
274    pub fn read(&mut self, input: &[u8]) -> Result<(Vec<u8>, usize, bool)> {
275        match self.state {
276            HandshakeState::WaitC0C1 => {
277                let need = VERSION_LEN + HANDSHAKE_PACKET_LEN;
278                need_in(input, need, "C0+C1")?;
279                let c0 = Version::parse(&input[..VERSION_LEN])?;
280                // #1108/RTMP-W11: the C0 version byte was parsed and
281                // discarded, so an RTMPE client (C0 = 6) or garbage was
282                // accepted, only to fail later as a confusing chunk-parse
283                // error instead of a clear one here.
284                if c0.0 != RTMP_VERSION {
285                    return Err(RtmpError::Malformed { what: "C0 version" });
286                }
287                let c1 = HandshakePacket::parse(&input[VERSION_LEN..need])?;
288
289                let s0 = Version(RTMP_VERSION);
290                let s1 = HandshakePacket {
291                    time: self.local_time,
292                    zero: 0,
293                    random: self.local_random,
294                };
295                let s2 = EchoPacket {
296                    time: c1.time,
297                    time2: self.read_time,
298                    random_echo: c1.random,
299                };
300
301                let reply_len = VERSION_LEN + HANDSHAKE_PACKET_LEN + HANDSHAKE_PACKET_LEN;
302                let mut reply = vec![0u8; reply_len];
303                s0.serialize_into(&mut reply[..VERSION_LEN])?;
304                s1.serialize_into(&mut reply[VERSION_LEN..VERSION_LEN + HANDSHAKE_PACKET_LEN])?;
305                s2.serialize_into(&mut reply[VERSION_LEN + HANDSHAKE_PACKET_LEN..])?;
306
307                self.state = HandshakeState::WaitC2;
308                Ok((reply, need, false))
309            }
310            HandshakeState::WaitC2 => {
311                need_in(input, HANDSHAKE_PACKET_LEN, "C2")?;
312                let _c2 = EchoPacket::parse(&input[..HANDSHAKE_PACKET_LEN])?;
313                self.state = HandshakeState::Done;
314                Ok((Vec::new(), HANDSHAKE_PACKET_LEN, true))
315            }
316            HandshakeState::Done => Ok((Vec::new(), 0, true)),
317        }
318    }
319}
320
321#[cfg(test)]
322mod tests {
323    use broadcast_common::error::BufferTooShort;
324
325    use super::*;
326
327    fn patterned_random(seed: u8) -> [u8; RANDOM_LEN] {
328        let mut r = [0u8; RANDOM_LEN];
329        for (i, b) in r.iter_mut().enumerate() {
330            *b = seed.wrapping_add((i & 0xFF) as u8);
331        }
332        r
333    }
334
335    // ── C0/S0 round-trip ─────────────────────────────────────────────────
336
337    #[test]
338    fn version_round_trip_build_serialize_parse() {
339        let v = Version(RTMP_VERSION);
340        let mut buf = [0u8; VERSION_LEN];
341        let n = v.serialize_into(&mut buf).unwrap();
342        assert_eq!(n, VERSION_LEN);
343        let parsed = Version::parse(&buf).unwrap();
344        assert_eq!(parsed, v);
345    }
346
347    #[test]
348    fn version_round_trip_parse_serialize_byte_identical() {
349        let bytes = [3u8];
350        let v = Version::parse(&bytes).unwrap();
351        let mut buf = [0u8; VERSION_LEN];
352        v.serialize_into(&mut buf).unwrap();
353        assert_eq!(buf, bytes);
354    }
355
356    #[test]
357    fn version_short_input_is_buffer_too_short() {
358        let bytes: [u8; 0] = [];
359        assert!(matches!(
360            Version::parse(&bytes),
361            Err(RtmpError::BufferTooShort(BufferTooShort {
362                need: VERSION_LEN,
363                have: 0,
364                ..
365            }))
366        ));
367    }
368
369    // ── C1/S1 round-trip ─────────────────────────────────────────────────
370
371    #[test]
372    fn handshake_packet_round_trip_build_serialize_parse() {
373        let hp = HandshakePacket {
374            time: 0x1122_3344,
375            zero: 0,
376            random: patterned_random(0xAB),
377        };
378        let mut buf = [0u8; HANDSHAKE_PACKET_LEN];
379        let n = hp.serialize_into(&mut buf).unwrap();
380        assert_eq!(n, HANDSHAKE_PACKET_LEN);
381        let parsed = HandshakePacket::parse(&buf).unwrap();
382        assert_eq!(parsed, hp);
383    }
384
385    #[test]
386    fn handshake_packet_round_trip_parse_serialize_byte_identical() {
387        let mut bytes = [0u8; HANDSHAKE_PACKET_LEN];
388        bytes[0..4].copy_from_slice(&0xDEAD_BEEFu32.to_be_bytes());
389        // bytes[4..8] left as the required-zero `zero` field.
390        for (i, b) in bytes[8..].iter_mut().enumerate() {
391            *b = (i as u8).wrapping_mul(7);
392        }
393        let hp = HandshakePacket::parse(&bytes).unwrap();
394        assert_eq!(hp.time, 0xDEAD_BEEF);
395        assert_eq!(hp.zero, 0);
396        let mut buf = [0u8; HANDSHAKE_PACKET_LEN];
397        hp.serialize_into(&mut buf).unwrap();
398        assert_eq!(buf, bytes, "C1/S1 byte-identical round trip");
399    }
400
401    #[test]
402    fn handshake_packet_short_input_is_buffer_too_short() {
403        let bytes = [0u8; HANDSHAKE_PACKET_LEN - 1];
404        assert!(matches!(
405            HandshakePacket::parse(&bytes),
406            Err(RtmpError::BufferTooShort(BufferTooShort {
407                need: HANDSHAKE_PACKET_LEN,
408                have,
409                ..
410            })) if have == HANDSHAKE_PACKET_LEN - 1
411        ));
412    }
413
414    // ── C2/S2 round-trip ─────────────────────────────────────────────────
415
416    #[test]
417    fn echo_packet_round_trip_build_serialize_parse() {
418        let ep = EchoPacket {
419            time: 0x0102_0304,
420            time2: 0x0506_0708,
421            random_echo: patterned_random(0x5A),
422        };
423        let mut buf = [0u8; HANDSHAKE_PACKET_LEN];
424        let n = ep.serialize_into(&mut buf).unwrap();
425        assert_eq!(n, HANDSHAKE_PACKET_LEN);
426        let parsed = EchoPacket::parse(&buf).unwrap();
427        assert_eq!(parsed, ep);
428    }
429
430    #[test]
431    fn echo_packet_round_trip_parse_serialize_byte_identical() {
432        let mut bytes = [0u8; HANDSHAKE_PACKET_LEN];
433        bytes[0..4].copy_from_slice(&0x1111_2222u32.to_be_bytes());
434        bytes[4..8].copy_from_slice(&0x3333_4444u32.to_be_bytes());
435        for (i, b) in bytes[8..].iter_mut().enumerate() {
436            *b = (i as u8) ^ 0x5A;
437        }
438        let ep = EchoPacket::parse(&bytes).unwrap();
439        let mut buf = [0u8; HANDSHAKE_PACKET_LEN];
440        ep.serialize_into(&mut buf).unwrap();
441        assert_eq!(buf, bytes, "C2/S2 byte-identical round trip");
442    }
443
444    #[test]
445    fn echo_packet_short_input_is_buffer_too_short() {
446        let bytes = [0u8; 10];
447        assert!(matches!(
448            EchoPacket::parse(&bytes),
449            Err(RtmpError::BufferTooShort(BufferTooShort {
450                need: HANDSHAKE_PACKET_LEN,
451                have: 10,
452                ..
453            }))
454        ));
455    }
456
457    // ── FSM happy path ────────────────────────────────────────────────────
458
459    fn build_c0_c1(client_time: u32, client_random: [u8; RANDOM_LEN]) -> Vec<u8> {
460        let mut v = vec![0u8; VERSION_LEN + HANDSHAKE_PACKET_LEN];
461        v[0] = RTMP_VERSION;
462        let c1 = HandshakePacket {
463            time: client_time,
464            zero: 0,
465            random: client_random,
466        };
467        c1.serialize_into(&mut v[VERSION_LEN..]).unwrap();
468        v
469    }
470
471    fn build_c2(time: u32, time2: u32, random_echo: [u8; RANDOM_LEN]) -> Vec<u8> {
472        let c2 = EchoPacket {
473            time,
474            time2,
475            random_echo,
476        };
477        let mut v = vec![0u8; HANDSHAKE_PACKET_LEN];
478        c2.serialize_into(&mut v).unwrap();
479        v
480    }
481
482    #[test]
483    fn fsm_happy_path_reaches_done_and_s2_echoes_c1() {
484        let client_time = 0x0000_1234;
485        let client_random = patterned_random(0x77);
486
487        let mut hs = Handshake::new();
488        assert!(!hs.is_done());
489
490        let c0_c1 = build_c0_c1(client_time, client_random);
491        let (reply, consumed, done) = hs.read(&c0_c1).unwrap();
492
493        assert_eq!(consumed, VERSION_LEN + HANDSHAKE_PACKET_LEN);
494        assert!(!done);
495        assert!(!hs.is_done());
496        assert_eq!(
497            reply.len(),
498            VERSION_LEN + HANDSHAKE_PACKET_LEN + HANDSHAKE_PACKET_LEN,
499            "S0+S1+S2 must total 3073 bytes"
500        );
501
502        // S0.
503        let s0 = Version::parse(&reply[..VERSION_LEN]).unwrap();
504        assert_eq!(s0.0, RTMP_VERSION);
505
506        // S1 (not checked for content beyond length — S1 is our own data).
507        let s1_start = VERSION_LEN;
508        let s1_end = s1_start + HANDSHAKE_PACKET_LEN;
509        let _s1 = HandshakePacket::parse(&reply[s1_start..s1_end]).unwrap();
510
511        // S2 — MUST echo C1's time and random bytes (§5.2.4).
512        let s2 = EchoPacket::parse(&reply[s1_end..]).unwrap();
513        assert_eq!(s2.time, client_time, "S2.time must echo C1.time");
514        assert_eq!(
515            s2.random_echo, client_random,
516            "S2.random_echo must equal C1's random bytes verbatim"
517        );
518
519        // Client now sends C2, echoing S1's time/random (use S1's actual
520        // values, which the client would have parsed out of the reply).
521        let s1 = HandshakePacket::parse(&reply[s1_start..s1_end]).unwrap();
522        let c2 = build_c2(s1.time, 0, s1.random);
523        let (reply2, consumed2, done2) = hs.read(&c2).unwrap();
524        assert_eq!(consumed2, HANDSHAKE_PACKET_LEN);
525        assert!(done2);
526        assert!(hs.is_done());
527        assert!(
528            reply2.is_empty(),
529            "C2 receipt produces no further reply bytes"
530        );
531    }
532
533    /// RTMP-W11 (#1108): C0's version byte used to be parsed and discarded,
534    /// so an RTMPE client (C0 = 6) or garbage was accepted here and only
535    /// surfaced later as a confusing chunk-parse error.
536    #[test]
537    fn fsm_rejects_bad_c0_version() {
538        let mut hs = Handshake::new();
539        let mut c0_c1 = build_c0_c1(0, patterned_random(3));
540        c0_c1[0] = 6; // RTMPE, not plain RTMP
541        let err = hs.read(&c0_c1).unwrap_err();
542        assert!(matches!(err, RtmpError::Malformed { what: "C0 version" }));
543    }
544
545    #[test]
546    fn fsm_partial_c1_is_buffer_too_short() {
547        let mut hs = Handshake::new();
548        // C0 present, C1 truncated by one byte.
549        let full = build_c0_c1(0, patterned_random(1));
550        let partial = &full[..full.len() - 1];
551        let err = hs.read(partial).unwrap_err();
552        assert!(matches!(err, RtmpError::BufferTooShort(..)));
553        assert!(!hs.is_done(), "state must not advance on a short read");
554    }
555
556    #[test]
557    fn fsm_partial_c2_is_buffer_too_short() {
558        let mut hs = Handshake::new();
559        let c0_c1 = build_c0_c1(0, patterned_random(2));
560        let (_reply, _consumed, done) = hs.read(&c0_c1).unwrap();
561        assert!(!done);
562
563        let full_c2 = build_c2(0, 0, patterned_random(2));
564        let partial_c2 = &full_c2[..full_c2.len() - 1];
565        let err = hs.read(partial_c2).unwrap_err();
566        assert!(matches!(err, RtmpError::BufferTooShort(..)));
567        assert!(
568            !hs.is_done(),
569            "state must not advance to Done on a short C2 read"
570        );
571    }
572
573    #[test]
574    fn fsm_done_is_idempotent_noop() {
575        let mut hs = Handshake::new();
576        let c0_c1 = build_c0_c1(0, patterned_random(3));
577        hs.read(&c0_c1).unwrap();
578        let full_c2 = build_c2(0, 0, patterned_random(3));
579        hs.read(&full_c2).unwrap();
580        assert!(hs.is_done());
581
582        let (reply, consumed, done) = hs.read(&[]).unwrap();
583        assert!(reply.is_empty());
584        assert_eq!(consumed, 0);
585        assert!(done);
586    }
587
588    // ── Mutation-check sentinels ──────────────────────────────────────────
589    // These pin the exact behaviors a broken serializer/FSM could silently
590    // drop; see the module-level test suite as a whole for the mutation
591    // scenarios the brief calls out (dropped random tail, non-echoing S2).
592
593    #[test]
594    fn handshake_packet_serialize_writes_full_random_tail() {
595        let hp = HandshakePacket {
596            time: 1,
597            zero: 0,
598            random: [0xFFu8; RANDOM_LEN],
599        };
600        let mut buf = [0u8; HANDSHAKE_PACKET_LEN];
601        hp.serialize_into(&mut buf).unwrap();
602        assert!(
603            buf[8..].iter().all(|&b| b == 0xFF),
604            "every random byte must be written, not just a prefix"
605        );
606    }
607
608    #[test]
609    fn echo_packet_random_echo_must_differ_from_local_pattern_to_catch_non_echo_bugs() {
610        // Sanity check that our two "seeds" actually produce different byte
611        // sequences, so a test asserting S2.random_echo == client_random
612        // would fail if the FSM instead echoed its *own* S1 random.
613        assert_ne!(patterned_random(0x77), default_random_fill());
614    }
615}