s2_kit/connect/client/session.rs
1//! Driving session initiation over HTTPS, and holding the connection open afterwards.
2
3use alloc::string::ToString;
4use alloc::vec::Vec;
5
6use crate::connect::proto::{
7 AccessToken, Backoff, CommunicationDetails, NodeId, SessionCredentials, SessionGrant,
8 SessionInitClient, TokenStore,
9};
10use crate::connect::tls::TlsPolicy;
11use crate::types::{ProtocolVersion, Timestamp};
12
13use super::http::{Error, Http};
14
15const INITIATE_SESSION: &str = "initiateSession";
16const CONFIRM_ACCESS_TOKEN: &str = "confirmAccessToken";
17const UNPAIR: &str = "unpair";
18
19/// Turns a stored pairing into an authorised WebSocket, as often as needed.
20///
21/// One `Session` is one pairing. It owns the token store, so the rotation the protocol
22/// requires happens whether or not the caller remembers it exists — but the caller must
23/// persist [`Session::tokens`] after every [`Session::initiate`], because a token that
24/// only ever lived in memory is a pairing that does not survive a restart.
25///
26/// ```no_run
27/// use s2_kit::connect::client::Session;
28/// use s2_kit::connect::proto::*;
29/// use s2_kit::connect::tls::TlsPolicy;
30/// use s2_kit::types::Timestamp;
31///
32/// # async fn run(paired: s2_kit::connect::client::Paired) -> Result<(), Box<dyn std::error::Error>> {
33/// let mut session = Session::new(
34/// &paired.pairing.details.initiate_session_url,
35/// &paired.policy(),
36/// paired.pairing.local,
37/// paired.pairing.remote.id,
38/// TokenStore::new(paired.pairing.details.access_token.clone()),
39/// )?;
40///
41/// let credentials = session.initiate(Timestamp::now()).await?;
42/// // Persist the rotated tokens *now*, before connecting.
43/// let to_store = session.tokens();
44/// # let _ = (credentials, to_store);
45/// # Ok(())
46/// # }
47/// ```
48#[derive(Debug)]
49pub struct Session {
50 http: Http,
51 machine: SessionInitClient,
52 client_node_id: NodeId,
53 server_node_id: NodeId,
54 backoff: Backoff,
55 attempt: u32,
56}
57
58impl Session {
59 /// How long any single session-initiation request may take.
60 ///
61 /// Well inside the thirty seconds a communication token lives, so that a slow request
62 /// cannot hand back credentials that have already expired.
63 pub const REQUEST_TIMEOUT: core::time::Duration = core::time::Duration::from_secs(10);
64
65 /// A session for one pairing.
66 ///
67 /// `policy` should be [`Paired::policy`](super::Paired::policy) — the pinned CA for a
68 /// LAN peer, the public PKI for a WAN one. Using [`TlsPolicy::LanPairingOnly`] here
69 /// would leave the channel unauthenticated, so it is refused.
70 pub fn new(
71 base_url: &str,
72 policy: &TlsPolicy,
73 client_node_id: NodeId,
74 server_node_id: NodeId,
75 tokens: TokenStore,
76 ) -> Result<Self, Error> {
77 if !policy.authenticates() {
78 return Err(Error::Url(
79 "a session must not run under the pairing-only TLS policy".to_string(),
80 ));
81 }
82 Ok(Self {
83 http: Http::new(base_url, policy, Self::REQUEST_TIMEOUT)?,
84 machine: SessionInitClient::new(client_node_id, server_node_id, tokens),
85 client_node_id,
86 server_node_id,
87 backoff: Backoff::default(),
88 attempt: 0,
89 })
90 }
91
92 /// Offer a different set of S2 JSON message versions, newest first.
93 #[must_use]
94 pub fn with_s2_message_versions(mut self, versions: Vec<ProtocolVersion>) -> Self {
95 let tokens = self.machine.tokens().clone();
96 self.machine = SessionInitClient::new(self.client_node_id, self.server_node_id, tokens)
97 .with_s2_message_versions(versions);
98 self
99 }
100
101 /// The tokens, to persist. Read this after every [`Self::initiate`].
102 #[must_use]
103 pub fn tokens(&self) -> &TokenStore {
104 self.machine.tokens()
105 }
106
107 /// Run both requests and come back with somewhere to connect.
108 ///
109 /// A `401` on the first is not a failure: the store may hold a token the server has
110 /// already retired, so this works down the list the way `S2C §Recovery` prescribes,
111 /// and only gives up when every one has been refused.
112 pub async fn initiate(&mut self, now: Timestamp) -> Result<SessionCredentials, Error> {
113 loop {
114 let (bearer, body) = self.machine.initiate()?;
115 let grant: SessionGrant = match self
116 .http
117 .post(
118 "initiateSession",
119 INITIATE_SESSION,
120 Some(bearer.as_str()),
121 &body,
122 )
123 .await
124 {
125 Ok(grant) => grant,
126 Err(Error::Http { status, .. }) if status.is_unauthorized() => {
127 // Refused: try the next token, or conclude the pairing is gone.
128 crate::trace::event!(
129 warn,
130 remaining = self.machine.tokens().len(),
131 "the access token was refused; trying the next"
132 );
133 self.machine.unauthorized()?;
134 continue;
135 }
136 Err(e) => return Err(e),
137 };
138
139 self.machine.accept(grant, now)?;
140 // The store now holds the replacement. A caller that persists here survives a
141 // crash before the confirmation; one that does not, does not.
142 let confirm = self.machine.confirm()?;
143 // No request body: `S2C-OAS session-init/confirmAccessToken` defines none, and
144 // the bearer is the whole message.
145 let details: CommunicationDetails = self
146 .http
147 .post_bodyless(
148 "confirmAccessToken",
149 CONFIRM_ACCESS_TOKEN,
150 Some(confirm.as_str()),
151 )
152 .await?;
153 let credentials = self.machine.connected(details, now)?;
154 crate::trace::event!(
155 info,
156 url = %credentials.websocket_url,
157 profile = ?credentials.profile,
158 expires = %credentials.expires(),
159 "session initiated"
160 );
161 self.attempt = 0;
162 return Ok(credentials);
163 }
164 }
165
166 /// Forget the pairing, telling the server so.
167 ///
168 /// The local store is cleared whether or not the server answers: a client that keeps
169 /// a token for a pairing it has renounced is a client that will keep trying to use it.
170 pub async fn unpair(&mut self) -> Result<(), Error> {
171 let token = self.machine.tokens().current().cloned();
172 let body = self.machine.unpaired();
173 let Some(token) = token else {
174 return Ok(());
175 };
176 self.http
177 .post_empty("unpair", UNPAIR, Some(token.as_str()), Some(&body))
178 .await
179 }
180
181 /// How long to wait before the next attempt, after one has failed.
182 ///
183 /// `S2C §Reconnection strategy`: `delay_n = random(0, min(600 s, 2 s × 2^n))`. The
184 /// randomness is drawn here because a fleet of devices that all reconnect on the same
185 /// schedule is a thundering herd; `Backoff::delay_with` takes it as a parameter for a
186 /// test that wants it pinned.
187 pub fn backoff(&mut self) -> core::time::Duration {
188 let delay = self.backoff.delay_with(self.attempt);
189 self.attempt = self.attempt.saturating_add(1);
190 core::time::Duration::from(delay)
191 }
192
193 /// Give up on the current run of failures, so the next one starts from two seconds
194 /// again.
195 pub fn reset_backoff(&mut self) {
196 self.attempt = 0;
197 }
198
199 /// A token that has been refused, so the next attempt does not start from the top.
200 #[must_use]
201 pub fn access_token(&self) -> Option<&AccessToken> {
202 self.machine.tokens().current()
203 }
204}