fix(auth): Windows keeps the MSAL cache key across restarts (#152)
@@ -188,6 +188,7 @@ async fn supervise(
188
188
}
189
189
};
190
190
tokio::spawn(org_list(home.clone(), guest_tenant.clone(), events.clone()));
191
tokio::spawn(msal_key_loop(home.clone()));
191
192
// Calls stay on the home tenant's registration, like rings for the home org while a guest org is open.
192
193
// Chat files of a guest org go to the home OneDrive: the guest tenant has none.
193
194
let (session, home_drive) = match &guest_tenant {
@@ -240,6 +241,39 @@ async fn supervise(
240
241
refresh_loop(engine, events, nudges).await;
241
242
}
242
243
244
/// Gives the MSAL cache key an expiry once the page is signed in, so the next start can read the
245
/// token cache. WebView2 drops session cookies with the process just like Chromium does. One
246
/// success is enough: the expiry is renewed on the next start, and repeated CDP calls would wake a
247
/// parked WebView2.
248
async fn msal_key_loop(session: Session) {
249
if !session.can_persist_msal_key() {
250
return;
251
}
252
let mut wait = Duration::from_secs(5);
253
loop {
254
tokio::time::sleep(wait).await;
255
let outcome =
256
tokio::time::timeout(Duration::from_secs(10), session.persist_msal_key()).await;
257
match outcome {
258
Ok(Ok(true)) => {
259
crate::diagnostics::record("msal: key cookie persisted");
260
return;
261
}
262
Ok(Ok(false)) => {
263
wait = (wait * 2).min(Duration::from_secs(300));
264
}
265
Ok(Err(error)) => {
266
crate::diagnostics::record(format!("msal: key cookie not persisted: {error}"));
267
wait = (wait * 2).min(Duration::from_secs(300));
268
}
269
Err(_) => {
270
crate::diagnostics::record("msal: key cookie persistence timed out");
271
wait = (wait * 2).min(Duration::from_secs(300));
272
}
273
}
274
}
275
}
276
243
277
/// Fetches the account's organizations once per start, retried a few times while sign-in settles,
244
278
/// and keeps every org that is not open live for notifications.
245
279
async fn org_list(home: Session, open_guest: Option<String>, events: EventSender) {
@@ -352,6 +386,7 @@ async fn realtime_loop(
352
386
let _ = events.send(BackendEvent::Live(LiveState::Connecting));
353
387
let config = RealtimeConfig {
354
388
initially_active: *activity.borrow(),
389
retry: Some(live_retry.clone()),
355
390
..RealtimeConfig::default()
356
391
};
357
392
match Realtime::start_with(&session, config).await {
@@ -398,6 +433,12 @@ async fn realtime_loop(
398
433
let _ = events.send(BackendEvent::Typing(typing));
399
434
}
400
435
RealtimeEvent::Status(status) => {
436
if status.kind != StatusKind::Connected {
437
crate::diagnostics::record(format!(
438
"live: {:?} {}",
439
status.kind, status.detail
440
));
441
}
401
442
let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));
402
443
if let Some(signal) = link_signal_for(status.kind) {
403
444
let _ = link.send(signal);
@@ -425,7 +466,8 @@ async fn realtime_loop(
425
466
let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));
426
467
let _ = link.send(LinkSignal::Disconnected);
427
468
}
428
Err(_) => {
469
Err(error) => {
470
crate::diagnostics::record(format!("live: start failed: {error}"));
429
471
let _ = events.send(BackendEvent::Live(LiveState::Failed));
430
472
let _ = link.send(LinkSignal::Disconnected);
431
473
}
@@ -188,6 +188,7 @@ async fn supervise(188
}188
}189
};189
};190
tokio::spawn(org_list(home.clone(), guest_tenant.clone(), events.clone()));190
tokio::spawn(org_list(home.clone(), guest_tenant.clone(), events.clone()));191
tokio::spawn(msal_key_loop(home.clone()));191
// Calls stay on the home tenant's registration, like rings for the home org while a guest org is open.192
// Calls stay on the home tenant's registration, like rings for the home org while a guest org is open.192
// Chat files of a guest org go to the home OneDrive: the guest tenant has none.193
// Chat files of a guest org go to the home OneDrive: the guest tenant has none.193
let (session, home_drive) = match &guest_tenant {194
let (session, home_drive) = match &guest_tenant {@@ -240,6 +241,39 @@ async fn supervise(240
refresh_loop(engine, events, nudges).await;241
refresh_loop(engine, events, nudges).await;241
}242
}242
243
244
/// Gives the MSAL cache key an expiry once the page is signed in, so the next start can read the245
/// token cache. WebView2 drops session cookies with the process just like Chromium does. One246
/// success is enough: the expiry is renewed on the next start, and repeated CDP calls would wake a247
/// parked WebView2.248
async fn msal_key_loop(session: Session) {249
if !session.can_persist_msal_key() {250
return;251
}252
let mut wait = Duration::from_secs(5);253
loop {254
tokio::time::sleep(wait).await;255
let outcome =256
tokio::time::timeout(Duration::from_secs(10), session.persist_msal_key()).await;257
match outcome {258
Ok(Ok(true)) => {259
crate::diagnostics::record("msal: key cookie persisted");260
return;261
}262
Ok(Ok(false)) => {263
wait = (wait * 2).min(Duration::from_secs(300));264
}265
Ok(Err(error)) => {266
crate::diagnostics::record(format!("msal: key cookie not persisted: {error}"));267
wait = (wait * 2).min(Duration::from_secs(300));268
}269
Err(_) => {270
crate::diagnostics::record("msal: key cookie persistence timed out");271
wait = (wait * 2).min(Duration::from_secs(300));272
}273
}274
}275
}276
243
/// Fetches the account's organizations once per start, retried a few times while sign-in settles,277
/// Fetches the account's organizations once per start, retried a few times while sign-in settles,244
/// and keeps every org that is not open live for notifications.278
/// and keeps every org that is not open live for notifications.245
async fn org_list(home: Session, open_guest: Option<String>, events: EventSender) {279
async fn org_list(home: Session, open_guest: Option<String>, events: EventSender) {@@ -352,6 +386,7 @@ async fn realtime_loop(352
let _ = events.send(BackendEvent::Live(LiveState::Connecting));386
let _ = events.send(BackendEvent::Live(LiveState::Connecting));353
let config = RealtimeConfig {387
let config = RealtimeConfig {354
initially_active: *activity.borrow(),388
initially_active: *activity.borrow(),389
retry: Some(live_retry.clone()),355
..RealtimeConfig::default()390
..RealtimeConfig::default()356
};391
};357
match Realtime::start_with(&session, config).await {392
match Realtime::start_with(&session, config).await {@@ -398,6 +433,12 @@ async fn realtime_loop(398
let _ = events.send(BackendEvent::Typing(typing));433
let _ = events.send(BackendEvent::Typing(typing));399
}434
}400
RealtimeEvent::Status(status) => {435
RealtimeEvent::Status(status) => {436
if status.kind != StatusKind::Connected {437
crate::diagnostics::record(format!(438
"live: {:?} {}",439
status.kind, status.detail440
));441
}401
let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));442
let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));402
if let Some(signal) = link_signal_for(status.kind) {443
if let Some(signal) = link_signal_for(status.kind) {403
let _ = link.send(signal);444
let _ = link.send(signal);@@ -425,7 +466,8 @@ async fn realtime_loop(425
let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));466
let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));426
let _ = link.send(LinkSignal::Disconnected);467
let _ = link.send(LinkSignal::Disconnected);427
}468
}428
Err(_) => {469
Err(error) => {470
crate::diagnostics::record(format!("live: start failed: {error}"));429
let _ = events.send(BackendEvent::Live(LiveState::Failed));471
let _ = events.send(BackendEvent::Live(LiveState::Failed));430
let _ = link.send(LinkSignal::Disconnected);472
let _ = link.send(LinkSignal::Disconnected);431
}473
}@@ -67,7 +67,10 @@ pub fn banner_text(kind: BannerKind, last_sync: Option<DateTime<Utc>>) -> Banner
67
67
};
68
68
match kind {
69
69
BannerKind::Connecting => text("auth.banner.connecting"),
70
BannerKind::Reconnecting => text("auth.banner.reconnecting"),
70
BannerKind::Reconnecting => BannerText {
71
action: Some(app_base::ui_locale::tr("common.retry")),
72
..text("auth.banner.reconnecting")
73
},
71
74
BannerKind::Offline => BannerText {
72
75
detail: last_sync.map(|time| {
73
76
app_base::ui_locale::tr("auth.banner.last_synced").replace(
@@ -81,6 +84,7 @@ pub fn banner_text(kind: BannerKind, last_sync: Option<DateTime<Utc>>) -> Banner
81
84
..text("auth.banner.offline")
82
85
},
83
86
BannerKind::SignIn => {
87
#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(unused_mut))]
84
88
let mut banner = text("auth.banner.sign_in");
85
89
// Windows signs in through the embedded view. The managed window exists
86
90
// only on Linux and macOS, so other platforms get no button.
@@ -311,6 +315,7 @@ mod tests {
311
315
.action
312
316
.is_some()
313
317
);
318
assert!(banner_text(BannerKind::Reconnecting, None).action.is_some());
314
319
#[cfg(any(target_os = "linux", target_os = "macos"))]
315
320
assert!(banner_text(BannerKind::SignIn, None).action.is_some());
316
321
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
@@ -67,7 +67,10 @@ pub fn banner_text(kind: BannerKind, last_sync: Option<DateTime<Utc>>) -> Banner67
};67
};68
match kind {68
match kind {69
BannerKind::Connecting => text("auth.banner.connecting"),69
BannerKind::Connecting => text("auth.banner.connecting"),70
BannerKind::Reconnecting => text("auth.banner.reconnecting"),70
BannerKind::Reconnecting => BannerText {71
action: Some(app_base::ui_locale::tr("common.retry")),72
..text("auth.banner.reconnecting")73
},71
BannerKind::Offline => BannerText {74
BannerKind::Offline => BannerText {72
detail: last_sync.map(|time| {75
detail: last_sync.map(|time| {73
app_base::ui_locale::tr("auth.banner.last_synced").replace(76
app_base::ui_locale::tr("auth.banner.last_synced").replace(@@ -81,6 +84,7 @@ pub fn banner_text(kind: BannerKind, last_sync: Option<DateTime<Utc>>) -> Banner81
..text("auth.banner.offline")84
..text("auth.banner.offline")82
},85
},83
BannerKind::SignIn => {86
BannerKind::SignIn => {87
#[cfg_attr(not(any(target_os = "linux", target_os = "macos")), allow(unused_mut))]84
let mut banner = text("auth.banner.sign_in");88
let mut banner = text("auth.banner.sign_in");85
// Windows signs in through the embedded view. The managed window exists89
// Windows signs in through the embedded view. The managed window exists86
// only on Linux and macOS, so other platforms get no button.90
// only on Linux and macOS, so other platforms get no button.@@ -311,6 +315,7 @@ mod tests {311
.action315
.action312
.is_some()316
.is_some()313
);317
);318
assert!(banner_text(BannerKind::Reconnecting, None).action.is_some());314
#[cfg(any(target_os = "linux", target_os = "macos"))]319
#[cfg(any(target_os = "linux", target_os = "macos"))]315
assert!(banner_text(BannerKind::SignIn, None).action.is_some());320
assert!(banner_text(BannerKind::SignIn, None).action.is_some());316
#[cfg(not(any(target_os = "linux", target_os = "macos")))]321
#[cfg(not(any(target_os = "linux", target_os = "macos")))]@@ -67,6 +67,10 @@ fn protocol(error: BrowserError) -> Error {
67
67
}
68
68
69
69
impl Transport for BidiTransport {
70
fn supports_cdp(&self) -> bool {
71
false
72
}
73
70
74
fn check(&self) -> BoxFuture<'_, Result<()>> {
71
75
Box::pin(async move { self.contexts().await.map(drop) })
72
76
}
@@ -67,6 +67,10 @@ fn protocol(error: BrowserError) -> Error {67
}67
}68
68
69
impl Transport for BidiTransport {69
impl Transport for BidiTransport {70
fn supports_cdp(&self) -> bool {71
false72
}73
70
fn check(&self) -> BoxFuture<'_, Result<()>> {74
fn check(&self) -> BoxFuture<'_, Result<()>> {71
Box::pin(async move { self.contexts().await.map(drop) })75
Box::pin(async move { self.contexts().await.map(drop) })72
}76
}@@ -626,7 +626,7 @@ async fn keep_msal_cache_key(websocket_url: &str) {
626
626
.map_or(0, |elapsed| elapsed.as_secs());
627
627
let outcome = async {
628
628
let cookies = cdp_call(websocket_url, "Storage.getCookies", json!({}), CDP_TIMEOUT).await?;
629
let Some(params) = crate::msal_key::persisted_key_cookies(&cookies, now_secs) else {
629
let Some(params) = session::msal_key::persisted_key_cookies(&cookies, now_secs) else {
630
630
return Ok(());
631
631
};
632
632
cdp_call(websocket_url, "Storage.setCookies", params, CDP_TIMEOUT)
@@ -626,7 +626,7 @@ async fn keep_msal_cache_key(websocket_url: &str) {626
.map_or(0, |elapsed| elapsed.as_secs());626
.map_or(0, |elapsed| elapsed.as_secs());627
let outcome = async {627
let outcome = async {628
let cookies = cdp_call(websocket_url, "Storage.getCookies", json!({}), CDP_TIMEOUT).await?;628
let cookies = cdp_call(websocket_url, "Storage.getCookies", json!({}), CDP_TIMEOUT).await?;629
let Some(params) = crate::msal_key::persisted_key_cookies(&cookies, now_secs) else {629
let Some(params) = session::msal_key::persisted_key_cookies(&cookies, now_secs) else {630
return Ok(());630
return Ok(());631
};631
};632
cdp_call(websocket_url, "Storage.setCookies", params, CDP_TIMEOUT)632
cdp_call(websocket_url, "Storage.setCookies", params, CDP_TIMEOUT)@@ -6,7 +6,6 @@ mod error;
6
6
mod host;
7
7
mod http;
8
8
mod launch;
9
mod msal_key;
10
9
mod process;
11
10
mod sign_in_choice;
12
11
mod sign_in_ready;
@@ -6,7 +6,6 @@ mod error;6
mod host;6
mod host;7
mod http;7
mod http;8
mod launch;8
mod launch;9
mod msal_key;10
mod process;9
mod process;11
mod sign_in_choice;10
mod sign_in_choice;12
mod sign_in_ready;11
mod sign_in_ready;@@ -40,6 +40,8 @@ pub struct RealtimeConfig {
40
40
pub ringable: bool,
41
41
pub initially_active: bool,
42
42
pub native: bool,
43
/// Wakes the native reconnect backoff early, e.g. from the banner's Retry action.
44
pub retry: Option<Arc<Notify>>,
43
45
}
44
46
45
47
/// Page globals of one Trouter client; a second client in the same tab needs its own names.
@@ -74,6 +76,7 @@ impl Default for RealtimeConfig {
74
76
ringable: false,
75
77
initially_active: false,
76
78
native: std::env::var_os("TEAMS_PAGE_TROUTER").is_none(),
79
retry: None,
77
80
}
78
81
}
79
82
}
@@ -40,6 +40,8 @@ pub struct RealtimeConfig {40
pub ringable: bool,40
pub ringable: bool,41
pub initially_active: bool,41
pub initially_active: bool,42
pub native: bool,42
pub native: bool,43
/// Wakes the native reconnect backoff early, e.g. from the banner's Retry action.44
pub retry: Option<Arc<Notify>>,43
}45
}44
46
45
/// Page globals of one Trouter client; a second client in the same tab needs its own names.47
/// Page globals of one Trouter client; a second client in the same tab needs its own names.@@ -74,6 +76,7 @@ impl Default for RealtimeConfig {74
ringable: false,76
ringable: false,75
initially_active: false,77
initially_active: false,76
native: std::env::var_os("TEAMS_PAGE_TROUTER").is_none(),78
native: std::env::var_os("TEAMS_PAGE_TROUTER").is_none(),79
retry: None,77
}80
}78
}81
}79
}82
}@@ -322,6 +322,7 @@ pub(super) struct NativeTrouter {
322
322
pub endpoint_id: String,
323
323
force_refresh: bool,
324
324
retry: u32,
325
retry_signal: Option<Arc<Notify>>,
325
326
ack_counter: u64,
326
327
surl: String,
327
328
registered_at: Option<Instant>,
@@ -353,6 +354,7 @@ impl NativeTrouter {
353
354
activity: watch::Receiver<bool>,
354
355
resend: Arc<Notify>,
355
356
) -> Self {
357
let retry_signal = config.retry.clone();
356
358
NativeTrouter {
357
359
session,
358
360
config,
@@ -364,6 +366,7 @@ impl NativeTrouter {
364
366
endpoint_id: uuid::Uuid::new_v4().to_string(),
365
367
force_refresh: false,
366
368
retry: 0,
369
retry_signal,
367
370
ack_counter: 0,
368
371
surl: String::new(),
369
372
registered_at: None,
@@ -389,6 +392,7 @@ impl NativeTrouter {
389
392
}
390
393
391
394
pub(super) async fn run(mut self, mut stop: oneshot::Receiver<oneshot::Sender<()>>) {
395
let retry_signal = self.retry_signal.clone();
392
396
loop {
393
397
let connected = tokio::select! {
394
398
connected = self.connect() => connected,
@@ -422,6 +426,12 @@ impl NativeTrouter {
422
426
}
423
427
return;
424
428
}
429
_ = async {
430
match &retry_signal {
431
Some(signal) => signal.notified().await,
432
None => std::future::pending().await,
433
}
434
} => self.retry = 0,
425
435
_ = self.output.closed() => return,
426
436
}
427
437
}
@@ -322,6 +322,7 @@ pub(super) struct NativeTrouter {322
pub endpoint_id: String,322
pub endpoint_id: String,323
force_refresh: bool,323
force_refresh: bool,324
retry: u32,324
retry: u32,325
retry_signal: Option<Arc<Notify>>,325
ack_counter: u64,326
ack_counter: u64,326
surl: String,327
surl: String,327
registered_at: Option<Instant>,328
registered_at: Option<Instant>,@@ -353,6 +354,7 @@ impl NativeTrouter {353
activity: watch::Receiver<bool>,354
activity: watch::Receiver<bool>,354
resend: Arc<Notify>,355
resend: Arc<Notify>,355
) -> Self {356
) -> Self {357
let retry_signal = config.retry.clone();356
NativeTrouter {358
NativeTrouter {357
session,359
session,358
config,360
config,@@ -364,6 +366,7 @@ impl NativeTrouter {364
endpoint_id: uuid::Uuid::new_v4().to_string(),366
endpoint_id: uuid::Uuid::new_v4().to_string(),365
force_refresh: false,367
force_refresh: false,366
retry: 0,368
retry: 0,369
retry_signal,367
ack_counter: 0,370
ack_counter: 0,368
surl: String::new(),371
surl: String::new(),369
registered_at: None,372
registered_at: None,@@ -389,6 +392,7 @@ impl NativeTrouter {389
}392
}390
393
391
pub(super) async fn run(mut self, mut stop: oneshot::Receiver<oneshot::Sender<()>>) {394
pub(super) async fn run(mut self, mut stop: oneshot::Receiver<oneshot::Sender<()>>) {395
let retry_signal = self.retry_signal.clone();392
loop {396
loop {393
let connected = tokio::select! {397
let connected = tokio::select! {394
connected = self.connect() => connected,398
connected = self.connect() => connected,@@ -422,6 +426,12 @@ impl NativeTrouter {422
}426
}423
return;427
return;424
}428
}429
_ = async {430
match &retry_signal {431
Some(signal) => signal.notified().await,432
None => std::future::pending().await,433
}434
} => self.retry = 0,425
_ = self.output.closed() => return,435
_ = self.output.closed() => return,426
}436
}427
}437
}@@ -193,6 +193,7 @@ impl Runner {
193
193
) {
194
194
let mut attached = Some(first);
195
195
let mut backoff = Duration::from_secs(1);
196
let retry_signal = self.config.retry.clone();
196
197
loop {
197
198
let current = match attached.take() {
198
199
Some(current) => current,
@@ -207,6 +208,12 @@ impl Runner {
207
208
_ = sleep(backoff) => {}
208
209
_ = &mut stop => return,
209
210
_ = self.output.closed() => return,
211
_ = async {
212
match &retry_signal {
213
Some(signal) => signal.notified().await,
214
None => std::future::pending().await,
215
}
216
} => backoff = Duration::from_millis(500),
210
217
}
211
218
backoff = (backoff * 2).min(self.config.max_reattach_backoff);
212
219
continue;
@@ -193,6 +193,7 @@ impl Runner {193
) {193
) {194
let mut attached = Some(first);194
let mut attached = Some(first);195
let mut backoff = Duration::from_secs(1);195
let mut backoff = Duration::from_secs(1);196
let retry_signal = self.config.retry.clone();196
loop {197
loop {197
let current = match attached.take() {198
let current = match attached.take() {198
Some(current) => current,199
Some(current) => current,@@ -207,6 +208,12 @@ impl Runner {207
_ = sleep(backoff) => {}208
_ = sleep(backoff) => {}208
_ = &mut stop => return,209
_ = &mut stop => return,209
_ = self.output.closed() => return,210
_ = self.output.closed() => return,211
_ = async {212
match &retry_signal {213
Some(signal) => signal.notified().await,214
None => std::future::pending().await,215
}216
} => backoff = Duration::from_millis(500),210
}217
}211
backoff = (backoff * 2).min(self.config.max_reattach_backoff);218
backoff = (backoff * 2).min(self.config.max_reattach_backoff);212
continue;219
continue;@@ -2,6 +2,7 @@ mod app;
2
2
mod error;
3
3
mod events;
4
4
mod http;
5
pub mod msal_key;
5
6
mod native;
6
7
mod page_script;
7
8
mod request;
@@ -2,6 +2,7 @@ mod app;2
mod error;2
mod error;3
mod events;3
mod events;4
mod http;4
mod http;5
pub mod msal_key;5
mod native;6
mod native;6
mod page_script;7
mod page_script;7
mod request;8
mod request;@@ -1,19 +1,21 @@
1
//! Keeps the key of the Teams token cache across browser restarts (issue #84).
1
//! Keeps the key of the Teams token cache across app restarts (issue #84).
2
2
//!
3
3
//! MSAL.js encrypts its localStorage cache with a key held in the session cookie
4
//! `msal.cache.encryption`. A session cookie dies with the process, so every restart (headless
5
//! hand-over, login window, hung renderer, app exit) made MSAL create a new key, drop the cache
6
//! and ask for sign-in again. Before Chromium stops, the cookie gets an expiry instead; the key
7
//! then sits in the profile next to the cache it protects, which the profile already holds.
4
//! `msal.cache.encryption`. A session cookie dies with the page, so every restart made MSAL create
5
//! a new key, drop the cache and ask for sign-in again. While the page is signed in, the cookie
6
//! gets an expiry instead; the key then sits in the profile next to the cache it protects, which
7
//! the profile already holds. The managed Chromium path also does this once more on a graceful
8
//! stop as a second chance.
8
9
//!
9
10
//! Trade-off: the key moves from a session cookie into the profile's cookie store, encrypted by
10
//! the OS keyring (or Chromium's fixed key where no keyring is available). The profile already
11
//! the OS keyring (or the browser's fixed key where no keyring is available). The profile already
11
12
//! holds the equally powerful ESTS cookies that keep the session alive, so this is a conscious
12
13
//! choice, not a new credential at rest.
13
14
14
use serde_json::{Map, Value, json};
15
15
use std::collections::HashSet;
16
16
17
use serde_json::{Map, Value, json};
18
17
19
/// The cookie MSAL.js reads its cache encryption key from; only its name and value matter to it.
18
20
const MSAL_KEY_COOKIE: &str = "msal.cache.encryption";
19
21
/// How long the key outlives the last stop; every stop renews the expiry. 90 days is the chosen
@@ -37,7 +39,7 @@ const CARRIED_FIELDS: [&str; 10] = [
37
39
/// `Storage.setCookies` parameters for the current MSAL key cookies. Duplicates by
38
40
/// `(domain, path, partitionKey)` are collapsed, preferring host-only cookies over stale domain
39
41
/// cookies that could otherwise shadow the active key.
40
pub(crate) fn persisted_key_cookies(get_cookies: &Value, now_secs: u64) -> Option<Value> {
42
pub fn persisted_key_cookies(get_cookies: &Value, now_secs: u64) -> Option<Value> {
41
43
let expires = now_secs + KEY_LIFETIME_SECS;
42
44
let mut candidates: Vec<&Value> = get_cookies["cookies"]
43
45
.as_array()?
@@ -1,19 +1,21 @@1
//! Keeps the key of the Teams token cache across browser restarts (issue #84).1
//! Keeps the key of the Teams token cache across app restarts (issue #84).2
//!2
//!3
//! MSAL.js encrypts its localStorage cache with a key held in the session cookie3
//! MSAL.js encrypts its localStorage cache with a key held in the session cookie4
//! `msal.cache.encryption`. A session cookie dies with the process, so every restart (headless4
//! `msal.cache.encryption`. A session cookie dies with the page, so every restart made MSAL create5
//! hand-over, login window, hung renderer, app exit) made MSAL create a new key, drop the cache5
//! a new key, drop the cache and ask for sign-in again. While the page is signed in, the cookie6
//! and ask for sign-in again. Before Chromium stops, the cookie gets an expiry instead; the key6
//! gets an expiry instead; the key then sits in the profile next to the cache it protects, which7
//! then sits in the profile next to the cache it protects, which the profile already holds.7
//! the profile already holds. The managed Chromium path also does this once more on a graceful8
//! stop as a second chance.8
//!9
//!9
//! Trade-off: the key moves from a session cookie into the profile's cookie store, encrypted by10
//! Trade-off: the key moves from a session cookie into the profile's cookie store, encrypted by10
//! the OS keyring (or Chromium's fixed key where no keyring is available). The profile already11
//! the OS keyring (or the browser's fixed key where no keyring is available). The profile already11
//! holds the equally powerful ESTS cookies that keep the session alive, so this is a conscious12
//! holds the equally powerful ESTS cookies that keep the session alive, so this is a conscious12
//! choice, not a new credential at rest.13
//! choice, not a new credential at rest.13
14
14
use serde_json::{Map, Value, json};15
use std::collections::HashSet;15
use std::collections::HashSet;16
16
17
use serde_json::{Map, Value, json};18
17
/// The cookie MSAL.js reads its cache encryption key from; only its name and value matter to it.19
/// The cookie MSAL.js reads its cache encryption key from; only its name and value matter to it.18
const MSAL_KEY_COOKIE: &str = "msal.cache.encryption";20
const MSAL_KEY_COOKIE: &str = "msal.cache.encryption";19
/// How long the key outlives the last stop; every stop renews the expiry. 90 days is the chosen21
/// How long the key outlives the last stop; every stop renews the expiry. 90 days is the chosen@@ -37,7 +39,7 @@ const CARRIED_FIELDS: [&str; 10] = [37
/// `Storage.setCookies` parameters for the current MSAL key cookies. Duplicates by39
/// `Storage.setCookies` parameters for the current MSAL key cookies. Duplicates by38
/// `(domain, path, partitionKey)` are collapsed, preferring host-only cookies over stale domain40
/// `(domain, path, partitionKey)` are collapsed, preferring host-only cookies over stale domain39
/// cookies that could otherwise shadow the active key.41
/// cookies that could otherwise shadow the active key.40
pub(crate) fn persisted_key_cookies(get_cookies: &Value, now_secs: u64) -> Option<Value> {42
pub fn persisted_key_cookies(get_cookies: &Value, now_secs: u64) -> Option<Value> {41
let expires = now_secs + KEY_LIFETIME_SECS;43
let expires = now_secs + KEY_LIFETIME_SECS;42
let mut candidates: Vec<&Value> = get_cookies["cookies"]44
let mut candidates: Vec<&Value> = get_cookies["cookies"]43
.as_array()?45
.as_array()?@@ -334,6 +334,60 @@ impl Session {
334
334
.to_string()
335
335
}
336
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
337
391
pub(crate) async fn evaluate_in(&self, app: App, expression: &str) -> Result<Option<Value>> {
338
392
let mut slot = self.tabs[&app].lock().await;
339
393
if slot.is_none() {
@@ -334,6 +334,60 @@ impl Session {334
.to_string()334
.to_string()335
}335
}336
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 token365
/// 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) = self374
.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(_) = self383
.cdp_in(App::Teams, "Storage.setCookies", params)384
.await?385
else {386
return Ok(false);387
};388
Ok(true)389
}390
337
pub(crate) async fn evaluate_in(&self, app: App, expression: &str) -> Result<Option<Value>> {391
pub(crate) async fn evaluate_in(&self, app: App, expression: &str) -> Result<Option<Value>> {338
let mut slot = self.tabs[&app].lock().await;392
let mut slot = self.tabs[&app].lock().await;339
if slot.is_none() {393
if slot.is_none() {@@ -29,6 +29,12 @@ pub trait Transport: Send + Sync {
29
29
30
30
fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>>;
31
31
32
/// Whether the transport accepts raw CDP methods. WebDriver BiDi does not, so session-level
33
/// CDP work such as the MSAL cookie must stay off it.
34
fn supports_cdp(&self) -> bool {
35
true
36
}
37
32
38
/// While held the host must not navigate the app on its own (no parking).
33
39
fn hold(&self, _app: App, _held: bool) {}
34
40
}
@@ -29,6 +29,12 @@ pub trait Transport: Send + Sync {29
29
30
fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>>;30
fn diagnose(&self) -> BoxFuture<'_, Result<Diagnosis>>;31
31
32
/// Whether the transport accepts raw CDP methods. WebDriver BiDi does not, so session-level33
/// CDP work such as the MSAL cookie must stay off it.34
fn supports_cdp(&self) -> bool {35
true36
}37
32
/// While held the host must not navigate the app on its own (no parking).38
/// While held the host must not navigate the app on its own (no parking).33
fn hold(&self, _app: App, _held: bool) {}39
fn hold(&self, _app: App, _held: bool) {}34
}40
}