Skip to main content

phoenix_http/
ws.rs

1//! Controlled HTTP/1.1 WebSocket upgrade facade.
2//!
3//! HTTP/2 extended CONNECT (RFC 8441) is intentionally unsupported.
4
5use std::future::Future;
6
7use bytes::Bytes;
8use futures_util::{SinkExt, StreamExt};
9use http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, Version, header};
10use hyper::upgrade::{OnUpgrade, Upgraded};
11use hyper_util::rt::TokioIo;
12use thiserror::Error;
13use tokio_tungstenite::{
14    WebSocketStream,
15    tungstenite::{
16        self,
17        handshake::derive_accept_key,
18        protocol::{Role, WebSocketConfig, frame::coding::CloseCode as TungsteniteCloseCode},
19    },
20};
21
22use crate::{ConnectionUpgrade, FromRequest, IntoResponse, Request, Response, rejection_response};
23
24const DEFAULT_MAX_MESSAGE_SIZE: usize = 64 * 1024;
25const DEFAULT_MAX_FRAME_SIZE: usize = 16 * 1024;
26const MAX_CONFIGURED_MESSAGE_SIZE: usize = 16 * 1024 * 1024;
27
28/// RFC 6455 close status codes used by the Phoenix WebSocket facade.
29#[derive(Clone, Copy, Debug, Eq, PartialEq)]
30pub struct CloseCode(u16);
31
32impl CloseCode {
33    pub const NORMAL: Self = Self(1000);
34    pub const AWAY: Self = Self(1001);
35    pub const PROTOCOL: Self = Self(1002);
36    pub const UNSUPPORTED: Self = Self(1003);
37    pub const ABNORMAL: Self = Self(1006);
38    pub const INVALID_PAYLOAD: Self = Self(1007);
39    pub const POLICY: Self = Self(1008);
40    pub const MESSAGE_TOO_BIG: Self = Self(1009);
41    pub const MANDATORY_EXT: Self = Self(1010);
42    pub const INTERNAL: Self = Self(1011);
43
44    #[must_use]
45    pub const fn new(code: u16) -> Self {
46        Self(code)
47    }
48
49    #[must_use]
50    pub const fn get(self) -> u16 {
51        self.0
52    }
53}
54
55impl From<CloseCode> for TungsteniteCloseCode {
56    fn from(value: CloseCode) -> Self {
57        Self::from(value.0)
58    }
59}
60
61impl From<TungsteniteCloseCode> for CloseCode {
62    fn from(value: TungsteniteCloseCode) -> Self {
63        Self(u16::from(value))
64    }
65}
66
67/// A WebSocket close frame observed by application code.
68#[derive(Clone, Debug, Eq, PartialEq)]
69pub struct CloseFrame {
70    pub code: CloseCode,
71    pub reason: String,
72}
73
74/// A WebSocket message.
75#[derive(Clone, Debug, Eq, PartialEq)]
76pub enum Message {
77    Text(String),
78    Binary(Bytes),
79    Ping(Bytes),
80    Pong(Bytes),
81    Close(Option<CloseFrame>),
82}
83
84impl Message {
85    #[must_use]
86    pub fn text(text: impl Into<String>) -> Self {
87        Self::Text(text.into())
88    }
89
90    #[must_use]
91    pub fn binary(data: impl Into<Bytes>) -> Self {
92        Self::Binary(data.into())
93    }
94
95    #[must_use]
96    pub const fn is_text(&self) -> bool {
97        matches!(self, Self::Text(_))
98    }
99
100    #[must_use]
101    pub const fn is_binary(&self) -> bool {
102        matches!(self, Self::Binary(_))
103    }
104
105    #[must_use]
106    pub const fn is_close(&self) -> bool {
107        matches!(self, Self::Close(_))
108    }
109
110    /// Return text payload when this is a text message.
111    ///
112    /// # Errors
113    ///
114    /// Returns [`WebSocketError::Protocol`] for non-text messages.
115    pub fn into_text(self) -> Result<String, WebSocketError> {
116        match self {
117            Self::Text(text) => Ok(text),
118            _ => Err(WebSocketError::Protocol),
119        }
120    }
121
122    fn into_tungstenite(self) -> tungstenite::Message {
123        match self {
124            Self::Text(text) => tungstenite::Message::Text(text.into()),
125            Self::Binary(data) => tungstenite::Message::Binary(data),
126            Self::Ping(data) => tungstenite::Message::Ping(data),
127            Self::Pong(data) => tungstenite::Message::Pong(data),
128            Self::Close(frame) => {
129                tungstenite::Message::Close(frame.map(|frame| tungstenite::protocol::CloseFrame {
130                    code: frame.code.into(),
131                    reason: frame.reason.into(),
132                }))
133            }
134        }
135    }
136
137    fn from_tungstenite(message: tungstenite::Message) -> Option<Self> {
138        match message {
139            tungstenite::Message::Text(text) => Some(Self::Text(text.to_string())),
140            tungstenite::Message::Binary(data) => Some(Self::Binary(data)),
141            tungstenite::Message::Ping(data) => Some(Self::Ping(data)),
142            tungstenite::Message::Pong(data) => Some(Self::Pong(data)),
143            tungstenite::Message::Close(frame) => {
144                Some(Self::Close(frame.map(|frame| CloseFrame {
145                    code: frame.code.into(),
146                    reason: frame.reason.to_string(),
147                })))
148            }
149            tungstenite::Message::Frame(_) => None,
150        }
151    }
152}
153
154/// Application-facing WebSocket I/O error. Details stay redacted.
155#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
156pub enum WebSocketError {
157    #[error("The WebSocket connection is closed.")]
158    Closed,
159    #[error("The WebSocket protocol was violated.")]
160    Protocol,
161    #[error("The WebSocket message exceeded the configured size limit.")]
162    MessageTooLarge,
163    #[error("The WebSocket transport failed.")]
164    Transport,
165}
166
167impl WebSocketError {
168    fn from_tungstenite(error: &tungstenite::Error) -> Self {
169        match error {
170            tungstenite::Error::ConnectionClosed | tungstenite::Error::AlreadyClosed => {
171                Self::Closed
172            }
173            tungstenite::Error::Capacity(_) => Self::MessageTooLarge,
174            tungstenite::Error::Protocol(_) | tungstenite::Error::Utf8(_) => Self::Protocol,
175            _ => Self::Transport,
176        }
177    }
178}
179
180/// An upgraded WebSocket connection.
181pub struct WebSocket {
182    inner: WebSocketStream<TokioIo<Upgraded>>,
183}
184
185impl std::fmt::Debug for WebSocket {
186    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
187        formatter.write_str("WebSocket")
188    }
189}
190
191impl WebSocket {
192    /// Receive the next message. `None` means the peer closed cleanly.
193    pub async fn recv(&mut self) -> Option<Result<Message, WebSocketError>> {
194        loop {
195            match self.inner.next().await? {
196                Ok(message) => {
197                    if let Some(message) = Message::from_tungstenite(message) {
198                        return Some(Ok(message));
199                    }
200                }
201                Err(error) => return Some(Err(WebSocketError::from_tungstenite(&error))),
202            }
203        }
204    }
205
206    /// Send a text or binary message (or control frame).
207    ///
208    /// # Errors
209    ///
210    /// Returns a redacted transport or protocol error when the send fails.
211    pub async fn send(&mut self, message: Message) -> Result<(), WebSocketError> {
212        self.inner
213            .send(message.into_tungstenite())
214            .await
215            .map_err(|error| WebSocketError::from_tungstenite(&error))
216    }
217
218    /// Send a close frame and flush. Prefer this over dropping for graceful shutdown.
219    ///
220    /// # Errors
221    ///
222    /// Returns a redacted transport error when the close cannot be written.
223    pub async fn close(&mut self, frame: Option<CloseFrame>) -> Result<(), WebSocketError> {
224        self.send(Message::Close(frame)).await
225    }
226}
227
228#[derive(Clone, Debug)]
229enum OriginPolicy {
230    Allowlist(Vec<String>),
231    Any,
232}
233
234/// Extractor that validates an HTTP/1.1 WebSocket handshake and upgrades the connection.
235pub struct WebSocketUpgrade {
236    sec_websocket_key: HeaderValue,
237    on_upgrade: OnUpgrade,
238    origin: Option<String>,
239    origin_policy: OriginPolicy,
240    max_message_size: usize,
241    max_frame_size: usize,
242}
243
244impl std::fmt::Debug for WebSocketUpgrade {
245    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246        formatter
247            .debug_struct("WebSocketUpgrade")
248            .field("origin_policy", &self.origin_policy)
249            .field("max_message_size", &self.max_message_size)
250            .field("max_frame_size", &self.max_frame_size)
251            .field("has_origin", &self.origin.is_some())
252            .finish_non_exhaustive()
253    }
254}
255
256impl WebSocketUpgrade {
257    /// Allow an exact Origin value. Repeating builds an allowlist.
258    #[must_use]
259    pub fn allowed_origin(mut self, origin: impl Into<String>) -> Self {
260        match &mut self.origin_policy {
261            OriginPolicy::Allowlist(origins) => origins.push(origin.into()),
262            OriginPolicy::Any => {
263                self.origin_policy = OriginPolicy::Allowlist(vec![origin.into()]);
264            }
265        }
266        self
267    }
268
269    /// Disable Origin checks. Intended for local tests, not production browsers.
270    #[must_use]
271    pub fn any_origin(mut self) -> Self {
272        self.origin_policy = OriginPolicy::Any;
273        self
274    }
275
276    /// Cap reassembled incoming message size.
277    ///
278    /// # Errors
279    ///
280    /// Rejects zero and values above 16 MiB.
281    pub fn max_message_size(mut self, bytes: usize) -> Result<Self, WebSocketConfigError> {
282        if bytes == 0 || bytes > MAX_CONFIGURED_MESSAGE_SIZE {
283            return Err(WebSocketConfigError::InvalidMessageSize);
284        }
285        self.max_message_size = bytes;
286        Ok(self)
287    }
288
289    /// Cap a single incoming frame payload.
290    ///
291    /// # Errors
292    ///
293    /// Rejects zero and values above 16 MiB.
294    pub fn max_frame_size(mut self, bytes: usize) -> Result<Self, WebSocketConfigError> {
295        if bytes == 0 || bytes > MAX_CONFIGURED_MESSAGE_SIZE {
296            return Err(WebSocketConfigError::InvalidFrameSize);
297        }
298        self.max_frame_size = bytes;
299        Ok(self)
300    }
301
302    /// Complete the handshake and run `callback` on the upgraded socket.
303    ///
304    /// Origin is checked here so [`Self::allowed_origin`] / [`Self::any_origin`] can run first.
305    ///
306    /// # Panics
307    ///
308    /// Panics only if the derived `Sec-WebSocket-Accept` value is somehow not a
309    /// valid header value (should be unreachable for RFC 6455 accept keys).
310    pub fn on_upgrade<F, Fut>(self, callback: F) -> Response
311    where
312        F: FnOnce(WebSocket) -> Fut + Send + 'static,
313        Fut: Future<Output = ()> + Send + 'static,
314    {
315        if let Err(rejection) = self.check_origin() {
316            return rejection.into_response();
317        }
318
319        let Self {
320            sec_websocket_key,
321            on_upgrade,
322            max_message_size,
323            max_frame_size,
324            ..
325        } = self;
326
327        let accept = derive_accept_key(sec_websocket_key.as_bytes());
328        let config = WebSocketConfig::default()
329            .max_message_size(Some(max_message_size))
330            .max_frame_size(Some(max_frame_size))
331            .write_buffer_size(0);
332
333        tokio::spawn(async move {
334            let Ok(upgraded) = on_upgrade.await else {
335                return;
336            };
337            let socket = WebSocketStream::from_raw_socket(
338                TokioIo::new(upgraded),
339                Role::Server,
340                Some(config),
341            )
342            .await;
343            callback(WebSocket { inner: socket }).await;
344        });
345
346        let mut response = Response::new(StatusCode::SWITCHING_PROTOCOLS, Bytes::new());
347        response
348            .headers_mut()
349            .insert(header::CONNECTION, HeaderValue::from_static("upgrade"));
350        response
351            .headers_mut()
352            .insert(header::UPGRADE, HeaderValue::from_static("websocket"));
353        response.headers_mut().insert(
354            HeaderName::from_static("sec-websocket-accept"),
355            HeaderValue::from_str(&accept).expect("derived accept key is a valid header"),
356        );
357        response
358    }
359
360    fn check_origin(&self) -> Result<(), WebSocketUpgradeRejection> {
361        match &self.origin_policy {
362            OriginPolicy::Any => Ok(()),
363            OriginPolicy::Allowlist(origins) => {
364                let Some(origin) = self.origin.as_deref() else {
365                    return Err(WebSocketUpgradeRejection::OriginDenied);
366                };
367                if origins.iter().any(|allowed| allowed == origin) {
368                    Ok(())
369                } else {
370                    Err(WebSocketUpgradeRejection::OriginDenied)
371                }
372            }
373        }
374    }
375}
376
377#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
378pub enum WebSocketConfigError {
379    #[error("The WebSocket message size limit must be between 1 byte and 16 MiB.")]
380    InvalidMessageSize,
381    #[error("The WebSocket frame size limit must be between 1 byte and 16 MiB.")]
382    InvalidFrameSize,
383}
384
385/// Why a WebSocket upgrade extractor rejected the request.
386#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
387pub enum WebSocketUpgradeRejection {
388    #[error("WebSocket upgrades require the GET method.")]
389    MethodNotGet,
390    #[error("WebSocket upgrades require HTTP/1.1.")]
391    UnsupportedVersion,
392    #[error("The WebSocket upgrade headers are invalid.")]
393    InvalidHandshake,
394    #[error("The WebSocket Origin is not allowed.")]
395    OriginDenied,
396    #[error("A WebSocket upgrade is unavailable on this connection.")]
397    UpgradeUnavailable,
398}
399
400impl WebSocketUpgradeRejection {
401    #[must_use]
402    pub const fn status(self) -> StatusCode {
403        match self {
404            Self::OriginDenied => StatusCode::FORBIDDEN,
405            Self::UnsupportedVersion => StatusCode::HTTP_VERSION_NOT_SUPPORTED,
406            Self::MethodNotGet | Self::InvalidHandshake | Self::UpgradeUnavailable => {
407                StatusCode::BAD_REQUEST
408            }
409        }
410    }
411}
412
413impl IntoResponse for WebSocketUpgradeRejection {
414    fn into_response(self) -> Response {
415        rejection_response(self.status(), &self.to_string())
416    }
417}
418
419impl IntoResponse for WebSocketConfigError {
420    fn into_response(self) -> Response {
421        rejection_response(StatusCode::INTERNAL_SERVER_ERROR, &self.to_string())
422    }
423}
424
425impl FromRequest for WebSocketUpgrade {
426    type Rejection = WebSocketUpgradeRejection;
427
428    fn from_request(request: &Request) -> Result<Self, Self::Rejection> {
429        if *request.method() != Method::GET {
430            return Err(WebSocketUpgradeRejection::MethodNotGet);
431        }
432        if request.version() != Version::HTTP_11 {
433            return Err(WebSocketUpgradeRejection::UnsupportedVersion);
434        }
435        if !header_contains_token(request.headers(), header::CONNECTION, "upgrade")
436            || !header_eq_ignore_ascii_case(request.headers(), header::UPGRADE, "websocket")
437        {
438            return Err(WebSocketUpgradeRejection::InvalidHandshake);
439        }
440        let version = request
441            .headers()
442            .get(HeaderName::from_static("sec-websocket-version"))
443            .ok_or(WebSocketUpgradeRejection::InvalidHandshake)?;
444        if version.as_bytes() != b"13" {
445            return Err(WebSocketUpgradeRejection::InvalidHandshake);
446        }
447        let sec_websocket_key = request
448            .headers()
449            .get(HeaderName::from_static("sec-websocket-key"))
450            .cloned()
451            .ok_or(WebSocketUpgradeRejection::InvalidHandshake)?;
452        if !is_plausible_websocket_key(sec_websocket_key.as_bytes()) {
453            return Err(WebSocketUpgradeRejection::InvalidHandshake);
454        }
455
456        let origin = request
457            .headers()
458            .get(header::ORIGIN)
459            .map(|value| {
460                value
461                    .to_str()
462                    .map(str::to_owned)
463                    .map_err(|_| WebSocketUpgradeRejection::InvalidHandshake)
464            })
465            .transpose()?;
466
467        let on_upgrade = request
468            .extensions()
469            .get::<ConnectionUpgrade>()
470            .and_then(ConnectionUpgrade::take)
471            .ok_or(WebSocketUpgradeRejection::UpgradeUnavailable)?;
472
473        Ok(Self {
474            sec_websocket_key,
475            on_upgrade,
476            origin,
477            origin_policy: OriginPolicy::Allowlist(Vec::new()),
478            max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
479            max_frame_size: DEFAULT_MAX_FRAME_SIZE,
480        })
481    }
482}
483
484fn header_contains_token(headers: &HeaderMap, name: HeaderName, token: &str) -> bool {
485    headers.get_all(name).iter().any(|value| {
486        value.to_str().is_ok_and(|text| {
487            text.split(',')
488                .any(|part| part.trim().eq_ignore_ascii_case(token))
489        })
490    })
491}
492
493fn header_eq_ignore_ascii_case(headers: &HeaderMap, name: HeaderName, expected: &str) -> bool {
494    headers
495        .get(name)
496        .and_then(|value| value.to_str().ok())
497        .is_some_and(|value| value.trim().eq_ignore_ascii_case(expected))
498}
499
500fn is_plausible_websocket_key(key: &[u8]) -> bool {
501    // RFC 6455: 16 bytes of random data, base64-encoded => 24 ASCII chars.
502    (16..=128).contains(&key.len())
503        && key
504            .iter()
505            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'='))
506}
507
508#[cfg(test)]
509mod tests {
510    use super::*;
511    use crate::{Extensions, Method, Request, Version};
512
513    fn pending_upgrade() -> OnUpgrade {
514        hyper::upgrade::on(http::Request::new(()))
515    }
516
517    fn upgrade_request(origin: Option<&str>) -> Request {
518        let mut request = Request::from_server_parts(
519            Method::GET,
520            "/ws".parse().unwrap(),
521            Version::HTTP_11,
522            HeaderMap::new(),
523            Extensions::new(),
524            Bytes::new(),
525        );
526        request
527            .headers_mut()
528            .insert(header::CONNECTION, HeaderValue::from_static("Upgrade"));
529        request
530            .headers_mut()
531            .insert(header::UPGRADE, HeaderValue::from_static("websocket"));
532        request.headers_mut().insert(
533            HeaderName::from_static("sec-websocket-version"),
534            HeaderValue::from_static("13"),
535        );
536        request.headers_mut().insert(
537            HeaderName::from_static("sec-websocket-key"),
538            HeaderValue::from_static("dGhlIHNhbXBsZSBub25jZQ=="),
539        );
540        if let Some(origin) = origin {
541            request
542                .headers_mut()
543                .insert(header::ORIGIN, HeaderValue::from_str(origin).unwrap());
544        }
545        request
546            .extensions_mut()
547            .insert(ConnectionUpgrade::new(pending_upgrade()));
548        request
549    }
550
551    #[test]
552    fn default_origin_policy_denies_until_allowlisted_or_relaxed() {
553        let request = upgrade_request(Some("https://app.example"));
554        let upgrade = WebSocketUpgrade::from_request(&request).unwrap();
555        assert!(matches!(
556            upgrade.check_origin(),
557            Err(WebSocketUpgradeRejection::OriginDenied)
558        ));
559
560        let request = upgrade_request(Some("https://app.example"));
561        let upgrade = WebSocketUpgrade::from_request(&request)
562            .unwrap()
563            .allowed_origin("https://app.example");
564        assert!(upgrade.check_origin().is_ok());
565
566        let request = upgrade_request(None);
567        let upgrade = WebSocketUpgrade::from_request(&request)
568            .unwrap()
569            .any_origin();
570        assert!(upgrade.check_origin().is_ok());
571    }
572
573    #[tokio::test]
574    async fn any_origin_upgrade_returns_switching_protocols() {
575        let request = upgrade_request(None);
576        let response = WebSocketUpgrade::from_request(&request)
577            .unwrap()
578            .any_origin()
579            .on_upgrade(|_| async {});
580        assert_eq!(response.status(), StatusCode::SWITCHING_PROTOCOLS);
581    }
582
583    #[test]
584    fn denied_origin_returns_forbidden_instead_of_switching_protocols() {
585        let request = upgrade_request(Some("https://evil.example"));
586        let response = WebSocketUpgrade::from_request(&request)
587            .unwrap()
588            .allowed_origin("https://app.example")
589            .on_upgrade(|_| async {});
590        assert_eq!(response.status(), StatusCode::FORBIDDEN);
591    }
592
593    #[test]
594    fn accept_key_matches_rfc_sample() {
595        assert_eq!(
596            derive_accept_key(b"dGhlIHNhbXBsZSBub25jZQ=="),
597            "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="
598        );
599    }
600
601    #[test]
602    fn rejects_http2_and_bad_handshake_headers() {
603        let request = upgrade_request(Some("https://app.example"));
604        let mut http2 = Request::from_server_parts(
605            Method::GET,
606            "/ws".parse().unwrap(),
607            Version::HTTP_2,
608            request.headers().clone(),
609            Extensions::new(),
610            Bytes::new(),
611        );
612        http2
613            .extensions_mut()
614            .insert(ConnectionUpgrade::new(pending_upgrade()));
615        assert!(matches!(
616            WebSocketUpgrade::from_request(&http2),
617            Err(WebSocketUpgradeRejection::UnsupportedVersion)
618        ));
619
620        let mut bad = upgrade_request(Some("https://app.example"));
621        bad.headers_mut()
622            .insert(header::UPGRADE, HeaderValue::from_static("not-websocket"));
623        assert!(matches!(
624            WebSocketUpgrade::from_request(&bad),
625            Err(WebSocketUpgradeRejection::InvalidHandshake)
626        ));
627    }
628
629    #[test]
630    fn missing_upgrade_extension_is_unavailable() {
631        let mut request = upgrade_request(None);
632        *request.extensions_mut() = Extensions::new();
633        assert!(matches!(
634            WebSocketUpgrade::from_request(&request),
635            Err(WebSocketUpgradeRejection::UpgradeUnavailable)
636        ));
637    }
638}