BlueGit

ict rusty-teams

Files

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

session.rs

session.rs 18.1 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 /// Runs one CDP method in the app tab, opening the tab when needed.
338 pub(crate) async fn cdp_in(
339 &self,
340 app: App,
341 method: &str,
342 params: Value,
343 ) -> Result<Option<Value>> {
344 let mut slot = self.tabs[&app].lock().await;
345 if slot.is_none() {
346 let Some((control, _)) = self.transport.open(app, false).await? else {
347 return Ok(None);
348 };
349 *slot = Some(control);
350 }
351 let control = slot.as_ref().expect("connection set above");
352 let outcome = control.call(method, params).await;
353 if outcome.is_err() {
354 *slot = None;
355 }
356 outcome.map(Some)
357 }
358
359 /// Whether [`Session::persist_msal_key`] can run on this transport.
360 pub fn can_persist_msal_key(&self) -> bool {
361 self.transport.supports_cdp()
362 }
363
364 /// Gives MSAL's session-cookie cache key an expiry so the next start can still read the token
365 /// cache. Works over CDP for WebView2 and for a managed Chrome session.
366 pub async fn persist_msal_key(&self) -> Result<bool> {
367 if !self.can_persist_msal_key() {
368 return Ok(false);
369 }
370 let now_secs = std::time::SystemTime::now()
371 .duration_since(std::time::UNIX_EPOCH)
372 .map_or(0, |elapsed| elapsed.as_secs());
373 let Some(cookies) = self
374 .cdp_in(App::Teams, "Storage.getCookies", json!({}))
375 .await?
376 else {
377 return Ok(false);
378 };
379 let Some(params) = crate::msal_key::persisted_key_cookies(&cookies, now_secs) else {
380 return Ok(false);
381 };
382 let Some(_) = self
383 .cdp_in(App::Teams, "Storage.setCookies", params)
384 .await?
385 else {
386 return Ok(false);
387 };
388 Ok(true)
389 }
390
391 pub(crate) async fn evaluate_in(&self, app: App, expression: &str) -> Result<Option<Value>> {
392 let mut slot = self.tabs[&app].lock().await;
393 if slot.is_none() {
394 let Some((control, _)) = self.transport.open(app, false).await? else {
395 return Ok(None);
396 };
397 *slot = Some(control);
398 }
399 let control = slot.as_ref().expect("connection set above");
400 let outcome = control
401 .evaluate_within(expression, self.config.evaluate_timeout)
402 .await;
403 if outcome.is_err() {
404 *slot = None;
405 }
406 outcome.map(Some)
407 }
408
409 async fn drop_connection(&self, app: App) {
410 *self.tabs[&app].lock().await = None;
411 }
412
413 async fn drop_all(&self) {
414 for app in App::ALL {
415 self.drop_connection(app).await;
416 }
417 }
418
419 async fn reload_all(&self) {
420 for app in App::ALL {
421 let _ = self.transport.wake(app).await;
422 }
423 }
424}
425
426pub struct TabHold {
427 transport: Arc<dyn Transport>,
428 app: App,
429}
430
431impl Drop for TabHold {
432 fn drop(&mut self) {
433 self.transport.hold(self.app, false);
434 }
435}
436
437fn native_http(config: &SessionConfig) -> Option<Arc<NativeHttp>> {
438 config
439 .native_http
440 .then(|| NativeHttp::new(config.evaluate_timeout, MAX_DOWNLOAD_BYTES))
441 .flatten()
442 .map(Arc::new)
443}
444
445pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
446 header
447 .and_then(|value| value.trim().parse::<f64>().ok())
448 .and_then(|seconds| Duration::try_from_secs_f64(seconds).ok())
449 .unwrap_or(default)
450}
451
452#[cfg(test)]
453mod tests {
454 use std::sync::Mutex as StdMutex;
455
456 use super::*;
457 use crate::transport::{BoxFuture, Diagnosis, OpenedTab};
458
459 #[derive(Default)]
460 struct HoldRecorder {
461 holds: StdMutex<Vec<(App, bool)>>,
462 }
463
464 impl Transport for HoldRecorder {
465 fn check(&self) -> BoxFuture<'_, Result<()>> {
466 Box::pin(async { Ok(()) })
467 }
468
469 fn open(&self, _app: App, _with_events: bool) -> BoxFuture<'_, Result<Option<OpenedTab>>> {
470 Box::pin(async { Ok(None) })
471 }
472
473 fn wake(&self, _app: App) -> BoxFuture<'_, Result<()>> {
474 Box::pin(async { Ok(()) })
475 }
476
477 fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>> {
478 Box::pin(async { Ok(Diagnosis::default()) })
479 }
480
481 fn hold(&self, app: App, held: bool) {
482 self.holds.lock().unwrap().push((app, held));
483 }
484 }
485
486 #[tokio::test]
487 async fn tab_hold_releases_the_tab_when_dropped() {
488 let recorder = Arc::new(HoldRecorder::default());
489 let session = Session::with_transport(recorder.clone(), SessionConfig::default())
490 .await
491 .unwrap();
492 let hold = session.hold_tab(App::Teams);
493 assert_eq!(*recorder.holds.lock().unwrap(), vec![(App::Teams, true)]);
494 drop(hold);
495 assert_eq!(
496 *recorder.holds.lock().unwrap(),
497 vec![(App::Teams, true), (App::Teams, false)]
498 );
499 }
500
501 #[tokio::test]
502 async fn a_tenant_session_asks_the_page_for_that_tenant_only() {
503 let home =
504 Session::with_transport(Arc::new(HoldRecorder::default()), SessionConfig::default())
505 .await
506 .unwrap();
507 let guest = home.in_tenant("AAAA-Guest");
508 let request = Request::get("https://graph.microsoft.com/v1.0/me");
509 let tenant_of = |session: &Session| {
510 let payload: Value =
511 serde_json::from_str(&session.payload(&[&request], &Scope::graph("User.Read")))
512 .unwrap();
513 payload["tenant"].clone()
514 };
515 assert_eq!(tenant_of(&home), Value::Null);
516 assert_eq!(tenant_of(&guest), json!("aaaa-guest"));
517 assert_eq!(home.tenant(), None);
518 }
519
520 #[test]
521 fn retry_after_seconds_parse() {
522 let default = Duration::from_secs(2);
523 assert_eq!(retry_wait(Some("7"), default), Duration::from_secs(7));
524 assert_eq!(
525 retry_wait(Some(" 1.5 "), default),
526 Duration::from_millis(1500)
527 );
528 }
529
530 #[test]
531 fn retry_after_falls_back() {
532 let default = Duration::from_secs(2);
533 assert_eq!(retry_wait(None, default), default);
534 assert_eq!(
535 retry_wait(Some("Wed, 21 Oct 2026 07:28:00 GMT"), default),
536 default
537 );
538 assert_eq!(retry_wait(Some("-3"), default), default);
539 assert_eq!(retry_wait(Some("1e20"), default), default);
540 }
541}