BlueGit

ict rusty-teams

Files

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

session.rs

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