| 1 | //! Keeps the key of the Teams token cache across app 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 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. |
| 9 | //! |
| 10 | //! Trade-off: the key moves from a session cookie into the profile's cookie store, encrypted by |
| 11 | //! the OS keyring (or the browser's fixed key where no keyring is available). The profile already |
| 12 | //! holds the equally powerful ESTS cookies that keep the session alive, so this is a conscious |
| 13 | //! choice, not a new credential at rest. |
| 14 | |
| 15 | use std::collections::HashSet; |
| 16 | |
| 17 | use serde_json::{Map, Value, json}; |
| 18 | |
| 19 | /// The cookie MSAL.js reads its cache encryption key from; only its name and value matter to it. |
| 20 | const MSAL_KEY_COOKIE: &str = "msal.cache.encryption"; |
| 21 | /// How long the key outlives the last stop; every stop renews the expiry. 90 days is the chosen |
| 22 | /// value, not a refresh-token lifetime: Entra gives SPA clients refresh tokens valid for 24 hours, |
| 23 | /// and the long-lived session comes from the ESTS cookie, which enables silent token renewal. |
| 24 | const KEY_LIFETIME_SECS: u64 = 90 * 24 * 60 * 60; |
| 25 | /// `Network.Cookie` fields that `Network.CookieParam` takes unchanged (CDP browser_protocol.json). |
| 26 | const CARRIED_FIELDS: [&str; 10] = [ |
| 27 | "name", |
| 28 | "value", |
| 29 | "path", |
| 30 | "secure", |
| 31 | "httpOnly", |
| 32 | "sameSite", |
| 33 | "priority", |
| 34 | "partitionKey", |
| 35 | "sourceScheme", |
| 36 | "sourcePort", |
| 37 | ]; |
| 38 | |
| 39 | /// `Storage.setCookies` parameters for the current MSAL key cookies. Duplicates by |
| 40 | /// `(domain, path, partitionKey)` are collapsed, preferring host-only cookies over stale domain |
| 41 | /// cookies that could otherwise shadow the active key. |
| 42 | pub fn persisted_key_cookies(get_cookies: &Value, now_secs: u64) -> Option<Value> { |
| 43 | let expires = now_secs + KEY_LIFETIME_SECS; |
| 44 | let mut candidates: Vec<&Value> = get_cookies["cookies"] |
| 45 | .as_array()? |
| 46 | .iter() |
| 47 | .filter(|cookie| cookie["name"] == MSAL_KEY_COOKIE) |
| 48 | .collect(); |
| 49 | candidates.sort_by_key(|cookie| { |
| 50 | cookie["domain"] |
| 51 | .as_str() |
| 52 | .is_some_and(|domain| domain.starts_with('.')) |
| 53 | }); |
| 54 | let mut seen = HashSet::new(); |
| 55 | let cookies: Vec<Value> = candidates |
| 56 | .into_iter() |
| 57 | .filter_map(|cookie| { |
| 58 | let key = ( |
| 59 | cookie["domain"] |
| 60 | .as_str() |
| 61 | .unwrap_or("") |
| 62 | .trim_start_matches('.') |
| 63 | .to_owned(), |
| 64 | cookie["path"].as_str().unwrap_or("/").to_owned(), |
| 65 | cookie |
| 66 | .get("partitionKey") |
| 67 | .map(Value::to_string) |
| 68 | .unwrap_or_default(), |
| 69 | ); |
| 70 | seen.insert(key).then(|| cookie_param(cookie, expires))? |
| 71 | }) |
| 72 | .collect(); |
| 73 | (!cookies.is_empty()).then(|| json!({ "cookies": cookies })) |
| 74 | } |
| 75 | |
| 76 | fn cookie_param(cookie: &Value, expires: u64) -> Option<Value> { |
| 77 | let domain = cookie["domain"].as_str()?; |
| 78 | let path = cookie["path"].as_str().unwrap_or("/"); |
| 79 | let mut param: Map<String, Value> = CARRIED_FIELDS |
| 80 | .iter() |
| 81 | .filter_map(|field| Some(((*field).to_owned(), cookie.get(*field)?.clone()))) |
| 82 | .collect(); |
| 83 | if domain.starts_with('.') { |
| 84 | param.insert("domain".into(), Value::String(domain.to_owned())); |
| 85 | } else { |
| 86 | // A host-only cookie set through `domain` would turn into a domain cookie; `url` keeps it host-only. |
| 87 | param.insert( |
| 88 | "url".into(), |
| 89 | Value::String(format!("https://{domain}{path}")), |
| 90 | ); |
| 91 | } |
| 92 | param.insert("expires".into(), json!(expires)); |
| 93 | Some(Value::Object(param)) |
| 94 | } |
| 95 | |
| 96 | #[cfg(test)] |
| 97 | mod tests { |
| 98 | use super::*; |
| 99 | |
| 100 | const NOW: u64 = 1_800_000_000; |
| 101 | |
| 102 | fn get_cookies() -> Value { |
| 103 | json!({"cookies": [ |
| 104 | {"name": "msal.cache.encryption", "value": "{\"id\":\"k\",\"key\":\"secret\"}", |
| 105 | "domain": "teams.cloud.microsoft", "path": "/", "expires": -1, "size": 40, |
| 106 | "httpOnly": false, "secure": true, "session": true, "sameSite": "None", |
| 107 | "priority": "Medium", "sourceScheme": "Secure", "sourcePort": 443}, |
| 108 | {"name": "other", "value": "x", "domain": ".microsoft.com", "path": "/", |
| 109 | "expires": -1, "size": 6, "httpOnly": true, "secure": true, "session": true, |
| 110 | "priority": "Medium", "sourceScheme": "Secure", "sourcePort": 443} |
| 111 | ]}) |
| 112 | } |
| 113 | |
| 114 | #[test] |
| 115 | fn the_msal_key_cookie_gets_an_expiry_and_keeps_its_attributes() { |
| 116 | let params = persisted_key_cookies(&get_cookies(), NOW).unwrap(); |
| 117 | let cookies = params["cookies"].as_array().unwrap(); |
| 118 | assert_eq!(cookies.len(), 1, "only the MSAL key cookie: {params}"); |
| 119 | let cookie = &cookies[0]; |
| 120 | assert_eq!(cookie["name"], MSAL_KEY_COOKIE); |
| 121 | assert_eq!(cookie["value"], "{\"id\":\"k\",\"key\":\"secret\"}"); |
| 122 | assert_eq!(cookie["expires"], NOW + KEY_LIFETIME_SECS); |
| 123 | assert_eq!(cookie["secure"], true); |
| 124 | assert_eq!(cookie["sameSite"], "None"); |
| 125 | assert_eq!(cookie["url"], "https://teams.cloud.microsoft/"); |
| 126 | assert!( |
| 127 | cookie.get("domain").is_none(), |
| 128 | "host-only stays host-only: {cookie}" |
| 129 | ); |
| 130 | for read_only in ["size", "session"] { |
| 131 | assert!( |
| 132 | cookie.get(read_only).is_none(), |
| 133 | "{read_only} is not a CookieParam field" |
| 134 | ); |
| 135 | } |
| 136 | assert_eq!(cookie["sourceScheme"], "Secure"); |
| 137 | assert_eq!(cookie["sourcePort"], 443); |
| 138 | } |
| 139 | |
| 140 | #[test] |
| 141 | fn a_domain_cookie_keeps_its_domain() { |
| 142 | let mut result = get_cookies(); |
| 143 | result["cookies"][0]["domain"] = json!(".teams.cloud.microsoft"); |
| 144 | let params = persisted_key_cookies(&result, NOW).unwrap(); |
| 145 | assert_eq!(params["cookies"][0]["domain"], ".teams.cloud.microsoft"); |
| 146 | assert!(params["cookies"][0].get("url").is_none()); |
| 147 | } |
| 148 | |
| 149 | #[test] |
| 150 | fn without_the_msal_key_cookie_nothing_is_set() { |
| 151 | let mut result = get_cookies(); |
| 152 | result["cookies"].as_array_mut().unwrap().remove(0); |
| 153 | assert_eq!(persisted_key_cookies(&result, NOW), None); |
| 154 | assert_eq!(persisted_key_cookies(&json!({}), NOW), None); |
| 155 | } |
| 156 | |
| 157 | #[test] |
| 158 | fn host_only_key_wins_over_a_stale_domain_duplicate() { |
| 159 | let mut result = get_cookies(); |
| 160 | let stale = json!({ |
| 161 | "name": MSAL_KEY_COOKIE, "value": "stale", "domain": ".teams.cloud.microsoft", |
| 162 | "path": "/", "expires": -1, "size": 4, "httpOnly": false, "secure": true, |
| 163 | "session": true, "sameSite": "None", "priority": "Medium", |
| 164 | "sourceScheme": "Secure", "sourcePort": 443 |
| 165 | }); |
| 166 | result["cookies"].as_array_mut().unwrap().insert(1, stale); |
| 167 | let params = persisted_key_cookies(&result, NOW).unwrap(); |
| 168 | let cookies = params["cookies"].as_array().unwrap(); |
| 169 | assert_eq!(cookies.len(), 1, "{params}"); |
| 170 | assert_eq!(cookies[0]["value"], "{\"id\":\"k\",\"key\":\"secret\"}"); |
| 171 | assert!(cookies[0].get("domain").is_none()); |
| 172 | } |
| 173 | |
| 174 | #[test] |
| 175 | fn partition_key_separates_key_cookies() { |
| 176 | let mut result = get_cookies(); |
| 177 | let mut partitioned = result["cookies"][0].clone(); |
| 178 | partitioned["partitionKey"] = json!({"topLevelSite": "https://teams.cloud.microsoft"}); |
| 179 | result["cookies"].as_array_mut().unwrap().push(partitioned); |
| 180 | let params = persisted_key_cookies(&result, NOW).unwrap(); |
| 181 | let cookies = params["cookies"].as_array().unwrap(); |
| 182 | assert_eq!(cookies.len(), 2, "{params}"); |
| 183 | assert!(cookies[0].get("partitionKey").is_none()); |
| 184 | assert!(cookies[1].get("partitionKey").is_some()); |
| 185 | } |
| 186 | |
| 187 | #[test] |
| 188 | fn an_existing_expiry_is_renewed() { |
| 189 | let mut result = get_cookies(); |
| 190 | result["cookies"][0]["expires"] = json!(NOW + 100); |
| 191 | let params = persisted_key_cookies(&result, NOW).unwrap(); |
| 192 | assert_eq!(params["cookies"][0]["expires"], NOW + KEY_LIFETIME_SECS); |
| 193 | } |
| 194 | |
| 195 | #[test] |
| 196 | fn a_cookie_without_a_domain_is_skipped() { |
| 197 | let mut result = get_cookies(); |
| 198 | result["cookies"][0] |
| 199 | .as_object_mut() |
| 200 | .unwrap() |
| 201 | .remove("domain"); |
| 202 | assert_eq!(persisted_key_cookies(&result, NOW), None); |
| 203 | } |
| 204 | } |