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 ///
113 /// Every other failure leaves this session ready for the next attempt — after
114 /// [`backoff`](Self::backoff) — with whatever tokens survived, because
115 /// `S2C §Reconnection strategy` says the client "**must** try to reconnect". A
116 /// `NoLongerPaired` is the exception: the pairing is gone, the tokens are cleared, and
117 /// only a new pairing helps.
118 pub async fn initiate(&mut self, now: Timestamp) -> Result<SessionCredentials, Error> {
119 let result = self.attempt(now).await;
120 if let Err(e) = &result
121 && !matches!(
122 e,
123 Error::Protocol(crate::connect::proto::ConnectError::SessionRefused(refused))
124 if refused.error_message == crate::connect::proto::SessionErrorMessage::NoLongerPaired
125 )
126 {
127 self.machine.restart();
128 }
129 result
130 }
131
132 async fn attempt(&mut self, now: Timestamp) -> Result<SessionCredentials, Error> {
133 loop {
134 let (bearer, body) = self.machine.initiate()?;
135 let grant: SessionGrant = match self
136 .http
137 .post(
138 "initiateSession",
139 INITIATE_SESSION,
140 Some(bearer.as_str()),
141 &body,
142 )
143 .await
144 {
145 Ok(grant) => grant,
146 Err(Error::Http { status, .. }) if status.is_unauthorized() => {
147 // Refused: try the next token, or conclude the pairing is gone.
148 crate::trace::event!(
149 warn,
150 remaining = self.machine.tokens().len(),
151 "the access token was refused; trying the next"
152 );
153 self.machine.unauthorized()?;
154 continue;
155 }
156 Err(Error::Http {
157 status,
158 detail: Some(detail),
159 ..
160 }) if status.0 == 400 => {
161 // A named refusal. `NoLongerPaired` means "Do not retry": forget.
162 if let Ok(refused) =
163 serde_json::from_str::<crate::connect::proto::SessionRefused>(&detail)
164 {
165 if refused.error_message
166 == crate::connect::proto::SessionErrorMessage::NoLongerPaired
167 {
168 let _ = self.machine.unpaired();
169 }
170 return Err(Error::Protocol(
171 crate::connect::proto::ConnectError::SessionRefused(refused),
172 ));
173 }
174 return Err(Error::Http {
175 operation: "initiateSession",
176 status,
177 detail: Some(detail),
178 });
179 }
180 Err(e) => return Err(e),
181 };
182
183 self.machine.accept(grant, now)?;
184 // The store now holds the replacement. A caller that persists here survives a
185 // crash before the confirmation; one that does not, does not.
186 let confirm = self.machine.confirm()?;
187 // No request body: `S2C-OAS session-init/confirmAccessToken` defines none, and
188 // the bearer is the whole message.
189 let details: CommunicationDetails = self
190 .http
191 .post_bodyless(
192 "confirmAccessToken",
193 CONFIRM_ACCESS_TOKEN,
194 Some(confirm.as_str()),
195 )
196 .await?;
197 let credentials = self.machine.connected(details, now)?;
198 crate::trace::event!(
199 info,
200 url = %credentials.websocket_url,
201 profile = ?credentials.profile,
202 expires = %credentials.expires(),
203 "session initiated"
204 );
205 self.attempt = 0;
206 return Ok(credentials);
207 }
208 }
209
210 /// Forget the pairing, telling the server so.
211 ///
212 /// The local store is cleared whether or not the server answers: a client that keeps
213 /// a token for a pairing it has renounced is a client that will keep trying to use it.
214 pub async fn unpair(&mut self) -> Result<(), Error> {
215 let token = self.machine.tokens().current().cloned();
216 let body = self.machine.unpaired();
217 let Some(token) = token else {
218 return Ok(());
219 };
220 self.http
221 .post_empty("unpair", UNPAIR, Some(token.as_str()), Some(&body))
222 .await
223 }
224
225 /// How long to wait before the next attempt, after one has failed.
226 ///
227 /// `S2C §Reconnection strategy`: `delay_n = random(0, min(600 s, 2 s × 2^n))`. The
228 /// randomness is drawn here because a fleet of devices that all reconnect on the same
229 /// schedule is a thundering herd; `Backoff::delay_with` takes it as a parameter for a
230 /// test that wants it pinned.
231 pub fn backoff(&mut self) -> core::time::Duration {
232 let delay = self.backoff.delay_with(self.attempt);
233 self.attempt = self.attempt.saturating_add(1);
234 core::time::Duration::from(delay)
235 }
236
237 /// Give up on the current run of failures, so the next one starts from two seconds
238 /// again.
239 pub fn reset_backoff(&mut self) {
240 self.attempt = 0;
241 }
242
243 /// A token that has been refused, so the next attempt does not start from the top.
244 #[must_use]
245 pub fn access_token(&self) -> Option<&AccessToken> {
246 self.machine.tokens().current()
247 }
248}