Skip to main content

s2_kit/connect/server/
session.rs

1//! The session-initiation endpoints, and the sessions they open.
2
3use alloc::string::String;
4use alloc::sync::Arc;
5use alloc::vec::Vec;
6
7use crate::connect::proto::{
8    AccessToken, COMMUNICATION_TOKEN_LIFETIME, CommunicationDetails, CommunicationToken,
9    ConnectError, SessionErrorMessage, SessionGrant, SessionInitServer, SessionRefused,
10    SessionRequest, TokenStore, UnpairRequest,
11};
12
13use super::store::{PairingKey, Store};
14use crate::types::{ProtocolVersion, Timestamp};
15
16/// Runs the session-initiation half of an endpoint.
17///
18/// Almost everything it needs is in the [`Store`] and in the bearer the client presented,
19/// including the replacement access token it issued and has not yet seen confirmed — a
20/// server that held *that* in memory would retire the wrong token after a restart.
21///
22/// What it keeps in memory is what must **not** survive a restart: the communication
23/// tokens handed out and not yet used (each valid for thirty seconds and one connection),
24/// and the WebSocket sessions currently open, so that unpairing can end them.
25pub struct SessionService {
26    store: Arc<dyn Store>,
27    websocket_url: String,
28    s2_message_versions: Vec<ProtocolVersion>,
29    /// Communication tokens handed out and not yet used, with the pairing each belongs to.
30    ///
31    /// The other half of `confirmAccessToken`: a server that returns a `websocketToken`
32    /// and keeps no copy has authorised nothing. The list stays tiny by construction —
33    /// each entry lives thirty seconds ([`COMMUNICATION_TOKEN_LIFETIME`]), is removed the
34    /// moment it is used, and expired ones are swept whenever one is added.
35    issued: std::sync::Mutex<Vec<IssuedConnection>>,
36    /// Held across every read-modify-write of one pairing's tokens.
37    ///
38    /// `initiateSession` and `confirmAccessToken` each read the token list from the store,
39    /// change it and write it back. Two of them interleaved can write back a list that
40    /// still holds a token the other just retired — and `S2C §Session initiation` makes
41    /// an access token usable "only once". One lock, held for microseconds and never
42    /// across an `.await`, makes each rotation atomic for any [`Store`].
43    rotation: std::sync::Mutex<()>,
44    /// The S2 WebSocket sessions open right now, so unpairing can end them.
45    live: std::sync::Mutex<Vec<LiveEntry>>,
46    next_live: core::sync::atomic::AtomicU64,
47}
48
49/// A communication token this endpoint issued and has not yet seen used.
50#[derive(Debug)]
51struct IssuedConnection {
52    key: PairingKey,
53    token: CommunicationToken,
54    issued: Timestamp,
55}
56
57#[derive(Debug)]
58struct LiveEntry {
59    key: PairingKey,
60    id: u64,
61    end: tokio::sync::watch::Sender<bool>,
62}
63
64/// One open S2 WebSocket session, as the endpoint tracks it.
65///
66/// Returned by [`SessionService::register_session`]; the session is tracked for as long
67/// as this lives. [`ended`](Self::ended) resolves when the pairing is undone —
68/// `S2C §Termination`: "After two nodes have unpaired, the S2 WebSocket connection
69/// **MUST** be terminated immediately."
70#[derive(Debug)]
71pub struct LiveSession {
72    key: PairingKey,
73    id: u64,
74    end: tokio::sync::watch::Receiver<bool>,
75    service: alloc::sync::Weak<SessionService>,
76}
77
78impl LiveSession {
79    /// The pairing this session belongs to.
80    #[must_use]
81    pub const fn key(&self) -> PairingKey {
82        self.key
83    }
84
85    /// Resolves when the session must end because its pairing was undone.
86    pub async fn ended(&mut self) {
87        // An error means the service is gone, which ends the session too.
88        let _ = self.end.wait_for(|ended| *ended).await;
89    }
90
91    /// Whether the session must end now.
92    #[must_use]
93    pub fn is_ended(&self) -> bool {
94        *self.end.borrow()
95    }
96
97    /// A receiver that observes the same signal, for a transport that wants to watch it.
98    pub(super) fn watch(&self) -> tokio::sync::watch::Receiver<bool> {
99        self.end.clone()
100    }
101}
102
103impl Drop for LiveSession {
104    fn drop(&mut self) {
105        if let Some(service) = self.service.upgrade()
106            && let Ok(mut live) = service.live.lock()
107        {
108            live.retain(|entry| entry.id != self.id);
109        }
110    }
111}
112
113impl core::fmt::Debug for SessionService {
114    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
115        f.debug_struct("SessionService")
116            .field("websocket_url", &self.websocket_url)
117            .field("s2_message_versions", &self.s2_message_versions)
118            .finish_non_exhaustive()
119    }
120}
121
122impl SessionService {
123    /// A service answering on `websocket_url`, which must be `wss://`
124    /// (`S2C §Encrypted connection`: "S2 **MUST NOT** be sent over unencrypted channels").
125    #[must_use]
126    pub fn new(store: Arc<dyn Store>, websocket_url: impl Into<String>) -> Self {
127        Self {
128            store,
129            websocket_url: websocket_url.into(),
130            s2_message_versions: alloc::vec![
131                crate::types::WireProfile::V1_0_0.connect_version(),
132                crate::types::WireProfile::V0_0_2Beta.connect_version(),
133            ],
134            issued: std::sync::Mutex::new(Vec::new()),
135            rotation: std::sync::Mutex::new(()),
136            live: std::sync::Mutex::new(Vec::new()),
137            next_live: core::sync::atomic::AtomicU64::new(0),
138        }
139    }
140
141    /// Offer a different set of S2 JSON message versions, newest first.
142    #[must_use]
143    pub fn with_s2_message_versions(mut self, versions: Vec<ProtocolVersion>) -> Self {
144        self.s2_message_versions = versions;
145        self
146    }
147
148    /// The store.
149    #[must_use]
150    pub fn store(&self) -> &Arc<dyn Store> {
151        &self.store
152    }
153
154    /// The state machine for one pairing, built from what the store holds.
155    ///
156    /// Per request rather than per pairing, and that is the point: everything that has to
157    /// survive a restart — the tokens, including the grant waiting to be confirmed — lives
158    /// in the [`Store`], so a machine built fresh from it knows everything the last one
159    /// did. The alternative is a second implementation of session initiation beside
160    /// [`SessionInitServer`], and two implementations of one protocol drift.
161    fn machine(&self, key: PairingKey) -> Option<(bool, SessionInitServer)> {
162        let paired = self.store.paired(key)?;
163        Some((
164            paired.revoked,
165            SessionInitServer::new(key.local, key.remote, paired.tokens, &self.websocket_url)
166                .with_s2_message_versions(self.s2_message_versions.clone()),
167        ))
168    }
169
170    /// `POST /v1/initiateSession`.
171    ///
172    /// The replacement token is stored **alongside** the presented one, never instead of
173    /// it: until the client confirms, either must work, or a lost reply destroys the
174    /// pairing.
175    ///
176    /// A pairing this endpoint revoked answers `NoLongerPaired` — once, to a client that
177    /// proves it held it — and is then forgotten.
178    pub fn initiate_session(
179        &self,
180        bearer: &AccessToken,
181        request: &SessionRequest,
182        access_entropy: &[u8],
183        now: Timestamp,
184    ) -> Result<SessionGrant, ConnectError> {
185        let key = PairingKey {
186            local: request.server_node_id,
187            remote: request.client_node_id,
188        };
189        let _rotation = self.rotation.lock().map_err(|_| ConnectError::NotPaired)?;
190        let (revoked, mut machine) = self.machine(key).ok_or(ConnectError::NotPaired)?;
191        if revoked {
192            if !machine.authenticates(bearer) {
193                return Err(ConnectError::NotPaired);
194            }
195            self.store.unpair(key);
196            return Err(ConnectError::SessionRefused(SessionRefused {
197                error_message: SessionErrorMessage::NoLongerPaired,
198                additional_info: None,
199            }));
200        }
201        let mut grant = machine.initiate_session(bearer, request, access_entropy, now)?;
202        self.store.set_tokens(key, machine.tokens().clone());
203        // The only thing the store knows and the state machine does not: who we are.
204        grant.server_node_description = self.store.node(key.local);
205        Ok(grant)
206    }
207
208    /// `POST /v1/confirmAccessToken`.
209    ///
210    /// The bearer *is* the confirmation. Every older token is retired here, and not one
211    /// request earlier.
212    pub fn confirm_access_token(
213        &self,
214        bearer: &AccessToken,
215        communication_entropy: &[u8],
216        now: Timestamp,
217    ) -> Result<(PairingKey, CommunicationDetails), ConnectError> {
218        let details = {
219            let _rotation = self.rotation.lock().map_err(|_| ConnectError::NotPaired)?;
220            let key = self
221                .store
222                .pairing_for_token(bearer)
223                .ok_or(ConnectError::NotPaired)?;
224            let (_, mut machine) = self.machine(key).ok_or(ConnectError::NotPaired)?;
225            // Refuses anything that is not a grant this endpoint issued, and any grant
226            // older than `PENDING_TOKEN_LIFETIME` — leaving, in both cases, the tokens the
227            // client already had in force.
228            let details = machine.confirm_access_token(bearer, communication_entropy, now)?;
229            self.store.set_tokens(key, machine.tokens().clone());
230            (key, details)
231        };
232        let (key, details) = details;
233
234        let CommunicationDetails::WebSocket {
235            websocket_token, ..
236        } = &details;
237        if let Ok(mut issued) = self.issued.lock() {
238            issued.retain(|entry| {
239                now.saturating_duration_since(entry.issued) < COMMUNICATION_TOKEN_LIFETIME
240                    && entry.key != key
241            });
242            issued.push(IssuedConnection {
243                key,
244                token: websocket_token.clone(),
245                issued: now,
246            });
247        }
248        Ok((key, details))
249    }
250
251    /// Whether a bearer presented on a WebSocket upgrade is one this endpoint issued, and
252    /// which pairing it belongs to.
253    ///
254    /// The token is consumed: `s2-connect-common.yml/CommunicationToken` is "valid for a
255    /// single connection … for maximum 30 seconds", so a replay is refused rather than
256    /// granted a second session in parallel with the first. Every token is compared in
257    /// constant time and the list is swept of expired entries on the way through.
258    ///
259    /// This is what a host mounts its `/s2` route on —
260    /// [`websocket_router`](super::websocket_router) does it for you.
261    pub fn authorize_connection(&self, presented: &str, now: Timestamp) -> Option<PairingKey> {
262        let mut issued = self.issued.lock().ok()?;
263        issued.retain(|entry| {
264            now.saturating_duration_since(entry.issued) < COMMUNICATION_TOKEN_LIFETIME
265        });
266        // Every entry is examined, so the time taken does not say which one matched.
267        let mut found = None;
268        for (index, entry) in issued.iter().enumerate() {
269            if entry.token.verify_str(presented) {
270                found = Some((index, entry.key));
271            }
272        }
273        let (index, key) = found?;
274        issued.remove(index);
275        Some(key)
276    }
277
278    /// How many issued communication tokens are still waiting to be used.
279    ///
280    /// For a health endpoint, and for a test that wants to see one consumed.
281    #[must_use]
282    pub fn pending_connections(&self) -> usize {
283        self.issued.lock().map_or(0, |issued| issued.len())
284    }
285
286    /// Start tracking an open WebSocket session, so unpairing can end it.
287    ///
288    /// [`websocket_router`](super::websocket_router) does this for every socket it
289    /// accepts; a host terminating the WebSocket itself calls it after
290    /// [`authorize_connection`](Self::authorize_connection).
291    #[must_use]
292    pub fn register_session(self: &Arc<Self>, key: PairingKey) -> LiveSession {
293        let id = self
294            .next_live
295            .fetch_add(1, core::sync::atomic::Ordering::Relaxed);
296        let (end, watch) = tokio::sync::watch::channel(false);
297        if let Ok(mut live) = self.live.lock() {
298            live.push(LiveEntry { key, id, end });
299        }
300        LiveSession {
301            key,
302            id,
303            end: watch,
304            service: Arc::downgrade(self),
305        }
306    }
307
308    /// How many WebSocket sessions are open for one pairing.
309    #[must_use]
310    pub fn live_sessions(&self, key: PairingKey) -> usize {
311        self.live
312            .lock()
313            .map_or(0, |live| live.iter().filter(|e| e.key == key).count())
314    }
315
316    /// End every open session of a pairing, and void its unused communication tokens.
317    pub fn end_sessions(&self, key: PairingKey) {
318        if let Ok(live) = self.live.lock() {
319            for entry in live.iter().filter(|e| e.key == key) {
320                let _ = entry.end.send(true);
321            }
322        }
323        if let Ok(mut issued) = self.issued.lock() {
324            issued.retain(|entry| entry.key != key);
325        }
326    }
327
328    /// `POST /v1/unpair` — the client renounces the pairing.
329    pub fn unpair(
330        &self,
331        bearer: &AccessToken,
332        request: &UnpairRequest,
333    ) -> Result<(), ConnectError> {
334        let key = PairingKey {
335            local: request.server_node_id,
336            remote: request.client_node_id,
337        };
338        {
339            let _rotation = self.rotation.lock().map_err(|_| ConnectError::NotPaired)?;
340            let (_, mut machine) = self.machine(key).ok_or(ConnectError::NotPaired)?;
341            machine.unpair(bearer, request)?;
342            self.store.unpair(key);
343        }
344        self.end_sessions(key);
345        Ok(())
346    }
347
348    /// Unpair from this side: end the pairing's sessions now, and answer its next
349    /// `initiateSession` with `NoLongerPaired`.
350    ///
351    /// `S2C §Unpairing by the communication server` also says the server "**should**
352    /// send an S2 `SessionRequest` … `RECONNECT`" over the open session first; that is a
353    /// message of the S2 session the host runs, so send it before calling this.
354    pub fn unpair_remote(&self, key: PairingKey) {
355        self.store.revoke(key);
356        self.end_sessions(key);
357    }
358
359    /// The tokens of one pairing, for a route that must check a bearer.
360    #[must_use]
361    pub fn tokens(&self, key: PairingKey) -> Option<TokenStore> {
362        self.store.paired(key).map(|p| p.tokens)
363    }
364}