Skip to main content

ntex/ws/
handshake.rs

1//! WebSocket opening-handshake helpers.
2use base64::{Engine, engine::general_purpose::STANDARD as base64};
3
4use crate::http::header::HeaderName;
5use crate::http::{HeaderMap, RequestHead, Response, ResponseBuilder};
6use crate::http::{Method, StatusCode, header};
7
8use super::error::HandshakeError;
9
10/// Verifies a WebSocket opening-handshake request and creates its response.
11///
12/// # Errors
13///
14/// Returns [`HandshakeError`] when the request method or required upgrade
15/// headers are invalid.
16pub fn handshake(req: &RequestHead) -> Result<ResponseBuilder, HandshakeError> {
17    verify_handshake(req)?;
18    Ok(handshake_response(req))
19}
20
21/// Verifies a WebSocket opening-handshake request.
22///
23/// The request must use `GET`, request a connection upgrade to WebSocket,
24/// include a `Sec-WebSocket-Key`, and use WebSocket version 13.
25///
26/// # Errors
27///
28/// Returns [`HandshakeError`] when the request method or required upgrade
29/// headers are invalid.
30pub fn verify_handshake(req: &RequestHead) -> Result<(), HandshakeError> {
31    // WebSocket accepts only GET
32    if req.method != Method::GET {
33        return Err(HandshakeError::GetMethodRequired);
34    }
35
36    // Check for "UPGRADE" to websocket header
37    if !header_contains_token(req.headers(), &header::UPGRADE, "websocket") {
38        return Err(HandshakeError::NoWebsocketUpgrade);
39    }
40
41    // Upgrade connection
42    if !header_contains_token(req.headers(), &header::CONNECTION, "upgrade") {
43        return Err(HandshakeError::NoConnectionUpgrade);
44    }
45
46    // check supported version
47    if !req.headers().contains_key(header::SEC_WEBSOCKET_VERSION) {
48        return Err(HandshakeError::NoVersionHeader);
49    }
50    let mut versions = req.headers().get_all(header::SEC_WEBSOCKET_VERSION);
51    if versions.next().is_none_or(|ver| ver != "13") || versions.next().is_some() {
52        return Err(HandshakeError::UnsupportedVersion);
53    }
54
55    // check client handshake for validity
56    let mut keys = req.headers().get_all(header::SEC_WEBSOCKET_KEY);
57    let valid_key = keys
58        .next()
59        .and_then(|key| base64.decode(key.as_bytes()).ok())
60        .is_some_and(|key| key.len() == 16)
61        && keys.next().is_none();
62    if !valid_key {
63        return Err(HandshakeError::BadWebsocketKey);
64    }
65    Ok(())
66}
67
68pub(super) fn header_contains_token(
69    headers: &HeaderMap,
70    name: &HeaderName,
71    expected: &str,
72) -> bool {
73    headers.get_all(name).any(|value| {
74        value.to_str().is_ok_and(|value| {
75            value
76                .split(',')
77                .any(|token| token.trim().eq_ignore_ascii_case(expected))
78        })
79    })
80}
81
82/// Creates a WebSocket opening-handshake response.
83///
84/// The returned response builder has status `101 Switching Protocols` and the
85/// required upgrade and challenge-response headers.
86///
87/// # Panics
88///
89/// Panics if `req` does not contain a `Sec-WebSocket-Key` header or the key
90/// exceeds the length accepted by [`hash_key`](crate::ws::hash_key). Use
91/// [`handshake`] when the request has not already been validated.
92pub fn handshake_response(req: &RequestHead) -> ResponseBuilder {
93    let key = {
94        let key = req.headers().get(header::SEC_WEBSOCKET_KEY).unwrap();
95        crate::ws::hash_key(key.as_ref()).expect("validated Sec-WebSocket-Key")
96    };
97
98    Response::builder(StatusCode::SWITCHING_PROTOCOLS)
99        .upgrade("websocket")
100        .header(header::SEC_WEBSOCKET_ACCEPT, key)
101        .take()
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107    use crate::http::{error::ResponseError, test::TestRequest};
108
109    /// STATEMENT: WebSocket handshakes validate method, tokenized upgrade headers, version, and challenge before switching protocols.
110    ///
111    /// HOW:
112    /// - Build progressively valid requests and compare each missing or malformed component's handshake error.
113    /// - Accept a complete request and verify the switching-protocols response has no transfer encoding.
114    #[test]
115    fn test_handshake() {
116        let req = TestRequest::default().method(Method::POST).build();
117        assert_eq!(
118            HandshakeError::GetMethodRequired,
119            verify_handshake(req.head()).err().unwrap()
120        );
121
122        let req = TestRequest::default().build();
123        assert_eq!(
124            HandshakeError::NoWebsocketUpgrade,
125            verify_handshake(req.head()).err().unwrap()
126        );
127
128        let req = TestRequest::default()
129            .header(header::UPGRADE, header::HeaderValue::from_static("test"))
130            .build();
131        assert_eq!(
132            HandshakeError::NoWebsocketUpgrade,
133            verify_handshake(req.head()).err().unwrap()
134        );
135
136        let req = TestRequest::default()
137            .header(
138                header::UPGRADE,
139                header::HeaderValue::from_static("notwebsocket"),
140            )
141            .build();
142        assert_eq!(
143            HandshakeError::NoWebsocketUpgrade,
144            verify_handshake(req.head()).err().unwrap()
145        );
146
147        let req = TestRequest::default()
148            .header(
149                header::UPGRADE,
150                header::HeaderValue::from_static("WebSocket"),
151            )
152            .build();
153        assert_eq!(
154            HandshakeError::NoConnectionUpgrade,
155            verify_handshake(req.head()).err().unwrap()
156        );
157
158        let req = TestRequest::default()
159            .header(
160                header::UPGRADE,
161                header::HeaderValue::from_static("websocket"),
162            )
163            .header(
164                header::CONNECTION,
165                header::HeaderValue::from_static("keep-alive, Upgrade"),
166            )
167            .build();
168        assert_eq!(
169            HandshakeError::NoVersionHeader,
170            verify_handshake(req.head()).err().unwrap()
171        );
172
173        let req = TestRequest::default()
174            .header(
175                header::UPGRADE,
176                header::HeaderValue::from_static("websocket"),
177            )
178            .header(
179                header::CONNECTION,
180                header::HeaderValue::from_static("keep-alive, upgraded"),
181            )
182            .build();
183        assert_eq!(
184            HandshakeError::NoConnectionUpgrade,
185            verify_handshake(req.head()).err().unwrap()
186        );
187
188        let req = TestRequest::default()
189            .header(
190                header::UPGRADE,
191                header::HeaderValue::from_static("websocket"),
192            )
193            .header(
194                header::CONNECTION,
195                header::HeaderValue::from_static("upgrade"),
196            )
197            .header(
198                header::SEC_WEBSOCKET_VERSION,
199                header::HeaderValue::from_static("5"),
200            )
201            .build();
202        assert_eq!(
203            HandshakeError::UnsupportedVersion,
204            verify_handshake(req.head()).err().unwrap()
205        );
206
207        let req = TestRequest::default()
208            .header(
209                header::UPGRADE,
210                header::HeaderValue::from_static("websocket"),
211            )
212            .header(
213                header::CONNECTION,
214                header::HeaderValue::from_static("upgrade"),
215            )
216            .header(
217                header::SEC_WEBSOCKET_VERSION,
218                header::HeaderValue::from_static("13"),
219            )
220            .build();
221        assert_eq!(
222            HandshakeError::BadWebsocketKey,
223            verify_handshake(req.head()).err().unwrap()
224        );
225
226        let req = TestRequest::default()
227            .header(
228                header::UPGRADE,
229                header::HeaderValue::from_static("websocket"),
230            )
231            .header(
232                header::CONNECTION,
233                header::HeaderValue::from_static("upgrade"),
234            )
235            .header(
236                header::SEC_WEBSOCKET_VERSION,
237                header::HeaderValue::from_static("13"),
238            )
239            .header(
240                header::SEC_WEBSOCKET_KEY,
241                header::HeaderValue::from_static("13"),
242            )
243            .build();
244        assert_eq!(
245            HandshakeError::BadWebsocketKey,
246            verify_handshake(req.head()).err().unwrap()
247        );
248
249        let req = TestRequest::default()
250            .header(
251                header::UPGRADE,
252                header::HeaderValue::from_static("websocket"),
253            )
254            .header(
255                header::CONNECTION,
256                header::HeaderValue::from_static("upgrade"),
257            )
258            .header(
259                header::SEC_WEBSOCKET_VERSION,
260                header::HeaderValue::from_static("13"),
261            )
262            .header(
263                header::SEC_WEBSOCKET_KEY,
264                header::HeaderValue::from_static("dGhlIHNhbXBsZSBub25jZQ=="),
265            )
266            .build();
267        verify_handshake(req.head()).unwrap();
268        let response = handshake_response(req.head()).build();
269        assert_eq!(StatusCode::SWITCHING_PROTOCOLS, response.status());
270        assert!(!response.headers().contains_key(header::TRANSFER_ENCODING));
271    }
272
273    /// STATEMENT: WebSocket handshakes accept only a single version-13 declaration.
274    ///
275    /// HOW:
276    /// - Verify version 13 succeeds while older versions and repeated mixed version headers fail.
277    #[test]
278    fn test_only_version_13_is_supported() {
279        let req = |versions: &[&'static str]| {
280            let mut req = TestRequest::default();
281            req.header(header::UPGRADE, "websocket")
282                .header(header::CONNECTION, "upgrade")
283                .header(header::SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==");
284            for ver in versions {
285                req.header(header::SEC_WEBSOCKET_VERSION, *ver);
286            }
287            req.build()
288        };
289        assert!(verify_handshake(req(&["13"]).head()).is_ok());
290        for versions in [&["8"][..], &["7"], &["13", "8"]] {
291            assert_eq!(
292                verify_handshake(req(versions).head()),
293                Err(HandshakeError::UnsupportedVersion)
294            );
295        }
296    }
297
298    /// STATEMENT: Handshake failures map to appropriate HTTP statuses and advertise the supported version when needed.
299    ///
300    /// HOW:
301    /// - Convert each handshake error into a response and inspect method-not-allowed or bad-request status.
302    /// - Check the unsupported-version response includes version 13.
303    #[test]
304    fn test_wserror_http_response() {
305        let resp: Response = HandshakeError::GetMethodRequired.error_response();
306        assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
307        let resp: Response = HandshakeError::NoWebsocketUpgrade.error_response();
308        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
309        let resp: Response = HandshakeError::NoConnectionUpgrade.error_response();
310        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
311        let resp: Response = HandshakeError::NoVersionHeader.error_response();
312        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
313        let resp: Response = HandshakeError::UnsupportedVersion.error_response();
314        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
315        assert_eq!(
316            resp.headers().get(header::SEC_WEBSOCKET_VERSION).unwrap(),
317            "13"
318        );
319        let resp: Response = HandshakeError::BadWebsocketKey.error_response();
320        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
321        let resp: Response = HandshakeError::BadWebsocketProtocol.error_response();
322        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
323    }
324}