BlueGit

ict rusty-teams

fix(browser): the sign-in window stays open until a token is usable (#137)

metis Joe Mild · pushed by metis

Authored 2026-11-27 · 4 days ago

Hash
f2082bc6f3a19302200817b4adfc1ff071b25633
Parent
c52f67bc
4 files changed +151 −5
crates/app/src/linux_browser.rs +18 −5
@@ -158,7 +158,7 @@ impl HideAfterLogin {
158 158 self.stable = 0;
159 159 }
160 160
161 fn step(&mut self, status: Option<&browser::Status>, has_msal_cache: bool) -> bool {
161 fn step(&mut self, status: Option<&browser::Status>, session_ready: bool) -> bool {
162 162 let Some(status) = status else {
163 163 self.stable = 0;
164 164 return false;
@@ -172,7 +172,7 @@ impl HideAfterLogin {
172 172 .tabs
173 173 .iter()
174 174 .any(|tab| tab.app == Some(browser::App::Teams) && !tab.parked);
175 if !teams_loaded || !has_msal_cache {
175 if !teams_loaded || !session_ready {
176 176 self.stable = 0;
177 177 return false;
178 178 }
@@ -199,7 +199,7 @@ async fn hide_after_login(browser: browser::Browser, headless_notify: Arc<Notify
199 199 continue;
200 200 }
201 201 let status = browser.status().await.ok();
202 let has_msal_cache = match status.as_ref() {
202 let session_ready = match status.as_ref() {
203 203 Some(status)
204 204 if status.running
205 205 && status.mode == browser::Mode::Visible
@@ -209,11 +209,11 @@ async fn hide_after_login(browser: browser::Browser, headless_notify: Arc<Notify
209 209 .iter()
210 210 .any(|tab| tab.app == Some(browser::App::Teams) && !tab.parked) =>
211 211 {
212 browser.teams_has_msal_cache().await
212 browser.teams_sign_in_ready().await
213 213 }
214 214 _ => false,
215 215 };
216 if tracker.step(status.as_ref(), has_msal_cache) {
216 if tracker.step(status.as_ref(), session_ready) {
217 217 log::info!("Teams sign-in finished: moving Chrome to the background");
218 218 publish_sign_in(BrowserSignInState::Finishing);
219 219 if let Err(error) = browser.headless().await {
@@ -542,6 +542,19 @@ mod tests {
542 542 }
543 543 }
544 544
545 #[test]
546 fn key_names_without_a_usable_token_keep_the_window_open() {
547 let mut tracker = HideAfterLogin::default();
548 let teams = status(
549 browser::Mode::Visible,
550 browser::LoginState::NotRequired,
551 vec![tab(Some(browser::App::Teams), false, false)],
552 );
553 for _ in 0..HIDE_STABLE_CHECKS + 2 {
554 assert!(!tracker.step(Some(&teams), false));
555 }
556 }
557
545 558 #[test]
546 559 fn stop_timeout_covers_browser_shutdown() {
547 560 let timeouts = browser::Timeouts::default();
@@ -158,7 +158,7 @@ impl HideAfterLogin {
158 self.stable = 0;
158 self.stable = 0;
159 }
159 }
160
160
161 fn step(&mut self, status: Option<&browser::Status>, has_msal_cache: bool) -> bool {
161 fn step(&mut self, status: Option<&browser::Status>, session_ready: bool) -> bool {
162 let Some(status) = status else {
162 let Some(status) = status else {
163 self.stable = 0;
163 self.stable = 0;
164 return false;
164 return false;
@@ -172,7 +172,7 @@ impl HideAfterLogin {
172 .tabs
172 .tabs
173 .iter()
173 .iter()
174 .any(|tab| tab.app == Some(browser::App::Teams) && !tab.parked);
174 .any(|tab| tab.app == Some(browser::App::Teams) && !tab.parked);
175 if !teams_loaded || !has_msal_cache {
175 if !teams_loaded || !session_ready {
176 self.stable = 0;
176 self.stable = 0;
177 return false;
177 return false;
178 }
178 }
@@ -199,7 +199,7 @@ async fn hide_after_login(browser: browser::Browser, headless_notify: Arc<Notify
199 continue;
199 continue;
200 }
200 }
201 let status = browser.status().await.ok();
201 let status = browser.status().await.ok();
202 let has_msal_cache = match status.as_ref() {
202 let session_ready = match status.as_ref() {
203 Some(status)
203 Some(status)
204 if status.running
204 if status.running
205 && status.mode == browser::Mode::Visible
205 && status.mode == browser::Mode::Visible
@@ -209,11 +209,11 @@ async fn hide_after_login(browser: browser::Browser, headless_notify: Arc<Notify
209 .iter()
209 .iter()
210 .any(|tab| tab.app == Some(browser::App::Teams) && !tab.parked) =>
210 .any(|tab| tab.app == Some(browser::App::Teams) && !tab.parked) =>
211 {
211 {
212 browser.teams_has_msal_cache().await
212 browser.teams_sign_in_ready().await
213 }
213 }
214 _ => false,
214 _ => false,
215 };
215 };
216 if tracker.step(status.as_ref(), has_msal_cache) {
216 if tracker.step(status.as_ref(), session_ready) {
217 log::info!("Teams sign-in finished: moving Chrome to the background");
217 log::info!("Teams sign-in finished: moving Chrome to the background");
218 publish_sign_in(BrowserSignInState::Finishing);
218 publish_sign_in(BrowserSignInState::Finishing);
219 if let Err(error) = browser.headless().await {
219 if let Err(error) = browser.headless().await {
@@ -542,6 +542,19 @@ mod tests {
542 }
542 }
543 }
543 }
544
544
545 #[test]
546 fn key_names_without_a_usable_token_keep_the_window_open() {
547 let mut tracker = HideAfterLogin::default();
548 let teams = status(
549 browser::Mode::Visible,
550 browser::LoginState::NotRequired,
551 vec![tab(Some(browser::App::Teams), false, false)],
552 );
553 for _ in 0..HIDE_STABLE_CHECKS + 2 {
554 assert!(!tracker.step(Some(&teams), false));
555 }
556 }
557
545 #[test]
558 #[test]
546 fn stop_timeout_covers_browser_shutdown() {
559 fn stop_timeout_covers_browser_shutdown() {
547 let timeouts = browser::Timeouts::default();
560 let timeouts = browser::Timeouts::default();
crates/browser/src/browser.rs +39 −0
@@ -296,6 +296,45 @@ impl Browser {
296 296 .unwrap_or(false)
297 297 }
298 298
299 /// True when the Teams page holds a still-valid access token, plain or decrypted from a
300 /// sealed cache entry. Key names and expired unsealed entries do not count.
301 pub async fn teams_sign_in_ready(&self) -> bool {
302 let Ok(tabs) = self.tabs().await else {
303 return false;
304 };
305 let Some(tab) = targets::app_tab(&tabs, App::Teams) else {
306 return false;
307 };
308 if tab.parked {
309 return false;
310 }
311 let expression = crate::sign_in_ready::PAGE_EXPRESSION;
312 if let Some(bidi) = &self.inner.bidi {
313 let evaluate = tokio::time::timeout(
314 self.inner.timeouts.probe,
315 bidi.evaluate(&tab.id, expression),
316 );
317 return match evaluate.await {
318 Ok(Ok(value)) => crate::sign_in_ready::sign_in_ready_from_page(&value),
319 _ => false,
320 };
321 }
322 let url = format!(
323 "ws://127.0.0.1:{}/devtools/page/{}",
324 self.inner.config.port, tab.id
325 );
326 let params = json!({
327 "expression": expression,
328 "returnByValue": true,
329 "awaitPromise": true
330 });
331 cdp_call(&url, "Runtime.evaluate", params, self.inner.timeouts.probe)
332 .await
333 .ok()
334 .and_then(|value| value.pointer("/result/value").cloned())
335 .is_some_and(|value| crate::sign_in_ready::sign_in_ready_from_page(&value))
336 }
337
299 338 pub async fn login_window(&self) -> Result<(), BrowserError> {
300 339 let _guard = self.inner.operation.lock().await;
301 340 if self.is_visible_managed() && self.is_running().await {
@@ -296,6 +296,45 @@ impl Browser {
296 .unwrap_or(false)
296 .unwrap_or(false)
297 }
297 }
298
298
299 /// True when the Teams page holds a still-valid access token, plain or decrypted from a
300 /// sealed cache entry. Key names and expired unsealed entries do not count.
301 pub async fn teams_sign_in_ready(&self) -> bool {
302 let Ok(tabs) = self.tabs().await else {
303 return false;
304 };
305 let Some(tab) = targets::app_tab(&tabs, App::Teams) else {
306 return false;
307 };
308 if tab.parked {
309 return false;
310 }
311 let expression = crate::sign_in_ready::PAGE_EXPRESSION;
312 if let Some(bidi) = &self.inner.bidi {
313 let evaluate = tokio::time::timeout(
314 self.inner.timeouts.probe,
315 bidi.evaluate(&tab.id, expression),
316 );
317 return match evaluate.await {
318 Ok(Ok(value)) => crate::sign_in_ready::sign_in_ready_from_page(&value),
319 _ => false,
320 };
321 }
322 let url = format!(
323 "ws://127.0.0.1:{}/devtools/page/{}",
324 self.inner.config.port, tab.id
325 );
326 let params = json!({
327 "expression": expression,
328 "returnByValue": true,
329 "awaitPromise": true
330 });
331 cdp_call(&url, "Runtime.evaluate", params, self.inner.timeouts.probe)
332 .await
333 .ok()
334 .and_then(|value| value.pointer("/result/value").cloned())
335 .is_some_and(|value| crate::sign_in_ready::sign_in_ready_from_page(&value))
336 }
337
299 pub async fn login_window(&self) -> Result<(), BrowserError> {
338 pub async fn login_window(&self) -> Result<(), BrowserError> {
300 let _guard = self.inner.operation.lock().await;
339 let _guard = self.inner.operation.lock().await;
301 if self.is_visible_managed() && self.is_running().await {
340 if self.is_visible_managed() && self.is_running().await {
crates/browser/src/lib.rs +1 −0
@@ -9,6 +9,7 @@ mod launch;
9 9 mod msal_key;
10 10 mod process;
11 11 mod sign_in_choice;
12 mod sign_in_ready;
12 13 mod targets;
13 14 mod watchdog;
14 15
@@ -9,6 +9,7 @@ mod launch;
9mod msal_key;
9mod msal_key;
10mod process;
10mod process;
11mod sign_in_choice;
11mod sign_in_choice;
12mod sign_in_ready;
12mod targets;
13mod targets;
13mod watchdog;
14mod watchdog;
14
15
crates/browser/src/sign_in_ready.rs added +93 −0
@@ -0,0 +1,93 @@
1 //! Decides that Teams sign-in is finished only when the page holds a fresh access token.
2 //!
3 //! Local storage key names that contain `accesstoken` or `refreshtoken` are not enough: a wiped
4 //! cache still has those names, and treating them as success restarts Chromium and drops the
5 //! encryption cookie. Merely decrypting sealed entries is not enough either once the encryption
6 //! cookie persists across restarts, because an expired session still unseals its old entries.
7
8 use serde_json::Value;
9
10 /// Page script. Returns `{opened, freshAccess}`. `opened` counts sealed entries decrypted with
11 /// the `msal.cache.encryption` cookie. `freshAccess` is a bearer access token whose `expiresOn`
12 /// is still in the future, in the clear or among the opened entries.
13 pub(crate) const PAGE_EXPRESSION: &str = r#"(async () => {
14 const sealed = [];
15 const plain = [];
16 for (let index = 0; index < localStorage.length; index++) {
17 const key = localStorage.key(index);
18 let entry;
19 try { entry = JSON.parse(localStorage.getItem(key)); } catch (error) { continue; }
20 if (!entry || typeof entry !== 'object') continue;
21 if (entry.id && entry.nonce && entry.data) sealed.push([key, entry]);
22 else plain.push(entry);
23 }
24 const openedEntries = [];
25 const cookie = document.cookie.split(';').map((part) => part.trim()).find((part) => part.startsWith('msal.cache.encryption='));
26 let sealing = null;
27 try { sealing = cookie && JSON.parse(decodeURIComponent(cookie.slice(cookie.indexOf('=') + 1))); } catch (error) {}
28 if (sealing && sealing.key && sealing.id && sealed.length) {
29 const bytes = (text) => Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(text.length / 4) * 4, '=')), (character) => character.charCodeAt(0));
30 const base = await crypto.subtle.importKey('raw', bytes(sealing.key), 'HKDF', false, ['deriveKey']);
31 for (const [key, entry] of sealed) {
32 if (entry.id !== sealing.id) continue;
33 const contexts = [...(String(key).match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi) || []), ''];
34 for (const context of new Set(contexts)) {
35 try {
36 const derived = await crypto.subtle.deriveKey(
37 {name: 'HKDF', salt: bytes(entry.nonce), hash: 'SHA-256', info: new TextEncoder().encode(context)},
38 base, {name: 'AES-GCM', length: 256}, false, ['decrypt']);
39 const data = await crypto.subtle.decrypt({name: 'AES-GCM', iv: new Uint8Array(12)}, derived, bytes(entry.data));
40 openedEntries.push(JSON.parse(new TextDecoder().decode(data)));
41 break;
42 } catch (error) {}
43 }
44 }
45 }
46 const now = Date.now();
47 const fresh = (entry) => entry && entry.credentialType === 'AccessToken' && (!entry.tokenType || entry.tokenType === 'Bearer') && Number(entry.expiresOn) * 1000 > now && typeof entry.secret === 'string' && entry.secret.length > 0;
48 return {opened: openedEntries.length, freshAccess: plain.some(fresh) || openedEntries.some(fresh)};
49 })()"#;
50
51 /// True when the page holds a valid access token, either plain or decrypted from a sealed entry.
52 /// Key names and expired unsealed entries are ignored on purpose.
53 pub(crate) fn sign_in_ready_from_page(value: &Value) -> bool {
54 value
55 .get("freshAccess")
56 .and_then(Value::as_bool)
57 .unwrap_or(false)
58 }
59
60 #[cfg(test)]
61 mod tests {
62 use super::*;
63 use serde_json::json;
64
65 #[test]
66 fn key_names_without_a_usable_token_are_not_ready() {
67 let report = json!({"opened": 0, "freshAccess": false, "keyNames": true});
68 assert!(!sign_in_ready_from_page(&report));
69 }
70
71 #[test]
72 fn opened_sealed_entries_without_a_fresh_access_token_are_not_ready() {
73 assert!(!sign_in_ready_from_page(
74 &json!({"opened": 3, "freshAccess": false})
75 ));
76 }
77
78 #[test]
79 fn a_fresh_access_token_is_ready_plain_or_sealed() {
80 assert!(sign_in_ready_from_page(
81 &json!({"opened": 0, "freshAccess": true})
82 ));
83 assert!(sign_in_ready_from_page(
84 &json!({"opened": 2, "freshAccess": true})
85 ));
86 }
87
88 #[test]
89 fn a_missing_report_is_not_ready() {
90 assert!(!sign_in_ready_from_page(&json!({})));
91 assert!(!sign_in_ready_from_page(&json!(null)));
92 }
93 }
@@ -0,0 +1,93 @@
1//! Decides that Teams sign-in is finished only when the page holds a fresh access token.
2//!
3//! Local storage key names that contain `accesstoken` or `refreshtoken` are not enough: a wiped
4//! cache still has those names, and treating them as success restarts Chromium and drops the
5//! encryption cookie. Merely decrypting sealed entries is not enough either once the encryption
6//! cookie persists across restarts, because an expired session still unseals its old entries.
7
8use serde_json::Value;
9
10/// Page script. Returns `{opened, freshAccess}`. `opened` counts sealed entries decrypted with
11/// the `msal.cache.encryption` cookie. `freshAccess` is a bearer access token whose `expiresOn`
12/// is still in the future, in the clear or among the opened entries.
13pub(crate) const PAGE_EXPRESSION: &str = r#"(async () => {
14 const sealed = [];
15 const plain = [];
16 for (let index = 0; index < localStorage.length; index++) {
17 const key = localStorage.key(index);
18 let entry;
19 try { entry = JSON.parse(localStorage.getItem(key)); } catch (error) { continue; }
20 if (!entry || typeof entry !== 'object') continue;
21 if (entry.id && entry.nonce && entry.data) sealed.push([key, entry]);
22 else plain.push(entry);
23 }
24 const openedEntries = [];
25 const cookie = document.cookie.split(';').map((part) => part.trim()).find((part) => part.startsWith('msal.cache.encryption='));
26 let sealing = null;
27 try { sealing = cookie && JSON.parse(decodeURIComponent(cookie.slice(cookie.indexOf('=') + 1))); } catch (error) {}
28 if (sealing && sealing.key && sealing.id && sealed.length) {
29 const bytes = (text) => Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(text.length / 4) * 4, '=')), (character) => character.charCodeAt(0));
30 const base = await crypto.subtle.importKey('raw', bytes(sealing.key), 'HKDF', false, ['deriveKey']);
31 for (const [key, entry] of sealed) {
32 if (entry.id !== sealing.id) continue;
33 const contexts = [...(String(key).match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi) || []), ''];
34 for (const context of new Set(contexts)) {
35 try {
36 const derived = await crypto.subtle.deriveKey(
37 {name: 'HKDF', salt: bytes(entry.nonce), hash: 'SHA-256', info: new TextEncoder().encode(context)},
38 base, {name: 'AES-GCM', length: 256}, false, ['decrypt']);
39 const data = await crypto.subtle.decrypt({name: 'AES-GCM', iv: new Uint8Array(12)}, derived, bytes(entry.data));
40 openedEntries.push(JSON.parse(new TextDecoder().decode(data)));
41 break;
42 } catch (error) {}
43 }
44 }
45 }
46 const now = Date.now();
47 const fresh = (entry) => entry && entry.credentialType === 'AccessToken' && (!entry.tokenType || entry.tokenType === 'Bearer') && Number(entry.expiresOn) * 1000 > now && typeof entry.secret === 'string' && entry.secret.length > 0;
48 return {opened: openedEntries.length, freshAccess: plain.some(fresh) || openedEntries.some(fresh)};
49})()"#;
50
51/// True when the page holds a valid access token, either plain or decrypted from a sealed entry.
52/// Key names and expired unsealed entries are ignored on purpose.
53pub(crate) fn sign_in_ready_from_page(value: &Value) -> bool {
54 value
55 .get("freshAccess")
56 .and_then(Value::as_bool)
57 .unwrap_or(false)
58}
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63 use serde_json::json;
64
65 #[test]
66 fn key_names_without_a_usable_token_are_not_ready() {
67 let report = json!({"opened": 0, "freshAccess": false, "keyNames": true});
68 assert!(!sign_in_ready_from_page(&report));
69 }
70
71 #[test]
72 fn opened_sealed_entries_without_a_fresh_access_token_are_not_ready() {
73 assert!(!sign_in_ready_from_page(
74 &json!({"opened": 3, "freshAccess": false})
75 ));
76 }
77
78 #[test]
79 fn a_fresh_access_token_is_ready_plain_or_sealed() {
80 assert!(sign_in_ready_from_page(
81 &json!({"opened": 0, "freshAccess": true})
82 ));
83 assert!(sign_in_ready_from_page(
84 &json!({"opened": 2, "freshAccess": true})
85 ));
86 }
87
88 #[test]
89 fn a_missing_report_is_not_ready() {
90 assert!(!sign_in_ready_from_page(&json!({})));
91 assert!(!sign_in_ready_from_page(&json!(null)));
92 }
93}