1use std::sync::Arc;
2use std::time::Duration;
3
4use tokio_tungstenite::tungstenite;
5
6#[derive(Debug, Clone, thiserror::Error)]
11#[non_exhaustive]
12pub enum Error {
13 #[error(transparent)]
15 Protocol(#[from] crate::protocol::Error),
16 #[error("invalid URL: {0}")]
18 InvalidUrl(#[from] url::ParseError),
19 #[error("unsupported URL scheme `{0}` (expected http, https, ws or wss)")]
21 InvalidUrlScheme(String),
22 #[error("HTTP request failed: {0}")]
24 Http(#[source] Arc<reqwest::Error>),
25 #[error("server answered HTTP {status}{}", message.as_ref().map(|m| format!(": {m}")).unwrap_or_default())]
28 #[non_exhaustive]
29 HttpStatus {
30 status: u16,
32 message: Option<String>,
35 },
36 #[error("proxy: {0}")]
38 ProxyFailed(String),
39 #[error("the server closed the websocket (code {code}{})", if reason.is_empty() { String::new() } else { format!(": {reason}") })]
41 #[non_exhaustive]
42 WebsocketClosed {
43 code: u16,
45 reason: String,
47 },
48 #[error("websocket error: {0}")]
50 Websocket(#[source] Arc<tungstenite::Error>),
51 #[error("invalid engine.io handshake: {0}")]
54 InvalidHandshake(String),
55 #[error("the engine.io connection is not open")]
57 NotConnected,
58 #[error("the server does not offer a websocket upgrade")]
60 UpgradeUnavailable,
61 #[error("websocket upgrade probe failed: {0}")]
63 UpgradeFailed(&'static str),
64 #[error("no ping from the server within pingInterval + pingTimeout")]
66 PingTimeout,
67 #[error("timed out after {0:?}")]
69 Timeout(Duration),
70 #[error(
72 "`{0}` needs TLS, but socketio-next was built without the `rustls` or `native-tls` feature"
73 )]
74 TlsNotEnabled(String),
75 #[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 #[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 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
112pub(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
142pub 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 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 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 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}