Skip to main content

s2_kit/connect/proto/
session_init.rs

1//! Session initiation: turning a stored pairing into one authorised WebSocket.
2//!
3//! # Why this is two requests and not one
4//!
5//! An access token is valid **one time**. A naive exchange — client presents the token,
6//! server burns it and issues a new one in the reply — loses the pairing outright if that
7//! reply never arrives: the server has retired a token the client never received, and the
8//! only way back is for a human to pair the devices again.
9//!
10//! S2 Connect solves it by making the *second* request the proof, and this module is that
11//! two-phase commit:
12//!
13//! ```text
14//!   communication client                         communication server
15//!   ────────────────────                         ────────────────────
16//!   POST /v1/initiateSession ────────────────▶   the presented token still works;
17//!     Bearer <accessToken>                       a new one is issued as *pending*
18//!     clientNodeId, serverNodeId,
19//!     versions, protocols
20//!                          ◀───────────────────  selectedS2MessageVersion,
21//!   store the new token                          selectedCommunicationProtocol,
22//!                                                accessToken (the replacement)
23//!   POST /v1/confirmAccessToken ─────────────▶   the *new* token is the bearer, which
24//!     Bearer <the new accessToken>               is the proof it was stored; only now
25//!                          ◀───────────────────  is the old one retired
26//!                                                websocketUrl, websocketToken
27//!   wss:// with Bearer <websocketToken>, inside 30 seconds
28//! ```
29//!
30//! Authenticating the confirmation *with the new token* is the whole trick: the server
31//! needs no separate assertion that the client stored it, because presenting it is the
32//! assertion. `S2C §confirmAccessToken`: "it is crucial that the server knows certainly
33//! that client has properly stored its access token."
34//!
35//! Until that confirmation arrives, **both** tokens open the door. A client that crashed
36//! in between retries with whichever it has — `S2C §Recovery`: "It should try all the
37//! accessTokens sequentially" — and the pairing survives.
38//!
39//! # Two lifetimes, deliberately different
40//!
41//! The access token lasts up to five years and is the long-term credential; the
42//! communication token lasts thirty seconds and authorises exactly one connection. If the
43//! WebSocket handshake does not happen inside that half-minute, the whole initiation is
44//! repeated — cheap, and far better than a bearer token loose in a log file for five
45//! years.
46
47use alloc::string::String;
48use alloc::vec::Vec;
49
50use serde::{Deserialize, Serialize};
51
52use crate::types::{Duration, ProtocolVersion, Timestamp, WireProfile};
53
54use super::{
55    AccessToken, CommunicationProtocol, CommunicationToken, ConnectError, EndpointDescription,
56    NodeDescription, NodeId,
57};
58
59/// How long a communication token stays usable.
60///
61/// `s2-connect-common.yml/CommunicationToken`: "valid for maximum 30 seconds".
62pub const COMMUNICATION_TOKEN_LIFETIME: Duration = Duration::from_secs(30);
63
64/// How long a freshly granted access token may wait to be confirmed.
65///
66/// `S2C §Session initiation`: the server activates the replacement it issued only if the
67/// confirmation arrives "not more than 15 seconds" later. After that the grant is stale —
68/// the client is told to start again, and the token it already held keeps working, which
69/// is what stops an interrupted rotation from destroying the pairing.
70pub const PENDING_TOKEN_LIFETIME: Duration = Duration::from_secs(15);
71
72// ---------------------------------------------------------------------------
73// Wire types — `s2-connect-session-init.yml`
74// ---------------------------------------------------------------------------
75
76/// The body of `POST /v1/initiateSession`.
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(rename_all = "camelCase")]
79pub struct SessionRequest {
80    /// Who is asking.
81    pub client_node_id: NodeId,
82    /// Who it wants to talk to.
83    pub server_node_id: NodeId,
84    /// **S2 JSON** message versions the client speaks, newest first.
85    pub supported_s2_message_versions: Vec<ProtocolVersion>,
86    /// How it can carry them.
87    pub supported_communication_protocols: Vec<CommunicationProtocol>,
88    /// An updated description, when something about the node has changed.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub client_node_description: Option<NodeDescription>,
91    /// An updated endpoint description.
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub client_endpoint_description: Option<EndpointDescription>,
94}
95
96/// The `200` body of `initiateSession`.
97#[derive(Debug, Clone, Serialize, Deserialize)]
98#[serde(rename_all = "camelCase")]
99pub struct SessionGrant {
100    /// The transport the server chose.
101    pub selected_communication_protocol: CommunicationProtocol,
102    /// The S2 JSON message version the server chose from the client's list.
103    ///
104    /// This is the same string a bare-WebSocket `Handshake` negotiates, which is why a
105    /// session opened through S2 Connect uses
106    /// [`Negotiation::PreNegotiated`](crate::session::Negotiation::PreNegotiated) and
107    /// must not send handshake messages at all.
108    pub selected_s2_message_version: ProtocolVersion,
109    /// The **replacement** access token, not yet in force.
110    pub access_token: AccessToken,
111    /// An updated description of the server's node.
112    #[serde(skip_serializing_if = "Option::is_none")]
113    pub server_node_description: Option<NodeDescription>,
114    /// An updated description of the server's endpoint.
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub server_endpoint_description: Option<EndpointDescription>,
117}
118
119impl SessionGrant {
120    /// The wire profile the chosen version selects, if this crate speaks it.
121    #[must_use]
122    pub fn profile(&self) -> Option<WireProfile> {
123        // Through `ProtocolVersion`, not a literal comparison: `S2C` spells this version
124        // `v1.0.0` and S2 JSON spells it `1.0.0`, and a server that follows its own
125        // specification must not read as "a version this crate does not speak" (E25).
126        self.selected_s2_message_version.wire_profile()
127    }
128}
129
130/// The `200` body of `confirmAccessToken`: where to connect, and with what.
131///
132/// `S2C-OAS session-init/WebSocketCommunicationDetails`. The discriminator is
133/// `communicationProtocol`; there is one variant today.
134#[derive(Debug, Clone, Serialize, Deserialize)]
135#[serde(tag = "communicationProtocol")]
136#[non_exhaustive]
137pub enum CommunicationDetails {
138    /// A WebSocket.
139    WebSocket {
140        /// Where to connect. `wss://`, always.
141        #[serde(rename = "websocketUrl")]
142        websocket_url: String,
143        /// The bearer for that one connection.
144        ///
145        /// The prose calls this `commToken` and the schema calls it `websocketToken`
146        /// (erratum E9); they are the same thing.
147        #[serde(rename = "websocketToken")]
148        websocket_token: CommunicationToken,
149    },
150}
151
152/// Why a session could not be initiated.
153/// `S2C-OAS session-init/CommunicationDetailsErrorMessage`.
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
155#[non_exhaustive]
156pub enum SessionErrorMessage {
157    /// No S2 JSON message version in common.
158    IncompatibleS2MessageVersions,
159    /// No transport in common.
160    IncompatibleCommunicationProtocols,
161    /// The pairing is gone; a human must pair the devices again.
162    NoLongerPaired,
163    /// The body was not understood.
164    ParsingError,
165    /// Anything else.
166    Other,
167}
168
169/// The `400` body of `initiateSession`.
170#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
171#[serde(rename_all = "camelCase")]
172pub struct SessionRefused {
173    /// Which of the enumerated reasons.
174    pub error_message: SessionErrorMessage,
175    /// Free text, for a log.
176    #[serde(skip_serializing_if = "Option::is_none")]
177    pub additional_info: Option<String>,
178}
179
180/// The body of `POST /v1/unpair`.
181#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
182#[serde(rename_all = "camelCase")]
183pub struct UnpairRequest {
184    /// Who is asking.
185    pub client_node_id: NodeId,
186    /// Who to forget.
187    pub server_node_id: NodeId,
188}
189
190/// A grant with the clock attached: what a driver actually needs to connect.
191#[derive(Debug, Clone)]
192pub struct SessionCredentials {
193    /// Where to connect.
194    pub websocket_url: String,
195    /// What to put in `Authorization: Bearer …`.
196    pub websocket_token: CommunicationToken,
197    /// The S2 JSON message version both sides settled on.
198    pub profile: Option<WireProfile>,
199    /// When it was issued.
200    pub issued: Timestamp,
201}
202
203impl SessionCredentials {
204    /// The moment after which the token will be refused.
205    #[must_use]
206    pub fn expires(&self) -> Timestamp {
207        self.issued
208            .checked_add(COMMUNICATION_TOKEN_LIFETIME)
209            .unwrap_or(self.issued)
210    }
211
212    /// Whether the thirty seconds have run out.
213    ///
214    /// Worth asking before dialling rather than after: a driver that queues a connection
215    /// behind a slow DNS lookup can easily arrive too late, and the failure a server
216    /// returns for an expired token looks exactly like the one it returns for a wrong one.
217    #[must_use]
218    pub fn is_expired(&self, now: Timestamp) -> bool {
219        now >= self.expires()
220    }
221}
222
223// ---------------------------------------------------------------------------
224// The token store
225// ---------------------------------------------------------------------------
226
227/// One access token the store holds, and when it was granted.
228#[derive(Debug, Clone)]
229struct Held {
230    token: AccessToken,
231    /// `None` for a token that is already in force — the one pairing produced, or one a
232    /// confirmation has activated. `Some(t)` for a replacement granted at `t` and not yet
233    /// confirmed, which is the only kind [`PENDING_TOKEN_LIFETIME`] applies to.
234    granted: Option<Timestamp>,
235}
236
237/// The access tokens a paired node holds, newest first, and the rules that govern them.
238///
239/// This is the piece that makes the pairing survivable. Storing a *list* rather than one
240/// token is why a dropped reply is a retry instead of a service call — and the list is
241/// what `S2C §Recovery` asks for: "It now has (at least) two accessTokens in its list, and
242/// does not know for certain which one is active at the communication server. It should
243/// try all the accessTokens sequentially."
244///
245/// Each entry remembers whether it is already in force or is a grant still waiting to be
246/// confirmed, because only the second kind expires — after
247/// [`PENDING_TOKEN_LIFETIME`], which is what stops a confirmation that arrives an hour
248/// late from retiring a token that still works.
249#[derive(Debug, Clone, Default)]
250pub struct TokenStore {
251    /// Newest first. Never more than [`Self::MAX`].
252    tokens: Vec<Held>,
253}
254
255impl TokenStore {
256    /// How many tokens are kept before the oldest is dropped.
257    ///
258    /// Each failed round trip adds one. Four is well past the two the protocol produces
259    /// in the worst ordinary case, and bounds what a peer can make us store.
260    pub const MAX: usize = 4;
261
262    /// A store holding the token pairing produced.
263    #[must_use]
264    pub fn new(current: AccessToken) -> Self {
265        Self {
266            tokens: alloc::vec![Held {
267                token: current,
268                granted: None,
269            }],
270        }
271    }
272
273    /// Whether a presented token opens the door.
274    ///
275    /// Any token in the list is accepted, because the client may hold any of them and the
276    /// alternative to accepting it is a dead pairing.
277    #[must_use]
278    pub fn accepts(&self, presented: &AccessToken) -> bool {
279        self.find(presented).is_some()
280    }
281
282    fn find(&self, presented: &AccessToken) -> Option<&Held> {
283        self.tokens.iter().find(|h| h.token.verify(presented))
284    }
285
286    /// Record a replacement granted at `now` and not yet confirmed.
287    ///
288    /// It joins the list rather than replacing it, because until the client proves it has
289    /// stored the new token both must open the door (`S2C §Recovery`). What `now` buys is
290    /// the other half of the rule: [`confirm`](Self::confirm) will not activate a grant
291    /// the client sat on for more than [`PENDING_TOKEN_LIFETIME`].
292    pub fn add(&mut self, token: AccessToken, now: Timestamp) {
293        if self.tokens.iter().any(|h| h.token.verify(&token)) {
294            return;
295        }
296        // Retire grants that can no longer be confirmed, *before* making room. A grant
297        // past [`PENDING_TOKEN_LIFETIME`] can never be activated — `confirm` refuses it —
298        // so it is a slot holding nothing, and the list is only four long. Without this,
299        // four `initiateSession` calls whose replies never reached the client would push
300        // the token that actually works off the end, and the pairing would be dead while
301        // every party still believed in it. That is the exact failure `S2C §Recovery`
302        // keeps a list to avoid.
303        self.tokens.retain(|held| {
304            held.granted.is_none_or(|granted| {
305                now.saturating_duration_since(granted) <= PENDING_TOKEN_LIFETIME
306            })
307        });
308        self.tokens.insert(
309            0,
310            Held {
311                token,
312                granted: Some(now),
313            },
314        );
315        self.evict();
316    }
317
318    /// Bring the list back to [`Self::MAX`], dropping the **oldest pending grant** first.
319    ///
320    /// Truncating from the end would drop whatever is oldest, and the oldest entry is
321    /// usually the token in force: four `initiateSession` calls inside fifteen seconds
322    /// whose replies all went missing would push it out, while the client — which never
323    /// saw any of the grants — still holds only that one. `S2C §Interruption`: the old
324    /// token is not invalidated until "both nodes confirm that they have successfully
325    /// persisted the new accessToken".
326    fn evict(&mut self) {
327        while self.tokens.len() > Self::MAX {
328            let victim = self
329                .tokens
330                .iter()
331                .rposition(|held| held.granted.is_some())
332                .unwrap_or(self.tokens.len() - 1);
333            self.tokens.remove(victim);
334        }
335    }
336
337    /// Record a token that is already in force, such as the one pairing produced.
338    pub fn adopt(&mut self, token: AccessToken) {
339        if self.tokens.iter().any(|h| h.token.verify(&token)) {
340            return;
341        }
342        self.tokens.insert(
343            0,
344            Held {
345                token,
346                granted: None,
347            },
348        );
349        self.evict();
350    }
351
352    /// Activate a granted token and retire every other, as `confirmAccessToken` does.
353    ///
354    /// Called when the client proves it holds one — by presenting it as the bearer of
355    /// `confirmAccessToken` — which is what makes retiring the others safe.
356    ///
357    /// # Errors
358    ///
359    /// [`ConnectError::NotPaired`] when the token is not one this store holds;
360    /// [`ConnectError::Expired`] when it was granted more than
361    /// [`PENDING_TOKEN_LIFETIME`] ago and so is no longer confirmable. An expired grant
362    /// leaves the store untouched, so whatever the client held before still works.
363    pub fn confirm(&mut self, token: &AccessToken, now: Timestamp) -> Result<(), ConnectError> {
364        let held = self.find(token).ok_or(ConnectError::NotPaired)?;
365        if let Some(granted) = held.granted
366            && now.saturating_duration_since(granted) > PENDING_TOKEN_LIFETIME
367        {
368            return Err(ConnectError::Expired {
369                what: "access token confirmation",
370                limit: PENDING_TOKEN_LIFETIME,
371            });
372        }
373        self.tokens.clear();
374        self.tokens.push(Held {
375            token: token.clone(),
376            granted: None,
377        });
378        Ok(())
379    }
380
381    /// Whether a presented token is a **grant** this store issued and has not yet seen
382    /// confirmed.
383    ///
384    /// `confirmAccessToken` must be authenticated with the *replacement*, not with any
385    /// token the store happens to accept: presenting the replacement is the proof the
386    /// client stored it, and that proof is the only reason retiring the others is safe.
387    #[must_use]
388    pub fn is_pending(&self, presented: &AccessToken) -> bool {
389        self.find(presented).is_some_and(|h| h.granted.is_some())
390    }
391
392    /// The token to present next: the newest.
393    #[must_use]
394    pub fn current(&self) -> Option<&AccessToken> {
395        self.tokens.first().map(|h| &h.token)
396    }
397
398    /// Every token to try, newest first.
399    ///
400    /// A client that got a `401` works down this list before concluding it is unpaired.
401    pub fn candidates(&self) -> impl Iterator<Item = &AccessToken> {
402        self.tokens.iter().map(|h| &h.token)
403    }
404
405    /// How many are held.
406    #[must_use]
407    pub fn len(&self) -> usize {
408        self.tokens.len()
409    }
410
411    /// Whether the pairing has no token at all, which means it is gone.
412    #[must_use]
413    pub fn is_empty(&self) -> bool {
414        self.tokens.is_empty()
415    }
416
417    /// Forget everything. What a `NoLongerPaired` means.
418    pub fn clear(&mut self) {
419        self.tokens.clear();
420    }
421}
422
423// ---------------------------------------------------------------------------
424// The client
425// ---------------------------------------------------------------------------
426
427#[derive(Debug, Clone, Copy, PartialEq, Eq)]
428enum Phase {
429    Start,
430    AwaitingGrant,
431    Granted,
432    Connected,
433    Failed,
434}
435
436impl Phase {
437    const fn name(self) -> &'static str {
438        match self {
439            Phase::Start => "the start of session initiation",
440            Phase::AwaitingGrant => "the session grant",
441            Phase::Granted => "confirmation of the new access token",
442            Phase::Connected => "a completed initiation",
443            Phase::Failed => "a failed initiation",
444        }
445    }
446}
447
448/// The communication client's half of session initiation.
449///
450/// ```
451/// use s2_kit::connect::proto::{AccessToken, NodeId, SessionInitClient, TokenStore};
452///
453/// let store = TokenStore::new(AccessToken::from_entropy(&[1u8; 32])?);
454/// let mut client = SessionInitClient::new(NodeId::parse("rm-1")?, NodeId::parse("cem-1")?, store);
455///
456/// let (bearer, body) = client.initiate()?;
457/// assert_eq!(body.client_node_id.to_string(), "rm-1");
458/// # let _ = bearer;
459/// # Ok::<(), Box<dyn core::error::Error>>(())
460/// ```
461#[derive(Debug)]
462pub struct SessionInitClient {
463    client_node_id: NodeId,
464    server_node_id: NodeId,
465    tokens: TokenStore,
466    s2_message_versions: Vec<ProtocolVersion>,
467    protocols: Vec<CommunicationProtocol>,
468    phase: Phase,
469    /// The token presented on the request in flight, so a `401` can move to the next.
470    attempted: Option<AccessToken>,
471    /// How many tokens of the store have been tried since the last success.
472    tried: usize,
473    granted: Option<SessionGrant>,
474    /// Accept a `ws://` `websocketUrl`. Off unless a test asks for it.
475    insecure_websocket: bool,
476}
477
478impl SessionInitClient {
479    /// A client for one pairing.
480    #[must_use]
481    pub fn new(client_node_id: NodeId, server_node_id: NodeId, tokens: TokenStore) -> Self {
482        Self {
483            client_node_id,
484            server_node_id,
485            tokens,
486            // The `v`-prefixed spelling, because `S2C §Versioning of JSON Schema
487            // files` requires it over S2 Connect. Matching is canonical, so a peer that
488            // offers the bare form is still understood (E25).
489            s2_message_versions: alloc::vec![
490                WireProfile::V1_0_0.connect_version(),
491                WireProfile::V0_0_2Beta.connect_version(),
492            ],
493            protocols: alloc::vec![CommunicationProtocol::WebSocket],
494            phase: Phase::Start,
495            attempted: None,
496            tried: 0,
497            granted: None,
498            insecure_websocket: false,
499        }
500    }
501
502    /// Accept a plaintext `ws://` `websocketUrl` — for a loopback test and nothing else.
503    ///
504    /// `S2C §Encrypted connection`: "S2 **MUST NOT** be sent over unencrypted channels.
505    /// Therefore a wss connection … must be used." The communication token is a bearer;
506    /// over `ws://` anyone on the path can read it and the session it opens.
507    #[must_use]
508    pub fn allowing_insecure_websocket(mut self) -> Self {
509        self.insecure_websocket = true;
510        self
511    }
512
513    /// Offer a different set of S2 JSON message versions, newest first.
514    #[must_use]
515    pub fn with_s2_message_versions(mut self, versions: Vec<ProtocolVersion>) -> Self {
516        self.s2_message_versions = versions;
517        self
518    }
519
520    /// Build `initiateSession`, with the bearer to send it under.
521    ///
522    /// A completed initiation is a legitimate place to start another: every reconnection
523    /// needs fresh credentials, because a communication token authorises exactly one
524    /// connection and lives thirty seconds. Requiring [`Self::restart`] in between would
525    /// make the common path the one a caller forgets.
526    pub fn initiate(&mut self) -> Result<(AccessToken, SessionRequest), ConnectError> {
527        if self.phase == Phase::Connected {
528            self.phase = Phase::Start;
529        }
530        self.expect(Phase::Start)?;
531        let token = self
532            .tokens
533            .candidates()
534            .nth(self.tried)
535            .cloned()
536            .ok_or(ConnectError::NotPaired)?;
537        self.attempted = Some(token.clone());
538        self.phase = Phase::AwaitingGrant;
539        Ok((
540            token,
541            SessionRequest {
542                client_node_id: self.client_node_id,
543                server_node_id: self.server_node_id,
544                supported_s2_message_versions: self.s2_message_versions.clone(),
545                supported_communication_protocols: self.protocols.clone(),
546                client_node_description: None,
547                client_endpoint_description: None,
548            },
549        ))
550    }
551
552    /// Handle a `401` on `initiateSession` by moving to the next stored token.
553    ///
554    /// `S2C §Recovery`: "It should try all the accessTokens sequentially." When they are
555    /// exhausted the pairing really is gone, and this returns [`ConnectError::NotPaired`]
556    /// — which is a call to a human, not a retry.
557    pub fn unauthorized(&mut self) -> Result<(), ConnectError> {
558        self.tried += 1;
559        self.phase = Phase::Start;
560        if self.tried >= self.tokens.len() {
561            self.phase = Phase::Failed;
562            return Err(ConnectError::NotPaired);
563        }
564        Ok(())
565    }
566
567    /// Take the grant and store the replacement token.
568    ///
569    /// Storing before confirming is the order the specification requires, and the reason
570    /// the two requests exist at all: a client that confirmed first and stored afterwards
571    /// has a window in which a crash loses the replacement for good.
572    ///
573    /// `now` starts the [`PENDING_TOKEN_LIFETIME`] clock on this side too, so a client
574    /// that was suspended between the two requests declines to retire the token it
575    /// already had rather than retiring it against a server that never activated the
576    /// replacement.
577    pub fn accept(&mut self, grant: SessionGrant, now: Timestamp) -> Result<(), ConnectError> {
578        self.expect(Phase::AwaitingGrant)?;
579        if !self
580            .protocols
581            .contains(&grant.selected_communication_protocol)
582        {
583            self.phase = Phase::Failed;
584            return Err(ConnectError::NoOverlap("communication protocol"));
585        }
586        if !self
587            .s2_message_versions
588            .iter()
589            .any(|v| v.matches(&grant.selected_s2_message_version))
590        {
591            self.phase = Phase::Failed;
592            return Err(ConnectError::NoOverlap("S2 message version"));
593        }
594        self.tokens.add(grant.access_token.clone(), now);
595        self.granted = Some(grant);
596        self.phase = Phase::Granted;
597        Ok(())
598    }
599
600    /// The bearer for `confirmAccessToken`: the **new** token.
601    ///
602    /// Presenting it *is* the confirmation, which is why there is no body.
603    pub fn confirm(&mut self) -> Result<AccessToken, ConnectError> {
604        self.expect(Phase::Granted)?;
605        let grant = self.granted.as_ref().ok_or(ConnectError::OutOfOrder {
606            got: "a confirmation",
607            expected: Phase::AwaitingGrant.name(),
608        })?;
609        Ok(grant.access_token.clone())
610    }
611
612    /// Take the communication details the confirmation returned.
613    ///
614    /// The old tokens are retired here and not before: the server has just proved it
615    /// accepted the new one.
616    pub fn connected(
617        &mut self,
618        details: CommunicationDetails,
619        now: Timestamp,
620    ) -> Result<SessionCredentials, ConnectError> {
621        self.expect(Phase::Granted)?;
622        let grant = self.granted.take().ok_or(ConnectError::OutOfOrder {
623            got: "communication details",
624            expected: Phase::AwaitingGrant.name(),
625        })?;
626        self.tokens.confirm(&grant.access_token, now)?;
627        self.tried = 0;
628        self.phase = Phase::Connected;
629        let CommunicationDetails::WebSocket {
630            websocket_url,
631            websocket_token,
632        } = details;
633        let secure = websocket_url
634            .get(..6)
635            .is_some_and(|scheme| scheme.eq_ignore_ascii_case("wss://"));
636        if !secure && !self.insecure_websocket {
637            self.phase = Phase::Failed;
638            return Err(ConnectError::OutOfOrder {
639                got: "a websocketUrl that is not wss://",
640                expected: "an encrypted WebSocket (S2C §Encrypted connection)",
641            });
642        }
643        Ok(SessionCredentials {
644            websocket_url,
645            websocket_token,
646            profile: grant.profile(),
647            issued: now,
648        })
649    }
650
651    /// Start again after a failure, keeping whatever tokens survived.
652    ///
653    /// This is what makes the two-phase commit worth having: after any failure at all, the
654    /// store still holds a token the server will accept.
655    pub fn restart(&mut self) {
656        self.phase = Phase::Start;
657        self.attempted = None;
658    }
659
660    /// Forget the pairing. What a `NoLongerPaired` means.
661    pub fn unpaired(&mut self) -> UnpairRequest {
662        self.tokens.clear();
663        self.phase = Phase::Failed;
664        UnpairRequest {
665            client_node_id: self.client_node_id,
666            server_node_id: self.server_node_id,
667        }
668    }
669
670    /// The tokens, to persist.
671    #[must_use]
672    pub fn tokens(&self) -> &TokenStore {
673        &self.tokens
674    }
675
676    fn expect(&mut self, phase: Phase) -> Result<(), ConnectError> {
677        if self.phase == phase {
678            return Ok(());
679        }
680        let got = self.phase.name();
681        self.phase = Phase::Failed;
682        Err(ConnectError::OutOfOrder {
683            got,
684            expected: phase.name(),
685        })
686    }
687}
688
689// ---------------------------------------------------------------------------
690// The server
691// ---------------------------------------------------------------------------
692
693/// The communication server's half of session initiation.
694///
695/// It owns the token store for one pairing and never hands out a communication token
696/// without having accepted an access token first.
697#[derive(Debug)]
698pub struct SessionInitServer {
699    node_id: NodeId,
700    peer_node_id: NodeId,
701    tokens: TokenStore,
702    websocket_url: String,
703    s2_message_versions: Vec<ProtocolVersion>,
704    protocols: Vec<CommunicationProtocol>,
705    /// The communication token the last confirmation handed out, until it is used or its
706    /// thirty seconds run out.
707    ///
708    /// The only state here that is *not* in the [`TokenStore`], and deliberately so: it
709    /// lives thirty seconds and authorises one connection, so a server that has restarted
710    /// holds none that are still good. The pending **access** token is in the store,
711    /// because that one must survive a restart — a server that kept it in memory would
712    /// refuse the confirmation of a grant it had just issued.
713    connection: Option<IssuedConnection>,
714}
715
716/// A communication token this server issued and has not yet seen used.
717#[derive(Debug, Clone)]
718struct IssuedConnection {
719    token: CommunicationToken,
720    issued: Timestamp,
721}
722
723impl SessionInitServer {
724    /// A server for one pairing.
725    #[must_use]
726    pub fn new(
727        node_id: NodeId,
728        peer_node_id: NodeId,
729        tokens: TokenStore,
730        websocket_url: impl Into<String>,
731    ) -> Self {
732        Self {
733            node_id,
734            peer_node_id,
735            tokens,
736            websocket_url: websocket_url.into(),
737            // The `v`-prefixed spelling, because `S2C §Versioning of JSON Schema
738            // files` requires it over S2 Connect. Matching is canonical, so a peer that
739            // offers the bare form is still understood (E25).
740            s2_message_versions: alloc::vec![
741                WireProfile::V1_0_0.connect_version(),
742                WireProfile::V0_0_2Beta.connect_version(),
743            ],
744            protocols: alloc::vec![CommunicationProtocol::WebSocket],
745            connection: None,
746        }
747    }
748
749    /// Offer a different set of S2 JSON message versions, newest first.
750    #[must_use]
751    pub fn with_s2_message_versions(mut self, versions: Vec<ProtocolVersion>) -> Self {
752        self.s2_message_versions = versions;
753        self
754    }
755
756    /// Whether a bearer presented on either endpoint is one we would accept.
757    ///
758    /// A `false` is a `401`.
759    #[must_use]
760    pub fn authenticates(&self, bearer: &AccessToken) -> bool {
761        self.tokens.accepts(bearer)
762    }
763
764    /// Handle `initiateSession`.
765    ///
766    /// `access_entropy` is a parameter for the same reason it is in
767    /// [`pairing`](super::pairing): a test needs it pinned, and this layer has no business
768    /// knowing where a system keeps its randomness.
769    ///
770    /// # Errors
771    ///
772    /// [`ConnectError::NotPaired`] is a `401`; a [`SessionRefused`] carried in
773    /// [`ConnectError::SessionRefused`] is a `400` with that body.
774    pub fn initiate_session(
775        &mut self,
776        bearer: &AccessToken,
777        request: &SessionRequest,
778        access_entropy: &[u8],
779        now: Timestamp,
780    ) -> Result<SessionGrant, ConnectError> {
781        if !self.tokens.accepts(bearer) {
782            return Err(ConnectError::NotPaired);
783        }
784        if request.server_node_id != self.node_id || request.client_node_id != self.peer_node_id {
785            return Err(ConnectError::SessionRefused(SessionRefused {
786                error_message: SessionErrorMessage::NoLongerPaired,
787                additional_info: None,
788            }));
789        }
790        let protocol = request
791            .supported_communication_protocols
792            .iter()
793            .find(|p| self.protocols.contains(p))
794            .copied()
795            .ok_or(ConnectError::SessionRefused(SessionRefused {
796                error_message: SessionErrorMessage::IncompatibleCommunicationProtocols,
797                additional_info: None,
798            }))?;
799        // Newest first in the client's list; we take the first we also speak.
800        let version = request
801            .supported_s2_message_versions
802            .iter()
803            .find(|v| self.s2_message_versions.iter().any(|ours| ours.matches(v)))
804            .cloned()
805            .ok_or(ConnectError::SessionRefused(SessionRefused {
806                error_message: SessionErrorMessage::IncompatibleS2MessageVersions,
807                additional_info: None,
808            }))?;
809
810        let replacement = AccessToken::from_entropy(access_entropy)?;
811        // Issued alongside, not instead of: the token the client just used stays valid
812        // until it proves it has the new one. `add` records *when*, which is what makes
813        // it a pending grant rather than simply another accepted token.
814        self.tokens.add(replacement.clone(), now);
815        Ok(SessionGrant {
816            selected_communication_protocol: protocol,
817            selected_s2_message_version: version,
818            access_token: replacement,
819            server_node_description: None,
820            server_endpoint_description: None,
821        })
822    }
823
824    /// Handle `confirmAccessToken`, retiring every older token.
825    ///
826    /// The bearer *is* the confirmation: a client that can present the new token has
827    /// stored it, so there is nothing else to check and nothing to take on trust.
828    pub fn confirm_access_token(
829        &mut self,
830        bearer: &AccessToken,
831        communication_entropy: &[u8],
832        now: Timestamp,
833    ) -> Result<CommunicationDetails, ConnectError> {
834        // The bearer must be a *pending grant*, not merely a token the store accepts:
835        // presenting the replacement is the proof it was stored, and that proof is the
836        // whole reason retiring the others is safe. The store is where that fact lives, so
837        // it survives a restart between the two requests.
838        if !self.tokens.is_pending(bearer) {
839            return Err(ConnectError::NotPaired);
840        }
841        self.tokens.confirm(bearer, now)?;
842        let token = CommunicationToken::from_entropy(communication_entropy)?;
843        // Remembered, because a server that hands out a bearer it does not keep has
844        // authorised nothing: the WebSocket upgrade later has nothing to check the
845        // `Authorization` header against. One token at a time — a second confirmation
846        // supersedes the first, exactly as it supersedes the access token.
847        self.connection = Some(IssuedConnection {
848            token: token.clone(),
849            issued: now,
850        });
851        Ok(CommunicationDetails::WebSocket {
852            websocket_url: self.websocket_url.clone(),
853            websocket_token: token,
854        })
855    }
856
857    /// Handle `unpair`.
858    pub fn unpair(
859        &mut self,
860        bearer: &AccessToken,
861        request: &UnpairRequest,
862    ) -> Result<(), ConnectError> {
863        if !self.tokens.accepts(bearer)
864            || request.server_node_id != self.node_id
865            || request.client_node_id != self.peer_node_id
866        {
867            return Err(ConnectError::NotPaired);
868        }
869        self.tokens.clear();
870        self.connection = None;
871        Ok(())
872    }
873
874    /// Whether a bearer presented on a WebSocket handshake is the one this server issued,
875    /// and still inside its thirty seconds.
876    ///
877    /// Takes `&mut self` and consumes the token on success, because
878    /// `s2-connect-common.yml/CommunicationToken` says it is "valid for a single
879    /// connection": a second upgrade with the same bearer is refused rather than
880    /// silently granted a parallel session.
881    pub fn accepts_connection(&mut self, presented: &str, now: Timestamp) -> bool {
882        let Some(connection) = &self.connection else {
883            return false;
884        };
885        if now.saturating_duration_since(connection.issued) >= COMMUNICATION_TOKEN_LIFETIME {
886            self.connection = None;
887            return false;
888        }
889        if !connection.token.verify_str(presented) {
890            return false;
891        }
892        self.connection = None;
893        true
894    }
895
896    /// The tokens, to persist.
897    #[must_use]
898    pub fn tokens(&self) -> &TokenStore {
899        &self.tokens
900    }
901}
902
903#[cfg(test)]
904mod tests {
905    use super::*;
906    use alloc::string::ToString;
907
908    fn t(secs: i64) -> Timestamp {
909        Timestamp::from_unix(1_700_000_000 + secs, 0)
910    }
911
912    #[test]
913    fn four_unanswered_grants_inside_the_window_keep_the_token_in_force() {
914        // Every grant is still inside its fifteen seconds, so none can be retired as stale,
915        // and the list is full: the one to drop is a grant, never the token in force.
916        let active = AccessToken::new("in-force");
917        let mut store = TokenStore::new(active.clone());
918        for i in 0..6 {
919            store.add(AccessToken::new(alloc::format!("grant-{i}")), t(i));
920        }
921        assert_eq!(store.len(), TokenStore::MAX);
922        assert!(
923            store.accepts(&active),
924            "the token the client holds still opens the door"
925        );
926        assert!(
927            store.accepts(&AccessToken::new("grant-5")),
928            "and the newest grant is kept"
929        );
930    }
931
932    #[test]
933    fn a_grant_nobody_confirmed_never_evicts_the_token_that_works() {
934        // Four `initiateSession` calls whose replies never reached the client each add a
935        // pending grant. With a four-deep list and no expiry, the fourth pushes the token
936        // that is actually in force off the end — and the pairing is dead while both
937        // parties still believe in it. A grant past `PENDING_TOKEN_LIFETIME` can never be
938        // confirmed, so it is a slot holding nothing and goes first.
939        let live = AccessToken::from_entropy(&[9u8; 32]).expect("32 bytes");
940        let mut store = TokenStore::new(live.clone());
941        for i in 0..6u8 {
942            let granted = AccessToken::from_entropy(&[i; 32]).expect("32 bytes");
943            // Each attempt a minute after the last: every earlier grant is long dead.
944            store.add(granted, t(i64::from(i) * 60));
945        }
946        assert!(
947            store.accepts(&live),
948            "the token the client is still holding must keep working"
949        );
950        assert_eq!(store.len(), 2, "one live token and the newest grant");
951
952        // Grants that are still inside their window are *not* dropped: two initiations a
953        // second apart are a client retrying, not a client leaking.
954        let live = AccessToken::from_entropy(&[9u8; 32]).expect("32 bytes");
955        let mut store = TokenStore::new(live.clone());
956        for i in 0..3u8 {
957            let granted = AccessToken::from_entropy(&[i; 32]).expect("32 bytes");
958            store.add(granted, t(i64::from(i)));
959        }
960        assert_eq!(store.len(), 4);
961        assert!(store.accepts(&live));
962    }
963
964    fn ids() -> (NodeId, NodeId) {
965        (
966            NodeId::parse("rm-1").expect("a legal id"),
967            NodeId::parse("cem-1").expect("a legal id"),
968        )
969    }
970
971    fn pair() -> (SessionInitClient, SessionInitServer, AccessToken) {
972        let (rm, cem) = ids();
973        let initial = AccessToken::from_entropy(&[1u8; 32]).expect("32 bytes");
974        let client = SessionInitClient::new(rm, cem, TokenStore::new(initial.clone()));
975        let server = SessionInitServer::new(
976            cem,
977            rm,
978            TokenStore::new(initial.clone()),
979            "wss://cem.example.com/s2",
980        );
981        (client, server, initial)
982    }
983
984    /// One whole initiation, both sides, with every step at `at`.
985    fn run_at(
986        client: &mut SessionInitClient,
987        server: &mut SessionInitServer,
988        new_access: u8,
989        comm: u8,
990        at: Timestamp,
991    ) -> SessionCredentials {
992        let (bearer, request) = client.initiate().unwrap();
993        let grant = server
994            .initiate_session(&bearer, &request, &[new_access; 32], at)
995            .unwrap();
996        client.accept(grant, at).unwrap();
997        let confirm = client.confirm().unwrap();
998        let details = server
999            .confirm_access_token(&confirm, &[comm; 32], at)
1000            .unwrap();
1001        client.connected(details, at).unwrap()
1002    }
1003
1004    /// One whole initiation at the epoch of this module's clock.
1005    fn run(
1006        client: &mut SessionInitClient,
1007        server: &mut SessionInitServer,
1008        new_access: u8,
1009        comm: u8,
1010    ) -> SessionCredentials {
1011        run_at(client, server, new_access, comm, t(0))
1012    }
1013
1014    #[test]
1015    fn a_websocket_url_that_is_not_encrypted_is_refused() {
1016        // `S2C §Encrypted connection`: "S2 MUST NOT be sent over unencrypted channels."
1017        // The communication token is a bearer; over `ws://` it is anyone's.
1018        let (rm, cem) = ids();
1019        let initial = AccessToken::from_entropy(&[1u8; 32]).expect("32 bytes");
1020        let plaintext = |mut client: SessionInitClient| {
1021            let mut server = SessionInitServer::new(
1022                cem,
1023                rm,
1024                TokenStore::new(initial.clone()),
1025                "ws://cem.example.com/s2",
1026            );
1027            let (bearer, request) = client.initiate().unwrap();
1028            let grant = server
1029                .initiate_session(&bearer, &request, &[2; 32], t(0))
1030                .unwrap();
1031            client.accept(grant, t(0)).unwrap();
1032            let confirm = client.confirm().unwrap();
1033            let details = server
1034                .confirm_access_token(&confirm, &[3; 32], t(0))
1035                .unwrap();
1036            client.connected(details, t(0))
1037        };
1038        let refused = plaintext(SessionInitClient::new(
1039            rm,
1040            cem,
1041            TokenStore::new(initial.clone()),
1042        ));
1043        assert!(matches!(refused, Err(ConnectError::OutOfOrder { .. })));
1044        let allowed = plaintext(
1045            SessionInitClient::new(rm, cem, TokenStore::new(initial.clone()))
1046                .allowing_insecure_websocket(),
1047        );
1048        assert!(allowed.is_ok(), "a loopback test may opt in");
1049    }
1050
1051    #[test]
1052    fn a_session_is_initiated_and_the_token_rotates() {
1053        let (mut client, mut server, initial) = pair();
1054        let creds = run(&mut client, &mut server, 2, 3);
1055
1056        assert_eq!(creds.websocket_url, "wss://cem.example.com/s2");
1057        assert_eq!(creds.profile, Some(WireProfile::V1_0_0));
1058        assert!(!creds.is_expired(t(29)));
1059
1060        // The old token is gone on both sides; the new one works on both.
1061        assert!(!server.tokens().accepts(&initial));
1062        assert_eq!(client.tokens().len(), 1);
1063        assert!(server.tokens().accepts(client.tokens().current().unwrap()));
1064    }
1065
1066    #[test]
1067    fn the_confirmation_is_authenticated_with_the_new_token() {
1068        // That is the whole trick: presenting it *is* the proof it was stored.
1069        let (mut client, mut server, initial) = pair();
1070        let (bearer, request) = client.initiate().unwrap();
1071        let grant = server
1072            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
1073            .unwrap();
1074        let replacement = grant.access_token.clone();
1075        client.accept(grant, t(0)).unwrap();
1076
1077        // The *old* token does not confirm anything.
1078        assert!(matches!(
1079            server.confirm_access_token(&initial, &[3u8; 32], t(0)),
1080            Err(ConnectError::NotPaired)
1081        ));
1082        // The new one does.
1083        assert!(
1084            server
1085                .confirm_access_token(&replacement, &[3u8; 32], t(0))
1086                .is_ok()
1087        );
1088    }
1089
1090    #[test]
1091    fn a_lost_grant_does_not_strand_the_pairing() {
1092        // The reply to initiateSession never arrives: the server has issued a replacement
1093        // the client has never seen, and the client still holds the old one.
1094        let (mut client, mut server, initial) = pair();
1095        let (bearer, request) = client.initiate().unwrap();
1096        let _lost = server
1097            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
1098            .unwrap();
1099
1100        // The client retries with what it has, and the server still accepts it.
1101        client.restart();
1102        assert!(server.tokens().accepts(&initial));
1103        let creds = run(&mut client, &mut server, 4, 5);
1104        assert!(!creds.websocket_url.is_empty());
1105        assert!(server.tokens().accepts(client.tokens().current().unwrap()));
1106    }
1107
1108    #[test]
1109    fn a_lost_confirmation_does_not_strand_the_pairing_either() {
1110        // The client stored the new token and then died before confirming.
1111        let (mut client, mut server, initial) = pair();
1112        let (bearer, request) = client.initiate().unwrap();
1113        let grant = server
1114            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
1115            .unwrap();
1116        client.accept(grant, t(0)).unwrap();
1117
1118        // Both tokens still open the door — the point of the phase.
1119        assert!(server.tokens().accepts(&initial));
1120        assert!(server.tokens().accepts(client.tokens().current().unwrap()));
1121        assert_eq!(client.tokens().len(), 2);
1122
1123        client.restart();
1124        let creds = run(&mut client, &mut server, 6, 7);
1125        assert!(!creds.websocket_url.is_empty());
1126        assert_eq!(
1127            client.tokens().len(),
1128            1,
1129            "and the list collapses on success"
1130        );
1131    }
1132
1133    #[test]
1134    fn a_client_works_down_its_list_after_a_401() {
1135        // Two failed rounds have left three tokens; only the newest is live.
1136        let (mut client, mut server, _) = pair();
1137        for entropy in [2u8, 3u8] {
1138            let (bearer, request) = client.initiate().unwrap();
1139            let grant = server
1140                .initiate_session(&bearer, &request, &[entropy; 32], t(0))
1141                .unwrap();
1142            client.accept(grant, t(0)).unwrap();
1143            client.restart();
1144        }
1145        assert_eq!(client.tokens().len(), 3);
1146
1147        // A server that has forgotten everything refuses each in turn, and the client
1148        // concludes it is unpaired rather than retrying for ever.
1149        let (rm, cem) = ids();
1150        let mut amnesiac = SessionInitServer::new(cem, rm, TokenStore::default(), "wss://x/");
1151        for _ in 0..3 {
1152            let (bearer, request) = client.initiate().unwrap();
1153            assert!(matches!(
1154                amnesiac.initiate_session(&bearer, &request, &[9u8; 32], t(0)),
1155                Err(ConnectError::NotPaired)
1156            ));
1157            if let Err(e) = client.unauthorized() {
1158                assert_eq!(e, ConnectError::NotPaired);
1159                return;
1160            }
1161        }
1162        panic!("the client should have given up after exhausting its tokens");
1163    }
1164
1165    #[test]
1166    fn a_token_the_server_never_issued_is_refused() {
1167        let (mut client, mut server, _) = pair();
1168        let (_, request) = client.initiate().unwrap();
1169        let forged = AccessToken::from_entropy(&[0xFFu8; 32]).unwrap();
1170        assert!(matches!(
1171            server.initiate_session(&forged, &request, &[2u8; 32], t(0)),
1172            Err(ConnectError::NotPaired)
1173        ));
1174    }
1175
1176    #[test]
1177    fn a_request_for_someone_elses_pairing_is_refused() {
1178        let (mut client, mut server, _) = pair();
1179        let (bearer, mut request) = client.initiate().unwrap();
1180        request.server_node_id = NodeId::parse("cem-2").unwrap();
1181        assert!(matches!(
1182            server.initiate_session(&bearer, &request, &[2u8; 32], t(0)),
1183            Err(ConnectError::SessionRefused(SessionRefused {
1184                error_message: SessionErrorMessage::NoLongerPaired,
1185                ..
1186            }))
1187        ));
1188    }
1189
1190    #[test]
1191    fn a_peer_that_spells_the_version_the_other_way_still_connects() {
1192        // Erratum E25: `S2C` requires `v1.0.0`, every deployed S2 JSON handshake writes
1193        // `1.0.0`, and `s2energy-connection`'s examples write `v1`. Exact matching on
1194        // both sides means two conforming implementations cannot agree on a version they
1195        // both speak — which is a pairing that fails for a reason no log would explain.
1196        for spelling in ["v1.0.0", "1.0.0"] {
1197            let (client, mut server, _) = pair();
1198            let mut client =
1199                client.with_s2_message_versions(alloc::vec![ProtocolVersion::new(spelling)]);
1200            let creds = run(&mut client, &mut server, 2, 3);
1201            assert_eq!(
1202                creds.profile,
1203                Some(WireProfile::V1_0_0),
1204                "a server offering the other spelling must still resolve {spelling}"
1205            );
1206        }
1207
1208        // And the same in the other direction: a server that offers only the bare form
1209        // answers a client that offered only the prefixed one.
1210        let (mut client, server, _) = pair();
1211        let mut server =
1212            server.with_s2_message_versions(alloc::vec![ProtocolVersion::new("1.0.0")]);
1213        let creds = run(&mut client, &mut server, 2, 3);
1214        assert_eq!(creds.profile, Some(WireProfile::V1_0_0));
1215    }
1216
1217    #[test]
1218    fn a_version_neither_side_speaks_is_refused_with_the_named_reason() {
1219        let (rm, cem) = ids();
1220        let initial = AccessToken::from_entropy(&[1u8; 32]).unwrap();
1221        let mut client = SessionInitClient::new(rm, cem, TokenStore::new(initial.clone()))
1222            .with_s2_message_versions(alloc::vec![crate::types::ProtocolVersion::new("9.9.9")]);
1223        let mut server = SessionInitServer::new(cem, rm, TokenStore::new(initial), "wss://x/");
1224        let (bearer, request) = client.initiate().unwrap();
1225        assert!(matches!(
1226            server.initiate_session(&bearer, &request, &[2u8; 32], t(0)),
1227            Err(ConnectError::SessionRefused(SessionRefused {
1228                error_message: SessionErrorMessage::IncompatibleS2MessageVersions,
1229                ..
1230            }))
1231        ));
1232    }
1233
1234    #[test]
1235    fn a_communication_token_is_good_for_thirty_seconds_and_not_a_moment_more() {
1236        let (mut client, mut server, _) = pair();
1237        let (bearer, request) = client.initiate().unwrap();
1238        let grant = server
1239            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
1240            .unwrap();
1241        client.accept(grant, t(0)).unwrap();
1242        let confirm = client.confirm().unwrap();
1243        let details = server
1244            .confirm_access_token(&confirm, &[3u8; 32], t(0))
1245            .unwrap();
1246        let CommunicationDetails::WebSocket {
1247            ref websocket_token,
1248            ..
1249        } = details;
1250        let presented = websocket_token.as_str().to_string();
1251        let creds = client.connected(details, t(0)).unwrap();
1252
1253        assert!(creds.is_expired(t(30)));
1254        assert_eq!(creds.expires(), t(30));
1255
1256        // The right timing with the wrong token is refused, and refusing it does not
1257        // spend the one the server is holding.
1258        assert!(!server.accepts_connection("something else", t(1)));
1259        // The right token inside the window is accepted...
1260        assert!(server.accepts_connection(&presented, t(29)));
1261        // ...exactly once: a communication token is "valid for a single connection".
1262        assert!(!server.accepts_connection(&presented, t(29)));
1263    }
1264
1265    #[test]
1266    fn a_communication_token_presented_too_late_is_refused() {
1267        let (mut client, mut server, _) = pair();
1268        let creds = run(&mut client, &mut server, 2, 3);
1269        let presented = creds.websocket_token.as_str().to_string();
1270        assert!(!server.accepts_connection(&presented, t(30)));
1271        // And the expired entry is gone, so it cannot come back inside the window.
1272        assert!(!server.accepts_connection(&presented, t(1)));
1273    }
1274
1275    #[test]
1276    fn a_server_restarted_between_the_two_requests_still_honours_the_grant() {
1277        // The pending grant lives in the `TokenStore`, which is the thing a host
1278        // persists — not in a field of the state machine. A server that kept it in memory
1279        // would refuse the confirmation of a grant it had itself issued a second earlier,
1280        // and the client would be left holding a token nobody activated.
1281        let (mut client, mut server, initial) = pair();
1282        let (bearer, request) = client.initiate().unwrap();
1283        let grant = server
1284            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
1285            .unwrap();
1286        client.accept(grant, t(0)).unwrap();
1287        let confirm = client.confirm().unwrap();
1288
1289        // The process dies here. Everything it persisted comes back; everything else
1290        // does not.
1291        let persisted = server.tokens().clone();
1292        let (rm, cem) = ids();
1293        let mut server = SessionInitServer::new(cem, rm, persisted, "wss://cem.example.com/s2");
1294
1295        let details = server
1296            .confirm_access_token(&confirm, &[3u8; 32], t(1))
1297            .expect("a restart must not lose the grant");
1298        let creds = client.connected(details, t(1)).unwrap();
1299        assert!(
1300            !server.tokens().accepts(&initial),
1301            "the old token is retired"
1302        );
1303        assert!(server.tokens().accepts(client.tokens().current().unwrap()));
1304        assert!(!creds.is_expired(t(2)));
1305    }
1306
1307    #[test]
1308    fn only_a_pending_grant_confirms_anything() {
1309        // Every token the store accepts is not a token that confirms: presenting the
1310        // *replacement* is the proof it was stored, which is the only reason retiring the
1311        // others is safe. A client that presents the token it already had proves nothing.
1312        let (mut client, mut server, initial) = pair();
1313        let (bearer, request) = client.initiate().unwrap();
1314        let grant = server
1315            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
1316            .unwrap();
1317        client.accept(grant, t(0)).unwrap();
1318
1319        assert!(
1320            server.tokens().accepts(&initial),
1321            "it is still a valid bearer"
1322        );
1323        assert!(
1324            matches!(
1325                server.confirm_access_token(&initial, &[3u8; 32], t(0)),
1326                Err(ConnectError::NotPaired)
1327            ),
1328            "but it is not the grant"
1329        );
1330        // And the real one still works afterwards: a wrong confirmation must not burn it.
1331        let confirm = client.confirm().unwrap();
1332        assert!(
1333            server
1334                .confirm_access_token(&confirm, &[3u8; 32], t(0))
1335                .is_ok()
1336        );
1337    }
1338
1339    #[test]
1340    fn a_grant_confirmed_too_late_leaves_the_old_token_in_force() {
1341        // `S2C §Session initiation`: the server activates the replacement only if the
1342        // confirmation arrives "not more than 15 seconds" later. The point of refusing a
1343        // late one is what it does *not* do — it must not retire the token the client is
1344        // still holding, or a slow network unpairs a device.
1345        let (mut client, mut server, initial) = pair();
1346        let (bearer, request) = client.initiate().unwrap();
1347        let grant = server
1348            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
1349            .unwrap();
1350        client.accept(grant, t(0)).unwrap();
1351        let confirm = client.confirm().unwrap();
1352
1353        let too_late = server.confirm_access_token(&confirm, &[3u8; 32], t(16));
1354        assert!(
1355            matches!(
1356                too_late,
1357                Err(ConnectError::Expired {
1358                    what: "access token confirmation",
1359                    ..
1360                })
1361            ),
1362            "{too_late:?}"
1363        );
1364        assert!(
1365            server.tokens().accepts(&initial),
1366            "the old token still works"
1367        );
1368
1369        // Fourteen seconds later is inside the window, and then the old one is gone.
1370        let (mut client, mut server, initial) = pair();
1371        let (bearer, request) = client.initiate().unwrap();
1372        let grant = server
1373            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
1374            .unwrap();
1375        client.accept(grant, t(0)).unwrap();
1376        let confirm = client.confirm().unwrap();
1377        let details = server
1378            .confirm_access_token(&confirm, &[3u8; 32], t(14))
1379            .expect("fourteen seconds is inside fifteen");
1380        let creds = client.connected(details, t(14)).unwrap();
1381        assert!(!server.tokens().accepts(&initial));
1382        assert_eq!(creds.profile, Some(WireProfile::V1_0_0));
1383    }
1384
1385    #[test]
1386    fn the_phases_cannot_be_taken_out_of_order() {
1387        let (mut client, _, _) = pair();
1388        assert!(matches!(
1389            client.confirm(),
1390            Err(ConnectError::OutOfOrder { .. })
1391        ));
1392        assert!(client.initiate().is_err());
1393        client.restart();
1394        assert!(client.initiate().is_ok());
1395    }
1396
1397    #[test]
1398    fn a_completed_session_can_be_followed_by_another() {
1399        // A communication token authorises one connection and lives thirty seconds, so
1400        // reconnecting is the normal case, not an exception.
1401        let (mut client, mut server, _) = pair();
1402        run(&mut client, &mut server, 2, 3);
1403        run(&mut client, &mut server, 4, 5);
1404        run(&mut client, &mut server, 6, 7);
1405        // Each round retires the last token, so the list never grows.
1406        assert_eq!(client.tokens().len(), 1);
1407        assert!(server.tokens().accepts(client.tokens().current().unwrap()));
1408    }
1409
1410    #[test]
1411    fn unpairing_forgets_the_pairing_on_both_sides() {
1412        let (mut client, mut server, _) = pair();
1413        run(&mut client, &mut server, 2, 3);
1414        let token = client.tokens().current().unwrap().clone();
1415        let request = client.unpaired();
1416        server.unpair(&token, &request).unwrap();
1417        assert!(server.tokens().is_empty());
1418        assert!(client.tokens().is_empty());
1419        // And nothing works afterwards.
1420        assert!(!server.authenticates(&token));
1421    }
1422
1423    #[test]
1424    fn the_bodies_are_the_shape_the_openapi_defines() {
1425        let (mut client, mut server, _) = pair();
1426        let (bearer, request) = client.initiate().unwrap();
1427        let json = serde_json::to_value(&request).unwrap();
1428        for key in [
1429            "clientNodeId",
1430            "serverNodeId",
1431            "supportedS2MessageVersions",
1432            "supportedCommunicationProtocols",
1433        ] {
1434            assert!(json.get(key).is_some(), "missing required property {key}");
1435        }
1436        assert!(json.get("clientNodeDescription").is_none());
1437        assert_eq!(json["supportedCommunicationProtocols"][0], "WebSocket");
1438
1439        let grant = server
1440            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
1441            .unwrap();
1442        let json = serde_json::to_value(&grant).unwrap();
1443        for key in [
1444            "selectedCommunicationProtocol",
1445            "selectedS2MessageVersion",
1446            "accessToken",
1447        ] {
1448            assert!(json.get(key).is_some(), "missing required property {key}");
1449        }
1450
1451        // The discriminated union the schema calls WebSocketCommunicationDetails.
1452        client.accept(grant, t(0)).unwrap();
1453        let confirm = client.confirm().unwrap();
1454        let details = server
1455            .confirm_access_token(&confirm, &[3u8; 32], t(0))
1456            .unwrap();
1457        let json = serde_json::to_value(&details).unwrap();
1458        assert_eq!(json["communicationProtocol"], "WebSocket");
1459        assert!(json.get("websocketUrl").is_some());
1460        assert!(json.get("websocketToken").is_some());
1461    }
1462}