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 let details: CommunicationDetails = self
144 .http
145 .post::<(), _>(
146 "confirmAccessToken",
147 CONFIRM_ACCESS_TOKEN,
148 Some(confirm.as_str()),
149 &(),
150 )
151 .await?;
152 let credentials = self.machine.connected(details, now)?;
153 crate::trace::event!(
154 info,
155 url = %credentials.websocket_url,
156 profile = ?credentials.profile,
157 expires = %credentials.expires(),
158 "session initiated"
159 );
160 self.attempt = 0;
161 return Ok(credentials);
162 }
163 }
164
165 /// Forget the pairing, telling the server so.
166 ///
167 /// The local store is cleared whether or not the server answers: a client that keeps
168 /// a token for a pairing it has renounced is a client that will keep trying to use it.
169 pub async fn unpair(&mut self) -> Result<(), Error> {
170 let token = self.machine.tokens().current().cloned();
171 let body = self.machine.unpaired();
172 let Some(token) = token else {
173 return Ok(());
174 };
175 self.http
176 .post_empty("unpair", UNPAIR, Some(token.as_str()), Some(&body))
177 .await
178 }
179
180 /// How long to wait before the next attempt, after one has failed.
181 ///
182 /// `S2C §Reconnection strategy`: `delay_n = random(0, min(600 s, 2 s × 2^n))`. The
183 /// randomness is drawn here because a fleet of devices that all reconnect on the same
184 /// schedule is a thundering herd; `Backoff::delay_with` takes it as a parameter for a
185 /// test that wants it pinned.
186 pub fn backoff(&mut self) -> core::time::Duration {
187 let delay = self.backoff.delay_with(self.attempt);
188 self.attempt = self.attempt.saturating_add(1);
189 core::time::Duration::from(delay)
190 }
191
192 /// Give up on the current run of failures, so the next one starts from two seconds
193 /// again.
194 pub fn reset_backoff(&mut self) {
195 self.attempt = 0;
196 }
197
198 /// A token that has been refused, so the next attempt does not start from the top.
199 #[must_use]
200 pub fn access_token(&self) -> Option<&AccessToken> {
201 self.machine.tokens().current()
202 }
203}