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