Skip to main content

socketio_next/engineio/
error.rs

1use std::sync::Arc;
2use std::time::Duration;
3
4use tokio_tungstenite::tungstenite;
5
6/// Everything that can go wrong in the engine.io client.
7///
8/// Errors never contain the request URL: query strings often carry tokens, so `reqwest`
9/// errors are stored without their URL.
10#[derive(Debug, Clone, thiserror::Error)]
11#[non_exhaustive]
12pub enum Error {
13    /// A packet broke the engine.io wire format.
14    #[error(transparent)]
15    Protocol(#[from] crate::protocol::Error),
16    /// The server URL does not parse.
17    #[error("invalid URL: {0}")]
18    InvalidUrl(#[from] url::ParseError),
19    /// The URL scheme is not http, https, ws or wss.
20    #[error("unsupported URL scheme `{0}` (expected http, https, ws or wss)")]
21    InvalidUrlScheme(String),
22    /// An HTTP request (polling transport) failed: connection refused, DNS, TLS, timeout, ...
23    #[error("HTTP request failed: {0}")]
24    Http(#[source] Arc<reqwest::Error>),
25    /// The server answered a polling request with a non-200 status (400 "Session ID unknown"
26    /// after a server restart, 403 from a proxy, ...).
27    #[error("server answered HTTP {status}{}", message.as_ref().map(|m| format!(": {m}")).unwrap_or_default())]
28    #[non_exhaustive]
29    HttpStatus {
30        /// The HTTP status code.
31        status: u16,
32        /// engine.io's error message when the body is its `{"code": n, "message": ".."}` JSON
33        /// (at most 200 characters, URLs and queries removed); `None` for any other body.
34        message: Option<String>,
35    },
36    /// The HTTP proxy refused or broke the `CONNECT` tunnel (never shows the proxy URL).
37    #[error("proxy: {0}")]
38    ProxyFailed(String),
39    /// The server closed the websocket with a close frame (code and reason as sent).
40    #[error("the server closed the websocket (code {code}{})", if reason.is_empty() { String::new() } else { format!(": {reason}") })]
41    #[non_exhaustive]
42    WebsocketClosed {
43        /// The close code (1000 normal, 1001 going away, 4xxx application codes, ...).
44        code: u16,
45        /// The close reason, possibly empty.
46        reason: String,
47    },
48    /// The websocket failed to open or broke.
49    #[error("websocket error: {0}")]
50    Websocket(#[source] Arc<tungstenite::Error>),
51    /// The handshake (`0{...}` open packet) is missing or malformed. An Engine.IO v3 server
52    /// answers in a format this v4 client does not speak.
53    #[error("invalid engine.io handshake: {0}")]
54    InvalidHandshake(String),
55    /// `emit` before `connect` or after the connection closed.
56    #[error("the engine.io connection is not open")]
57    NotConnected,
58    /// The handshake did not offer `websocket` in `upgrades` (server or proxy allows polling only).
59    #[error("the server does not offer a websocket upgrade")]
60    UpgradeUnavailable,
61    /// The websocket upgrade probe (`2probe` / `3probe`) failed.
62    #[error("websocket upgrade probe failed: {0}")]
63    UpgradeFailed(&'static str),
64    /// No ping from the server within pingInterval + pingTimeout: the link is dead.
65    #[error("no ping from the server within pingInterval + pingTimeout")]
66    PingTimeout,
67    /// The handshake or websocket connect took longer than the timeout.
68    #[error("timed out after {0:?}")]
69    Timeout(Duration),
70    /// `https`/`wss` without a TLS feature.
71    #[error(
72        "`{0}` needs TLS, but socketio-next was built without the `rustls` or `native-tls` feature"
73    )]
74    TlsNotEnabled(String),
75    /// Another crate in the build turned on reqwest's `rustls-no-provider` feature (e.g.
76    /// `tauri-plugin-updater`), so reqwest wants a rustls crypto provider that nobody installed.
77    #[error(
78        "reqwest was built with rustls by another crate but has no crypto provider: enable the `rustls` feature of socketio-next or install a rustls CryptoProvider before connecting"
79    )]
80    TlsProviderMissing,
81    /// The TLS configuration could not be built (bad PEM, unsupported protocol versions).
82    #[error("invalid TLS configuration: {0}")]
83    InvalidTlsConfig(String),
84}
85
86impl From<reqwest::Error> for Error {
87    fn from(err: reqwest::Error) -> Self {
88        Error::Http(Arc::new(err.without_url()))
89    }
90}
91
92impl From<tungstenite::Error> for Error {
93    fn from(err: tungstenite::Error) -> Self {
94        match err {
95            // a refused handshake (3xx, 4xx): its response may carry a `Location` with the
96            // query; only the status is kept
97            tungstenite::Error::Http(response) => Error::HttpStatus {
98                status: response.status().as_u16(),
99                message: None,
100            },
101            err => Error::Websocket(Arc::new(err)),
102        }
103    }
104}
105
106impl From<std::str::Utf8Error> for Error {
107    fn from(err: std::str::Utf8Error) -> Self {
108        Error::Protocol(err.into())
109    }
110}
111
112/// The message of a non-200 polling body (read up to 4 KiB). Only engine.io's own error
113/// JSON counts: an object with a numeric `code` and a string `message`; that message, at most
114/// 200 characters, with URL-, path- and query-like words removed. Any other body (an HTML
115/// page, text, other JSON) is `None`: it may echo the request, a header or a token in forms no
116/// filter can know.
117pub(crate) fn body_message(body: &[u8]) -> Option<String> {
118    let json: serde_json::Value = serde_json::from_slice(body).ok()?;
119    json.get("code")?.as_u64()?;
120    let message = json.get("message")?.as_str()?;
121    let text = message
122        .split_whitespace()
123        .map(|word| {
124            let lower = word.to_ascii_lowercase();
125            if word.contains("://") {
126                "<url>"
127            } else if word.starts_with('/')
128                || word.starts_with('?')
129                || ((lower.contains('?') || lower.contains('&')) && lower.contains('='))
130            {
131                "<redacted>"
132            } else {
133                word
134            }
135        })
136        .collect::<Vec<_>>()
137        .join(" ");
138    let text: String = text.chars().take(200).collect();
139    (!text.is_empty()).then_some(text)
140}
141
142/// Result alias of this crate.
143pub type Result<T> = std::result::Result<T, Error>;
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    #[test]
150    fn body_messages() {
151        // engine.io's error JSON: its message is kept (URLs and queries in it removed)
152        for (body, kept) in [
153            (
154                &br#"{"code":1,"message":"Session ID unknown"}"#[..],
155                "Session ID unknown",
156            ),
157            (br#"{"code":4,"message":"Forbidden"}"#, "Forbidden"),
158            (br#"{"code":4,"message":"token expired"}"#, "token expired"),
159            (
160                br#"{"code":4,"message":"denied by middleware: try again later"}"#,
161                "denied by middleware: try again later",
162            ),
163            (
164                br#"{"code":3,"message":"Bad request ?sid=x&token=S see https://h/?t=S"}"#,
165                "Bad request <redacted> see <url>",
166            ),
167        ] {
168            assert_eq!(body_message(body).as_deref(), Some(kept), "{body:?}");
169        }
170        let long = format!(r#"{{"code":1,"message":"{}"}}"#, "a".repeat(500));
171        assert_eq!(body_message(long.as_bytes()).unwrap().len(), 200);
172        // anything else says nothing: no filter knows every way a body can carry a secret
173        for body in [
174            &b"X-Auth-Token: S"[..],
175            b"access-token: S",
176            b"Authorization: Token S",
177            b"Authorization: ApiKey S",
178            b"Authorization: Digest username=\"u\", response=\"S\"",
179            br#"{"error":"denied","token":"S"}"#,
180            br#"{"message":"no code here","token":"S"}"#,
181            br#"{"code":"1","message":"string code"}"#,
182            b"token%3DS",
183            b"token = S",
184            b"password : S",
185            b"Cookie: a=b; sid=S",
186            b"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.S",
187            b"<b>password</b> S",
188            b"Cannot GET /socket.io/?EIO=4&token=S",
189            b"<h1>Forbidden</h1>",
190            b"  ",
191        ] {
192            assert_eq!(body_message(body), None, "{body:?}");
193        }
194        let e = Error::HttpStatus {
195            status: 400,
196            message: Some("Session ID unknown".into()),
197        };
198        assert_eq!(
199            e.to_string(),
200            "server answered HTTP 400: Session ID unknown"
201        );
202        let e = Error::WebsocketClosed {
203            code: 4001,
204            reason: "bye".into(),
205        };
206        assert_eq!(
207            e.to_string(),
208            "the server closed the websocket (code 4001: bye)"
209        );
210    }
211
212    #[tokio::test]
213    async fn http_errors_drop_the_url() {
214        tokio::time::timeout(std::time::Duration::from_secs(90), async move {
215            // nothing listens on port 9 of localhost
216            let client = crate::engineio::tls::apply_reqwest_tls!(reqwest::Client::builder(), None)
217                .build()
218                .unwrap();
219            let err = client
220                .get("http://127.0.0.1:9/engine.io/?token=SECRET")
221                .send()
222                .await
223                .unwrap_err();
224            let err = Error::from(err);
225            let text = format!("{err} {err:?}");
226            assert!(!text.contains("SECRET"), "{text}");
227        })
228        .await
229        .expect("test `http_errors_drop_the_url` timed out")
230    }
231}