s2_kit/connect/server/ws.rs
1//! The last mile: an authorised WebSocket.
2//!
3//! Session initiation produces a `websocketToken`; this module is what makes it mean
4//! something — the route that checks it, and the transport that carries S2 messages once
5//! it has. `S2C §WebSocket based communication` is short and all of it is here: the token
6//! in `Authorization: Bearer`, and the S2 session living exactly as long as the socket.
7//! `wss://` is the host's [`serve`](super::serve) call rather than this route.
8//!
9//! ```no_run
10//! use std::sync::Arc;
11//! use s2_kit::connect::server::{Endpoint, websocket_router};
12//! use s2_kit::io::Driver;
13//! use s2_kit::prelude::*;
14//!
15//! # fn build(endpoint: Endpoint) -> axum::Router {
16//! websocket_router(endpoint, "/s2", |node, socket| async move {
17//! // `node` is the paired peer the token belonged to: which resource this is.
18//! let mut cem = CemSession::new(CemConfig::default().pre_negotiated(WireProfile::V1_0_0));
19//! cem.open(Timestamp::now());
20//! let mut driver = Driver::new(socket);
21//! let _ = driver.run(&mut cem, |_event, _session| {}).await;
22//! let _ = node;
23//! })
24//! # }
25//! ```
26
27use alloc::string::{String, ToString};
28use core::future::Future;
29
30use axum::extract::State;
31use axum::extract::ws::{Message as WsMessage, WebSocket, WebSocketUpgrade};
32use axum::http::StatusCode;
33use axum::response::{IntoResponse, Response};
34use axum::routing::any;
35
36use crate::connect::proto::NodeId;
37use crate::io::{Error, TextTransport};
38
39use super::routes::Endpoint;
40
41/// A WebSocket an S2 Connect server accepted, as a transport an [`io::Driver`] can pump.
42///
43/// [`io::WebSocket`](crate::io::WebSocket) is the client's side of the same thing. They
44/// are separate types because the two halves come from different libraries — a client
45/// dials with `tokio-tungstenite`, a server upgrades with `axum` — and neither wants to
46/// depend on the other's stream type.
47///
48/// [`io::Driver`]: crate::io::Driver
49#[derive(Debug)]
50pub struct ServerSocket {
51 socket: WebSocket,
52}
53
54impl ServerSocket {
55 /// Wrap an upgraded socket.
56 #[must_use]
57 pub fn new(socket: WebSocket) -> Self {
58 Self { socket }
59 }
60}
61
62impl TextTransport for ServerSocket {
63 async fn send_text(&mut self, text: String) -> Result<(), Error> {
64 self.socket
65 .send(WsMessage::Text(text.into()))
66 .await
67 .map_err(|e| Error::Transport(e.to_string()))
68 }
69
70 // The arms are grouped by what happened, not by what is returned: "the stream ended"
71 // and "the peer sent a close frame" are different events that mean the same thing.
72 #[allow(clippy::match_same_arms)]
73 async fn recv_text(&mut self) -> Result<Option<String>, Error> {
74 loop {
75 match self.socket.recv().await {
76 None => return Ok(None),
77 Some(Err(e)) => return Err(Error::Transport(e.to_string())),
78 Some(Ok(WsMessage::Text(text))) => return Ok(Some(text.to_string())),
79 Some(Ok(WsMessage::Close(_))) => return Ok(None),
80 // Pong frames answer our own pings; a ping is answered by axum itself.
81 Some(Ok(WsMessage::Ping(_) | WsMessage::Pong(_))) => {}
82 Some(Ok(WsMessage::Binary(_))) => {
83 return Err(Error::UnexpectedFrame("binary".to_string()));
84 }
85 }
86 }
87 }
88
89 async fn ping(&mut self) -> Result<(), Error> {
90 self.socket
91 .send(WsMessage::Ping(axum::body::Bytes::new()))
92 .await
93 .map_err(|e| Error::Transport(e.to_string()))
94 }
95
96 async fn close(&mut self) {
97 let _ = self.socket.send(WsMessage::Close(None)).await;
98 }
99}
100
101/// Everything the WebSocket route needs: the endpoint, and what to do with a session.
102///
103/// `Clone` is written out rather than derived: the derive would demand `H: Clone`, and the
104/// handler is behind an `Arc` precisely so it does not have to be.
105struct WsState<H> {
106 endpoint: Endpoint,
107 handler: alloc::sync::Arc<H>,
108}
109
110impl<H> Clone for WsState<H> {
111 fn clone(&self) -> Self {
112 Self {
113 endpoint: self.endpoint.clone(),
114 handler: self.handler.clone(),
115 }
116 }
117}
118
119/// A router serving the S2 WebSocket at `path`, for clients that hold a communication
120/// token this endpoint issued.
121///
122/// The token is checked against
123/// [`SessionService::authorize_connection`](super::SessionService::authorize_connection)
124/// — which consumes it, because `s2-connect-common.yml/CommunicationToken` makes it
125/// "valid for a single connection … for maximum 30 seconds". A request with no bearer, an
126/// unknown one, an expired one or one already used is `401`, and the upgrade never
127/// happens.
128///
129/// `on_session` is given the paired node the token belonged to and the upgraded socket.
130/// The S2 session *is* the WebSocket session, so when it returns the socket is closed.
131///
132/// Mount it beside [`router`](super::router) or [`lan_router`](super::lan_router) with
133/// `Router::merge`, or serve it from another port. Separate for the same reason
134/// `lan_router` is: an RM in a LAN never accepts a connection, and should not have to opt
135/// *out* of serving one.
136pub fn websocket_router<H, Fut>(endpoint: Endpoint, path: &str, on_session: H) -> axum::Router
137where
138 H: Fn(NodeId, ServerSocket) -> Fut + Send + Sync + 'static,
139 Fut: Future<Output = ()> + Send + 'static,
140{
141 axum::Router::new()
142 .route(path, any(upgrade::<H, Fut>))
143 .with_state(WsState {
144 endpoint,
145 handler: alloc::sync::Arc::new(on_session),
146 })
147}
148
149async fn upgrade<H, Fut>(
150 State(state): State<WsState<H>>,
151 bearer: super::routes::Bearer,
152 upgrade: WebSocketUpgrade,
153) -> Response
154where
155 H: Fn(NodeId, ServerSocket) -> Fut + Send + Sync + 'static,
156 Fut: Future<Output = ()> + Send + 'static,
157{
158 let now = state.endpoint.now();
159 let Some(node) = state
160 .endpoint
161 .session()
162 .authorize_connection(bearer.as_str(), now)
163 else {
164 crate::trace::event!(warn, "refused a WebSocket with an unusable token");
165 return StatusCode::UNAUTHORIZED.into_response();
166 };
167 crate::trace::event!(info, node = %node, "accepted an S2 WebSocket");
168 let handler = state.handler.clone();
169 // The same cap the codec applies, applied where it actually bounds memory: by the
170 // time `decode` measures a frame, axum has buffered every byte of it. Without this
171 // the default ceiling is axum's, not this crate's.
172 upgrade
173 .max_message_size(state.endpoint.max_message_bytes())
174 .max_frame_size(state.endpoint.max_message_bytes())
175 .on_upgrade(move |socket| async move {
176 handler(node, ServerSocket::new(socket)).await;
177 })
178}