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