BlueGit

ict rusty-teams

Files

rusty-teams / crates / session / src / session.rs

session.rs

session.rs 16.3 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::sync::{Arc, LazyLock};
4use std::time::Duration;
5
6use serde_json::{Value, json};
7use tokio::sync::Mutex;
8use tokio::time::{Instant, sleep};
9
10use crate::app::App;
11use crate::error::{Error, Result};
12use crate::events::TabControl;
13use crate::native::NativeHttp;
14use crate::request::{ApiResponse, Method, Outcome, Request, WireRequest, WireResult};
15use crate::scope::Scope;
16use crate::transport::{CdpTransport, Transport};
17
18pub const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:9222";
19pub const UNSEAL_SCRIPT: &str = include_str!("../assets/unseal.js");
20pub(crate) static FETCH_SCRIPT: LazyLock<String> =
21 LazyLock::new(|| include_str!("../assets/fetch.js").replace("__UNSEAL__", UNSEAL_SCRIPT));
22pub(crate) const NOT_GRANTED_PREFIX: &str = "the app is not granted";
23const MAX_DOWNLOAD_BYTES: u64 = 60 * 1024 * 1024;
24const DEFAULT_CONCURRENCY: usize = 6;
25
26#[derive(Debug, Clone)]
27pub struct SessionConfig {
28 pub refresh_margin: Duration,
29 pub token_wait: Duration,
30 pub token_poll: Duration,
31 pub evaluate_timeout: Duration,
32 pub max_throttle_retries: usize,
33 pub max_retry_wait: Duration,
34 pub default_retry_wait: Duration,
35 pub unauthorized_reload_wait: Duration,
36 pub native_http: bool,
37}
38
39impl Default for SessionConfig {
40 fn default() -> Self {
41 SessionConfig {
42 refresh_margin: Duration::from_secs(120),
43 token_wait: Duration::from_secs(60),
44 token_poll: Duration::from_secs(3),
45 evaluate_timeout: Duration::from_secs(60),
46 max_throttle_retries: 3,
47 max_retry_wait: Duration::from_secs(30),
48 default_retry_wait: Duration::from_secs(2),
49 unauthorized_reload_wait: Duration::from_secs(5),
50 native_http: false,
51 }
52 }
53}
54
55impl SessionConfig {
56 /// The app's settings: requests go out from Rust unless TEAMS_PAGE_FETCH is set.
57 pub fn for_app() -> Self {
58 SessionConfig {
59 native_http: std::env::var_os("TEAMS_PAGE_FETCH").is_none(),
60 ..SessionConfig::default()
61 }
62 }
63}
64
65#[derive(Default)]
66struct TokenSearch {
67 refresh_error: Option<String>,
68 pages: Vec<String>,
69 ungranted: HashSet<App>,
70}
71
72#[derive(Clone)]
73pub struct Session {
74 pub(crate) transport: Arc<dyn Transport>,
75 pub(crate) config: SessionConfig,
76 tabs: Arc<HashMap<App, Mutex<Option<TabControl>>>>,
77 force_refresh: Arc<AtomicBool>,
78 native: Option<Arc<NativeHttp>>,
79 tenant: Option<Arc<str>>,
80}
81
82impl Session {
83 pub async fn connect(endpoint: &str) -> Result<Self> {
84 Self::connect_with(endpoint, SessionConfig::default()).await
85 }
86
87 pub async fn connect_with(endpoint: &str, config: SessionConfig) -> Result<Self> {
88 Self::with_transport(Arc::new(CdpTransport::new(endpoint)), config).await
89 }
90
91 pub async fn with_transport(
92 transport: Arc<dyn Transport>,
93 config: SessionConfig,
94 ) -> Result<Self> {
95 transport.check().await?;
96 Ok(Session {
97 native: native_http(&config),
98 tenant: None,
99 transport,
100 config,
101 tabs: Arc::new(
102 App::ALL
103 .into_iter()
104 .map(|app| (app, Mutex::new(None)))
105 .collect(),
106 ),
107 force_refresh: Arc::new(AtomicBool::new(false)),
108 })
109 }
110
111 /// The same browser session with tokens for `tenant_id`, e.g. a tenant the account is a guest in.
112 /// Tokens are held apart from the home tenant's, so both can run side by side.
113 pub fn in_tenant(&self, tenant_id: &str) -> Session {
114 Session {
115 native: native_http(&self.config),
116 force_refresh: Arc::new(AtomicBool::new(false)),
117 tenant: Some(tenant_id.to_ascii_lowercase().into()),
118 ..self.clone()
119 }
120 }
121
122 /// The tenant set with [`Session::in_tenant`]; `None` is the account's home tenant.
123 pub fn tenant(&self) -> Option<&str> {
124 self.tenant.as_deref()
125 }
126
127 pub async fn request(
128 &self,
129 method: Method,
130 url: &str,
131 scope: &Scope,
132 body: Option<Value>,
133 ) -> Result<ApiResponse> {
134 let request = Request {
135 method,
136 body,
137 ..Request::get(url)
138 };
139 self.send(request, scope).await
140 }
141
142 pub async fn send(&self, request: Request, scope: &Scope) -> Result<ApiResponse> {
143 let url = request.url.clone();
144 let response = self.batch(&[request], scope).await?.remove(0);
145 if response.status >= 400 || response.status == 0 {
146 return Err(Error::api(response.status, &url, response.body));
147 }
148 Ok(response)
149 }
150
151 pub async fn batch(&self, requests: &[Request], scope: &Scope) -> Result<Vec<ApiResponse>> {
152 let mut results: Vec<Option<ApiResponse>> = vec![None; requests.len()];
153 let mut pending: Vec<usize> = (0..requests.len()).collect();
154 let mut forced_here = false;
155 for attempt in 0..=self.config.max_throttle_retries {
156 let batch: Vec<&Request> = pending.iter().map(|&index| &requests[index]).collect();
157 let answers = match self.run_with_fresh_token(&batch, scope).await {
158 Ok(answers) => answers,
159 Err(error) => {
160 if forced_here {
161 self.force_refresh.store(false, Ordering::SeqCst);
162 }
163 return Err(error);
164 }
165 };
166 let unauthorized_first_try =
167 attempt == 0 && answers.iter().any(|answer| answer.status == 401);
168 if unauthorized_first_try {
169 // A CAE-revoked token stays unexpired in the app cache, so only a refresh-token grant replaces it.
170 self.force_refresh.store(true, Ordering::SeqCst);
171 forced_here = true;
172 self.reload_all().await;
173 sleep(self.config.unauthorized_reload_wait).await;
174 self.drop_all().await;
175 }
176 let mut retry = Vec::new();
177 for (&index, answer) in pending.iter().zip(answers) {
178 let throttled = answer.status == 429 || (attempt == 0 && answer.status == 401);
179 results[index] = Some(answer);
180 if throttled {
181 retry.push(index);
182 }
183 }
184 if forced_here && !unauthorized_first_try {
185 self.force_refresh.store(false, Ordering::SeqCst);
186 forced_here = false;
187 }
188 if retry.is_empty() || attempt == self.config.max_throttle_retries {
189 break;
190 }
191 let wait = retry
192 .iter()
193 .filter_map(|&index| results[index].as_ref())
194 .map(|answer| {
195 retry_wait(
196 answer.retry_after.as_deref(),
197 self.config.default_retry_wait,
198 )
199 })
200 .max()
201 .unwrap_or_default();
202 sleep(wait.min(self.config.max_retry_wait)).await;
203 pending = retry;
204 }
205 Ok(results.into_iter().flatten().collect())
206 }
207
208 /// Keeps the app tab where it is until the guard drops, e.g. for the length of a call.
209 pub fn hold_tab(&self, app: App) -> TabHold {
210 self.transport.hold(app, true);
211 TabHold {
212 transport: self.transport.clone(),
213 app,
214 }
215 }
216
217 pub async fn close(&self) {
218 self.drop_all().await;
219 }
220
221 async fn run_with_fresh_token(
222 &self,
223 requests: &[&Request],
224 scope: &Scope,
225 ) -> Result<Vec<ApiResponse>> {
226 if let Some(native) = &self.native
227 && let Some(results) = native
228 .run(
229 self,
230 requests,
231 scope,
232 self.force_refresh.load(Ordering::SeqCst),
233 )
234 .await
235 {
236 return Ok(results);
237 }
238 let mut search = TokenSearch::default();
239 if let Some(results) = self.run_in_any_tab(requests, scope, &mut search).await? {
240 return Ok(results);
241 }
242 if search.ungranted.len() == App::ALL.len() {
243 return Err(Error::LoginRequired(format!(
244 "the Teams web app is not granted {scope}"
245 )));
246 }
247 self.reload_all().await;
248 let deadline = Instant::now() + self.config.token_wait;
249 while Instant::now() < deadline {
250 sleep(self.config.token_poll).await;
251 self.drop_all().await;
252 if let Some(results) = self.run_in_any_tab(requests, scope, &mut search).await? {
253 return Ok(results);
254 }
255 }
256 let diagnosis = self.transport.diagnose().await?;
257 if diagnosis.login_pending {
258 return Err(Error::LoginRequired("sign in in the browser window".into()));
259 }
260 if !diagnosis.app_tab_open {
261 return Err(Error::NoAppTab);
262 }
263 let mut detail = search
264 .refresh_error
265 .map(|reason| format!(" (token refresh failed in {reason})"))
266 .unwrap_or_default();
267 if !search.pages.is_empty() {
268 detail.push_str(&format!(" [{}]", search.pages.join("; ")));
269 }
270 Err(Error::NoFreshToken {
271 scope: scope.to_string(),
272 detail,
273 })
274 }
275
276 async fn run_in_any_tab(
277 &self,
278 requests: &[&Request],
279 scope: &Scope,
280 search: &mut TokenSearch,
281 ) -> Result<Option<Vec<ApiResponse>>> {
282 let payload = self.payload(requests, scope);
283 let expression = format!("({})({payload})", FETCH_SCRIPT.as_str());
284 let has_write = requests.iter().any(|request| request.method != Method::Get);
285 for app in App::ALL {
286 let outcome = match self.evaluate_in(app, &expression).await {
287 Ok(Some(value)) => value,
288 Ok(None) => continue,
289 Err(error) => {
290 self.drop_connection(app).await;
291 if has_write {
292 return Err(Error::WriteInterrupted(error.to_string()));
293 }
294 continue;
295 }
296 };
297 let outcome: Outcome = serde_json::from_value(outcome)
298 .map_err(|error| Error::Cdp(format!("unexpected page answer: {error}")))?;
299 if let Some(results) = outcome.results {
300 return Ok(Some(results.into_iter().map(WireResult::into).collect()));
301 }
302 if let Some(page) = &outcome.page {
303 let line = format!("{app}: {page}");
304 search
305 .pages
306 .retain(|seen| !seen.starts_with(&format!("{app}:")));
307 search.pages.push(line);
308 }
309 if let Some(reason) = outcome.refresh_error {
310 if reason.starts_with(NOT_GRANTED_PREFIX) {
311 search.ungranted.insert(app);
312 }
313 search
314 .refresh_error
315 .get_or_insert_with(|| format!("{app}: {reason}"));
316 }
317 }
318 Ok(None)
319 }
320
321 fn payload(&self, requests: &[&Request], scope: &Scope) -> String {
322 let wire: Vec<WireRequest> = requests.iter().map(|&request| request.into()).collect();
323 json!({
324 "requests": wire,
325 "resource": scope.resource,
326 "scope": scope.name,
327 "nestedApp": scope.nested_app_json(),
328 "marginMs": self.config.refresh_margin.as_millis() as u64,
329 "concurrency": DEFAULT_CONCURRENCY,
330 "maxBytes": MAX_DOWNLOAD_BYTES,
331 "forceRefresh": self.force_refresh.load(Ordering::SeqCst),
332 "tenant": self.tenant(),
333 })
334 .to_string()
335 }
336
337 pub(crate) async fn evaluate_in(&self, app: App, expression: &str) -> Result<Option<Value>> {
338 let mut slot = self.tabs[&app].lock().await;
339 if slot.is_none() {
340 let Some((control, _)) = self.transport.open(app, false).await? else {
341 return Ok(None);
342 };
343 *slot = Some(control);
344 }
345 let control = slot.as_ref().expect("connection set above");
346 let outcome = control
347 .evaluate_within(expression, self.config.evaluate_timeout)
348 .await;
349 if outcome.is_err() {
350 *slot = None;
351 }
352 outcome.map(Some)
353 }
354
355 async fn drop_connection(&self, app: App) {
356 *self.tabs[&app].lock().await = None;
357 }
358
359 async fn drop_all(&self) {
360 for app in App::ALL {
361 self.drop_connection(app).await;
362 }
363 }
364
365 async fn reload_all(&self) {
366 for app in App::ALL {
367 let _ = self.transport.wake(app).await;
368 }
369 }
370}
371
372pub struct TabHold {
373 transport: Arc<dyn Transport>,
374 app: App,
375}
376
377impl Drop for TabHold {
378 fn drop(&mut self) {
379 self.transport.hold(self.app, false);
380 }
381}
382
383fn native_http(config: &SessionConfig) -> Option<Arc<NativeHttp>> {
384 config
385 .native_http
386 .then(|| NativeHttp::new(config.evaluate_timeout, MAX_DOWNLOAD_BYTES))
387 .flatten()
388 .map(Arc::new)
389}
390
391pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
392 header
393 .and_then(|value| value.trim().parse::<f64>().ok())
394 .and_then(|seconds| Duration::try_from_secs_f64(seconds).ok())
395 .unwrap_or(default)
396}
397
398#[cfg(test)]
399mod tests {
400 use std::sync::Mutex as StdMutex;
401
402 use super::*;
403 use crate::transport::{BoxFuture, Diagnosis, OpenedTab};
404
405 #[derive(Default)]
406 struct HoldRecorder {
407 holds: StdMutex<Vec<(App, bool)>>,
408 }
409
410 impl Transport for HoldRecorder {
411 fn check(&self) -> BoxFuture<'_, Result<()>> {
412 Box::pin(async { Ok(()) })
413 }
414
415 fn open(&self, _app: App, _with_events: bool) -> BoxFuture<'_, Result<Option<OpenedTab>>> {
416 Box::pin(async { Ok(None) })
417 }
418
419 fn wake(&self, _app: App) -> BoxFuture<'_, Result<()>> {
420 Box::pin(async { Ok(()) })
421 }
422
423 fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> {
424 Box::pin(async { Ok(Diagnosis::default()) })
425 }
426
427 fn hold(&self, app: App, held: bool) {
428 self.holds.lock().unwrap().push((app, held));
429 }
430 }
431
432 #[tokio::test]
433 async fn tab_hold_releases_the_tab_when_dropped() {
434 let recorder = Arc::new(HoldRecorder::default());
435 let session = Session::with_transport(recorder.clone(), SessionConfig::default())
436 .await
437 .unwrap();
438 let hold = session.hold_tab(App::Teams);
439 assert_eq!(*recorder.holds.lock().unwrap(), vec![(App::Teams, true)]);
440 drop(hold);
441 assert_eq!(
442 *recorder.holds.lock().unwrap(),
443 vec![(App::Teams, true), (App::Teams, false)]
444 );
445 }
446
447 #[tokio::test]
448 async fn a_tenant_session_asks_the_page_for_that_tenant_only() {
449 let home =
450 Session::with_transport(Arc::new(HoldRecorder::default()), SessionConfig::default())
451 .await
452 .unwrap();
453 let guest = home.in_tenant("AAAA-Guest");
454 let request = Request::get("https://graph.microsoft.com/v1.0/me");
455 let tenant_of = |session: &Session| {
456 let payload: Value =
457 serde_json::from_str(&session.payload(&[&request], &Scope::graph("User.Read")))
458 .unwrap();
459 payload["tenant"].clone()
460 };
461 assert_eq!(tenant_of(&home), Value::Null);
462 assert_eq!(tenant_of(&guest), json!("aaaa-guest"));
463 assert_eq!(home.tenant(), None);
464 }
465
466 #[test]
467 fn retry_after_seconds_parse() {
468 let default = Duration::from_secs(2);
469 assert_eq!(retry_wait(Some("7"), default), Duration::from_secs(7));
470 assert_eq!(
471 retry_wait(Some(" 1.5 "), default),
472 Duration::from_millis(1500)
473 );
474 }
475
476 #[test]
477 fn retry_after_falls_back() {
478 let default = Duration::from_secs(2);
479 assert_eq!(retry_wait(None, default), default);
480 assert_eq!(
481 retry_wait(Some("Wed, 21 Oct 2026 07:28:00 GMT"), default),
482 default
483 );
484 assert_eq!(retry_wait(Some("-3"), default), default);
485 assert_eq!(retry_wait(Some("1e20"), default), default);
486 }
487}