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.tokens.truncate(Self::MAX);
316    }
317
318    /// Record a token that is already in force, such as the one pairing produced.
319    pub fn adopt(&mut self, token: AccessToken) {
320        if self.tokens.iter().any(|h| h.token.verify(&token)) {
321            return;
322        }
323        self.tokens.insert(
324            0,
325            Held {
326                token,
327                granted: None,
328            },
329        );
330        self.tokens.truncate(Self::MAX);
331    }
332
333    /// Activate a granted token and retire every other, as `confirmAccessToken` does.
334    ///
335    /// Called when the client proves it holds one — by presenting it as the bearer of
336    /// `confirmAccessToken` — which is what makes retiring the others safe.
337    ///
338    /// # Errors
339    ///
340    /// [`ConnectError::NotPaired`] when the token is not one this store holds;
341    /// [`ConnectError::Expired`] when it was granted more than
342    /// [`PENDING_TOKEN_LIFETIME`] ago and so is no longer confirmable. An expired grant
343    /// leaves the store untouched, so whatever the client held before still works.
344    pub fn confirm(&mut self, token: &AccessToken, now: Timestamp) -> Result<(), ConnectError> {
345        let held = self.find(token).ok_or(ConnectError::NotPaired)?;
346        if let Some(granted) = held.granted
347            && now.saturating_duration_since(granted) > PENDING_TOKEN_LIFETIME
348        {
349            return Err(ConnectError::Expired {
350                what: "access token confirmation",
351                limit: PENDING_TOKEN_LIFETIME,
352            });
353        }
354        self.tokens.clear();
355        self.tokens.push(Held {
356            token: token.clone(),
357            granted: None,
358        });
359        Ok(())
360    }
361
362    /// Whether a presented token is a **grant** this store issued and has not yet seen
363    /// confirmed.
364    ///
365    /// `confirmAccessToken` must be authenticated with the *replacement*, not with any
366    /// token the store happens to accept: presenting the replacement is the proof the
367    /// client stored it, and that proof is the only reason retiring the others is safe.
368    #[must_use]
369    pub fn is_pending(&self, presented: &AccessToken) -> bool {
370        self.find(presented).is_some_and(|h| h.granted.is_some())
371    }
372
373    /// The token to present next: the newest.
374    #[must_use]
375    pub fn current(&self) -> Option<&AccessToken> {
376        self.tokens.first().map(|h| &h.token)
377    }
378
379    /// Every token to try, newest first.
380    ///
381    /// A client that got a `401` works down this list before concluding it is unpaired.
382    pub fn candidates(&self) -> impl Iterator<Item = &AccessToken> {
383        self.tokens.iter().map(|h| &h.token)
384    }
385
386    /// How many are held.
387    #[must_use]
388    pub fn len(&self) -> usize {
389        self.tokens.len()
390    }
391
392    /// Whether the pairing has no token at all, which means it is gone.
393    #[must_use]
394    pub fn is_empty(&self) -> bool {
395        self.tokens.is_empty()
396    }
397
398    /// Forget everything. What a `NoLongerPaired` means.
399    pub fn clear(&mut self) {
400        self.tokens.clear();
401    }
402}
403
404// ---------------------------------------------------------------------------
405// The client
406// ---------------------------------------------------------------------------
407
408#[derive(Debug, Clone, Copy, PartialEq, Eq)]
409enum Phase {
410    Start,
411    AwaitingGrant,
412    Granted,
413    Connected,
414    Failed,
415}
416
417impl Phase {
418    const fn name(self) -> &'static str {
419        match self {
420            Phase::Start => "the start of session initiation",
421            Phase::AwaitingGrant => "the session grant",
422            Phase::Granted => "confirmation of the new access token",
423            Phase::Connected => "a completed initiation",
424            Phase::Failed => "a failed initiation",
425        }
426    }
427}
428
429/// The communication client's half of session initiation.
430///
431/// ```
432/// use s2_kit::connect::proto::{AccessToken, NodeId, SessionInitClient, TokenStore};
433///
434/// let store = TokenStore::new(AccessToken::from_entropy(&[1u8; 32])?);
435/// let mut client = SessionInitClient::new(NodeId::parse("rm-1")?, NodeId::parse("cem-1")?, store);
436///
437/// let (bearer, body) = client.initiate()?;
438/// assert_eq!(body.client_node_id.to_string(), "rm-1");
439/// # let _ = bearer;
440/// # Ok::<(), Box<dyn core::error::Error>>(())
441/// ```
442#[derive(Debug)]
443pub struct SessionInitClient {
444    client_node_id: NodeId,
445    server_node_id: NodeId,
446    tokens: TokenStore,
447    s2_message_versions: Vec<ProtocolVersion>,
448    protocols: Vec<CommunicationProtocol>,
449    phase: Phase,
450    /// The token presented on the request in flight, so a `401` can move to the next.
451    attempted: Option<AccessToken>,
452    /// How many tokens of the store have been tried since the last success.
453    tried: usize,
454    granted: Option<SessionGrant>,
455}
456
457impl SessionInitClient {
458    /// A client for one pairing.
459    #[must_use]
460    pub fn new(client_node_id: NodeId, server_node_id: NodeId, tokens: TokenStore) -> Self {
461        Self {
462            client_node_id,
463            server_node_id,
464            tokens,
465            // The `v`-prefixed spelling, because `S2C §Versioning of JSON Schema
466            // files` requires it over S2 Connect. Matching is canonical, so a peer that
467            // offers the bare form is still understood (E25).
468            s2_message_versions: alloc::vec![
469                WireProfile::V1_0_0.connect_version(),
470                WireProfile::V0_0_2Beta.connect_version(),
471            ],
472            protocols: alloc::vec![CommunicationProtocol::WebSocket],
473            phase: Phase::Start,
474            attempted: None,
475            tried: 0,
476            granted: None,
477        }
478    }
479
480    /// Offer a different set of S2 JSON message versions, newest first.
481    #[must_use]
482    pub fn with_s2_message_versions(mut self, versions: Vec<ProtocolVersion>) -> Self {
483        self.s2_message_versions = versions;
484        self
485    }
486
487    /// Build `initiateSession`, with the bearer to send it under.
488    ///
489    /// A completed initiation is a legitimate place to start another: every reconnection
490    /// needs fresh credentials, because a communication token authorises exactly one
491    /// connection and lives thirty seconds. Requiring [`Self::restart`] in between would
492    /// make the common path the one a caller forgets.
493    pub fn initiate(&mut self) -> Result<(AccessToken, SessionRequest), ConnectError> {
494        if self.phase == Phase::Connected {
495            self.phase = Phase::Start;
496        }
497        self.expect(Phase::Start)?;
498        let token = self
499            .tokens
500            .candidates()
501            .nth(self.tried)
502            .cloned()
503            .ok_or(ConnectError::NotPaired)?;
504        self.attempted = Some(token.clone());
505        self.phase = Phase::AwaitingGrant;
506        Ok((
507            token,
508            SessionRequest {
509                client_node_id: self.client_node_id,
510                server_node_id: self.server_node_id,
511                supported_s2_message_versions: self.s2_message_versions.clone(),
512                supported_communication_protocols: self.protocols.clone(),
513                client_node_description: None,
514                client_endpoint_description: None,
515            },
516        ))
517    }
518
519    /// Handle a `401` on `initiateSession` by moving to the next stored token.
520    ///
521    /// `S2C §Recovery`: "It should try all the accessTokens sequentially." When they are
522    /// exhausted the pairing really is gone, and this returns [`ConnectError::NotPaired`]
523    /// — which is a call to a human, not a retry.
524    pub fn unauthorized(&mut self) -> Result<(), ConnectError> {
525        self.tried += 1;
526        self.phase = Phase::Start;
527        if self.tried >= self.tokens.len() {
528            self.phase = Phase::Failed;
529            return Err(ConnectError::NotPaired);
530        }
531        Ok(())
532    }
533
534    /// Take the grant and store the replacement token.
535    ///
536    /// Storing before confirming is the order the specification requires, and the reason
537    /// the two requests exist at all: a client that confirmed first and stored afterwards
538    /// has a window in which a crash loses the replacement for good.
539    ///
540    /// `now` starts the [`PENDING_TOKEN_LIFETIME`] clock on this side too, so a client
541    /// that was suspended between the two requests declines to retire the token it
542    /// already had rather than retiring it against a server that never activated the
543    /// replacement.
544    pub fn accept(&mut self, grant: SessionGrant, now: Timestamp) -> Result<(), ConnectError> {
545        self.expect(Phase::AwaitingGrant)?;
546        if !self
547            .protocols
548            .contains(&grant.selected_communication_protocol)
549        {
550            self.phase = Phase::Failed;
551            return Err(ConnectError::NoOverlap("communication protocol"));
552        }
553        if !self
554            .s2_message_versions
555            .iter()
556            .any(|v| v.matches(&grant.selected_s2_message_version))
557        {
558            self.phase = Phase::Failed;
559            return Err(ConnectError::NoOverlap("S2 message version"));
560        }
561        self.tokens.add(grant.access_token.clone(), now);
562        self.granted = Some(grant);
563        self.phase = Phase::Granted;
564        Ok(())
565    }
566
567    /// The bearer for `confirmAccessToken`: the **new** token.
568    ///
569    /// Presenting it *is* the confirmation, which is why there is no body.
570    pub fn confirm(&mut self) -> Result<AccessToken, ConnectError> {
571        self.expect(Phase::Granted)?;
572        let grant = self.granted.as_ref().ok_or(ConnectError::OutOfOrder {
573            got: "a confirmation",
574            expected: Phase::AwaitingGrant.name(),
575        })?;
576        Ok(grant.access_token.clone())
577    }
578
579    /// Take the communication details the confirmation returned.
580    ///
581    /// The old tokens are retired here and not before: the server has just proved it
582    /// accepted the new one.
583    pub fn connected(
584        &mut self,
585        details: CommunicationDetails,
586        now: Timestamp,
587    ) -> Result<SessionCredentials, ConnectError> {
588        self.expect(Phase::Granted)?;
589        let grant = self.granted.take().ok_or(ConnectError::OutOfOrder {
590            got: "communication details",
591            expected: Phase::AwaitingGrant.name(),
592        })?;
593        self.tokens.confirm(&grant.access_token, now)?;
594        self.tried = 0;
595        self.phase = Phase::Connected;
596        let CommunicationDetails::WebSocket {
597            websocket_url,
598            websocket_token,
599        } = details;
600        Ok(SessionCredentials {
601            websocket_url,
602            websocket_token,
603            profile: grant.profile(),
604            issued: now,
605        })
606    }
607
608    /// Start again after a failure, keeping whatever tokens survived.
609    ///
610    /// This is what makes the two-phase commit worth having: after any failure at all, the
611    /// store still holds a token the server will accept.
612    pub fn restart(&mut self) {
613        self.phase = Phase::Start;
614        self.attempted = None;
615    }
616
617    /// Forget the pairing. What a `NoLongerPaired` means.
618    pub fn unpaired(&mut self) -> UnpairRequest {
619        self.tokens.clear();
620        self.phase = Phase::Failed;
621        UnpairRequest {
622            client_node_id: self.client_node_id,
623            server_node_id: self.server_node_id,
624        }
625    }
626
627    /// The tokens, to persist.
628    #[must_use]
629    pub fn tokens(&self) -> &TokenStore {
630        &self.tokens
631    }
632
633    fn expect(&mut self, phase: Phase) -> Result<(), ConnectError> {
634        if self.phase == phase {
635            return Ok(());
636        }
637        let got = self.phase.name();
638        self.phase = Phase::Failed;
639        Err(ConnectError::OutOfOrder {
640            got,
641            expected: phase.name(),
642        })
643    }
644}
645
646// ---------------------------------------------------------------------------
647// The server
648// ---------------------------------------------------------------------------
649
650/// The communication server's half of session initiation.
651///
652/// It owns the token store for one pairing and never hands out a communication token
653/// without having accepted an access token first.
654#[derive(Debug)]
655pub struct SessionInitServer {
656    node_id: NodeId,
657    peer_node_id: NodeId,
658    tokens: TokenStore,
659    websocket_url: String,
660    s2_message_versions: Vec<ProtocolVersion>,
661    protocols: Vec<CommunicationProtocol>,
662    /// The communication token the last confirmation handed out, until it is used or its
663    /// thirty seconds run out.
664    ///
665    /// The only state here that is *not* in the [`TokenStore`], and deliberately so: it
666    /// lives thirty seconds and authorises one connection, so a server that has restarted
667    /// holds none that are still good. The pending **access** token is in the store,
668    /// because that one must survive a restart — a server that kept it in memory would
669    /// refuse the confirmation of a grant it had just issued.
670    connection: Option<IssuedConnection>,
671}
672
673/// A communication token this server issued and has not yet seen used.
674#[derive(Debug, Clone)]
675struct IssuedConnection {
676    token: CommunicationToken,
677    issued: Timestamp,
678}
679
680impl SessionInitServer {
681    /// A server for one pairing.
682    #[must_use]
683    pub fn new(
684        node_id: NodeId,
685        peer_node_id: NodeId,
686        tokens: TokenStore,
687        websocket_url: impl Into<String>,
688    ) -> Self {
689        Self {
690            node_id,
691            peer_node_id,
692            tokens,
693            websocket_url: websocket_url.into(),
694            // The `v`-prefixed spelling, because `S2C §Versioning of JSON Schema
695            // files` requires it over S2 Connect. Matching is canonical, so a peer that
696            // offers the bare form is still understood (E25).
697            s2_message_versions: alloc::vec![
698                WireProfile::V1_0_0.connect_version(),
699                WireProfile::V0_0_2Beta.connect_version(),
700            ],
701            protocols: alloc::vec![CommunicationProtocol::WebSocket],
702            connection: None,
703        }
704    }
705
706    /// Offer a different set of S2 JSON message versions, newest first.
707    #[must_use]
708    pub fn with_s2_message_versions(mut self, versions: Vec<ProtocolVersion>) -> Self {
709        self.s2_message_versions = versions;
710        self
711    }
712
713    /// Whether a bearer presented on either endpoint is one we would accept.
714    ///
715    /// A `false` is a `401`.
716    #[must_use]
717    pub fn authenticates(&self, bearer: &AccessToken) -> bool {
718        self.tokens.accepts(bearer)
719    }
720
721    /// Handle `initiateSession`.
722    ///
723    /// `access_entropy` is a parameter for the same reason it is in
724    /// [`pairing`](super::pairing): a test needs it pinned, and this layer has no business
725    /// knowing where a system keeps its randomness.
726    ///
727    /// # Errors
728    ///
729    /// [`ConnectError::NotPaired`] is a `401`; a [`SessionRefused`] carried in
730    /// [`ConnectError::SessionRefused`] is a `400` with that body.
731    pub fn initiate_session(
732        &mut self,
733        bearer: &AccessToken,
734        request: &SessionRequest,
735        access_entropy: &[u8],
736        now: Timestamp,
737    ) -> Result<SessionGrant, ConnectError> {
738        if !self.tokens.accepts(bearer) {
739            return Err(ConnectError::NotPaired);
740        }
741        if request.server_node_id != self.node_id || request.client_node_id != self.peer_node_id {
742            return Err(ConnectError::SessionRefused(SessionRefused {
743                error_message: SessionErrorMessage::NoLongerPaired,
744                additional_info: None,
745            }));
746        }
747        let protocol = request
748            .supported_communication_protocols
749            .iter()
750            .find(|p| self.protocols.contains(p))
751            .copied()
752            .ok_or(ConnectError::SessionRefused(SessionRefused {
753                error_message: SessionErrorMessage::IncompatibleCommunicationProtocols,
754                additional_info: None,
755            }))?;
756        // Newest first in the client's list; we take the first we also speak.
757        let version = request
758            .supported_s2_message_versions
759            .iter()
760            .find(|v| self.s2_message_versions.iter().any(|ours| ours.matches(v)))
761            .cloned()
762            .ok_or(ConnectError::SessionRefused(SessionRefused {
763                error_message: SessionErrorMessage::IncompatibleS2MessageVersions,
764                additional_info: None,
765            }))?;
766
767        let replacement = AccessToken::from_entropy(access_entropy)?;
768        // Issued alongside, not instead of: the token the client just used stays valid
769        // until it proves it has the new one. `add` records *when*, which is what makes
770        // it a pending grant rather than simply another accepted token.
771        self.tokens.add(replacement.clone(), now);
772        Ok(SessionGrant {
773            selected_communication_protocol: protocol,
774            selected_s2_message_version: version,
775            access_token: replacement,
776            server_node_description: None,
777            server_endpoint_description: None,
778        })
779    }
780
781    /// Handle `confirmAccessToken`, retiring every older token.
782    ///
783    /// The bearer *is* the confirmation: a client that can present the new token has
784    /// stored it, so there is nothing else to check and nothing to take on trust.
785    pub fn confirm_access_token(
786        &mut self,
787        bearer: &AccessToken,
788        communication_entropy: &[u8],
789        now: Timestamp,
790    ) -> Result<CommunicationDetails, ConnectError> {
791        // The bearer must be a *pending grant*, not merely a token the store accepts:
792        // presenting the replacement is the proof it was stored, and that proof is the
793        // whole reason retiring the others is safe. The store is where that fact lives, so
794        // it survives a restart between the two requests.
795        if !self.tokens.is_pending(bearer) {
796            return Err(ConnectError::NotPaired);
797        }
798        self.tokens.confirm(bearer, now)?;
799        let token = CommunicationToken::from_entropy(communication_entropy)?;
800        // Remembered, because a server that hands out a bearer it does not keep has
801        // authorised nothing: the WebSocket upgrade later has nothing to check the
802        // `Authorization` header against. One token at a time — a second confirmation
803        // supersedes the first, exactly as it supersedes the access token.
804        self.connection = Some(IssuedConnection {
805            token: token.clone(),
806            issued: now,
807        });
808        Ok(CommunicationDetails::WebSocket {
809            websocket_url: self.websocket_url.clone(),
810            websocket_token: token,
811        })
812    }
813
814    /// Handle `unpair`.
815    pub fn unpair(
816        &mut self,
817        bearer: &AccessToken,
818        request: &UnpairRequest,
819    ) -> Result<(), ConnectError> {
820        if !self.tokens.accepts(bearer)
821            || request.server_node_id != self.node_id
822            || request.client_node_id != self.peer_node_id
823        {
824            return Err(ConnectError::NotPaired);
825        }
826        self.tokens.clear();
827        self.connection = None;
828        Ok(())
829    }
830
831    /// Whether a bearer presented on a WebSocket handshake is the one this server issued,
832    /// and still inside its thirty seconds.
833    ///
834    /// Takes `&mut self` and consumes the token on success, because
835    /// `s2-connect-common.yml/CommunicationToken` says it is "valid for a single
836    /// connection": a second upgrade with the same bearer is refused rather than
837    /// silently granted a parallel session.
838    pub fn accepts_connection(&mut self, presented: &str, now: Timestamp) -> bool {
839        let Some(connection) = &self.connection else {
840            return false;
841        };
842        if now.saturating_duration_since(connection.issued) >= COMMUNICATION_TOKEN_LIFETIME {
843            self.connection = None;
844            return false;
845        }
846        if !connection.token.verify_str(presented) {
847            return false;
848        }
849        self.connection = None;
850        true
851    }
852
853    /// The tokens, to persist.
854    #[must_use]
855    pub fn tokens(&self) -> &TokenStore {
856        &self.tokens
857    }
858}
859
860#[cfg(test)]
861mod tests {
862    use super::*;
863    use alloc::string::ToString;
864
865    fn t(secs: i64) -> Timestamp {
866        Timestamp::from_unix(1_700_000_000 + secs, 0)
867    }
868
869    #[test]
870    fn a_grant_nobody_confirmed_never_evicts_the_token_that_works() {
871        // Four `initiateSession` calls whose replies never reached the client each add a
872        // pending grant. With a four-deep list and no expiry, the fourth pushes the token
873        // that is actually in force off the end — and the pairing is dead while both
874        // parties still believe in it. A grant past `PENDING_TOKEN_LIFETIME` can never be
875        // confirmed, so it is a slot holding nothing and goes first.
876        let live = AccessToken::from_entropy(&[9u8; 32]).expect("32 bytes");
877        let mut store = TokenStore::new(live.clone());
878        for i in 0..6u8 {
879            let granted = AccessToken::from_entropy(&[i; 32]).expect("32 bytes");
880            // Each attempt a minute after the last: every earlier grant is long dead.
881            store.add(granted, t(i64::from(i) * 60));
882        }
883        assert!(
884            store.accepts(&live),
885            "the token the client is still holding must keep working"
886        );
887        assert_eq!(store.len(), 2, "one live token and the newest grant");
888
889        // Grants that are still inside their window are *not* dropped: two initiations a
890        // second apart are a client retrying, not a client leaking.
891        let live = AccessToken::from_entropy(&[9u8; 32]).expect("32 bytes");
892        let mut store = TokenStore::new(live.clone());
893        for i in 0..3u8 {
894            let granted = AccessToken::from_entropy(&[i; 32]).expect("32 bytes");
895            store.add(granted, t(i64::from(i)));
896        }
897        assert_eq!(store.len(), 4);
898        assert!(store.accepts(&live));
899    }
900
901    fn ids() -> (NodeId, NodeId) {
902        (
903            NodeId::parse("rm-1").expect("a legal id"),
904            NodeId::parse("cem-1").expect("a legal id"),
905        )
906    }
907
908    fn pair() -> (SessionInitClient, SessionInitServer, AccessToken) {
909        let (rm, cem) = ids();
910        let initial = AccessToken::from_entropy(&[1u8; 32]).expect("32 bytes");
911        let client = SessionInitClient::new(rm, cem, TokenStore::new(initial.clone()));
912        let server = SessionInitServer::new(
913            cem,
914            rm,
915            TokenStore::new(initial.clone()),
916            "wss://cem.example.com/s2",
917        );
918        (client, server, initial)
919    }
920
921    /// One whole initiation, both sides, with every step at `at`.
922    fn run_at(
923        client: &mut SessionInitClient,
924        server: &mut SessionInitServer,
925        new_access: u8,
926        comm: u8,
927        at: Timestamp,
928    ) -> SessionCredentials {
929        let (bearer, request) = client.initiate().unwrap();
930        let grant = server
931            .initiate_session(&bearer, &request, &[new_access; 32], at)
932            .unwrap();
933        client.accept(grant, at).unwrap();
934        let confirm = client.confirm().unwrap();
935        let details = server
936            .confirm_access_token(&confirm, &[comm; 32], at)
937            .unwrap();
938        client.connected(details, at).unwrap()
939    }
940
941    /// One whole initiation at the epoch of this module's clock.
942    fn run(
943        client: &mut SessionInitClient,
944        server: &mut SessionInitServer,
945        new_access: u8,
946        comm: u8,
947    ) -> SessionCredentials {
948        run_at(client, server, new_access, comm, t(0))
949    }
950
951    #[test]
952    fn a_session_is_initiated_and_the_token_rotates() {
953        let (mut client, mut server, initial) = pair();
954        let creds = run(&mut client, &mut server, 2, 3);
955
956        assert_eq!(creds.websocket_url, "wss://cem.example.com/s2");
957        assert_eq!(creds.profile, Some(WireProfile::V1_0_0));
958        assert!(!creds.is_expired(t(29)));
959
960        // The old token is gone on both sides; the new one works on both.
961        assert!(!server.tokens().accepts(&initial));
962        assert_eq!(client.tokens().len(), 1);
963        assert!(server.tokens().accepts(client.tokens().current().unwrap()));
964    }
965
966    #[test]
967    fn the_confirmation_is_authenticated_with_the_new_token() {
968        // That is the whole trick: presenting it *is* the proof it was stored.
969        let (mut client, mut server, initial) = pair();
970        let (bearer, request) = client.initiate().unwrap();
971        let grant = server
972            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
973            .unwrap();
974        let replacement = grant.access_token.clone();
975        client.accept(grant, t(0)).unwrap();
976
977        // The *old* token does not confirm anything.
978        assert!(matches!(
979            server.confirm_access_token(&initial, &[3u8; 32], t(0)),
980            Err(ConnectError::NotPaired)
981        ));
982        // The new one does.
983        assert!(
984            server
985                .confirm_access_token(&replacement, &[3u8; 32], t(0))
986                .is_ok()
987        );
988    }
989
990    #[test]
991    fn a_lost_grant_does_not_strand_the_pairing() {
992        // The reply to initiateSession never arrives: the server has issued a replacement
993        // the client has never seen, and the client still holds the old one.
994        let (mut client, mut server, initial) = pair();
995        let (bearer, request) = client.initiate().unwrap();
996        let _lost = server
997            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
998            .unwrap();
999
1000        // The client retries with what it has, and the server still accepts it.
1001        client.restart();
1002        assert!(server.tokens().accepts(&initial));
1003        let creds = run(&mut client, &mut server, 4, 5);
1004        assert!(!creds.websocket_url.is_empty());
1005        assert!(server.tokens().accepts(client.tokens().current().unwrap()));
1006    }
1007
1008    #[test]
1009    fn a_lost_confirmation_does_not_strand_the_pairing_either() {
1010        // The client stored the new token and then died before confirming.
1011        let (mut client, mut server, initial) = pair();
1012        let (bearer, request) = client.initiate().unwrap();
1013        let grant = server
1014            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
1015            .unwrap();
1016        client.accept(grant, t(0)).unwrap();
1017
1018        // Both tokens still open the door — the point of the phase.
1019        assert!(server.tokens().accepts(&initial));
1020        assert!(server.tokens().accepts(client.tokens().current().unwrap()));
1021        assert_eq!(client.tokens().len(), 2);
1022
1023        client.restart();
1024        let creds = run(&mut client, &mut server, 6, 7);
1025        assert!(!creds.websocket_url.is_empty());
1026        assert_eq!(
1027            client.tokens().len(),
1028            1,
1029            "and the list collapses on success"
1030        );
1031    }
1032
1033    #[test]
1034    fn a_client_works_down_its_list_after_a_401() {
1035        // Two failed rounds have left three tokens; only the newest is live.
1036        let (mut client, mut server, _) = pair();
1037        for entropy in [2u8, 3u8] {
1038            let (bearer, request) = client.initiate().unwrap();
1039            let grant = server
1040                .initiate_session(&bearer, &request, &[entropy; 32], t(0))
1041                .unwrap();
1042            client.accept(grant, t(0)).unwrap();
1043            client.restart();
1044        }
1045        assert_eq!(client.tokens().len(), 3);
1046
1047        // A server that has forgotten everything refuses each in turn, and the client
1048        // concludes it is unpaired rather than retrying for ever.
1049        let (rm, cem) = ids();
1050        let mut amnesiac = SessionInitServer::new(cem, rm, TokenStore::default(), "wss://x/");
1051        for _ in 0..3 {
1052            let (bearer, request) = client.initiate().unwrap();
1053            assert!(matches!(
1054                amnesiac.initiate_session(&bearer, &request, &[9u8; 32], t(0)),
1055                Err(ConnectError::NotPaired)
1056            ));
1057            if let Err(e) = client.unauthorized() {
1058                assert_eq!(e, ConnectError::NotPaired);
1059                return;
1060            }
1061        }
1062        panic!("the client should have given up after exhausting its tokens");
1063    }
1064
1065    #[test]
1066    fn a_token_the_server_never_issued_is_refused() {
1067        let (mut client, mut server, _) = pair();
1068        let (_, request) = client.initiate().unwrap();
1069        let forged = AccessToken::from_entropy(&[0xFFu8; 32]).unwrap();
1070        assert!(matches!(
1071            server.initiate_session(&forged, &request, &[2u8; 32], t(0)),
1072            Err(ConnectError::NotPaired)
1073        ));
1074    }
1075
1076    #[test]
1077    fn a_request_for_someone_elses_pairing_is_refused() {
1078        let (mut client, mut server, _) = pair();
1079        let (bearer, mut request) = client.initiate().unwrap();
1080        request.server_node_id = NodeId::parse("cem-2").unwrap();
1081        assert!(matches!(
1082            server.initiate_session(&bearer, &request, &[2u8; 32], t(0)),
1083            Err(ConnectError::SessionRefused(SessionRefused {
1084                error_message: SessionErrorMessage::NoLongerPaired,
1085                ..
1086            }))
1087        ));
1088    }
1089
1090    #[test]
1091    fn a_peer_that_spells_the_version_the_other_way_still_connects() {
1092        // Erratum E25: `S2C` requires `v1.0.0`, every deployed S2 JSON handshake writes
1093        // `1.0.0`, and `s2energy-connection`'s examples write `v1`. Exact matching on
1094        // both sides means two conforming implementations cannot agree on a version they
1095        // both speak — which is a pairing that fails for a reason no log would explain.
1096        for spelling in ["v1.0.0", "1.0.0"] {
1097            let (client, mut server, _) = pair();
1098            let mut client =
1099                client.with_s2_message_versions(alloc::vec![ProtocolVersion::new(spelling)]);
1100            let creds = run(&mut client, &mut server, 2, 3);
1101            assert_eq!(
1102                creds.profile,
1103                Some(WireProfile::V1_0_0),
1104                "a server offering the other spelling must still resolve {spelling}"
1105            );
1106        }
1107
1108        // And the same in the other direction: a server that offers only the bare form
1109        // answers a client that offered only the prefixed one.
1110        let (mut client, server, _) = pair();
1111        let mut server =
1112            server.with_s2_message_versions(alloc::vec![ProtocolVersion::new("1.0.0")]);
1113        let creds = run(&mut client, &mut server, 2, 3);
1114        assert_eq!(creds.profile, Some(WireProfile::V1_0_0));
1115    }
1116
1117    #[test]
1118    fn a_version_neither_side_speaks_is_refused_with_the_named_reason() {
1119        let (rm, cem) = ids();
1120        let initial = AccessToken::from_entropy(&[1u8; 32]).unwrap();
1121        let mut client = SessionInitClient::new(rm, cem, TokenStore::new(initial.clone()))
1122            .with_s2_message_versions(alloc::vec![crate::types::ProtocolVersion::new("9.9.9")]);
1123        let mut server = SessionInitServer::new(cem, rm, TokenStore::new(initial), "wss://x/");
1124        let (bearer, request) = client.initiate().unwrap();
1125        assert!(matches!(
1126            server.initiate_session(&bearer, &request, &[2u8; 32], t(0)),
1127            Err(ConnectError::SessionRefused(SessionRefused {
1128                error_message: SessionErrorMessage::IncompatibleS2MessageVersions,
1129                ..
1130            }))
1131        ));
1132    }
1133
1134    #[test]
1135    fn a_communication_token_is_good_for_thirty_seconds_and_not_a_moment_more() {
1136        let (mut client, mut server, _) = pair();
1137        let (bearer, request) = client.initiate().unwrap();
1138        let grant = server
1139            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
1140            .unwrap();
1141        client.accept(grant, t(0)).unwrap();
1142        let confirm = client.confirm().unwrap();
1143        let details = server
1144            .confirm_access_token(&confirm, &[3u8; 32], t(0))
1145            .unwrap();
1146        let CommunicationDetails::WebSocket {
1147            ref websocket_token,
1148            ..
1149        } = details;
1150        let presented = websocket_token.as_str().to_string();
1151        let creds = client.connected(details, t(0)).unwrap();
1152
1153        assert!(creds.is_expired(t(30)));
1154        assert_eq!(creds.expires(), t(30));
1155
1156        // The right timing with the wrong token is refused, and refusing it does not
1157        // spend the one the server is holding.
1158        assert!(!server.accepts_connection("something else", t(1)));
1159        // The right token inside the window is accepted...
1160        assert!(server.accepts_connection(&presented, t(29)));
1161        // ...exactly once: a communication token is "valid for a single connection".
1162        assert!(!server.accepts_connection(&presented, t(29)));
1163    }
1164
1165    #[test]
1166    fn a_communication_token_presented_too_late_is_refused() {
1167        let (mut client, mut server, _) = pair();
1168        let creds = run(&mut client, &mut server, 2, 3);
1169        let presented = creds.websocket_token.as_str().to_string();
1170        assert!(!server.accepts_connection(&presented, t(30)));
1171        // And the expired entry is gone, so it cannot come back inside the window.
1172        assert!(!server.accepts_connection(&presented, t(1)));
1173    }
1174
1175    #[test]
1176    fn a_server_restarted_between_the_two_requests_still_honours_the_grant() {
1177        // The pending grant lives in the `TokenStore`, which is the thing a host
1178        // persists — not in a field of the state machine. A server that kept it in memory
1179        // would refuse the confirmation of a grant it had itself issued a second earlier,
1180        // and the client would be left holding a token nobody activated.
1181        let (mut client, mut server, initial) = pair();
1182        let (bearer, request) = client.initiate().unwrap();
1183        let grant = server
1184            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
1185            .unwrap();
1186        client.accept(grant, t(0)).unwrap();
1187        let confirm = client.confirm().unwrap();
1188
1189        // The process dies here. Everything it persisted comes back; everything else
1190        // does not.
1191        let persisted = server.tokens().clone();
1192        let (rm, cem) = ids();
1193        let mut server = SessionInitServer::new(cem, rm, persisted, "wss://cem.example.com/s2");
1194
1195        let details = server
1196            .confirm_access_token(&confirm, &[3u8; 32], t(1))
1197            .expect("a restart must not lose the grant");
1198        let creds = client.connected(details, t(1)).unwrap();
1199        assert!(
1200            !server.tokens().accepts(&initial),
1201            "the old token is retired"
1202        );
1203        assert!(server.tokens().accepts(client.tokens().current().unwrap()));
1204        assert!(!creds.is_expired(t(2)));
1205    }
1206
1207    #[test]
1208    fn only_a_pending_grant_confirms_anything() {
1209        // Every token the store accepts is not a token that confirms: presenting the
1210        // *replacement* is the proof it was stored, which is the only reason retiring the
1211        // others is safe. A client that presents the token it already had proves nothing.
1212        let (mut client, mut server, initial) = pair();
1213        let (bearer, request) = client.initiate().unwrap();
1214        let grant = server
1215            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
1216            .unwrap();
1217        client.accept(grant, t(0)).unwrap();
1218
1219        assert!(
1220            server.tokens().accepts(&initial),
1221            "it is still a valid bearer"
1222        );
1223        assert!(
1224            matches!(
1225                server.confirm_access_token(&initial, &[3u8; 32], t(0)),
1226                Err(ConnectError::NotPaired)
1227            ),
1228            "but it is not the grant"
1229        );
1230        // And the real one still works afterwards: a wrong confirmation must not burn it.
1231        let confirm = client.confirm().unwrap();
1232        assert!(
1233            server
1234                .confirm_access_token(&confirm, &[3u8; 32], t(0))
1235                .is_ok()
1236        );
1237    }
1238
1239    #[test]
1240    fn a_grant_confirmed_too_late_leaves_the_old_token_in_force() {
1241        // `S2C §Session initiation`: the server activates the replacement only if the
1242        // confirmation arrives "not more than 15 seconds" later. The point of refusing a
1243        // late one is what it does *not* do — it must not retire the token the client is
1244        // still holding, or a slow network unpairs a device.
1245        let (mut client, mut server, initial) = pair();
1246        let (bearer, request) = client.initiate().unwrap();
1247        let grant = server
1248            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
1249            .unwrap();
1250        client.accept(grant, t(0)).unwrap();
1251        let confirm = client.confirm().unwrap();
1252
1253        let too_late = server.confirm_access_token(&confirm, &[3u8; 32], t(16));
1254        assert!(
1255            matches!(
1256                too_late,
1257                Err(ConnectError::Expired {
1258                    what: "access token confirmation",
1259                    ..
1260                })
1261            ),
1262            "{too_late:?}"
1263        );
1264        assert!(
1265            server.tokens().accepts(&initial),
1266            "the old token still works"
1267        );
1268
1269        // Fourteen seconds later is inside the window, and then the old one is gone.
1270        let (mut client, mut server, initial) = pair();
1271        let (bearer, request) = client.initiate().unwrap();
1272        let grant = server
1273            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
1274            .unwrap();
1275        client.accept(grant, t(0)).unwrap();
1276        let confirm = client.confirm().unwrap();
1277        let details = server
1278            .confirm_access_token(&confirm, &[3u8; 32], t(14))
1279            .expect("fourteen seconds is inside fifteen");
1280        let creds = client.connected(details, t(14)).unwrap();
1281        assert!(!server.tokens().accepts(&initial));
1282        assert_eq!(creds.profile, Some(WireProfile::V1_0_0));
1283    }
1284
1285    #[test]
1286    fn the_phases_cannot_be_taken_out_of_order() {
1287        let (mut client, _, _) = pair();
1288        assert!(matches!(
1289            client.confirm(),
1290            Err(ConnectError::OutOfOrder { .. })
1291        ));
1292        assert!(client.initiate().is_err());
1293        client.restart();
1294        assert!(client.initiate().is_ok());
1295    }
1296
1297    #[test]
1298    fn a_completed_session_can_be_followed_by_another() {
1299        // A communication token authorises one connection and lives thirty seconds, so
1300        // reconnecting is the normal case, not an exception.
1301        let (mut client, mut server, _) = pair();
1302        run(&mut client, &mut server, 2, 3);
1303        run(&mut client, &mut server, 4, 5);
1304        run(&mut client, &mut server, 6, 7);
1305        // Each round retires the last token, so the list never grows.
1306        assert_eq!(client.tokens().len(), 1);
1307        assert!(server.tokens().accepts(client.tokens().current().unwrap()));
1308    }
1309
1310    #[test]
1311    fn unpairing_forgets_the_pairing_on_both_sides() {
1312        let (mut client, mut server, _) = pair();
1313        run(&mut client, &mut server, 2, 3);
1314        let token = client.tokens().current().unwrap().clone();
1315        let request = client.unpaired();
1316        server.unpair(&token, &request).unwrap();
1317        assert!(server.tokens().is_empty());
1318        assert!(client.tokens().is_empty());
1319        // And nothing works afterwards.
1320        assert!(!server.authenticates(&token));
1321    }
1322
1323    #[test]
1324    fn the_bodies_are_the_shape_the_openapi_defines() {
1325        let (mut client, mut server, _) = pair();
1326        let (bearer, request) = client.initiate().unwrap();
1327        let json = serde_json::to_value(&request).unwrap();
1328        for key in [
1329            "clientNodeId",
1330            "serverNodeId",
1331            "supportedS2MessageVersions",
1332            "supportedCommunicationProtocols",
1333        ] {
1334            assert!(json.get(key).is_some(), "missing required property {key}");
1335        }
1336        assert!(json.get("clientNodeDescription").is_none());
1337        assert_eq!(json["supportedCommunicationProtocols"][0], "WebSocket");
1338
1339        let grant = server
1340            .initiate_session(&bearer, &request, &[2u8; 32], t(0))
1341            .unwrap();
1342        let json = serde_json::to_value(&grant).unwrap();
1343        for key in [
1344            "selectedCommunicationProtocol",
1345            "selectedS2MessageVersion",
1346            "accessToken",
1347        ] {
1348            assert!(json.get(key).is_some(), "missing required property {key}");
1349        }
1350
1351        // The discriminated union the schema calls WebSocketCommunicationDetails.
1352        client.accept(grant, t(0)).unwrap();
1353        let confirm = client.confirm().unwrap();
1354        let details = server
1355            .confirm_access_token(&confirm, &[3u8; 32], t(0))
1356            .unwrap();
1357        let json = serde_json::to_value(&details).unwrap();
1358        assert_eq!(json["communicationProtocol"], "WebSocket");
1359        assert!(json.get("websocketUrl").is_some());
1360        assert!(json.get("websocketToken").is_some());
1361    }
1362}