fix(browser): keep the MSAL cache key across Chromium restarts (#123)
@@ -1103,6 +1103,7 @@ version = "0.6.1"
1103
1103
dependencies = [
1104
1104
"directories",
1105
1105
"futures-util",
1106
"log",
1106
1107
"serde",
1107
1108
"serde_json",
1108
1109
"session",
@@ -1103,6 +1103,7 @@ version = "0.6.1"1103
dependencies = [1103
dependencies = [1104
"directories",1104
"directories",1105
"futures-util",1105
"futures-util",1106
"log",1106
"serde",1107
"serde",1107
"serde_json",1108
"serde_json",1108
"session",1109
"session",@@ -15,7 +15,8 @@ const POLL_STEP: Duration = Duration::from_millis(100);
15
15
const CHECK_WAIT: Duration = Duration::from_millis(250);
16
16
const HIDE_POLL: Duration = Duration::from_millis(500);
17
17
const HIDE_STABLE_CHECKS: u32 = 4;
18
const STOP_TIMEOUT: Duration = Duration::from_secs(2);
18
// MSAL key budget (500 ms) + CDP close (up to 3 s) + profile release (2 s) must fit.
19
const STOP_TIMEOUT: Duration = Duration::from_secs(6);
19
20
20
21
static LINUX_BROWSER: OnceLock<browser::Browser> = OnceLock::new();
21
22
static LIVE_RETRY: OnceLock<Mutex<Option<Arc<Notify>>>> = OnceLock::new();
@@ -540,4 +541,11 @@ mod tests {
540
541
assert!(!tracker.step(Some(&stuck_login), true));
541
542
}
542
543
}
544
545
#[test]
546
fn stop_timeout_covers_browser_shutdown() {
547
let timeouts = browser::Timeouts::default();
548
let worst_case = timeouts.msal_key + timeouts.profile_release + Duration::from_secs(3);
549
assert!(STOP_TIMEOUT >= worst_case);
550
}
543
551
}
@@ -15,7 +15,8 @@ const POLL_STEP: Duration = Duration::from_millis(100);15
const CHECK_WAIT: Duration = Duration::from_millis(250);15
const CHECK_WAIT: Duration = Duration::from_millis(250);16
const HIDE_POLL: Duration = Duration::from_millis(500);16
const HIDE_POLL: Duration = Duration::from_millis(500);17
const HIDE_STABLE_CHECKS: u32 = 4;17
const HIDE_STABLE_CHECKS: u32 = 4;18
const STOP_TIMEOUT: Duration = Duration::from_secs(2);18
// MSAL key budget (500 ms) + CDP close (up to 3 s) + profile release (2 s) must fit.19
const STOP_TIMEOUT: Duration = Duration::from_secs(6);19
20
20
static LINUX_BROWSER: OnceLock<browser::Browser> = OnceLock::new();21
static LINUX_BROWSER: OnceLock<browser::Browser> = OnceLock::new();21
static LIVE_RETRY: OnceLock<Mutex<Option<Arc<Notify>>>> = OnceLock::new();22
static LIVE_RETRY: OnceLock<Mutex<Option<Arc<Notify>>>> = OnceLock::new();@@ -540,4 +541,11 @@ mod tests {540
assert!(!tracker.step(Some(&stuck_login), true));541
assert!(!tracker.step(Some(&stuck_login), true));541
}542
}542
}543
}544
545
#[test]546
fn stop_timeout_covers_browser_shutdown() {547
let timeouts = browser::Timeouts::default();548
let worst_case = timeouts.msal_key + timeouts.profile_release + Duration::from_secs(3);549
assert!(STOP_TIMEOUT >= worst_case);550
}543
}551
}@@ -9,6 +9,7 @@ publish.workspace = true
9
9
directories.workspace = true
10
10
futures-util.workspace = true
11
11
serde.workspace = true
12
log = "0.4"
12
13
serde_json.workspace = true
13
14
session.workspace = true
14
15
thiserror.workspace = true
@@ -9,6 +9,7 @@ publish.workspace = true9
directories.workspace = true9
directories.workspace = true10
futures-util.workspace = true10
futures-util.workspace = true11
serde.workspace = true11
serde.workspace = true12
log = "0.4"12
serde_json.workspace = true13
serde_json.workspace = true13
session.workspace = true14
session.workspace = true14
thiserror.workspace = true15
thiserror.workspace = true@@ -51,6 +51,7 @@ pub struct Timeouts {
51
51
pub probe: Duration,
52
52
pub poll: Duration,
53
53
pub profile_release: Duration,
54
pub msal_key: Duration,
54
55
pub jitter_min: Duration,
55
56
pub jitter_max: Duration,
56
57
}
@@ -62,6 +63,7 @@ impl Default for Timeouts {
62
63
stop: Duration::from_secs(15),
63
64
probe: Duration::from_secs(5),
64
65
poll: Duration::from_millis(250),
66
msal_key: Duration::from_millis(500),
65
67
profile_release: Duration::from_secs(2),
66
68
jitter_min: Duration::ZERO,
67
69
jitter_max: Duration::ZERO,
@@ -501,6 +503,12 @@ impl Browser {
501
503
let port = self.inner.config.port;
502
504
let _ = tokio::task::spawn_blocking(move || launcher.terminate_listener(port)).await;
503
505
} else if let Some(info) = self.version().await {
506
let budget = self.inner.timeouts.msal_key;
507
if let Err(error) =
508
tokio::time::timeout(budget, keep_msal_cache_key(&info.websocket_url)).await
509
{
510
log::warn!("MSAL cache key not kept within the {budget:?} stop budget: {error}");
511
}
504
512
close_over_cdp(&info.websocket_url).await;
505
513
}
506
514
}
@@ -571,6 +579,27 @@ async fn cdp_call(
571
579
.map_err(|_| BrowserError::Cdp(format!("{method} timed out")))?
572
580
}
573
581
582
/// Gives MSAL's session-cookie cache key an expiry so the next start can still read the token
583
/// cache (#84). Best effort: a failure only means one more sign-in, so it is logged and the stop goes on.
584
async fn keep_msal_cache_key(websocket_url: &str) {
585
let now_secs = std::time::SystemTime::now()
586
.duration_since(std::time::UNIX_EPOCH)
587
.map_or(0, |elapsed| elapsed.as_secs());
588
let outcome = async {
589
let cookies = cdp_call(websocket_url, "Storage.getCookies", json!({}), CDP_TIMEOUT).await?;
590
let Some(params) = crate::msal_key::persisted_key_cookies(&cookies, now_secs) else {
591
return Ok(());
592
};
593
cdp_call(websocket_url, "Storage.setCookies", params, CDP_TIMEOUT)
594
.await
595
.map(|_| ())
596
}
597
.await;
598
if let Err(error) = outcome {
599
log::warn!("MSAL cache key not kept across the restart: {error}");
600
}
601
}
602
574
603
async fn close_over_cdp(websocket_url: &str) {
575
604
let Ok(Ok((mut socket, _))) = tokio::time::timeout(
576
605
Duration::from_secs(3),
@@ -51,6 +51,7 @@ pub struct Timeouts {51
pub probe: Duration,51
pub probe: Duration,52
pub poll: Duration,52
pub poll: Duration,53
pub profile_release: Duration,53
pub profile_release: Duration,54
pub msal_key: Duration,54
pub jitter_min: Duration,55
pub jitter_min: Duration,55
pub jitter_max: Duration,56
pub jitter_max: Duration,56
}57
}@@ -62,6 +63,7 @@ impl Default for Timeouts {62
stop: Duration::from_secs(15),63
stop: Duration::from_secs(15),63
probe: Duration::from_secs(5),64
probe: Duration::from_secs(5),64
poll: Duration::from_millis(250),65
poll: Duration::from_millis(250),66
msal_key: Duration::from_millis(500),65
profile_release: Duration::from_secs(2),67
profile_release: Duration::from_secs(2),66
jitter_min: Duration::ZERO,68
jitter_min: Duration::ZERO,67
jitter_max: Duration::ZERO,69
jitter_max: Duration::ZERO,@@ -501,6 +503,12 @@ impl Browser {501
let port = self.inner.config.port;503
let port = self.inner.config.port;502
let _ = tokio::task::spawn_blocking(move || launcher.terminate_listener(port)).await;504
let _ = tokio::task::spawn_blocking(move || launcher.terminate_listener(port)).await;503
} else if let Some(info) = self.version().await {505
} else if let Some(info) = self.version().await {506
let budget = self.inner.timeouts.msal_key;507
if let Err(error) =508
tokio::time::timeout(budget, keep_msal_cache_key(&info.websocket_url)).await509
{510
log::warn!("MSAL cache key not kept within the {budget:?} stop budget: {error}");511
}504
close_over_cdp(&info.websocket_url).await;512
close_over_cdp(&info.websocket_url).await;505
}513
}506
}514
}@@ -571,6 +579,27 @@ async fn cdp_call(571
.map_err(|_| BrowserError::Cdp(format!("{method} timed out")))?579
.map_err(|_| BrowserError::Cdp(format!("{method} timed out")))?572
}580
}573
581
582
/// Gives MSAL's session-cookie cache key an expiry so the next start can still read the token583
/// cache (#84). Best effort: a failure only means one more sign-in, so it is logged and the stop goes on.584
async fn keep_msal_cache_key(websocket_url: &str) {585
let now_secs = std::time::SystemTime::now()586
.duration_since(std::time::UNIX_EPOCH)587
.map_or(0, |elapsed| elapsed.as_secs());588
let outcome = async {589
let cookies = cdp_call(websocket_url, "Storage.getCookies", json!({}), CDP_TIMEOUT).await?;590
let Some(params) = crate::msal_key::persisted_key_cookies(&cookies, now_secs) else {591
return Ok(());592
};593
cdp_call(websocket_url, "Storage.setCookies", params, CDP_TIMEOUT)594
.await595
.map(|_| ())596
}597
.await;598
if let Err(error) = outcome {599
log::warn!("MSAL cache key not kept across the restart: {error}");600
}601
}602
574
async fn close_over_cdp(websocket_url: &str) {603
async fn close_over_cdp(websocket_url: &str) {575
let Ok(Ok((mut socket, _))) = tokio::time::timeout(604
let Ok(Ok((mut socket, _))) = tokio::time::timeout(576
Duration::from_secs(3),605
Duration::from_secs(3),@@ -6,6 +6,7 @@ mod error;
6
6
mod host;
7
7
mod http;
8
8
mod launch;
9
mod msal_key;
9
10
mod process;
10
11
mod sign_in_choice;
11
12
mod targets;
@@ -6,6 +6,7 @@ mod error;6
mod host;6
mod host;7
mod http;7
mod http;8
mod launch;8
mod launch;9
mod msal_key;9
mod process;10
mod process;10
mod sign_in_choice;11
mod sign_in_choice;11
mod targets;12
mod targets;@@ -0,0 +1,202 @@
1
//! Keeps the key of the Teams token cache across browser restarts (issue #84).
2
//!
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.
8
//!
9
//! 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
//! holds the equally powerful ESTS cookies that keep the session alive, so this is a conscious
12
//! choice, not a new credential at rest.
13
14
use serde_json::{Map, Value, json};
15
use std::collections::HashSet;
16
17
/// 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";
19
/// How long the key outlives the last stop; every stop renews the expiry. 90 days is the chosen
20
/// value, not a refresh-token lifetime: Entra gives SPA clients refresh tokens valid for 24 hours,
21
/// and the long-lived session comes from the ESTS cookie, which enables silent token renewal.
22
const KEY_LIFETIME_SECS: u64 = 90 * 24 * 60 * 60;
23
/// `Network.Cookie` fields that `Network.CookieParam` takes unchanged (CDP browser_protocol.json).
24
const CARRIED_FIELDS: [&str; 10] = [
25
"name",
26
"value",
27
"path",
28
"secure",
29
"httpOnly",
30
"sameSite",
31
"priority",
32
"partitionKey",
33
"sourceScheme",
34
"sourcePort",
35
];
36
37
/// `Storage.setCookies` parameters for the current MSAL key cookies. Duplicates by
38
/// `(domain, path, partitionKey)` are collapsed, preferring host-only cookies over stale domain
39
/// cookies that could otherwise shadow the active key.
40
pub(crate) fn persisted_key_cookies(get_cookies: &Value, now_secs: u64) -> Option<Value> {
41
let expires = now_secs + KEY_LIFETIME_SECS;
42
let mut candidates: Vec<&Value> = get_cookies["cookies"]
43
.as_array()?
44
.iter()
45
.filter(|cookie| cookie["name"] == MSAL_KEY_COOKIE)
46
.collect();
47
candidates.sort_by_key(|cookie| {
48
cookie["domain"]
49
.as_str()
50
.is_some_and(|domain| domain.starts_with('.'))
51
});
52
let mut seen = HashSet::new();
53
let cookies: Vec<Value> = candidates
54
.into_iter()
55
.filter_map(|cookie| {
56
let key = (
57
cookie["domain"]
58
.as_str()
59
.unwrap_or("")
60
.trim_start_matches('.')
61
.to_owned(),
62
cookie["path"].as_str().unwrap_or("/").to_owned(),
63
cookie
64
.get("partitionKey")
65
.map(Value::to_string)
66
.unwrap_or_default(),
67
);
68
seen.insert(key).then(|| cookie_param(cookie, expires))?
69
})
70
.collect();
71
(!cookies.is_empty()).then(|| json!({ "cookies": cookies }))
72
}
73
74
fn cookie_param(cookie: &Value, expires: u64) -> Option<Value> {
75
let domain = cookie["domain"].as_str()?;
76
let path = cookie["path"].as_str().unwrap_or("/");
77
let mut param: Map<String, Value> = CARRIED_FIELDS
78
.iter()
79
.filter_map(|field| Some(((*field).to_owned(), cookie.get(*field)?.clone())))
80
.collect();
81
if domain.starts_with('.') {
82
param.insert("domain".into(), Value::String(domain.to_owned()));
83
} else {
84
// A host-only cookie set through `domain` would turn into a domain cookie; `url` keeps it host-only.
85
param.insert(
86
"url".into(),
87
Value::String(format!("https://{domain}{path}")),
88
);
89
}
90
param.insert("expires".into(), json!(expires));
91
Some(Value::Object(param))
92
}
93
94
#[cfg(test)]
95
mod tests {
96
use super::*;
97
98
const NOW: u64 = 1_800_000_000;
99
100
fn get_cookies() -> Value {
101
json!({"cookies": [
102
{"name": "msal.cache.encryption", "value": "{\"id\":\"k\",\"key\":\"secret\"}",
103
"domain": "teams.cloud.microsoft", "path": "/", "expires": -1, "size": 40,
104
"httpOnly": false, "secure": true, "session": true, "sameSite": "None",
105
"priority": "Medium", "sourceScheme": "Secure", "sourcePort": 443},
106
{"name": "other", "value": "x", "domain": ".microsoft.com", "path": "/",
107
"expires": -1, "size": 6, "httpOnly": true, "secure": true, "session": true,
108
"priority": "Medium", "sourceScheme": "Secure", "sourcePort": 443}
109
]})
110
}
111
112
#[test]
113
fn the_msal_key_cookie_gets_an_expiry_and_keeps_its_attributes() {
114
let params = persisted_key_cookies(&get_cookies(), NOW).unwrap();
115
let cookies = params["cookies"].as_array().unwrap();
116
assert_eq!(cookies.len(), 1, "only the MSAL key cookie: {params}");
117
let cookie = &cookies[0];
118
assert_eq!(cookie["name"], MSAL_KEY_COOKIE);
119
assert_eq!(cookie["value"], "{\"id\":\"k\",\"key\":\"secret\"}");
120
assert_eq!(cookie["expires"], NOW + KEY_LIFETIME_SECS);
121
assert_eq!(cookie["secure"], true);
122
assert_eq!(cookie["sameSite"], "None");
123
assert_eq!(cookie["url"], "https://teams.cloud.microsoft/");
124
assert!(
125
cookie.get("domain").is_none(),
126
"host-only stays host-only: {cookie}"
127
);
128
for read_only in ["size", "session"] {
129
assert!(
130
cookie.get(read_only).is_none(),
131
"{read_only} is not a CookieParam field"
132
);
133
}
134
assert_eq!(cookie["sourceScheme"], "Secure");
135
assert_eq!(cookie["sourcePort"], 443);
136
}
137
138
#[test]
139
fn a_domain_cookie_keeps_its_domain() {
140
let mut result = get_cookies();
141
result["cookies"][0]["domain"] = json!(".teams.cloud.microsoft");
142
let params = persisted_key_cookies(&result, NOW).unwrap();
143
assert_eq!(params["cookies"][0]["domain"], ".teams.cloud.microsoft");
144
assert!(params["cookies"][0].get("url").is_none());
145
}
146
147
#[test]
148
fn without_the_msal_key_cookie_nothing_is_set() {
149
let mut result = get_cookies();
150
result["cookies"].as_array_mut().unwrap().remove(0);
151
assert_eq!(persisted_key_cookies(&result, NOW), None);
152
assert_eq!(persisted_key_cookies(&json!({}), NOW), None);
153
}
154
155
#[test]
156
fn host_only_key_wins_over_a_stale_domain_duplicate() {
157
let mut result = get_cookies();
158
let stale = json!({
159
"name": MSAL_KEY_COOKIE, "value": "stale", "domain": ".teams.cloud.microsoft",
160
"path": "/", "expires": -1, "size": 4, "httpOnly": false, "secure": true,
161
"session": true, "sameSite": "None", "priority": "Medium",
162
"sourceScheme": "Secure", "sourcePort": 443
163
});
164
result["cookies"].as_array_mut().unwrap().insert(1, stale);
165
let params = persisted_key_cookies(&result, NOW).unwrap();
166
let cookies = params["cookies"].as_array().unwrap();
167
assert_eq!(cookies.len(), 1, "{params}");
168
assert_eq!(cookies[0]["value"], "{\"id\":\"k\",\"key\":\"secret\"}");
169
assert!(cookies[0].get("domain").is_none());
170
}
171
172
#[test]
173
fn partition_key_separates_key_cookies() {
174
let mut result = get_cookies();
175
let mut partitioned = result["cookies"][0].clone();
176
partitioned["partitionKey"] = json!({"topLevelSite": "https://teams.cloud.microsoft"});
177
result["cookies"].as_array_mut().unwrap().push(partitioned);
178
let params = persisted_key_cookies(&result, NOW).unwrap();
179
let cookies = params["cookies"].as_array().unwrap();
180
assert_eq!(cookies.len(), 2, "{params}");
181
assert!(cookies[0].get("partitionKey").is_none());
182
assert!(cookies[1].get("partitionKey").is_some());
183
}
184
185
#[test]
186
fn an_existing_expiry_is_renewed() {
187
let mut result = get_cookies();
188
result["cookies"][0]["expires"] = json!(NOW + 100);
189
let params = persisted_key_cookies(&result, NOW).unwrap();
190
assert_eq!(params["cookies"][0]["expires"], NOW + KEY_LIFETIME_SECS);
191
}
192
193
#[test]
194
fn a_cookie_without_a_domain_is_skipped() {
195
let mut result = get_cookies();
196
result["cookies"][0]
197
.as_object_mut()
198
.unwrap()
199
.remove("domain");
200
assert_eq!(persisted_key_cookies(&result, NOW), None);
201
}
202
}
@@ -0,0 +1,202 @@1
//! Keeps the key of the Teams token cache across browser restarts (issue #84).2
//!3
//! 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 (headless5
//! hand-over, login window, hung renderer, app exit) made MSAL create a new key, drop the cache6
//! and ask for sign-in again. Before Chromium stops, the cookie gets an expiry instead; the key7
//! then sits in the profile next to the cache it protects, which the profile already holds.8
//!9
//! 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
//! holds the equally powerful ESTS cookies that keep the session alive, so this is a conscious12
//! choice, not a new credential at rest.13
14
use serde_json::{Map, Value, json};15
use std::collections::HashSet;16
17
/// 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";19
/// How long the key outlives the last stop; every stop renews the expiry. 90 days is the chosen20
/// value, not a refresh-token lifetime: Entra gives SPA clients refresh tokens valid for 24 hours,21
/// and the long-lived session comes from the ESTS cookie, which enables silent token renewal.22
const KEY_LIFETIME_SECS: u64 = 90 * 24 * 60 * 60;23
/// `Network.Cookie` fields that `Network.CookieParam` takes unchanged (CDP browser_protocol.json).24
const CARRIED_FIELDS: [&str; 10] = [25
"name",26
"value",27
"path",28
"secure",29
"httpOnly",30
"sameSite",31
"priority",32
"partitionKey",33
"sourceScheme",34
"sourcePort",35
];36
37
/// `Storage.setCookies` parameters for the current MSAL key cookies. Duplicates by38
/// `(domain, path, partitionKey)` are collapsed, preferring host-only cookies over stale domain39
/// cookies that could otherwise shadow the active key.40
pub(crate) fn persisted_key_cookies(get_cookies: &Value, now_secs: u64) -> Option<Value> {41
let expires = now_secs + KEY_LIFETIME_SECS;42
let mut candidates: Vec<&Value> = get_cookies["cookies"]43
.as_array()?44
.iter()45
.filter(|cookie| cookie["name"] == MSAL_KEY_COOKIE)46
.collect();47
candidates.sort_by_key(|cookie| {48
cookie["domain"]49
.as_str()50
.is_some_and(|domain| domain.starts_with('.'))51
});52
let mut seen = HashSet::new();53
let cookies: Vec<Value> = candidates54
.into_iter()55
.filter_map(|cookie| {56
let key = (57
cookie["domain"]58
.as_str()59
.unwrap_or("")60
.trim_start_matches('.')61
.to_owned(),62
cookie["path"].as_str().unwrap_or("/").to_owned(),63
cookie64
.get("partitionKey")65
.map(Value::to_string)66
.unwrap_or_default(),67
);68
seen.insert(key).then(|| cookie_param(cookie, expires))?69
})70
.collect();71
(!cookies.is_empty()).then(|| json!({ "cookies": cookies }))72
}73
74
fn cookie_param(cookie: &Value, expires: u64) -> Option<Value> {75
let domain = cookie["domain"].as_str()?;76
let path = cookie["path"].as_str().unwrap_or("/");77
let mut param: Map<String, Value> = CARRIED_FIELDS78
.iter()79
.filter_map(|field| Some(((*field).to_owned(), cookie.get(*field)?.clone())))80
.collect();81
if domain.starts_with('.') {82
param.insert("domain".into(), Value::String(domain.to_owned()));83
} else {84
// A host-only cookie set through `domain` would turn into a domain cookie; `url` keeps it host-only.85
param.insert(86
"url".into(),87
Value::String(format!("https://{domain}{path}")),88
);89
}90
param.insert("expires".into(), json!(expires));91
Some(Value::Object(param))92
}93
94
#[cfg(test)]95
mod tests {96
use super::*;97
98
const NOW: u64 = 1_800_000_000;99
100
fn get_cookies() -> Value {101
json!({"cookies": [102
{"name": "msal.cache.encryption", "value": "{\"id\":\"k\",\"key\":\"secret\"}",103
"domain": "teams.cloud.microsoft", "path": "/", "expires": -1, "size": 40,104
"httpOnly": false, "secure": true, "session": true, "sameSite": "None",105
"priority": "Medium", "sourceScheme": "Secure", "sourcePort": 443},106
{"name": "other", "value": "x", "domain": ".microsoft.com", "path": "/",107
"expires": -1, "size": 6, "httpOnly": true, "secure": true, "session": true,108
"priority": "Medium", "sourceScheme": "Secure", "sourcePort": 443}109
]})110
}111
112
#[test]113
fn the_msal_key_cookie_gets_an_expiry_and_keeps_its_attributes() {114
let params = persisted_key_cookies(&get_cookies(), NOW).unwrap();115
let cookies = params["cookies"].as_array().unwrap();116
assert_eq!(cookies.len(), 1, "only the MSAL key cookie: {params}");117
let cookie = &cookies[0];118
assert_eq!(cookie["name"], MSAL_KEY_COOKIE);119
assert_eq!(cookie["value"], "{\"id\":\"k\",\"key\":\"secret\"}");120
assert_eq!(cookie["expires"], NOW + KEY_LIFETIME_SECS);121
assert_eq!(cookie["secure"], true);122
assert_eq!(cookie["sameSite"], "None");123
assert_eq!(cookie["url"], "https://teams.cloud.microsoft/");124
assert!(125
cookie.get("domain").is_none(),126
"host-only stays host-only: {cookie}"127
);128
for read_only in ["size", "session"] {129
assert!(130
cookie.get(read_only).is_none(),131
"{read_only} is not a CookieParam field"132
);133
}134
assert_eq!(cookie["sourceScheme"], "Secure");135
assert_eq!(cookie["sourcePort"], 443);136
}137
138
#[test]139
fn a_domain_cookie_keeps_its_domain() {140
let mut result = get_cookies();141
result["cookies"][0]["domain"] = json!(".teams.cloud.microsoft");142
let params = persisted_key_cookies(&result, NOW).unwrap();143
assert_eq!(params["cookies"][0]["domain"], ".teams.cloud.microsoft");144
assert!(params["cookies"][0].get("url").is_none());145
}146
147
#[test]148
fn without_the_msal_key_cookie_nothing_is_set() {149
let mut result = get_cookies();150
result["cookies"].as_array_mut().unwrap().remove(0);151
assert_eq!(persisted_key_cookies(&result, NOW), None);152
assert_eq!(persisted_key_cookies(&json!({}), NOW), None);153
}154
155
#[test]156
fn host_only_key_wins_over_a_stale_domain_duplicate() {157
let mut result = get_cookies();158
let stale = json!({159
"name": MSAL_KEY_COOKIE, "value": "stale", "domain": ".teams.cloud.microsoft",160
"path": "/", "expires": -1, "size": 4, "httpOnly": false, "secure": true,161
"session": true, "sameSite": "None", "priority": "Medium",162
"sourceScheme": "Secure", "sourcePort": 443163
});164
result["cookies"].as_array_mut().unwrap().insert(1, stale);165
let params = persisted_key_cookies(&result, NOW).unwrap();166
let cookies = params["cookies"].as_array().unwrap();167
assert_eq!(cookies.len(), 1, "{params}");168
assert_eq!(cookies[0]["value"], "{\"id\":\"k\",\"key\":\"secret\"}");169
assert!(cookies[0].get("domain").is_none());170
}171
172
#[test]173
fn partition_key_separates_key_cookies() {174
let mut result = get_cookies();175
let mut partitioned = result["cookies"][0].clone();176
partitioned["partitionKey"] = json!({"topLevelSite": "https://teams.cloud.microsoft"});177
result["cookies"].as_array_mut().unwrap().push(partitioned);178
let params = persisted_key_cookies(&result, NOW).unwrap();179
let cookies = params["cookies"].as_array().unwrap();180
assert_eq!(cookies.len(), 2, "{params}");181
assert!(cookies[0].get("partitionKey").is_none());182
assert!(cookies[1].get("partitionKey").is_some());183
}184
185
#[test]186
fn an_existing_expiry_is_renewed() {187
let mut result = get_cookies();188
result["cookies"][0]["expires"] = json!(NOW + 100);189
let params = persisted_key_cookies(&result, NOW).unwrap();190
assert_eq!(params["cookies"][0]["expires"], NOW + KEY_LIFETIME_SECS);191
}192
193
#[test]194
fn a_cookie_without_a_domain_is_skipped() {195
let mut result = get_cookies();196
result["cookies"][0]197
.as_object_mut()198
.unwrap()199
.remove("domain");200
assert_eq!(persisted_key_cookies(&result, NOW), None);201
}202
}@@ -341,6 +341,7 @@ pub async fn harness() -> Harness {
341
341
probe: Duration::from_millis(200),
342
342
poll: Duration::from_millis(20),
343
343
profile_release: Duration::from_millis(10),
344
msal_key: Duration::from_millis(20),
344
345
jitter_min: Duration::from_millis(5),
345
346
jitter_max: Duration::from_millis(20),
346
347
};
@@ -341,6 +341,7 @@ pub async fn harness() -> Harness {341
probe: Duration::from_millis(200),341
probe: Duration::from_millis(200),342
poll: Duration::from_millis(20),342
poll: Duration::from_millis(20),343
profile_release: Duration::from_millis(10),343
profile_release: Duration::from_millis(10),344
msal_key: Duration::from_millis(20),344
jitter_min: Duration::from_millis(5),345
jitter_min: Duration::from_millis(5),345
jitter_max: Duration::from_millis(20),346
jitter_max: Duration::from_millis(20),346
};347
};