BlueGit

ict rusty-teams

Files

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

session.rs

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