Skip to main content

ntex/ws/
codec.rs

1use std::cell::Cell;
2#[cfg(feature = "compress")]
3use std::rc::Rc;
4
5use crate::codec::{Decoder, Encoder};
6use crate::util::{BytePage, BytePages, ByteString, Bytes, BytesMut};
7
8#[cfg(feature = "compress")]
9use super::deflate::{Deflate, DeflateConfig};
10use super::error::ProtocolError;
11use super::frame::Parser;
12use super::proto::{CloseCode, CloseReason, OpCode};
13
14/// An outgoing WebSocket message.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum Message {
17    /// UTF-8 text message.
18    Text(ByteString),
19    /// Binary message.
20    Binary(Bytes),
21    /// Fragment of a text or binary message.
22    Continuation(Item),
23    /// Ping control message.
24    Ping(Bytes),
25    /// Pong control message.
26    Pong(Bytes),
27    /// Close control message with an optional reason.
28    Close(Option<CloseReason>),
29}
30
31/// A decoded WebSocket frame.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum Frame {
34    /// Text frame.
35    ///
36    /// The payload is valid UTF-8 unless validation is disabled with
37    /// [`Codec::validate_utf8()`].
38    Text(Bytes),
39    /// Binary frame.
40    Binary(Bytes),
41    /// Fragmented text or binary frame.
42    Continuation(Item),
43    /// Ping control frame.
44    Ping(Bytes),
45    /// Pong control frame.
46    Pong(Bytes),
47    /// Close control frame with an optional reason.
48    Close(Option<CloseReason>),
49}
50
51/// A fragment in a WebSocket continuation sequence.
52///
53/// When decoding, a single fragment of a text message is not necessarily
54/// valid UTF-8 on its own, a character can be split between fragments. The
55/// codec validates the text of the whole message, see
56/// [`Codec::validate_utf8()`].
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum Item {
59    /// First fragment of a text message.
60    FirstText(Bytes),
61    /// First fragment of a binary message.
62    FirstBinary(Bytes),
63    /// Intermediate fragment.
64    Continue(Bytes),
65    /// Final fragment.
66    Last(Bytes),
67}
68
69#[derive(Debug, Clone)]
70/// Encoder and decoder for WebSocket frames.
71///
72/// With the `compress` feature, the codec can use the `permessage-deflate`
73/// extension, see [`Codec::set_deflate()`]. Clones of a codec share the
74/// compression state.
75///
76/// The decoder limits the payload of each frame, see [`Codec::max_size()`],
77/// and the total payload of a message, see [`Codec::max_message_size()`].
78/// It also checks that text messages are valid UTF-8, see
79/// [`Codec::validate_utf8()`].
80pub struct Codec {
81    flags: Cell<Flags>,
82    max_size: usize,
83    max_message_size: usize,
84    validate_utf8: bool,
85    /// Payload size of the incoming fragmented message.
86    msg_size: Cell<usize>,
87    /// Incomplete UTF-8 character at the end of the last text fragment.
88    utf8_tail: Cell<Utf8Tail>,
89    #[cfg(feature = "compress")]
90    deflate: Option<Rc<Deflate>>,
91}
92
93bitflags::bitflags! {
94    #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
95    struct Flags: u8 {
96        const SERVER         = 0b0000_0001;
97        const R_CONTINUATION = 0b0000_0010;
98        const W_CONTINUATION = 0b0000_0100;
99        const CLOSED         = 0b0000_1000;
100        const R_CLOSED       = 0b0001_0000;
101        const R_COMPRESSED   = 0b0010_0000;
102        const R_TEXT         = 0b0100_0000;
103        /// A pong was encoded since the last `auto_reply()` for a ping.
104        const W_PONG         = 0b1000_0000;
105    }
106}
107
108#[derive(Copy, Clone, Debug, Default)]
109struct Utf8Tail {
110    buf: [u8; 3],
111    len: u8,
112}
113
114/// Validates the next fragment of a UTF-8 text message.
115///
116/// `tail` is the incomplete character at the end of the previous fragment,
117/// the result is the incomplete character at the end of `data`. A message
118/// must not end with an incomplete character.
119fn validate_utf8(tail: Utf8Tail, mut data: &[u8], fin: bool) -> Result<Utf8Tail, ProtocolError> {
120    if tail.len > 0 {
121        // complete the character started by the previous fragment
122        let mut ch = [0; 4];
123        let mut len = usize::from(tail.len);
124        ch[..len].copy_from_slice(&tail.buf[..len]);
125        loop {
126            let Some((&b, rest)) = data.split_first() else {
127                return if fin {
128                    Err(ProtocolError::InvalidUtf8)
129                } else {
130                    Ok(Utf8Tail {
131                        buf: [ch[0], ch[1], ch[2]],
132                        len: len as u8,
133                    })
134                };
135            };
136            // a prefix of three bytes is the longest incomplete character
137            ch[len] = b;
138            len += 1;
139            data = rest;
140            match simdutf8::compat::from_utf8(&ch[..len]) {
141                Ok(_) => break,
142                Err(e) if e.error_len().is_some() => return Err(ProtocolError::InvalidUtf8),
143                Err(_) => {}
144            }
145        }
146    }
147
148    if simdutf8::basic::from_utf8(data).is_ok() {
149        return Ok(Utf8Tail::default());
150    }
151    match simdutf8::compat::from_utf8(data) {
152        Err(e) if e.error_len().is_none() && !fin => {
153            let rest = &data[e.valid_up_to()..];
154            let mut tail = Utf8Tail {
155                len: rest.len() as u8,
156                ..Utf8Tail::default()
157            };
158            tail.buf[..rest.len()].copy_from_slice(rest);
159            Ok(tail)
160        }
161        _ => Err(ProtocolError::InvalidUtf8),
162    }
163}
164
165impl Codec {
166    /// Creates a codec in server mode.
167    ///
168    /// The codec limits frames to 64 KiB and messages to 4 MiB of payload,
169    /// and validates incoming text messages.
170    #[must_use]
171    pub fn new() -> Codec {
172        Codec {
173            max_size: 65_536,
174            max_message_size: 4 * 1024 * 1024,
175            validate_utf8: true,
176            msg_size: Cell::new(0),
177            utf8_tail: Cell::new(Utf8Tail::default()),
178            flags: Cell::new(Flags::SERVER),
179            #[cfg(feature = "compress")]
180            deflate: None,
181        }
182    }
183
184    /// Sets the maximum accepted frame payload size.
185    ///
186    /// The default is 64 KiB. With the `permessage-deflate` extension, the
187    /// limit applies to both the compressed and the decompressed payload of
188    /// a frame.
189    ///
190    /// A fragmented message can consist of many frames, its total size is
191    /// limited by [`Codec::max_message_size()`].
192    #[must_use]
193    pub fn max_size(mut self, size: usize) -> Self {
194        self.max_size = size;
195        self
196    }
197
198    /// Sets the maximum accepted payload size of an incoming message.
199    ///
200    /// The limit applies to the total payload of all frames of a fragmented
201    /// message, and to single-frame messages. With the `permessage-deflate`
202    /// extension, it applies to the decompressed payload. Control frames are
203    /// not counted. A message that exceeds the limit fails with
204    /// [`ProtocolError::Overflow`].
205    ///
206    /// The default is 4 MiB. Raise it together with [`Codec::max_size()`]
207    /// to accept larger single-frame messages, use `usize::MAX` to only
208    /// limit frames, for example to stream data with
209    /// [`WsTransport`](super::WsTransport).
210    #[must_use]
211    pub fn max_message_size(mut self, size: usize) -> Self {
212        self.max_message_size = size;
213        self
214    }
215
216    /// Enables or disables UTF-8 validation of incoming text messages.
217    ///
218    /// When enabled, the payload of [`Frame::Text`] is valid UTF-8 and the
219    /// fragments of a text message form valid UTF-8 when joined. A single
220    /// fragment can end or start in the middle of a character. Invalid text
221    /// fails with [`ProtocolError::InvalidUtf8`] as soon as it is detected,
222    /// as RFC 6455 requires.
223    ///
224    /// Validation is enabled by default.
225    #[must_use]
226    pub fn validate_utf8(mut self, enabled: bool) -> Self {
227        self.validate_utf8 = enabled;
228        self
229    }
230
231    /// Configures the codec for client-side masking rules.
232    ///
233    /// Client mode masks encoded frames and rejects masked incoming frames.
234    /// By default, the codec uses server-side masking rules.
235    #[must_use]
236    pub fn set_client_mode(self) -> Self {
237        self.remove_flags(Flags::SERVER);
238        self
239    }
240
241    #[cfg(feature = "compress")]
242    /// Enables the `permessage-deflate` extension with the agreed parameters.
243    ///
244    /// Outgoing text and binary messages are compressed, incoming messages
245    /// with the RSV1 bit set are decompressed. The parameters must be the
246    /// result of the extension negotiation, the client and server roles of
247    /// the parameters follow the codec mode.
248    #[must_use]
249    pub fn set_deflate(mut self, cfg: DeflateConfig) -> Self {
250        self.deflate = Some(Rc::new(Deflate::new(cfg)));
251        self
252    }
253
254    #[cfg(feature = "compress")]
255    /// Returns the `permessage-deflate` parameters, if the extension is used.
256    pub fn deflate(&self) -> Option<&DeflateConfig> {
257        self.deflate.as_deref().map(Deflate::config)
258    }
259
260    /// Returns `true` after this codec has encoded a close message.
261    pub fn is_closed(&self) -> bool {
262        self.flags().contains(Flags::CLOSED)
263    }
264
265    fn flags(&self) -> Flags {
266        self.flags.get()
267    }
268
269    fn insert_flags(&self, f: Flags) {
270        self.flags.set(self.flags() | f);
271    }
272
273    fn remove_flags(&self, f: Flags) {
274        self.flags.set(self.flags() - f);
275    }
276
277    fn is_server(&self) -> bool {
278        self.flags().contains(Flags::SERVER)
279    }
280
281    /// Returns the reply to `frame` that is sent when a frame service
282    /// returns no response, pass it to [`Codec::unanswered()`] after the
283    /// service call.
284    ///
285    /// A ping is answered with a pong carrying the same payload, and a close
286    /// with a close echoing the peer's code. A server cannot send the
287    /// extension code, it answers it with a normal close.
288    pub(crate) fn auto_reply(&self, frame: &Frame) -> Option<Message> {
289        match frame {
290            Frame::Ping(data) => {
291                self.remove_flags(Flags::W_PONG);
292                Some(Message::Pong(data.clone()))
293            }
294            Frame::Close(reason) => Some(Message::Close(reason.as_ref().map(|r| {
295                if self.is_server() && r.code == CloseCode::Extension {
296                    CloseCode::Normal.into()
297                } else {
298                    r.code.into()
299                }
300            }))),
301            _ => None,
302        }
303    }
304
305    /// Returns the service response, or the automatic `reply` if the service
306    /// returned none.
307    ///
308    /// The automatic reply is dropped once a close message has been sent,
309    /// and a pong is dropped if one was sent while the service handled
310    /// the ping, e.g. through a sink.
311    pub(crate) fn unanswered(
312        &self,
313        res: Option<Message>,
314        reply: Option<Message>,
315    ) -> Option<Message> {
316        res.or_else(|| match reply {
317            _ if self.is_closed() => None,
318            Some(Message::Pong(_)) if self.flags().contains(Flags::W_PONG) => None,
319            reply => reply,
320        })
321    }
322
323    #[cfg_attr(not(feature = "compress"), allow(clippy::unused_self))]
324    fn is_compressed(&self) -> bool {
325        #[cfg(feature = "compress")]
326        {
327            self.deflate.is_some()
328        }
329        #[cfg(not(feature = "compress"))]
330        {
331            false
332        }
333    }
334
335    /// Writes a data frame, compressed if the extension is used.
336    ///
337    /// `first` marks the first frame of a message, it carries the RSV1 bit.
338    fn write_data<B>(
339        &self,
340        dst: &mut BytePages,
341        payload: B,
342        op: OpCode,
343        first: bool,
344        fin: bool,
345    ) -> Result<(), ProtocolError>
346    where
347        BytePage: From<B>,
348    {
349        let payload = BytePage::from(payload);
350        #[cfg(feature = "compress")]
351        if let Some(deflate) = &self.deflate
352            && !(first && fin && deflate.is_skipped(payload.len(), self.is_server()))
353        {
354            let payload = deflate.compress(payload.as_ref(), fin, self.is_server());
355            return Parser::write_frame(dst, payload.into(), op, fin, first, !self.is_server());
356        }
357        let _ = first;
358        Parser::write_frame(dst, payload, op, fin, false, !self.is_server())
359    }
360
361    /// Decompresses the payload of a data frame, if the message is
362    /// compressed.
363    #[cfg_attr(
364        not(feature = "compress"),
365        allow(clippy::unused_self, clippy::unnecessary_wraps)
366    )]
367    #[inline]
368    fn read_data(&self, payload: Option<Bytes>, fin: bool) -> Result<Bytes, ProtocolError> {
369        // only set if the extension is used
370        #[cfg(feature = "compress")]
371        if self.flags().contains(Flags::R_COMPRESSED) {
372            return self.decompress(payload, fin);
373        }
374        let _ = fin;
375        Ok(payload.unwrap_or_default())
376    }
377
378    #[cfg(feature = "compress")]
379    #[inline(never)]
380    fn decompress(&self, payload: Option<Bytes>, fin: bool) -> Result<Bytes, ProtocolError> {
381        let payload = payload.unwrap_or_default();
382        if fin {
383            self.remove_flags(Flags::R_COMPRESSED);
384        }
385        self.deflate
386            .as_ref()
387            .expect("compressed messages require the extension")
388            .decompress(&payload, fin, self.is_server(), self.max_size)
389            .map(BytesMut::freeze)
390    }
391
392    /// Checks the payload of an incoming data frame against the message size
393    /// limit and, for a text message, validates its UTF-8 encoding.
394    ///
395    /// `first` is `Some(is_text)` for the first frame of a message.
396    fn check_data(
397        &self,
398        data: Bytes,
399        first: Option<bool>,
400        fin: bool,
401    ) -> Result<Bytes, ProtocolError> {
402        let (size, text) = match first {
403            Some(text) => (data.len(), text),
404            None => (
405                self.msg_size.get().saturating_add(data.len()),
406                self.flags().contains(Flags::R_TEXT),
407            ),
408        };
409        if size > self.max_message_size {
410            return Err(ProtocolError::Overflow);
411        }
412        if text && self.validate_utf8 {
413            let tail = if first.is_some() {
414                Utf8Tail::default()
415            } else {
416                self.utf8_tail.get()
417            };
418            self.utf8_tail.set(validate_utf8(tail, &data, fin)?);
419        }
420
421        if !fin {
422            self.msg_size.set(size);
423            if text {
424                self.insert_flags(Flags::R_TEXT);
425            } else {
426                self.remove_flags(Flags::R_TEXT);
427            }
428        }
429        Ok(data)
430    }
431
432    /// Encodes `page` as a final binary frame.
433    ///
434    /// # Errors
435    ///
436    /// Returns [`ProtocolError::Closed`] if a close message has already been
437    /// encoded, or [`ProtocolError::ContinuationStarted`] if a fragmented
438    /// message is in progress.
439    pub fn encode_page(&self, page: BytePage, dst: &mut BytePages) -> Result<(), ProtocolError> {
440        if self.is_closed() {
441            return Err(ProtocolError::Closed);
442        }
443        if self.flags().contains(Flags::W_CONTINUATION) {
444            return Err(ProtocolError::ContinuationStarted);
445        }
446        self.write_data(dst, page, OpCode::Binary, true, true)
447            .expect("binary frames are always valid");
448        Ok(())
449    }
450}
451
452impl Default for Codec {
453    fn default() -> Self {
454        Self::new()
455    }
456}
457
458impl Encoder for Codec {
459    type Item = Message;
460    type Error = ProtocolError;
461
462    fn encode(&self, item: Message, dst: &mut BytePages) -> Result<(), Self::Error> {
463        if self.is_closed() {
464            return Err(ProtocolError::Closed);
465        }
466
467        match item {
468            Message::Text(txt) => {
469                if self.flags().contains(Flags::W_CONTINUATION) {
470                    return Err(ProtocolError::ContinuationStarted);
471                }
472                self.write_data(dst, txt, OpCode::Text, true, true)?;
473            }
474            Message::Binary(bin) => {
475                if self.flags().contains(Flags::W_CONTINUATION) {
476                    return Err(ProtocolError::ContinuationStarted);
477                }
478                self.write_data(dst, bin, OpCode::Binary, true, true)?;
479            }
480            Message::Ping(txt) => {
481                Parser::write_message(dst, txt, OpCode::Ping, true, !self.is_server())?;
482            }
483            Message::Pong(txt) => {
484                Parser::write_message(dst, txt, OpCode::Pong, true, !self.is_server())?;
485                self.insert_flags(Flags::W_PONG);
486            }
487            Message::Close(reason) => {
488                Parser::write_close(dst, reason, !self.is_server())?;
489                self.insert_flags(Flags::CLOSED);
490            }
491            Message::Continuation(cont) => match cont {
492                Item::FirstText(data) => {
493                    if self.flags().contains(Flags::W_CONTINUATION) {
494                        return Err(ProtocolError::ContinuationStarted);
495                    }
496                    self.insert_flags(Flags::W_CONTINUATION);
497                    self.write_data(dst, data, OpCode::Text, true, false)?;
498                }
499                Item::FirstBinary(data) => {
500                    if self.flags().contains(Flags::W_CONTINUATION) {
501                        return Err(ProtocolError::ContinuationStarted);
502                    }
503                    self.insert_flags(Flags::W_CONTINUATION);
504                    self.write_data(dst, data, OpCode::Binary, true, false)?;
505                }
506                Item::Continue(data) => {
507                    if self.flags().contains(Flags::W_CONTINUATION) {
508                        self.write_data(dst, data, OpCode::Continue, false, false)?;
509                    } else {
510                        return Err(ProtocolError::ContinuationNotStarted);
511                    }
512                }
513                Item::Last(data) => {
514                    if self.flags().contains(Flags::W_CONTINUATION) {
515                        self.remove_flags(Flags::W_CONTINUATION);
516                        self.write_data(dst, data, OpCode::Continue, false, true)?;
517                    } else {
518                        return Err(ProtocolError::ContinuationNotStarted);
519                    }
520                }
521            },
522        }
523        Ok(())
524    }
525}
526
527impl Decoder for Codec {
528    type Item = Frame;
529    type Error = ProtocolError;
530
531    fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
532        // the peer must not send anything after its close frame, discard it
533        if self.flags().contains(Flags::R_CLOSED) {
534            src.clear();
535            return Ok(None);
536        }
537
538        let Some((finished, rsv1, opcode, payload)) =
539            Parser::parse_frame(src, self.is_server(), self.max_size, self.is_compressed())?
540        else {
541            return Ok(None);
542        };
543
544        // only the first frame of a data message can be compressed
545        if rsv1 {
546            if !matches!(opcode, OpCode::Text | OpCode::Binary) {
547                return Err(ProtocolError::ReservedBits(0b100));
548            }
549            if !self.flags().contains(Flags::R_CONTINUATION) {
550                self.insert_flags(Flags::R_COMPRESSED);
551            }
552        }
553
554        // handle continuation
555        if finished {
556            match opcode {
557                OpCode::Continue => {
558                    if self.flags().contains(Flags::R_CONTINUATION) {
559                        self.remove_flags(Flags::R_CONTINUATION);
560                        let data = self.read_data(payload, true)?;
561                        Ok(Some(Frame::Continuation(Item::Last(
562                            self.check_data(data, None, true)?,
563                        ))))
564                    } else {
565                        Err(ProtocolError::ContinuationNotStarted)
566                    }
567                }
568                OpCode::Close => {
569                    let reason = if let Some(pl) = payload {
570                        Parser::parse_close_payload(&pl)?
571                    } else {
572                        None
573                    };
574                    self.insert_flags(Flags::R_CLOSED);
575                    Ok(Some(Frame::Close(reason)))
576                }
577                OpCode::Ping => Ok(Some(Frame::Ping(payload.unwrap_or_default()))),
578                OpCode::Pong => Ok(Some(Frame::Pong(payload.unwrap_or_default()))),
579                OpCode::Binary => {
580                    if self.flags().contains(Flags::R_CONTINUATION) {
581                        Err(ProtocolError::ContinuationStarted)
582                    } else {
583                        let data = self.read_data(payload, true)?;
584                        Ok(Some(Frame::Binary(self.check_data(
585                            data,
586                            Some(false),
587                            true,
588                        )?)))
589                    }
590                }
591                OpCode::Text => {
592                    if self.flags().contains(Flags::R_CONTINUATION) {
593                        Err(ProtocolError::ContinuationStarted)
594                    } else {
595                        let data = self.read_data(payload, true)?;
596                        Ok(Some(Frame::Text(self.check_data(
597                            data,
598                            Some(true),
599                            true,
600                        )?)))
601                    }
602                }
603            }
604        } else {
605            match opcode {
606                OpCode::Continue => {
607                    if self.flags().contains(Flags::R_CONTINUATION) {
608                        let data = self.read_data(payload, false)?;
609                        Ok(Some(Frame::Continuation(Item::Continue(
610                            self.check_data(data, None, false)?,
611                        ))))
612                    } else {
613                        Err(ProtocolError::ContinuationNotStarted)
614                    }
615                }
616                OpCode::Binary => {
617                    if self.flags().contains(Flags::R_CONTINUATION) {
618                        Err(ProtocolError::ContinuationStarted)
619                    } else {
620                        self.insert_flags(Flags::R_CONTINUATION);
621                        let data = self.read_data(payload, false)?;
622                        Ok(Some(Frame::Continuation(Item::FirstBinary(
623                            self.check_data(data, Some(false), false)?,
624                        ))))
625                    }
626                }
627                OpCode::Text => {
628                    if self.flags().contains(Flags::R_CONTINUATION) {
629                        Err(ProtocolError::ContinuationStarted)
630                    } else {
631                        self.insert_flags(Flags::R_CONTINUATION);
632                        let data = self.read_data(payload, false)?;
633                        Ok(Some(Frame::Continuation(Item::FirstText(
634                            self.check_data(data, Some(true), false)?,
635                        ))))
636                    }
637                }
638                // rejected by the parser, kept for exhaustiveness
639                OpCode::Ping | OpCode::Pong | OpCode::Close => {
640                    Err(ProtocolError::FragmentedControlFrame(opcode))
641                }
642            }
643        }
644    }
645}
646
647#[cfg(test)]
648mod tests {
649    use super::*;
650    use crate::ws::CloseCode;
651
652    /// STATEMENT: Text frames are UTF-8 validated by default, and disabling validation returns the payload unchanged.
653    ///
654    /// HOW:
655    /// - Decode a text frame containing `0xff` with a default codec and expect `InvalidUtf8`.
656    /// - Expect `InvalidUtf8` for a text frame that ends inside a multi-byte character.
657    /// - Decode valid multi-byte text with a default codec and expect it unchanged.
658    /// - Decode the invalid frame with `validate_utf8(false)` and expect the raw byte back.
659    #[test]
660    fn text_payload_is_validated() {
661        let codec = Codec::new().set_client_mode();
662        assert!(matches!(
663            decode(&codec, &[0x81, 0x01, 0xff]),
664            Err(ProtocolError::InvalidUtf8)
665        ));
666        assert!(matches!(
667            decode(&Codec::new().set_client_mode(), b"\x81\x02a\xe2"),
668            Err(ProtocolError::InvalidUtf8)
669        ));
670        assert!(matches!(
671            decode(&Codec::new().set_client_mode(), b"\x81\x03a\xc3\xa9"),
672            Ok(Some(Frame::Text(data))) if data == "a\u{e9}".as_bytes()
673        ));
674
675        let codec = Codec::new().set_client_mode().validate_utf8(false);
676        assert!(matches!(
677            decode(&codec, &[0x81, 0x01, 0xff]),
678            Ok(Some(Frame::Text(data))) if data == Bytes::from_static(&[0xff])
679        ));
680    }
681
682    /// STATEMENT: Fragmented text is validated as a whole message, so characters may span fragments but the message must be valid UTF-8.
683    ///
684    /// HOW:
685    /// - Split `\u{20ac}` (`e2 82 ac`) over first, continue, and last fragments with an empty fragment in between and expect all to decode.
686    /// - Expect `InvalidUtf8` when a split character is completed with a non-continuation byte, when a message ends inside a character, and for an invalid byte in a later fragment.
687    /// - Decode binary fragments with `0xff` and confirm binary data is not validated.
688    #[test]
689    fn fragmented_text_is_validated() {
690        let codec = Codec::new().set_client_mode();
691        for frame in [
692            &b"\x01\x02a\xe2"[..],
693            b"\x00\x00",
694            b"\x00\x01\x82",
695            b"\x80\x02\xacb",
696        ] {
697            assert!(matches!(
698                decode(&codec, frame),
699                Ok(Some(Frame::Continuation(_)))
700            ));
701        }
702
703        let codec = Codec::new().set_client_mode();
704        assert!(decode(&codec, b"\x01\x01\xe2").is_ok());
705        assert!(matches!(
706            decode(&codec, b"\x80\x01a"),
707            Err(ProtocolError::InvalidUtf8)
708        ));
709
710        let codec = Codec::new().set_client_mode();
711        assert!(decode(&codec, b"\x01\x02a\xe2").is_ok());
712        assert!(decode(&codec, b"\x00\x01\x82").is_ok());
713        assert!(matches!(
714            decode(&codec, b"\x80\x00"),
715            Err(ProtocolError::InvalidUtf8)
716        ));
717
718        let codec = Codec::new().set_client_mode();
719        assert!(decode(&codec, b"\x01\x01a").is_ok());
720        assert!(matches!(
721            decode(&codec, b"\x00\x02b\xff"),
722            Err(ProtocolError::InvalidUtf8)
723        ));
724
725        let codec = Codec::new().set_client_mode();
726        assert!(decode(&codec, b"\x02\x01\xe2").is_ok());
727        assert!(matches!(
728            decode(&codec, b"\x80\x01\xff"),
729            Ok(Some(Frame::Continuation(Item::Last(_))))
730        ));
731    }
732
733    /// STATEMENT: The message size limit bounds the total payload of a fragmented message, applies to single frames, ignores control frames, and resets per message.
734    ///
735    /// HOW:
736    /// - With `max_message_size(3)`, decode a 3-byte message split by a ping and expect success, then a second message of the same size.
737    /// - Expect `Overflow` for a fragment that takes the total to 4 bytes and for a 4-byte single frame.
738    #[test]
739    fn message_size_limit() {
740        let codec = Codec::new().set_client_mode().max_message_size(3);
741        for _ in 0..2 {
742            assert!(decode(&codec, b"\x02\x02ab").is_ok());
743            assert!(matches!(
744                decode(&codec, b"\x89\x04ping"),
745                Ok(Some(Frame::Ping(_)))
746            ));
747            assert!(matches!(
748                decode(&codec, b"\x80\x01c"),
749                Ok(Some(Frame::Continuation(Item::Last(_))))
750            ));
751        }
752
753        assert!(decode(&codec, b"\x01\x02ab").is_ok());
754        assert!(decode(&codec, b"\x00\x01c").is_ok());
755        assert!(matches!(
756            decode(&codec, b"\x80\x01d"),
757            Err(ProtocolError::Overflow)
758        ));
759
760        let codec = Codec::new().set_client_mode().max_message_size(3);
761        assert!(matches!(
762            decode(&codec, b"\x82\x04abcd"),
763            Err(ProtocolError::Overflow)
764        ));
765    }
766
767    /// STATEMENT: Receiving close discards both buffered and subsequently received frames.
768    ///
769    /// HOW:
770    /// - Decode close followed by text, then add another text frame and verify both later decodes clear input without output.
771    #[test]
772    fn input_after_close_is_discarded() {
773        let codec = Codec::new().set_client_mode();
774        // close frame, followed by a text frame
775        let mut src = BytesMut::from(&[0x88, 0x00, 0x81, 0x01, b'a'][..]);
776        assert!(matches!(
777            codec.decode(&mut src),
778            Ok(Some(Frame::Close(None)))
779        ));
780        assert!(matches!(codec.decode(&mut src), Ok(None)));
781        assert!(src.is_empty());
782
783        src.extend_from_slice(&[0x81, 0x01, b'b']);
784        assert!(matches!(codec.decode(&mut src), Ok(None)));
785        assert!(src.is_empty());
786    }
787
788    /// STATEMENT: Receivers accept extension close code 1010 even though server-side encoders reject sending it.
789    ///
790    /// HOW:
791    /// - Decode a peer close with code 1010 and attempt to encode the same reason in server mode.
792    #[test]
793    fn accepts_extension_close_code() {
794        // servers should not send 1010, but receivers accept it
795        let codec = Codec::new().set_client_mode();
796        let mut close = BytesMut::from(&[0x88, 0x02, 0x03, 0xf2][..]);
797        assert!(matches!(
798            codec.decode(&mut close),
799            Ok(Some(Frame::Close(Some(CloseReason {
800                code: CloseCode::Extension,
801                ..
802            }))))
803        ));
804
805        // servers still cannot send it
806        let codec = Codec::new();
807        let mut dst = BytePages::default();
808        assert!(matches!(
809            codec.encode(Message::Close(Some(CloseCode::Extension.into())), &mut dst),
810            Err(ProtocolError::InvalidCloseCode(1010))
811        ));
812    }
813
814    /// STATEMENT: An active fragmented message prevents unrelated text or page messages until its last fragment.
815    ///
816    /// HOW:
817    /// - Start a binary continuation, reject text/page sends, end it, and verify a page can then be encoded.
818    #[test]
819    fn validates_outgoing_continuations() {
820        let codec = Codec::new();
821        let mut dst = BytePages::default();
822        codec
823            .encode(
824                Message::Continuation(Item::FirstBinary(Bytes::new())),
825                &mut dst,
826            )
827            .unwrap();
828        assert!(matches!(
829            codec.encode(Message::Text("text".into()), &mut dst),
830            Err(ProtocolError::ContinuationStarted)
831        ));
832        assert!(matches!(
833            codec.encode_page(BytePage::from(Bytes::new()), &mut dst),
834            Err(ProtocolError::ContinuationStarted)
835        ));
836
837        codec
838            .encode(Message::Continuation(Item::Last(Bytes::new())), &mut dst)
839            .unwrap();
840        codec
841            .encode_page(BytePage::from(Bytes::new()), &mut dst)
842            .unwrap();
843    }
844
845    /// STATEMENT: Sending close prevents later text and page messages.
846    ///
847    /// HOW:
848    /// - Encode close, then check both outgoing data APIs return the closed-protocol error.
849    #[test]
850    fn rejects_messages_after_close() {
851        let codec = Codec::new();
852        let mut dst = BytePages::default();
853        codec.encode(Message::Close(None), &mut dst).unwrap();
854
855        assert!(matches!(
856            codec.encode(Message::Text("text".into()), &mut dst),
857            Err(ProtocolError::Closed)
858        ));
859        assert!(matches!(
860            codec.encode_page(BytePage::from(Bytes::new()), &mut dst),
861            Err(ProtocolError::Closed)
862        ));
863    }
864
865    /// STATEMENT: Encoding rejects oversized controls and invalid continuation transitions.
866    ///
867    /// HOW:
868    /// - Reject oversized ping/pong, new data during a text continuation, and continuation after its last fragment.
869    #[test]
870    fn encode_errors() {
871        let codec = Codec::new();
872        let mut dst = BytePages::default();
873        let big = Bytes::from(vec![0; 126]);
874        assert!(matches!(
875            codec.encode(Message::Ping(big.clone()), &mut dst),
876            Err(ProtocolError::InvalidLength(126))
877        ));
878        assert!(matches!(
879            codec.encode(Message::Pong(big), &mut dst),
880            Err(ProtocolError::InvalidLength(126))
881        ));
882
883        codec
884            .encode(Message::Continuation(Item::FirstText("a".into())), &mut dst)
885            .unwrap();
886        assert!(matches!(
887            codec.encode(Message::Binary("b".into()), &mut dst),
888            Err(ProtocolError::ContinuationStarted)
889        ));
890        assert!(matches!(
891            codec.encode(
892                Message::Continuation(Item::FirstBinary("b".into())),
893                &mut dst
894            ),
895            Err(ProtocolError::ContinuationStarted)
896        ));
897        codec
898            .encode(Message::Continuation(Item::Last("c".into())), &mut dst)
899            .unwrap();
900        assert!(matches!(
901            codec.encode(Message::Continuation(Item::Continue("d".into())), &mut dst),
902            Err(ProtocolError::ContinuationNotStarted)
903        ));
904    }
905
906    fn decode(codec: &Codec, frame: &[u8]) -> Result<Option<Frame>, ProtocolError> {
907        codec.decode(&mut BytesMut::from(frame))
908    }
909
910    /// STATEMENT: Decoding enforces fragmented-message ordering without preventing valid later continuation frames.
911    ///
912    /// HOW:
913    /// - Reject orphan continuations and new data while a binary message is open.
914    /// - Continue that message and verify an empty final fragment completes it.
915    #[test]
916    fn decode_continuation_errors() {
917        let codec = Codec::new().set_client_mode();
918        // continuation without a first frame
919        assert!(matches!(
920            decode(&codec, &[0x80, 0x01, b'a']),
921            Err(ProtocolError::ContinuationNotStarted)
922        ));
923        assert!(matches!(
924            decode(&codec, &[0x00, 0x01, b'a']),
925            Err(ProtocolError::ContinuationNotStarted)
926        ));
927
928        // new data frames while a fragmented message is in progress
929        assert!(matches!(
930            decode(&codec, &[0x02, 0x01, b'a']),
931            Ok(Some(Frame::Continuation(Item::FirstBinary(_))))
932        ));
933        for frame in [
934            &[0x82, 0x01, b'a'],
935            &[0x81, 0x01, b'a'],
936            &[0x02, 0x01, b'a'],
937            &[0x01, 0x01, b'a'],
938        ] {
939            assert!(matches!(
940                decode(&codec, frame),
941                Err(ProtocolError::ContinuationStarted)
942            ));
943        }
944        assert!(matches!(
945            decode(&codec, &[0x00, 0x01, b'b']),
946            Ok(Some(Frame::Continuation(Item::Continue(_))))
947        ));
948        assert!(matches!(
949            decode(&codec, &[0x80, 0x00]),
950            Ok(Some(Frame::Continuation(Item::Last(data)))) if data.is_empty()
951        ));
952    }
953
954    #[cfg(feature = "compress")]
955    mod deflate {
956        use super::*;
957        use crate::ws::DeflateConfig;
958
959        fn client() -> Codec {
960            Codec::new()
961                .set_client_mode()
962                .set_deflate(DeflateConfig::new())
963        }
964
965        fn server() -> Codec {
966            Codec::new().set_deflate(DeflateConfig::new())
967        }
968
969        fn encode(codec: &Codec, msg: Message) -> BytesMut {
970            let mut dst = BytePages::default();
971            codec.encode(msg, &mut dst).unwrap();
972            BytesMut::from(&Bytes::from(dst)[..])
973        }
974
975        fn decode_all(codec: &Codec, mut src: BytesMut) -> Vec<Frame> {
976            let mut frames = Vec::new();
977            while let Some(frame) = codec.decode(&mut src).unwrap() {
978                frames.push(frame);
979            }
980            assert!(src.is_empty());
981            frames
982        }
983
984        fn text(data: &'static str) -> Frame {
985            Frame::Text(Bytes::from_static(data.as_bytes()))
986        }
987
988        /// STATEMENT: Deflate frame decoding matches RFC 7692 examples across fragmentation, context reuse, and block forms.
989        ///
990        /// HOW:
991        /// - Decode published single/fragmented, context-dependent, stored, final-block, multi-block, and empty messages.
992        /// - Compare their text and continuation outputs.
993        #[test]
994        fn rfc7692_examples() {
995            // 7.2.3.1, a message in one frame and in two fragments
996            let frames = decode_all(
997                &client(),
998                BytesMut::from(&[0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00][..]),
999            );
1000            assert_eq!(frames, [text("Hello")]);
1001            let frames = decode_all(
1002                &client(),
1003                BytesMut::from(
1004                    &[
1005                        0x41, 0x03, 0xf2, 0x48, 0xcd, 0x80, 0x04, 0xc9, 0xc9, 0x07, 0x00,
1006                    ][..],
1007                ),
1008            );
1009            assert_eq!(
1010                frames,
1011                [
1012                    Frame::Continuation(Item::FirstText(Bytes::from_static(b"He"))),
1013                    Frame::Continuation(Item::Last(Bytes::from_static(b"llo"))),
1014                ]
1015            );
1016
1017            // 7.2.3.2, the second message refers to the first one
1018            let frames = decode_all(
1019                &client(),
1020                BytesMut::from(
1021                    &[
1022                        0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00, 0xc1, 0x05, 0xf2,
1023                        0x00, 0x11, 0x00, 0x00,
1024                    ][..],
1025                ),
1026            );
1027            assert_eq!(frames, [text("Hello"), text("Hello")]);
1028
1029            // 7.2.3.3, a stored block
1030            // 7.2.3.4, a block with BFINAL set, followed by a new stream
1031            // 7.2.3.5, two blocks in one message
1032            // 7.2.3.6, an empty message
1033            let frames = decode_all(
1034                &client(),
1035                BytesMut::from(
1036                    &[
1037                        0xc1, 0x0b, 0x00, 0x05, 0x00, 0xfa, 0xff, 0x48, 0x65, 0x6c, 0x6c, 0x6f,
1038                        0x00, 0xc1, 0x08, 0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00, 0x00, 0xc1,
1039                        0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00, 0xc1, 0x0d, 0xf2, 0x48,
1040                        0x05, 0x00, 0x00, 0x00, 0xff, 0xff, 0xca, 0xc9, 0xc9, 0x07, 0x00, 0xc1,
1041                        0x01, 0x00, 0xc1, 0x00,
1042                    ][..],
1043                ),
1044            );
1045            assert_eq!(
1046                frames,
1047                [
1048                    text("Hello"),
1049                    text("Hello"),
1050                    text("Hello"),
1051                    text("Hello"),
1052                    text(""),
1053                    text("")
1054                ]
1055            );
1056        }
1057
1058        /// STATEMENT: No-context-takeover servers skip small whole messages but still compress fragments.
1059        ///
1060        /// HOW:
1061        /// - Inspect frame flags and round trips around the small-message threshold, then encode a fragment.
1062        /// - Verify the client still compresses small messages when its context remains enabled.
1063        #[test]
1064        fn small_messages_without_context_takeover() {
1065            let cfg = DeflateConfig::new().set_server_no_context_takeover(true);
1066            let server = Codec::new().set_deflate(cfg.clone());
1067            let client = Codec::new().set_client_mode().set_deflate(cfg);
1068
1069            // small unfragmented messages are not compressed
1070            for (len, first) in [(0, 0x82), (32, 0x82), (33, 0xc2)] {
1071                let data = Bytes::from("a".repeat(len));
1072                let frame = encode(&server, Message::Binary(data.clone()));
1073                assert_eq!(frame[0], first);
1074                assert_eq!(decode_all(&client, frame), [Frame::Binary(data)]);
1075            }
1076
1077            // fragmented messages are compressed
1078            let frame = encode(
1079                &server,
1080                Message::Continuation(Item::FirstText(Bytes::from_static(b"a"))),
1081            );
1082            assert_eq!(frame[0], 0x41);
1083
1084            // the client keeps its context
1085            let frame = encode(&client, Message::Text("Hello".into()));
1086            assert_eq!(frame[0], 0xc1);
1087        }
1088
1089        /// STATEMENT: Deflate text encoding reproduces the RFC 7692 Hello example.
1090        ///
1091        /// HOW:
1092        /// - Encode the example message and compare every compressed frame byte.
1093        #[test]
1094        fn encode_rfc7692_example() {
1095            let codec = Codec::new().set_deflate(DeflateConfig::new());
1096            assert_eq!(
1097                &encode(&codec, Message::Text("Hello".into()))[..],
1098                &[0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00]
1099            );
1100        }
1101
1102        /// STATEMENT: Deflate codecs round-trip mixed messages and interleaved controls in both client/server directions.
1103        ///
1104        /// HOW:
1105        /// - Repeatedly encode text, large/empty binary data, controls, and text/binary continuations.
1106        /// - Decode each combined buffer and compare the complete frame sequence.
1107        #[test]
1108        fn roundtrip() {
1109            let (client, server) = (client(), server());
1110            let data: Vec<u8> = (0..60_000u32)
1111                .map(|i| if i % 7 == 0 { (i >> 3) as u8 } else { b'a' })
1112                .collect();
1113            let data = Bytes::from(data);
1114
1115            for _ in 0..3 {
1116                for (from, to) in [(&client, &server), (&server, &client)] {
1117                    let msgs = [
1118                        Message::Text("text message".into()),
1119                        Message::Binary(data.clone()),
1120                        Message::Binary(Bytes::new()),
1121                        Message::Ping("ping".into()),
1122                        Message::Continuation(Item::FirstBinary(data.slice(..1000))),
1123                        Message::Pong("pong".into()),
1124                        Message::Continuation(Item::Continue(Bytes::new())),
1125                        Message::Continuation(Item::Continue(data.slice(1000..30_000))),
1126                        Message::Continuation(Item::Last(data.slice(30_000..))),
1127                        Message::Continuation(Item::FirstText("a".into())),
1128                        Message::Continuation(Item::Last("b".into())),
1129                    ];
1130                    let mut src = BytesMut::new();
1131                    for msg in msgs {
1132                        src.extend_from_slice(&encode(from, msg));
1133                    }
1134                    assert_eq!(
1135                        decode_all(to, src),
1136                        [
1137                            text("text message"),
1138                            Frame::Binary(data.clone()),
1139                            Frame::Binary(Bytes::new()),
1140                            Frame::Ping("ping".into()),
1141                            Frame::Continuation(Item::FirstBinary(data.slice(..1000))),
1142                            Frame::Pong("pong".into()),
1143                            Frame::Continuation(Item::Continue(Bytes::new())),
1144                            Frame::Continuation(Item::Continue(data.slice(1000..30_000))),
1145                            Frame::Continuation(Item::Last(data.slice(30_000..))),
1146                            Frame::Continuation(Item::FirstText("a".into())),
1147                            Frame::Continuation(Item::Last("b".into())),
1148                        ]
1149                    );
1150                }
1151            }
1152        }
1153
1154        /// STATEMENT: Compressed payloads remain decodable when reframed into small fragments with an empty final fragment.
1155        ///
1156        /// HOW:
1157        /// - Split compressed binary messages into 16-byte frames, append an empty last frame, and repeat with reused contexts.
1158        /// - Reassemble decoded continuation data and compare the original payload.
1159        #[test]
1160        fn fragmented_compressed_payload() {
1161            // a compressed message split into frames of 16 bytes, like the
1162            // auto-fragmentation of autobahn, the last frame can be empty
1163            let sender = server();
1164            let codec = client();
1165            let data = Bytes::from(b"Hello, Hello, Hello".repeat(40));
1166            for _ in 0..3 {
1167                let mut frame = encode(&sender, Message::Binary(data.clone()));
1168                frame.advance_to(2);
1169                let len = frame.len();
1170                frame.advance_to(if len < 126 { 0 } else { 2 });
1171                let payload = frame.freeze();
1172                let chunks: Vec<_> = payload.chunks(16).chain([&[][..]]).collect();
1173
1174                let mut src = BytesMut::new();
1175                for (i, chunk) in chunks.iter().enumerate() {
1176                    let mut first = if i == 0 { 0x42 } else { 0x00 };
1177                    if i == chunks.len() - 1 {
1178                        first |= 0x80;
1179                    }
1180                    src.extend_from_slice(&[first, chunk.len() as u8]);
1181                    src.extend_from_slice(chunk);
1182                }
1183                let mut out = BytesMut::new();
1184                for frame in decode_all(&codec, src) {
1185                    match frame {
1186                        Frame::Continuation(
1187                            Item::FirstBinary(b) | Item::Continue(b) | Item::Last(b),
1188                        ) => out.extend_from_slice(&b),
1189                        f => panic!("{f:?}"),
1190                    }
1191                }
1192                assert_eq!(out, data);
1193            }
1194        }
1195
1196        /// STATEMENT: Deflate sets RSV1 only on initial data frames and leaves controls uncompressed.
1197        ///
1198        /// HOW:
1199        /// - Inspect whole-message, continuation, ping, and close wire flags and bytes.
1200        /// - Encode a binary page and verify its compressed flag and decoded payload.
1201        #[test]
1202        fn rsv1_only_on_first_data_frame() {
1203            let codec = server();
1204            let data = Bytes::from(vec![b'x'; 1000]);
1205            let frame = encode(&codec, Message::Binary(data.clone()));
1206            assert_eq!(frame[0], 0xc2);
1207            assert!(frame.len() < 100);
1208
1209            let frame = encode(&codec, Message::Continuation(Item::FirstText("a".into())));
1210            assert_eq!(frame[0], 0x41);
1211            let frame = encode(&codec, Message::Continuation(Item::Continue("b".into())));
1212            assert_eq!(frame[0], 0x00);
1213            let frame = encode(&codec, Message::Continuation(Item::Last("c".into())));
1214            assert_eq!(frame[0], 0x80);
1215
1216            // control frames are not compressed
1217            let frame = encode(&codec, Message::Ping("ping".into()));
1218            assert_eq!(&frame[..], b"\x89\x04ping");
1219            let frame = encode(&codec, Message::Close(None));
1220            assert_eq!(&frame[..], &[0x88, 0x00]);
1221
1222            // binary pages are compressed
1223            let mut dst = BytePages::default();
1224            server()
1225                .encode_page(BytePage::from(data.clone()), &mut dst)
1226                .unwrap();
1227            let mut src = BytesMut::from(&Bytes::from(dst)[..]);
1228            assert_eq!(src[0], 0xc2);
1229            assert_eq!(
1230                client().decode(&mut src).unwrap(),
1231                Some(Frame::Binary(data))
1232            );
1233        }
1234
1235        /// STATEMENT: Negotiating deflate still permits uncompressed whole and fragmented messages.
1236        ///
1237        /// HOW:
1238        /// - Decode a buffer mixing uncompressed text/fragments/binary and an empty compressed message.
1239        /// - Compare the complete expected frame sequence.
1240        #[test]
1241        fn uncompressed_messages() {
1242            // the peer may send uncompressed messages
1243            let codec = client();
1244            let frames = decode_all(
1245                &codec,
1246                BytesMut::from(&b"\x81\x05Hello\x01\x01a\x80\x01b\xc1\x01\x00\x82\x01c"[..]),
1247            );
1248            assert_eq!(
1249                frames,
1250                [
1251                    text("Hello"),
1252                    Frame::Continuation(Item::FirstText("a".into())),
1253                    Frame::Continuation(Item::Last("b".into())),
1254                    text(""),
1255                    Frame::Binary("c".into()),
1256                ]
1257            );
1258        }
1259
1260        /// STATEMENT: Deflate does not permit RSV1 on controls/continuations or any use of RSV2/RSV3.
1261        ///
1262        /// HOW:
1263        /// - Decode illegal flag combinations and inspect reserved-bit errors.
1264        /// - Verify RSV1 is also rejected when compression was not negotiated.
1265        #[test]
1266        fn reserved_bits() {
1267            for frame in [
1268                // RSV1 on control frames and continuation frames
1269                &b"\xc9\x00"[..],
1270                b"\xca\x00",
1271                b"\xc8\x00",
1272                // RSV2 and RSV3 are not used by the extension
1273                b"\xa1\x00",
1274                b"\x91\x00",
1275                b"\xe1\x00",
1276            ] {
1277                assert!(
1278                    matches!(
1279                        decode(&client(), frame),
1280                        Err(ProtocolError::ReservedBits(_))
1281                    ),
1282                    "{frame:?}"
1283                );
1284            }
1285
1286            let codec = client();
1287            assert!(matches!(
1288                decode(&codec, b"\x01\x01a"),
1289                Ok(Some(Frame::Continuation(Item::FirstText(_))))
1290            ));
1291            assert!(matches!(
1292                decode(&codec, b"\xc0\x01\x00"),
1293                Err(ProtocolError::ReservedBits(0b100))
1294            ));
1295
1296            // RSV1 is reserved without the extension
1297            assert!(matches!(
1298                decode(
1299                    &Codec::new().set_client_mode(),
1300                    &[0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00]
1301                ),
1302                Err(ProtocolError::ReservedBits(0b100))
1303            ));
1304        }
1305
1306        /// STATEMENT: Invalid compressed data is rejected in both complete and initial-fragment frames.
1307        ///
1308        /// HOW:
1309        /// - Decode malformed deflate bytes with final and nonfinal text headers and compare protocol errors.
1310        #[test]
1311        fn invalid_data() {
1312            assert!(matches!(
1313                decode(&client(), b"\xc1\x02\xff\xff"),
1314                Err(ProtocolError::InvalidCompressedData)
1315            ));
1316            assert!(matches!(
1317                decode(&client(), b"\x41\x02\xff\xff"),
1318                Err(ProtocolError::InvalidCompressedData)
1319            ));
1320        }
1321
1322        /// STATEMENT: Frame-size limits apply to decompressed bytes, independently for each fragment.
1323        ///
1324        /// HOW:
1325        /// - Decode a highly compressed payload at and below its expanded-size limit.
1326        /// - Accept a boundary-sized first fragment and reject an oversized last fragment.
1327        #[test]
1328        fn decompressed_size_limit() {
1329            let data = Bytes::from(vec![0; 1024 * 1024]);
1330            let frame = encode(&server(), Message::Binary(data.clone()));
1331            assert!(frame.len() < 2048);
1332
1333            let codec = Codec::new()
1334                .set_client_mode()
1335                .max_size(data.len() - 1)
1336                .set_deflate(DeflateConfig::new());
1337            assert!(matches!(
1338                codec.decode(&mut frame.clone()),
1339                Err(ProtocolError::Overflow)
1340            ));
1341
1342            let codec = Codec::new()
1343                .set_client_mode()
1344                .max_size(data.len())
1345                .set_deflate(DeflateConfig::new());
1346            assert_eq!(
1347                codec.decode(&mut frame.clone()).unwrap(),
1348                Some(Frame::Binary(data))
1349            );
1350
1351            // the limit applies to each fragment
1352            let codec = Codec::new()
1353                .set_client_mode()
1354                .max_size(1000)
1355                .set_deflate(DeflateConfig::new());
1356            let sender = server();
1357            let mut src = encode(
1358                &sender,
1359                Message::Continuation(Item::FirstBinary(vec![0; 1000].into())),
1360            );
1361            src.extend_from_slice(&encode(
1362                &sender,
1363                Message::Continuation(Item::Last(vec![0; 1001].into())),
1364            ));
1365            assert!(matches!(
1366                codec.decode(&mut src),
1367                Ok(Some(Frame::Continuation(Item::FirstBinary(_))))
1368            ));
1369            assert!(matches!(
1370                codec.decode(&mut src),
1371                Err(ProtocolError::Overflow)
1372            ));
1373        }
1374
1375        /// STATEMENT: Message size limits and UTF-8 validation apply to decompressed payloads.
1376        ///
1377        /// HOW:
1378        /// - Send two compressed 1000-byte fragments to a codec with `max_message_size(1500)` and expect `Overflow` on the second.
1379        /// - Send a compressed text fragment holding `0xff` and expect `InvalidUtf8`.
1380        #[test]
1381        fn message_limits_after_decompression() {
1382            let sender = server();
1383            let codec = client().max_message_size(1500);
1384            let mut src = encode(
1385                &sender,
1386                Message::Continuation(Item::FirstBinary(vec![0; 1000].into())),
1387            );
1388            src.extend_from_slice(&encode(
1389                &sender,
1390                Message::Continuation(Item::Last(vec![0; 1000].into())),
1391            ));
1392            assert!(src.len() < 1500);
1393            assert!(matches!(
1394                codec.decode(&mut src),
1395                Ok(Some(Frame::Continuation(Item::FirstBinary(_))))
1396            ));
1397            assert!(matches!(
1398                codec.decode(&mut src),
1399                Err(ProtocolError::Overflow)
1400            ));
1401
1402            let src = encode(
1403                &server(),
1404                Message::Continuation(Item::FirstText(Bytes::from_static(&[0xff]))),
1405            );
1406            assert!(matches!(
1407                client().decode(&mut src.clone()),
1408                Err(ProtocolError::InvalidUtf8)
1409            ));
1410        }
1411
1412        /// STATEMENT: Negotiated server context resets reject cross-message references without resetting the client's compressor.
1413        ///
1414        /// HOW:
1415        /// - Compare repeated server frames and decode them with fresh contexts, then reject a back-reference-only message.
1416        /// - Verify repeated client messages shrink through retained compression history.
1417        #[test]
1418        fn context_takeover() {
1419            // the server resets its context, the client reads each message
1420            // with a new context
1421            let cfg = DeflateConfig::new().set_server_no_context_takeover(true);
1422            let server = Codec::new().set_deflate(cfg.clone());
1423            let client = Codec::new().set_client_mode().set_deflate(cfg);
1424            let first = encode(&server, Message::Text("Hello".into()));
1425            assert_eq!(encode(&server, Message::Text("Hello".into())), first);
1426            let mut src = first.clone();
1427            src.extend_from_slice(&first);
1428            assert_eq!(decode_all(&client, src), [text("Hello"), text("Hello")]);
1429
1430            // a message that refers to the previous one
1431            assert!(matches!(
1432                decode(&client, &[0xc1, 0x05, 0xf2, 0x00, 0x11, 0x00, 0x00]),
1433                Err(ProtocolError::InvalidCompressedData)
1434            ));
1435
1436            // the client keeps its context
1437            let first = encode(&client, Message::Text("Hello".into()));
1438            assert!(encode(&client, Message::Text("Hello".into())).len() < first.len());
1439        }
1440
1441        /// STATEMENT: Cloned WebSocket codecs share negotiated compression configuration and history.
1442        ///
1443        /// HOW:
1444        /// - Inspect clone/default configuration, encode consecutive messages through separate clones, and decode both together.
1445        #[test]
1446        fn clones_share_state() {
1447            let (client, server) = (client(), server());
1448            let server2 = server.clone();
1449            assert_eq!(server2.deflate(), Some(&DeflateConfig::new()));
1450            assert_eq!(Codec::new().deflate(), None);
1451
1452            let mut src = encode(&server, Message::Text("Hello".into()));
1453            src.extend_from_slice(&encode(&server2, Message::Text("Hello".into())));
1454            assert_eq!(decode_all(&client, src), [text("Hello"), text("Hello")]);
1455        }
1456    }
1457}