| 1 | //! Koppelen in de sessiebrowser van rusty-teams in plaats van de systeembrowser. |
| 2 | //! |
| 3 | //! rusty-teams heeft al een browserprofiel met de Microsoft-sessie (ADR 0003). Als de |
| 4 | //! koppelpagina daar in een los tabblad opent, loopt de Entra-SSO van de Login stil |
| 5 | //! door. De app klikt dan zelf op «Koppelen» op de toestemmingspagina: de gebruiker |
| 6 | //! heeft dat al gedaan met de knop in Instellingen. De Login-pagina, de CSRF-check en |
| 7 | //! de loopback-redirect blijven precies zoals bij de systeembrowser; er gaat geen |
| 8 | //! Teams- of Graph-token naar de Login. |
| 9 | //! |
| 10 | //! Vraagt de pagina iets wat alleen de gebruiker kan (accountkeuze, MFA, wachtwoord) |
| 11 | //! of loopt het vast, dan geeft [`drive`] [`Outcome::NeedsUser`] en opent de app |
| 12 | //! dezelfde koppeling in de systeembrowser. |
| 13 | |
| 14 | use std::future::Future; |
| 15 | use std::pin::Pin; |
| 16 | use std::time::Duration; |
| 17 | |
| 18 | use serde_json::Value; |
| 19 | |
| 20 | pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>; |
| 21 | |
| 22 | /// Tabbladen in de sessiebrowser (Linux/macOS: de beheerde Chrome/Firefox). |
| 23 | pub trait SessionTabs: Send + Sync { |
| 24 | fn open<'a>(&'a self, url: &'a str) -> BoxFuture<'a, Result<String, String>>; |
| 25 | fn evaluate<'a>( |
| 26 | &'a self, |
| 27 | tab: &'a str, |
| 28 | expression: &'a str, |
| 29 | ) -> BoxFuture<'a, Result<Value, String>>; |
| 30 | fn close<'a>(&'a self, tab: &'a str) -> BoxFuture<'a, ()>; |
| 31 | } |
| 32 | |
| 33 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 34 | pub enum Outcome { |
| 35 | /// De browser is naar de loopback doorgestuurd; [`crate::connect::finish`] krijgt de code. |
| 36 | Redirected, |
| 37 | /// Hier lukt het niet stil: open de koppeling in de systeembrowser. |
| 38 | NeedsUser, |
| 39 | } |
| 40 | |
| 41 | #[derive(Debug, Clone, Copy)] |
| 42 | pub struct Timing { |
| 43 | pub poll: Duration, |
| 44 | /// Zo lang mag een Microsoft-loginpagina openstaan voordat we aannemen dat hij |
| 45 | /// om invoer vraagt. |
| 46 | pub microsoft_grace: Duration, |
| 47 | pub total: Duration, |
| 48 | } |
| 49 | |
| 50 | impl Default for Timing { |
| 51 | fn default() -> Self { |
| 52 | Timing { |
| 53 | poll: Duration::from_millis(400), |
| 54 | microsoft_grace: Duration::from_secs(8), |
| 55 | total: Duration::from_secs(45), |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | const MICROSOFT_LOGIN_HOSTS: [&str; 3] = [ |
| 61 | "login.microsoftonline.com", |
| 62 | "login.live.com", |
| 63 | "login.microsoft.com", |
| 64 | ]; |
| 65 | |
| 66 | /// Waar staat het tabblad, en staat de knop «Koppelen» van `app_connect.php` er? |
| 67 | const PROBE: &str = r#"(() => { const allow = document.querySelector('form[action="app_connect.php"] button[name="decision"][value="allow"]'); return { host: location.hostname, path: location.pathname, allow: !!allow, ready: document.readyState === 'complete' }; })()"#; |
| 68 | const APPROVE: &str = r#"(() => { const allow = document.querySelector('form[action="app_connect.php"] button[name="decision"][value="allow"]'); if (!allow) return false; allow.click(); return true; })()"#; |
| 69 | |
| 70 | #[derive(Debug, PartialEq, Eq)] |
| 71 | enum Page { |
| 72 | Loopback, |
| 73 | Consent, |
| 74 | Microsoft, |
| 75 | Other, |
| 76 | } |
| 77 | |
| 78 | fn classify(probe: &Value, sleutels_host: &str) -> Page { |
| 79 | let host = probe["host"].as_str().unwrap_or_default(); |
| 80 | if host == "127.0.0.1" || host == "localhost" { |
| 81 | return Page::Loopback; |
| 82 | } |
| 83 | if host == sleutels_host |
| 84 | && probe["path"] |
| 85 | .as_str() |
| 86 | .unwrap_or_default() |
| 87 | .ends_with("/app_connect.php") |
| 88 | && probe["allow"] == true |
| 89 | { |
| 90 | return Page::Consent; |
| 91 | } |
| 92 | if MICROSOFT_LOGIN_HOSTS.contains(&host) { |
| 93 | return Page::Microsoft; |
| 94 | } |
| 95 | Page::Other |
| 96 | } |
| 97 | |
| 98 | /// Open `url` in een tabblad van de sessiebrowser en help de koppeling stil door. |
| 99 | /// Sluit het tabblad weer, behalve als het naar de loopback ging (dan sluit de |
| 100 | /// aanroeper het zodra de code binnen is, zie [`close_after`]). |
| 101 | pub async fn drive( |
| 102 | tabs: &dyn SessionTabs, |
| 103 | url: &str, |
| 104 | sleutels_host: &str, |
| 105 | timing: Timing, |
| 106 | ) -> (Outcome, Option<String>) { |
| 107 | let Ok(tab) = tabs.open(url).await else { |
| 108 | return (Outcome::NeedsUser, None); |
| 109 | }; |
| 110 | let started = tokio::time::Instant::now(); |
| 111 | let mut microsoft_since: Option<tokio::time::Instant> = None; |
| 112 | let mut clicked = false; |
| 113 | loop { |
| 114 | tokio::time::sleep(timing.poll).await; |
| 115 | let now = tokio::time::Instant::now(); |
| 116 | if now - started > timing.total { |
| 117 | break; |
| 118 | } |
| 119 | let Ok(probe) = tabs.evaluate(&tab, PROBE).await else { |
| 120 | // Tijdens een navigatie kan evaluate falen; gewoon opnieuw. |
| 121 | continue; |
| 122 | }; |
| 123 | match classify(&probe, sleutels_host) { |
| 124 | Page::Loopback => return (Outcome::Redirected, Some(tab)), |
| 125 | Page::Consent if !clicked && probe["ready"] == true => { |
| 126 | clicked = matches!(tabs.evaluate(&tab, APPROVE).await, Ok(Value::Bool(true))); |
| 127 | microsoft_since = None; |
| 128 | } |
| 129 | Page::Consent => microsoft_since = None, |
| 130 | Page::Microsoft => { |
| 131 | let since = *microsoft_since.get_or_insert(now); |
| 132 | if now - since > timing.microsoft_grace { |
| 133 | break; |
| 134 | } |
| 135 | } |
| 136 | Page::Other => microsoft_since = None, |
| 137 | } |
| 138 | } |
| 139 | tabs.close(&tab).await; |
| 140 | (Outcome::NeedsUser, None) |
| 141 | } |
| 142 | |
| 143 | /// Het tabblad sluiten nadat de loopback de code heeft. |
| 144 | pub async fn close_after(tabs: &dyn SessionTabs, tab: Option<String>) { |
| 145 | if let Some(tab) = tab { |
| 146 | tabs.close(&tab).await; |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | #[cfg(test)] |
| 151 | mod tests { |
| 152 | use std::sync::Mutex; |
| 153 | |
| 154 | use serde_json::json; |
| 155 | |
| 156 | use super::*; |
| 157 | |
| 158 | /// Speelt een reeks pagina's af; elke evaluate van PROBE schuift één stap op. |
| 159 | struct Script { |
| 160 | pages: Mutex<Vec<Value>>, |
| 161 | log: Mutex<Vec<String>>, |
| 162 | open_fails: bool, |
| 163 | } |
| 164 | |
| 165 | impl Script { |
| 166 | fn new(pages: Vec<Value>) -> Self { |
| 167 | Script { |
| 168 | pages: Mutex::new(pages), |
| 169 | log: Mutex::new(Vec::new()), |
| 170 | open_fails: false, |
| 171 | } |
| 172 | } |
| 173 | fn log(&self) -> Vec<String> { |
| 174 | self.log.lock().unwrap().clone() |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | impl SessionTabs for Script { |
| 179 | fn open<'a>(&'a self, url: &'a str) -> BoxFuture<'a, Result<String, String>> { |
| 180 | self.log.lock().unwrap().push(format!("open {url}")); |
| 181 | let fails = self.open_fails; |
| 182 | Box::pin(async move { |
| 183 | if fails { |
| 184 | Err("no browser".into()) |
| 185 | } else { |
| 186 | Ok("tab1".into()) |
| 187 | } |
| 188 | }) |
| 189 | } |
| 190 | fn evaluate<'a>( |
| 191 | &'a self, |
| 192 | _: &'a str, |
| 193 | expression: &'a str, |
| 194 | ) -> BoxFuture<'a, Result<Value, String>> { |
| 195 | let result = if expression == APPROVE { |
| 196 | self.log.lock().unwrap().push("click".into()); |
| 197 | Ok(Value::Bool(true)) |
| 198 | } else { |
| 199 | let mut pages = self.pages.lock().unwrap(); |
| 200 | if pages.len() > 1 { |
| 201 | Ok(pages.remove(0)) |
| 202 | } else { |
| 203 | pages.first().cloned().ok_or_else(|| "gone".to_owned()) |
| 204 | } |
| 205 | }; |
| 206 | Box::pin(async move { result }) |
| 207 | } |
| 208 | fn close<'a>(&'a self, tab: &'a str) -> BoxFuture<'a, ()> { |
| 209 | self.log.lock().unwrap().push(format!("close {tab}")); |
| 210 | Box::pin(async {}) |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | fn page(host: &str, path: &str, allow: bool) -> Value { |
| 215 | json!({"host": host, "path": path, "allow": allow, "ready": true}) |
| 216 | } |
| 217 | |
| 218 | fn fast() -> Timing { |
| 219 | Timing { |
| 220 | poll: Duration::from_millis(1), |
| 221 | microsoft_grace: Duration::from_millis(30), |
| 222 | total: Duration::from_millis(500), |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | #[tokio::test] |
| 227 | async fn silent_sso_clicks_connect_once_and_reaches_the_loopback() { |
| 228 | let script = Script::new(vec![ |
| 229 | page("login.microsoftonline.com", "/x/oauth2/authorize", false), |
| 230 | page("sleutels.kvt.nl", "/login/app_connect.php", true), |
| 231 | page("sleutels.kvt.nl", "/login/app_connect.php", true), |
| 232 | page("127.0.0.1", "/kvt-callback", false), |
| 233 | ]); |
| 234 | let (outcome, tab) = drive( |
| 235 | &script, |
| 236 | "https://sleutels.kvt.nl/login/app_connect.php?x", |
| 237 | "sleutels.kvt.nl", |
| 238 | fast(), |
| 239 | ) |
| 240 | .await; |
| 241 | assert_eq!(outcome, Outcome::Redirected); |
| 242 | assert_eq!(tab.as_deref(), Some("tab1")); |
| 243 | assert_eq!( |
| 244 | script.log().iter().filter(|line| *line == "click").count(), |
| 245 | 1 |
| 246 | ); |
| 247 | close_after(&script, tab).await; |
| 248 | assert_eq!(script.log().last().map(String::as_str), Some("close tab1")); |
| 249 | } |
| 250 | |
| 251 | #[tokio::test] |
| 252 | async fn a_microsoft_page_that_waits_for_input_falls_back() { |
| 253 | let script = Script::new(vec![page( |
| 254 | "login.microsoftonline.com", |
| 255 | "/common/oauth2/authorize", |
| 256 | false, |
| 257 | )]); |
| 258 | let (outcome, tab) = drive( |
| 259 | &script, |
| 260 | "https://sleutels.kvt.nl/login/app_connect.php", |
| 261 | "sleutels.kvt.nl", |
| 262 | fast(), |
| 263 | ) |
| 264 | .await; |
| 265 | assert_eq!(outcome, Outcome::NeedsUser); |
| 266 | assert!(tab.is_none()); |
| 267 | assert!(!script.log().contains(&"click".to_owned())); |
| 268 | assert_eq!(script.log().last().map(String::as_str), Some("close tab1")); |
| 269 | } |
| 270 | |
| 271 | #[tokio::test] |
| 272 | async fn never_clicks_on_a_look_alike_host() { |
| 273 | let script = Script::new(vec![page( |
| 274 | "sleutels.kvt.nl.example.com", |
| 275 | "/login/app_connect.php", |
| 276 | true, |
| 277 | )]); |
| 278 | let (outcome, _) = drive( |
| 279 | &script, |
| 280 | "https://sleutels.kvt.nl/", |
| 281 | "sleutels.kvt.nl", |
| 282 | fast(), |
| 283 | ) |
| 284 | .await; |
| 285 | assert_eq!(outcome, Outcome::NeedsUser); |
| 286 | assert!(!script.log().contains(&"click".to_owned())); |
| 287 | } |
| 288 | |
| 289 | #[tokio::test] |
| 290 | async fn no_session_browser_means_system_browser() { |
| 291 | let mut script = Script::new(vec![]); |
| 292 | script.open_fails = true; |
| 293 | let (outcome, _) = drive( |
| 294 | &script, |
| 295 | "https://sleutels.kvt.nl/", |
| 296 | "sleutels.kvt.nl", |
| 297 | fast(), |
| 298 | ) |
| 299 | .await; |
| 300 | assert_eq!(outcome, Outcome::NeedsUser); |
| 301 | } |
| 302 | } |