Skip to main content

ntex/ws/
error.rs

1//! WebSocket protocol related errors.
2use std::io;
3
4use crate::error::ErrorDiagnostic;
5use crate::http::error::{DecodeError, EncodeError, ResponseError};
6use crate::http::header::{ALLOW, HeaderValue, SEC_WEBSOCKET_VERSION};
7use crate::http::{Response, StatusCode};
8use crate::{connect::ConnectError, util::Either, util::clone_io_error};
9
10use super::OpCode;
11
12/// Errors produced by a WebSocket dispatcher.
13#[derive(Debug, thiserror::Error)]
14pub enum WsError<E> {
15    /// Error returned by the frame service.
16    #[error("Service error")]
17    Service(#[source] E),
18    /// The keep-alive timer expired.
19    #[error("Keep-alive error")]
20    KeepAlive,
21    /// Reading a frame timed out.
22    #[error("Frame read timeout")]
23    ReadTimeout,
24    /// Write backpressure stayed enabled for longer than the write timeout.
25    #[error("Write timeout")]
26    WriteTimeout,
27    /// WebSocket protocol error.
28    #[error("Ws protocol level error")]
29    Protocol(#[source] ProtocolError),
30    /// WebSocket opening-handshake error.
31    #[error("Ws handshake error")]
32    Handshake(#[from] HandshakeError),
33    /// The peer disconnected.
34    #[error("Peer has been disconnected: {0:?}")]
35    Disconnected(#[source] Option<io::Error>),
36}
37
38/// WebSocket protocol errors.
39#[derive(Copy, Clone, Debug, thiserror::Error)]
40pub enum ProtocolError {
41    /// Received an unmasked frame from client
42    #[error("Received an unmasked frame from client")]
43    UnmaskedFrame,
44    /// Received a masked frame from server
45    #[error("Received a masked frame from server")]
46    MaskedFrame,
47    /// Encountered invalid opcode
48    #[error("Invalid opcode: {0}")]
49    InvalidOpcode(u8),
50    /// Reserved frame bits are set without a negotiated extension.
51    #[error("Reserved frame bits are set: {0:#05b}")]
52    ReservedBits(u8),
53    /// A control frame is fragmented.
54    #[error("Fragmented control frame: {0}")]
55    FragmentedControlFrame(OpCode),
56    /// Invalid control frame length
57    #[error("Invalid control frame length: {0}")]
58    InvalidLength(usize),
59    /// A payload length does not use its shortest valid encoding.
60    #[error("Invalid payload length encoding")]
61    InvalidLengthEncoding,
62    /// Invalid close status code.
63    #[error("Invalid close status code: {0}")]
64    InvalidCloseCode(u16),
65    /// Invalid close-frame payload.
66    #[error("Invalid close-frame payload")]
67    InvalidClosePayload,
68    /// A text message or a close-frame description is not valid UTF-8.
69    #[error("Invalid UTF-8 in text message or close-frame description")]
70    InvalidUtf8,
71    /// A message was encoded after a close message.
72    #[error("WebSocket codec is closed")]
73    Closed,
74    /// A frame or message payload exceeds the size limit.
75    #[error("A payload reached size limit.")]
76    Overflow,
77    /// Continuation is not started
78    #[error("Continuation is not started.")]
79    ContinuationNotStarted,
80    /// Received new continuation but it is already started
81    #[error("Received new continuation but it is already started")]
82    ContinuationStarted,
83    /// A compressed message cannot be decompressed.
84    #[error("Invalid compressed message")]
85    InvalidCompressedData,
86}
87
88/// Errors produced while configuring a WebSocket client.
89#[derive(Clone, Debug, thiserror::Error)]
90pub enum WsConfigError {
91    /// The URI does not contain a scheme.
92    #[error("Missing url scheme")]
93    MissingScheme,
94    /// The URI uses an unsupported scheme.
95    #[error("Unknown url scheme")]
96    UnknownScheme,
97    /// The URI does not contain a host.
98    #[error("Missing host name")]
99    MissingHost,
100    /// The URI uses `wss` or `https`, but the client uses the default plain
101    /// connector.
102    #[error("Secure url scheme requires a TLS connector")]
103    TlsRequired,
104    /// The URI could not be parsed.
105    #[error("Url parse error: {0}")]
106    Parse(
107        #[from]
108        #[source]
109        urly::InvalidUrl,
110    ),
111}
112
113impl From<std::convert::Infallible> for WsConfigError {
114    fn from(err: std::convert::Infallible) -> WsConfigError {
115        match err {}
116    }
117}
118
119/// Errors produced while establishing or using a WebSocket client connection.
120#[derive(Debug, thiserror::Error)]
121pub enum WsClientError {
122    /// Invalid client configuration.
123    #[error("Invalid client configuration: {0}")]
124    Config(
125        #[from]
126        #[source]
127        WsConfigError,
128    ),
129    /// Invalid request
130    #[error("Invalid request")]
131    InvalidRequest(
132        #[from]
133        #[source]
134        EncodeError,
135    ),
136    /// Invalid response
137    #[error("Invalid response")]
138    InvalidResponse(
139        #[from]
140        #[source]
141        DecodeError,
142    ),
143    /// Invalid response status
144    #[error("Invalid response status: {0}")]
145    InvalidResponseStatus(StatusCode),
146    /// Invalid upgrade header
147    #[error("Invalid upgrade header")]
148    InvalidUpgradeHeader,
149    /// Invalid connection header
150    #[error("Invalid connection header")]
151    InvalidConnectionHeader(HeaderValue),
152    /// Missing CONNECTION header
153    #[error("Missing CONNECTION header")]
154    MissingConnectionHeader,
155    /// Missing SEC-WEBSOCKET-ACCEPT header
156    #[error("Missing SEC-WEBSOCKET-ACCEPT header")]
157    MissingWebSocketAcceptHeader,
158    /// Invalid challenge response
159    #[error("Invalid challenge response")]
160    InvalidChallengeResponse(String, HeaderValue),
161    /// The server selected an invalid or unrequested WebSocket subprotocol.
162    #[error("Invalid WebSocket subprotocol: {0:?}")]
163    InvalidWebSocketProtocol(HeaderValue),
164    /// The server returned an extension that the client did not offer.
165    #[error("Unexpected WebSocket extensions: {0:?}")]
166    UnexpectedWebSocketExtensions(HeaderValue),
167    /// The server accepted an offered extension with invalid parameters.
168    #[error("Invalid WebSocket extensions: {0:?}")]
169    InvalidWebSocketExtensions(HeaderValue),
170    /// Protocol error
171    #[error("{0}")]
172    Protocol(
173        #[from]
174        #[source]
175        ProtocolError,
176    ),
177    /// The opening handshake timed out.
178    #[error("Timeout while waiting for response")]
179    Timeout,
180    /// Failed to connect to host
181    #[error("Failed to connect to host: {0}")]
182    Connect(
183        #[from]
184        #[source]
185        ConnectError,
186    ),
187    /// Connector has been disconnected
188    #[error("Connector has been disconnected: {0:?}")]
189    Disconnected(#[source] Option<io::Error>),
190}
191
192impl From<Either<DecodeError, io::Error>> for WsClientError {
193    fn from(err: Either<DecodeError, io::Error>) -> Self {
194        match err {
195            Either::Left(err) => WsClientError::InvalidResponse(err),
196            Either::Right(err) => WsClientError::Disconnected(Some(err)),
197        }
198    }
199}
200
201impl From<Either<EncodeError, io::Error>> for WsClientError {
202    fn from(err: Either<EncodeError, io::Error>) -> Self {
203        match err {
204            Either::Left(err) => WsClientError::InvalidRequest(err),
205            Either::Right(err) => WsClientError::Disconnected(Some(err)),
206        }
207    }
208}
209
210impl Clone for WsClientError {
211    fn clone(&self) -> Self {
212        match self {
213            WsClientError::Config(err) => WsClientError::Config(err.clone()),
214            WsClientError::InvalidRequest(err) => WsClientError::InvalidRequest(err.clone()),
215            WsClientError::InvalidResponse(err) => WsClientError::InvalidResponse(*err),
216            WsClientError::InvalidResponseStatus(err) => WsClientError::InvalidResponseStatus(*err),
217            WsClientError::InvalidUpgradeHeader => WsClientError::InvalidUpgradeHeader,
218            WsClientError::InvalidConnectionHeader(err) => {
219                WsClientError::InvalidConnectionHeader(err.clone())
220            }
221            WsClientError::MissingConnectionHeader => WsClientError::MissingConnectionHeader,
222            WsClientError::MissingWebSocketAcceptHeader => {
223                WsClientError::MissingWebSocketAcceptHeader
224            }
225            WsClientError::InvalidChallengeResponse(n, val) => {
226                WsClientError::InvalidChallengeResponse(n.clone(), val.clone())
227            }
228            WsClientError::InvalidWebSocketProtocol(val) => {
229                WsClientError::InvalidWebSocketProtocol(val.clone())
230            }
231            WsClientError::UnexpectedWebSocketExtensions(val) => {
232                WsClientError::UnexpectedWebSocketExtensions(val.clone())
233            }
234            WsClientError::InvalidWebSocketExtensions(val) => {
235                WsClientError::InvalidWebSocketExtensions(val.clone())
236            }
237            WsClientError::Protocol(err) => WsClientError::Protocol(*err),
238            WsClientError::Timeout => WsClientError::Timeout,
239            WsClientError::Connect(err) => WsClientError::Connect(err.clone()),
240            WsClientError::Disconnected(err) => {
241                WsClientError::Disconnected(err.as_ref().map(clone_io_error))
242            }
243        }
244    }
245}
246
247impl ErrorDiagnostic for WsClientError {
248    fn signature(&self) -> &'static str {
249        "ntex-ws-client"
250    }
251}
252
253/// Errors produced while validating a WebSocket opening handshake.
254#[derive(Copy, Clone, PartialEq, Eq, Debug, thiserror::Error)]
255pub enum HandshakeError {
256    /// Only get method is allowed
257    #[error("Method not allowed")]
258    GetMethodRequired,
259    /// Upgrade header if not set to websocket
260    #[error("Websocket upgrade is expected")]
261    NoWebsocketUpgrade,
262    /// Connection header is not set to upgrade
263    #[error("Connection upgrade is expected")]
264    NoConnectionUpgrade,
265    /// Websocket version header is not set
266    #[error("Websocket version header is required")]
267    NoVersionHeader,
268    /// Unsupported websocket version
269    #[error("Unsupported version")]
270    UnsupportedVersion,
271    /// Websocket key is not set or wrong
272    #[error("Unknown websocket key")]
273    BadWebsocketKey,
274    /// The selected WebSocket subprotocol was not requested by the client.
275    #[error("Invalid websocket subprotocol")]
276    BadWebsocketProtocol,
277}
278
279impl ResponseError for HandshakeError {
280    fn error_response(&self) -> Response {
281        match *self {
282            HandshakeError::GetMethodRequired => {
283                Response::MethodNotAllowed().header(ALLOW, "GET").build()
284            }
285            HandshakeError::NoWebsocketUpgrade => Response::BadRequest()
286                .reason("No WebSocket UPGRADE header found")
287                .build(),
288            HandshakeError::NoConnectionUpgrade => Response::BadRequest()
289                .reason("No CONNECTION upgrade")
290                .build(),
291            HandshakeError::NoVersionHeader => Response::BadRequest()
292                .reason("Websocket version header is required")
293                .header(SEC_WEBSOCKET_VERSION, "13")
294                .build(),
295            HandshakeError::UnsupportedVersion => Response::BadRequest()
296                .reason("Unsupported version")
297                .header(SEC_WEBSOCKET_VERSION, "13")
298                .build(),
299            HandshakeError::BadWebsocketKey => {
300                Response::BadRequest().reason("Handshake error").build()
301            }
302            HandshakeError::BadWebsocketProtocol => Response::BadRequest()
303                .reason("Invalid websocket subprotocol")
304                .build(),
305        }
306    }
307}
308
309impl ResponseError for ProtocolError {}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314
315    /// STATEMENT: WebSocket client conversion distinguishes codec failures from transport disconnects.
316    ///
317    /// HOW:
318    /// - Convert both sides of decoding and encoding error unions and inspect the resulting error variants.
319    #[test]
320    fn test_client_error_from_either() {
321        let err = WsClientError::from(Either::<DecodeError, io::Error>::Left(DecodeError::Method));
322        assert!(matches!(
323            err,
324            WsClientError::InvalidResponse(DecodeError::Method)
325        ));
326        let err = WsClientError::from(Either::<DecodeError, _>::Right(io::Error::other("x")));
327        assert!(matches!(err, WsClientError::Disconnected(Some(_))));
328
329        let err = WsClientError::from(Either::<EncodeError, io::Error>::Left(
330            EncodeError::UnexpectedEof,
331        ));
332        assert!(matches!(
333            err,
334            WsClientError::InvalidRequest(EncodeError::UnexpectedEof)
335        ));
336        let err = WsClientError::from(Either::<EncodeError, _>::Right(io::Error::other("x")));
337        assert!(matches!(err, WsClientError::Disconnected(Some(_))));
338    }
339
340    /// STATEMENT: Cloning WebSocket client errors preserves their diagnostics and error signature.
341    ///
342    /// HOW:
343    /// - Clone configuration, handshake, protocol, timeout, connection, and disconnect errors.
344    /// - Compare display/debug output and check the common client-error signature.
345    #[test]
346    fn test_client_error_clone() {
347        let hdr = HeaderValue::from_static("v");
348        let errs = [
349            WsClientError::Config(WsConfigError::MissingHost),
350            WsClientError::InvalidRequest(EncodeError::UnexpectedEof),
351            WsClientError::InvalidResponse(DecodeError::Method),
352            WsClientError::InvalidResponseStatus(StatusCode::OK),
353            WsClientError::InvalidUpgradeHeader,
354            WsClientError::InvalidConnectionHeader(hdr.clone()),
355            WsClientError::MissingConnectionHeader,
356            WsClientError::MissingWebSocketAcceptHeader,
357            WsClientError::InvalidChallengeResponse("key".into(), hdr.clone()),
358            WsClientError::InvalidWebSocketProtocol(hdr.clone()),
359            WsClientError::UnexpectedWebSocketExtensions(hdr.clone()),
360            WsClientError::InvalidWebSocketExtensions(hdr),
361            WsClientError::Protocol(ProtocolError::Overflow),
362            WsClientError::Timeout,
363            WsClientError::Connect(ConnectError::Unresolved),
364            WsClientError::Disconnected(None),
365            WsClientError::Disconnected(Some(io::Error::other("disconnected"))),
366        ];
367        for err in errs {
368            assert_eq!(err.clone().to_string(), err.to_string());
369            assert_eq!(format!("{:?}", err.clone()), format!("{err:?}"));
370            assert_eq!(err.signature(), "ntex-ws-client");
371        }
372    }
373}