Skip to main content

s2_kit/connect/server/
session.rs

1//! The session-initiation endpoints.
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, NodeId, SessionGrant, SessionInitServer, SessionRequest, TokenStore,
10    UnpairRequest,
11};
12
13use super::store::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/// The one thing it keeps in memory is the set of communication tokens it has handed out
23/// and not yet seen used. Those are deliberately not persisted: each is valid for thirty
24/// seconds and one connection, so a server that has restarted has none that are still
25/// good, and a client whose upgrade is refused simply initiates again.
26pub struct SessionService {
27    store: Arc<dyn Store>,
28    websocket_url: String,
29    s2_message_versions: Vec<ProtocolVersion>,
30    /// Communication tokens handed out and not yet used, with the node each belongs to.
31    ///
32    /// The other half of `confirmAccessToken`: a server that returns a `websocketToken`
33    /// and keeps no copy has authorised nothing. The list stays tiny by construction —
34    /// each entry lives thirty seconds ([`COMMUNICATION_TOKEN_LIFETIME`]), is removed the
35    /// moment it is used, and expired ones are swept whenever one is added.
36    issued: std::sync::Mutex<Vec<IssuedConnection>>,
37}
38
39/// A communication token this endpoint issued and has not yet seen used.
40#[derive(Debug)]
41struct IssuedConnection {
42    remote: NodeId,
43    token: CommunicationToken,
44    issued: Timestamp,
45}
46
47impl core::fmt::Debug for SessionService {
48    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
49        f.debug_struct("SessionService")
50            .field("websocket_url", &self.websocket_url)
51            .field("s2_message_versions", &self.s2_message_versions)
52            .finish_non_exhaustive()
53    }
54}
55
56impl SessionService {
57    /// A service answering on `websocket_url`.
58    #[must_use]
59    pub fn new(store: Arc<dyn Store>, websocket_url: impl Into<String>) -> Self {
60        Self {
61            store,
62            websocket_url: websocket_url.into(),
63            s2_message_versions: alloc::vec![
64                crate::types::WireProfile::V1_0_0.connect_version(),
65                crate::types::WireProfile::V0_0_2Beta.connect_version(),
66            ],
67            issued: std::sync::Mutex::new(Vec::new()),
68        }
69    }
70
71    /// Offer a different set of S2 JSON message versions, newest first.
72    #[must_use]
73    pub fn with_s2_message_versions(mut self, versions: Vec<ProtocolVersion>) -> Self {
74        self.s2_message_versions = versions;
75        self
76    }
77
78    /// The store.
79    #[must_use]
80    pub fn store(&self) -> &Arc<dyn Store> {
81        &self.store
82    }
83
84    /// The state machine for one pairing, built from what the store holds.
85    ///
86    /// Per request rather than per pairing, and that is the point: everything that has to
87    /// survive a restart — the tokens, including the grant waiting to be confirmed — lives
88    /// in the [`Store`], so a machine built fresh from it knows everything the last one
89    /// did. The alternative is a second implementation of session initiation beside
90    /// [`SessionInitServer`], and two implementations of one protocol drift.
91    fn machine(&self, remote: NodeId) -> Option<(NodeId, SessionInitServer)> {
92        let paired = self.store.paired(remote)?;
93        Some((
94            paired.local,
95            SessionInitServer::new(paired.local, remote, paired.tokens, &self.websocket_url)
96                .with_s2_message_versions(self.s2_message_versions.clone()),
97        ))
98    }
99
100    /// `POST /v1/initiateSession`.
101    ///
102    /// The replacement token is stored **alongside** the presented one, never instead of
103    /// it: until the client confirms, either must work, or a lost reply destroys the
104    /// pairing.
105    pub fn initiate_session(
106        &self,
107        bearer: &AccessToken,
108        request: &SessionRequest,
109        access_entropy: &[u8],
110        now: Timestamp,
111    ) -> Result<SessionGrant, ConnectError> {
112        let (local, mut machine) = self
113            .machine(request.client_node_id)
114            .ok_or(ConnectError::NotPaired)?;
115        let mut grant = machine.initiate_session(bearer, request, access_entropy, now)?;
116        self.store
117            .set_tokens(request.client_node_id, machine.tokens().clone());
118        // The only thing the store knows and the state machine does not: who we are.
119        grant.server_node_description = self.store.node(local);
120        Ok(grant)
121    }
122
123    /// `POST /v1/confirmAccessToken`.
124    ///
125    /// The bearer *is* the confirmation. Every older token is retired here, and not one
126    /// request earlier.
127    pub fn confirm_access_token(
128        &self,
129        bearer: &AccessToken,
130        communication_entropy: &[u8],
131        now: Timestamp,
132    ) -> Result<(NodeId, CommunicationDetails), ConnectError> {
133        let remote = self
134            .store
135            .node_for_token(bearer)
136            .ok_or(ConnectError::NotPaired)?;
137        let (_, mut machine) = self.machine(remote).ok_or(ConnectError::NotPaired)?;
138        // Refuses anything that is not a grant this endpoint issued, and any grant older
139        // than `PENDING_TOKEN_LIFETIME` — leaving, in both cases, the tokens the client
140        // already had in force.
141        let details = machine.confirm_access_token(bearer, communication_entropy, now)?;
142        self.store.set_tokens(remote, machine.tokens().clone());
143
144        let CommunicationDetails::WebSocket {
145            websocket_token, ..
146        } = &details;
147        if let Ok(mut issued) = self.issued.lock() {
148            issued.retain(|entry| {
149                now.saturating_duration_since(entry.issued) < COMMUNICATION_TOKEN_LIFETIME
150                    && entry.remote != remote
151            });
152            issued.push(IssuedConnection {
153                remote,
154                token: websocket_token.clone(),
155                issued: now,
156            });
157        }
158        Ok((remote, details))
159    }
160
161    /// Whether a bearer presented on a WebSocket upgrade is one this endpoint issued, and
162    /// which node it belongs to.
163    ///
164    /// The token is consumed: `s2-connect-common.yml/CommunicationToken` is "valid for a
165    /// single connection … for maximum 30 seconds", so a replay is refused rather than
166    /// granted a second session in parallel with the first. Every token is compared in
167    /// constant time and the list is swept of expired entries on the way through.
168    ///
169    /// This is what a host mounts its `/s2` route on —
170    /// [`websocket_router`](super::websocket_router) does it for you.
171    pub fn authorize_connection(&self, presented: &str, now: Timestamp) -> Option<NodeId> {
172        let mut issued = self.issued.lock().ok()?;
173        issued.retain(|entry| {
174            now.saturating_duration_since(entry.issued) < COMMUNICATION_TOKEN_LIFETIME
175        });
176        // Every entry is examined, so the time taken does not say which one matched.
177        let mut found = None;
178        for (index, entry) in issued.iter().enumerate() {
179            if entry.token.verify_str(presented) {
180                found = Some((index, entry.remote));
181            }
182        }
183        let (index, remote) = found?;
184        issued.remove(index);
185        Some(remote)
186    }
187
188    /// How many issued communication tokens are still waiting to be used.
189    ///
190    /// For a health endpoint, and for a test that wants to see one consumed.
191    #[must_use]
192    pub fn pending_connections(&self) -> usize {
193        self.issued.lock().map_or(0, |issued| issued.len())
194    }
195
196    /// `POST /v1/unpair`.
197    pub fn unpair(
198        &self,
199        bearer: &AccessToken,
200        request: &UnpairRequest,
201    ) -> Result<(), ConnectError> {
202        let (_, mut machine) = self
203            .machine(request.client_node_id)
204            .ok_or(ConnectError::NotPaired)?;
205        machine.unpair(bearer, request)?;
206        self.store.unpair(request.client_node_id);
207        if let Ok(mut issued) = self.issued.lock() {
208            issued.retain(|entry| entry.remote != request.client_node_id);
209        }
210        Ok(())
211    }
212
213    /// The tokens of one pairing, for a route that must check a bearer.
214    #[must_use]
215    pub fn tokens(&self, remote: NodeId) -> Option<TokenStore> {
216        self.store.paired(remote).map(|p| p.tokens)
217    }
218}