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", |pairing, socket| async move {
17//! // `pairing.remote` is the paired peer the token belonged to: which resource this is;
18//! // `pairing.local` is which of this endpoint's nodes it is talking to.
19//! let mut cem = CemSession::new(CemConfig::default().pre_negotiated(WireProfile::V1_0_0));
20//! cem.open(Timestamp::now());
21//! let mut driver = Driver::new(socket);
22//! let _ = driver.run(&mut cem, |_event, _session| {}).await;
23//! let _ = pairing;
24//! })
25//! # }
26//! ```
27
28use alloc::string::{String, ToString};
29use core::future::Future;
30
31use axum::extract::State;
32use axum::extract::ws::{Message as WsMessage, WebSocket, WebSocketUpgrade};
33use axum::http::StatusCode;
34use axum::response::{IntoResponse, Response};
35use axum::routing::any;
36
37use crate::io::{Error, Received, TextTransport};
38
39use super::store::PairingKey;
40
41use super::routes::Endpoint;
42
43/// A WebSocket an S2 Connect server accepted, as a transport an [`io::Driver`] can pump.
44///
45/// [`io::WebSocket`](crate::io::WebSocket) is the client's side of the same thing. They
46/// are separate types because the two halves come from different libraries — a client
47/// dials with `tokio-tungstenite`, a server upgrades with `axum` — and neither wants to
48/// depend on the other's stream type.
49///
50/// [`io::Driver`]: crate::io::Driver
51#[derive(Debug)]
52pub struct ServerSocket {
53 socket: WebSocket,
54 /// Fires when the pairing is undone; the socket then closes and reads as closed.
55 ended: Option<tokio::sync::watch::Receiver<bool>>,
56}
57
58impl ServerSocket {
59 /// Wrap an upgraded socket.
60 #[must_use]
61 pub fn new(socket: WebSocket) -> Self {
62 Self {
63 socket,
64 ended: None,
65 }
66 }
67
68 /// Close this socket when `session` ends — when its pairing is undone.
69 ///
70 /// [`websocket_router`] does this for you; a host that upgrades sockets itself pairs
71 /// each with the [`LiveSession`](super::LiveSession) it registered.
72 #[must_use]
73 pub fn ending_with(mut self, session: &super::LiveSession) -> Self {
74 self.ended = Some(session.watch());
75 self
76 }
77}
78
79impl TextTransport for ServerSocket {
80 async fn send_text(&mut self, text: String) -> Result<(), Error> {
81 self.socket
82 .send(WsMessage::Text(text.into()))
83 .await
84 .map_err(|e| Error::Transport(e.to_string()))
85 }
86
87 // The arms are grouped by what happened, not by what is returned: "the stream ended"
88 // and "the peer sent a close frame" are different events that mean the same thing.
89 #[allow(clippy::match_same_arms)]
90 async fn recv_text(&mut self) -> Result<Option<String>, Error> {
91 loop {
92 match self.recv().await? {
93 None => return Ok(None),
94 Some(Received::Text(text)) => return Ok(Some(text)),
95 Some(Received::Alive) => {}
96 }
97 }
98 }
99
100 async fn recv(&mut self) -> Result<Option<Received>, Error> {
101 {
102 let frame = match self.ended.as_mut() {
103 Some(ended) => {
104 tokio::select! {
105 frame = self.socket.recv() => Some(frame),
106 // `S2C §Termination`: "After two nodes have unpaired, the S2
107 // WebSocket connection MUST be terminated immediately."
108 _ = async { ended.wait_for(|ended| *ended).await.is_ok() } => None,
109 }
110 }
111 None => Some(self.socket.recv().await),
112 };
113 let Some(frame) = frame else {
114 let _ = self.socket.send(WsMessage::Close(None)).await;
115 return Ok(None);
116 };
117 match frame {
118 // The stream ended, or the peer said goodbye: the same thing to a session.
119 None | Some(Ok(WsMessage::Close(_))) => Ok(None),
120 Some(Err(e)) => Err(Error::Transport(e.to_string())),
121 Some(Ok(WsMessage::Text(text))) => Ok(Some(Received::Text(text.to_string()))),
122 // Pong frames answer our own pings, a ping is answered by axum itself, and
123 // both prove the peer is there.
124 Some(Ok(WsMessage::Ping(_) | WsMessage::Pong(_))) => Ok(Some(Received::Alive)),
125 Some(Ok(WsMessage::Binary(_))) => Err(Error::UnexpectedFrame("binary".to_string())),
126 }
127 }
128 }
129
130 async fn ping(&mut self) -> Result<(), Error> {
131 self.socket
132 .send(WsMessage::Ping(axum::body::Bytes::new()))
133 .await
134 .map_err(|e| Error::Transport(e.to_string()))
135 }
136
137 async fn close(&mut self) {
138 let _ = self.socket.send(WsMessage::Close(None)).await;
139 }
140}
141
142/// Everything the WebSocket route needs: the endpoint, and what to do with a session.
143///
144/// `Clone` is written out rather than derived: the derive would demand `H: Clone`, and the
145/// handler is behind an `Arc` precisely so it does not have to be.
146struct WsState<H> {
147 endpoint: Endpoint,
148 handler: alloc::sync::Arc<H>,
149}
150
151impl<H> Clone for WsState<H> {
152 fn clone(&self) -> Self {
153 Self {
154 endpoint: self.endpoint.clone(),
155 handler: self.handler.clone(),
156 }
157 }
158}
159
160/// A router serving the S2 WebSocket at `path`, for clients that hold a communication
161/// token this endpoint issued.
162///
163/// The token is checked against
164/// [`SessionService::authorize_connection`](super::SessionService::authorize_connection)
165/// — which consumes it, because `s2-connect-common.yml/CommunicationToken` makes it
166/// "valid for a single connection … for maximum 30 seconds". A request with no bearer, an
167/// unknown one, an expired one or one already used is `401`, and the upgrade never
168/// happens.
169///
170/// `on_session` is given the pairing the token belonged to and the upgraded socket. The
171/// S2 session *is* the WebSocket session, so when it returns the socket is closed — and
172/// when the pairing is undone (unpair by either side, or a re-pair that replaces it) the
173/// socket closes by itself and reads as closed, so the session ends.
174///
175/// Mount it beside [`router`](super::router) or [`lan_router`](super::lan_router) with
176/// `Router::merge`, or serve it from another port. Separate for the same reason
177/// `lan_router` is: an RM in a LAN never accepts a connection, and should not have to opt
178/// *out* of serving one.
179pub fn websocket_router<H, Fut>(endpoint: Endpoint, path: &str, on_session: H) -> axum::Router
180where
181 H: Fn(PairingKey, ServerSocket) -> Fut + Send + Sync + 'static,
182 Fut: Future<Output = ()> + Send + 'static,
183{
184 axum::Router::new()
185 .route(path, any(upgrade::<H, Fut>))
186 .with_state(WsState {
187 endpoint,
188 handler: alloc::sync::Arc::new(on_session),
189 })
190}
191
192async fn upgrade<H, Fut>(
193 State(state): State<WsState<H>>,
194 bearer: super::routes::Bearer,
195 upgrade: WebSocketUpgrade,
196) -> Response
197where
198 H: Fn(PairingKey, ServerSocket) -> Fut + Send + Sync + 'static,
199 Fut: Future<Output = ()> + Send + 'static,
200{
201 let now = state.endpoint.now();
202 let Some(key) = state
203 .endpoint
204 .session()
205 .authorize_connection(bearer.as_str(), now)
206 else {
207 crate::trace::event!(warn, "refused a WebSocket with an unusable token");
208 return StatusCode::UNAUTHORIZED.into_response();
209 };
210 crate::trace::event!(info, node = %key.remote, "accepted an S2 WebSocket");
211 let handler = state.handler.clone();
212 let live = state.endpoint.session().register_session(key);
213 // The same cap the codec applies, applied where it actually bounds memory: by the
214 // time `decode` measures a frame, axum has buffered every byte of it. Without this
215 // the default ceiling is axum's, not this crate's.
216 upgrade
217 .max_message_size(state.endpoint.max_message_bytes())
218 .max_frame_size(state.endpoint.max_message_bytes())
219 .on_upgrade(move |socket| async move {
220 let socket = ServerSocket::new(socket).ending_with(&live);
221 handler(key, socket).await;
222 drop(live);
223 })
224}