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