| 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 | } |