diff --git a/desktop/src-tauri/src/connected/relay.rs b/desktop/src-tauri/src/connected/relay.rs index 0506ddf871..259cb5d26c 100644 --- a/desktop/src-tauri/src/connected/relay.rs +++ b/desktop/src-tauri/src/connected/relay.rs @@ -27,6 +27,14 @@ What keeps it to that: the relay's own page is same-site, and carries it. That page has no script and no secret in it, sends no referrer (the address it was opened at holds the secret), and replaces itself in the window's history. +- A page load it refuses (a navigation of a window, not a request a page makes) is kept, by its path, + until the window enters again or a page load passes (`Relay::refused_page`), and every refusal is + written to the log with why, never with the secret. The window can come back without the cookie + (WebKit let it go, or the load began on another site), and the refusal is a page with no script: + the shell sends the window back through the entry at that page (`desktop_connected`). A request of + the window's page that comes without it (`Sec-Fetch-Site: same-origin`, which no other site's page + can send) tells the shell the same (`Ended::WindowLostItsCookie`). Before, a window that met the + refusal stayed on it until the app quit (1.2.0-rc.5, connected to OpenBot Cloud). - It forwards to the typed address and nowhere else: only origin-form request targets (no absolute URL, no CONNECT), and a redirect is handed back to the page, never followed. - On the way out it drops `Origin`, `Cookie`, `Referer`, `Forwarded` and `X-Forwarded-*`, and any @@ -122,11 +130,59 @@ pub enum Ended { SessionEnded, /// The OpenBot did not answer. The relay keeps going; said at most once in a while. Unreachable, + /// A request of the window's own page came without the run's cookie: it says it is the page's + /// own (`Sec-Fetch-Site: same-origin`), and WebKit no longer sends the cookie. The relay keeps + /// going; the shell sends the window back through the entry. + WindowLostItsCookie, } /// How often `Ended::Unreachable` is said while the OpenBot stays unreachable. const UNREACHABLE_SAID_EVERY: Duration = Duration::from_secs(30); +/// How often a refused request that is not a page load is written to the log, at most: a page that +/// lost the cookie asks several times a second. Every refused page load is written. +const REFUSAL_SAID_EVERY: Duration = Duration::from_secs(30); + +/// How often the shell is told `Ended::WindowLostItsCookie`, at most, while the page keeps asking. +const LOST_COOKIE_TOLD_EVERY: Duration = Duration::from_secs(5); + +/// Why the relay refused a request as not the OpenBot window's, for the log. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Refused { + /// Its `Origin` is not the relay's own. + AnotherOrigin, + /// `Sec-Fetch-Site` says another site sent it. + AnotherSite, + /// It came without the run's cookie. + NoCookie, +} + +impl Refused { + fn said(self) -> &'static str { + match self { + Self::AnotherOrigin => "another site's page sent it (Origin)", + Self::AnotherSite => "another site sent it (Sec-Fetch-Site)", + Self::NoCookie => "it came without the window's cookie", + } + } +} + +/// Whether the request is a window's page load (a navigation), not a request a page makes: +/// `Sec-Fetch-Dest: document`, or, from a webview that sends no `Sec-Fetch-Dest`, a `GET` that asks +/// for HTML. +fn page_load(method: &Method, headers: &HeaderMap) -> bool { + if method != Method::GET { + return false; + } + match headers.get("sec-fetch-dest") { + Some(destination) => destination == "document", + None => headers + .get(header::ACCEPT) + .and_then(|accept| accept.to_str().ok()) + .is_some_and(|accept| accept.contains("text/html")), + } +} + /// How long a connection to OpenBot is kept open, idle, for the next request. A load balancer or /// an ingress in front of OpenBot closes an idle connection on a timer of its own (AWS's load /// balancer after 60 s, nginx after 75 s), and a request sent at the moment it does so is lost. @@ -159,6 +215,13 @@ struct Shared { on_ended: Box, session_ended: AtomicBool, unreachable_said: Mutex>, + /// The path of the page load refused last, until the window enters again or a page load + /// passes (`Relay::refused_page`). + refused_page: Arc>>, + /// When a refused request that is not a page load was last written to the log. + refusal_said: Mutex>, + /// When the shell was last told `Ended::WindowLostItsCookie`. + lost_cookie_told: Mutex>, stop: tokio::sync::watch::Sender, } @@ -167,6 +230,7 @@ pub struct Relay { address: SocketAddr, secret: String, organization: Arc>>, + refused_page: Arc>>, stop: tokio::sync::watch::Sender, runtime: Option, } @@ -208,6 +272,7 @@ impl Relay { .map_err(|error| format!("could not start the relay: {error}"))?; let (stop, stopped) = tokio::sync::watch::channel(false); let secret = crate::provider_oauth::random(); + let refused_page = Arc::new(Mutex::new(None)); let shared = Arc::new(Shared { session, host: address.to_string(), @@ -220,6 +285,9 @@ impl Relay { on_ended: Box::new(on_ended), session_ended: AtomicBool::new(false), unreachable_said: Mutex::new(None), + refused_page: refused_page.clone(), + refusal_said: Mutex::new(None), + lost_cookie_told: Mutex::new(None), stop: stop.clone(), }); runtime.spawn(serve(listener, shared, stopped)); @@ -228,6 +296,7 @@ impl Relay { address, secret, organization, + refused_page, stop, runtime: Some(runtime), }) @@ -262,6 +331,13 @@ impl Relay { } format!("{}&to={to}", self.entry()) } + + /// The page load the relay refused last as not the window's (a path from the root, such as + /// `/` or `/connections`), until the window enters again or a page load passes. A window on + /// that page sits on the refusal, and goes back through the entry at it (`entry_to`). + pub fn refused_page(&self) -> Option { + self.refused_page.lock().unwrap().clone() + } } impl Drop for Relay { @@ -344,6 +420,63 @@ fn has_cookie(headers: &HeaderMap, secret: &str) -> bool { .any(|(name, value)| name == COOKIE && same_secret(value, secret)) } +/** +A request refused as not the window's (`why`): a page load is kept by its path (`refused_page`) and +written to the log, and anything else is written at most once in `REFUSAL_SAID_EVERY`. The method +and the path only: never a header, so never the cookie or the secret. A request of the window's own +page that came without the cookie tells the shell (`Ended::WindowLostItsCookie`). +*/ +fn say_refused( + shared: &Arc, + request: &Request, + why: Refused, + loading_a_page: bool, +) { + let path = request.uri().path(); + if loading_a_page { + *shared.refused_page.lock().unwrap() = Some(path.to_owned()); + } + let now = Instant::now(); + let said = { + let mut said = shared.refusal_said.lock().unwrap(); + let due = said.is_none_or(|at| now.duration_since(at) >= REFUSAL_SAID_EVERY); + if due && !loading_a_page { + *said = Some(now); + } + due || loading_a_page + }; + if said { + let what = if loading_a_page { + "the page load" + } else { + "the request" + }; + log::warn!( + "[relay] refused {what} {} {path} as not the OpenBot window's: {}", + request.method(), + why.said() + ); + } + let the_pages_own = request + .headers() + .get("sec-fetch-site") + .is_some_and(|site| site == "same-origin"); + if why == Refused::NoCookie && the_pages_own && !loading_a_page { + let due = { + let mut told = shared.lost_cookie_told.lock().unwrap(); + let due = told.is_none_or(|at| now.duration_since(at) >= LOST_COOKIE_TOLD_EVERY); + if due { + *told = Some(now); + } + due + }; + if due { + let shared = shared.clone(); + std::thread::spawn(move || (shared.on_ended)(Ended::WindowLostItsCookie)); + } + } +} + /// Headers that belong to one connection, not to the request (RFC 9110 ยง7.6.1). fn hop_by_hop(name: &HeaderName) -> bool { matches!( @@ -430,6 +563,8 @@ async fn answer(mut request: Request, shared: Arc) -> Response .and_then(|query| query.split('&').find_map(|pair| pair.strip_prefix("to="))) .filter(|to| app_page(to)) .unwrap_or("/"); + // The window is entering again: whatever page it was refused before, it is let in now. + *shared.refused_page.lock().unwrap() = None; // A page, not a redirect: see the module's documentation. return Response::builder() .status(StatusCode::OK) @@ -466,12 +601,27 @@ async fn answer(mut request: Request, shared: Arc) -> Response .get_all("sec-fetch-site") .iter() .any(|site| site == "cross-site" || site == "same-site"); - if foreign_origin || from_another_site || !has_cookie(request.headers(), &shared.secret) { + let refused = if foreign_origin { + Some(Refused::AnotherOrigin) + } else if from_another_site { + Some(Refused::AnotherSite) + } else if !has_cookie(request.headers(), &shared.secret) { + Some(Refused::NoCookie) + } else { + None + }; + let loading_a_page = page_load(request.method(), request.headers()); + if let Some(why) = refused { + say_refused(&shared, &request, why, loading_a_page); return plain( StatusCode::FORBIDDEN, "This relay is for the OpenBot window.", ); } + if loading_a_page { + // The window's page loads with the cookie: it sits on no refusal. + *shared.refused_page.lock().unwrap() = None; + } if request.uri().path().starts_with(OWN_PREFIX) { return plain(StatusCode::NOT_FOUND, "Not found."); } @@ -2124,7 +2274,20 @@ mod tests { .filter(|(_, _, strict)| !strict || same_site(&began_on, &url)) .map(|(name, value, _)| format!("{name}={value}")) .collect(); - let mut request = http().get(url.clone()); + // A page load, as WebKit sends one: where it began says which site sent it. + let site = if began_on.origin() == url.origin() { + "same-origin" + } else if same_site(&began_on, &url) { + "same-site" + } else { + "cross-site" + }; + let mut request = http() + .get(url.clone()) + .header("accept", "text/html,application/xhtml+xml,*/*;q=0.8") + .header("sec-fetch-dest", "document") + .header("sec-fetch-mode", "navigate") + .header("sec-fetch-site", site); if !cookies.is_empty() { request = request.header("cookie", cookies.join("; ")); } @@ -2263,6 +2426,84 @@ mod tests { assert!(app_page("/settings/computer")); } + /** + The window's page load came without the run's cookie and was refused: the white page that says + "This relay is for the OpenBot window.", which a window sat on in dogfooding (1.2.0-rc.5, connected to + OpenBot Cloud) until the app quit. The relay keeps which page it refused, so the shell can + send the window back through the entry at that page, and the entry hands it the cookie again: the + page loads, and nothing is kept any more. A request the page makes (a fetch, an image) is never + taken for the page load. One of the page's own that came without the cookie + (`Sec-Fetch-Site: same-origin`) tells the shell once in a while; one from another site, or one + that doesn't say, never does. + */ + #[test] + fn a_page_load_refused_for_want_of_the_cookie_is_kept_until_the_window_enters_again() { + let rig = rig(); + let origin = rig.relay.origin(); + let mut window = WebKitWindow::new(); + let arrived = window.navigate(SETUP_PAGE, &rig.relay.entry()); + assert_eq!(arrived.status, 200); + assert_eq!(rig.relay.refused_page(), None); + + // WebKit let the cookie go, and the page is loaded again. + window.jar.clear(); + let page = format!("{origin}/landing"); + let refused = window.navigate(&page, &page); + assert_eq!(refused.status, 403); + assert_eq!(refused.body, "This relay is for the OpenBot window."); + assert_eq!(rig.relay.refused_page().as_deref(), Some("/landing")); + assert_eq!(rig.openbot.seen_at("/landing").len(), 0); + + // The page's own requests are refused as well, and are not the page load. + for (site, tells) in [ + (Some("same-origin"), true), + (Some("cross-site"), false), + (None, false), + ] { + let mut request = http().get(format!("{origin}{ECHO}")); + if let Some(site) = site { + request = request + .header("sec-fetch-site", site) + .header("sec-fetch-dest", "empty"); + } + let answered = request.send().unwrap(); + assert_eq!(answered.status(), 403, "{site:?}"); + assert_eq!( + rig.relay.refused_page().as_deref(), + Some("/landing"), + "{site:?}" + ); + let deadline = Instant::now() + Duration::from_secs(2); + let told = || { + rig.ended + .lock() + .unwrap() + .iter() + .filter(|why| **why == Ended::WindowLostItsCookie) + .count() + }; + while tells && told() == 0 { + assert!(Instant::now() < deadline, "the shell was never told"); + std::thread::sleep(Duration::from_millis(10)); + } + std::thread::sleep(Duration::from_millis(100)); + assert_eq!(told(), 1, "{site:?}: told once, for the page's own"); + } + assert_eq!(rig.echoes(), 0); + + // Back through the entry at that page: the cookie again, and the page loads. + let entered = window.navigate(&page, &rig.relay.entry_to("/landing")); + assert_eq!(entered.status, 200); + assert_eq!(entered.url.as_str(), page); + assert_eq!(rig.openbot.seen_at("/landing").len(), 1); + assert_eq!(rig.relay.refused_page(), None); + assert_eq!( + window.navigate(&page, &format!("{origin}{ECHO}")).status, + 200 + ); + assert!(!rig.ended.lock().unwrap().contains(&Ended::SessionEnded)); + } + /// The entry address holds the run's secret, and the log's redaction covers it. #[test] fn the_entry_address_and_the_cookie_are_redacted_in_a_log_line() { diff --git a/desktop/src-tauri/src/desktop_connected.rs b/desktop/src-tauri/src/desktop_connected.rs index 65943c7fa3..6581e7ba0a 100644 --- a/desktop/src-tauri/src/desktop_connected.rs +++ b/desktop/src-tauri/src/desktop_connected.rs @@ -68,6 +68,9 @@ pub struct State { loads: Mutex<(u64, u64)>, /// About is asking which account the window is signed in as (`learn_account`). learning: std::sync::atomic::AtomicBool, + /// When the window was last sent back through the relay's entry by itself, in the last minute + /// (`enter_relay_again`). + entered_again: Mutex>, /// The window's cookies, in a test: the mock webview keeps none. #[cfg(test)] pub(crate) jar_for_test: Mutex>, @@ -218,6 +221,95 @@ fn relay_entry(app: &tauri::AppHandle) -> Option { .map(|live| live.relay.entry()) } +/// Whether the window at `url` sits on the relay's refusal: on the relay's origin, at the page load +/// the relay refused last (`relay::Relay::refused_page`). +fn on_the_relays_refusal(app: &tauri::AppHandle, url: &tauri::Url) -> bool { + state(app) + .connected + .live + .lock() + .unwrap() + .as_ref() + .filter(|live| live.relay.origin() == url.origin().ascii_serialization()) + .and_then(|live| live.relay.refused_page()) + .is_some_and(|refused| refused == url.path()) +} + +/// How many times a minute the window is sent back through the relay's entry by itself, at most, +/// and how long after the last time, at least. A window whose cookie never sticks is not sent round +/// in circles; opening it again (`show_window`) always enters again. +const ENTERED_AGAIN_AT_MOST: usize = 3; +const ENTERED_AGAIN_AFTER: std::time::Duration = std::time::Duration::from_secs(5); + +/** +The relay refused the window's page, or a request of its page, for want of the run's cookie: the +window goes back through the relay's entry, at the page `at` it was on, and the entry hands it the +cookie again, so the page loads. Before, the window stayed on the relay's refusal, "This relay is +for the OpenBot window.", a page with no script, until the app quit (1.2.0-rc.5, connected to +OpenBot Cloud). `why` is for the log. Whether the window was sent. +*/ +fn enter_relay_again(app: &tauri::AppHandle, at: &str, why: &str) -> bool { + let Some(entry) = state(app) + .connected + .live + .lock() + .unwrap() + .as_ref() + .map(|live| live.relay.entry_to(at)) + else { + return false; + }; + { + let shell = state(app); + let mut entered = shell.connected.entered_again.lock().unwrap(); + let now = std::time::Instant::now(); + entered.retain(|at| now.duration_since(*at) < std::time::Duration::from_secs(60)); + if entered + .last() + .is_some_and(|last| now.duration_since(*last) < ENTERED_AGAIN_AFTER) + { + return false; + } + if entered.len() >= ENTERED_AGAIN_AT_MOST { + log::warn!( + "[connect] the relay refused {why} again after the window entered {} times in a \ + minute; it stays as it is until it is opened again", + entered.len() + ); + return false; + } + entered.push(now); + } + log::info!("[connect] the relay refused {why}; the window enters it again"); + // The entry holds the run's secret: never logged. + navigate(app, &entry).is_ok() +} + +/// A page load in the main window ended. On the relay's refusal (`on_the_relays_refusal`), the +/// window goes back through the entry at that page by itself (`enter_relay_again`). +pub fn watch_relay_load( + app: &tauri::AppHandle, + url: &tauri::Url, + finished: bool, +) { + if finished && on_the_relays_refusal(app, url) { + enter_relay_again(app, url.path(), "the window's page load"); + } +} + +/// The relay heard the window's page ask without the run's cookie (`Ended::WindowLostItsCookie`): +/// while the window shows a page on the relay's origin, it enters again at that page. +fn window_lost_its_cookie(app: &tauri::AppHandle) { + let Some(at) = app + .get_webview_window("main") + .and_then(|window| window.url().ok()) + .filter(|url| relay_origin(app).as_deref() == Some(&*url.origin().ascii_serialization())) + else { + return; + }; + enter_relay_again(app, at.path(), "a request of the window's page"); +} + /// The address of the OpenBot the window shows, through the relay or at its own origin, while it /// does. pub fn connected_address(app: &tauri::AppHandle) -> Option { @@ -1471,6 +1563,7 @@ fn show( }, ); } + relay::Ended::WindowLostItsCookie => window_lost_its_cookie(&listening), }) .map_err(|detail| { Problem::with( @@ -1747,7 +1840,28 @@ pub fn show_window(app: &tauri::AppHandle) { let already_showing = current .as_ref() .is_some_and(|current| crate::same_window_app(current, &destination)); - if !already_showing { + // On the relay's origin is not always showing OpenBot: on the relay's refusal, the window + // goes back through the entry at the page it was on. Before, it was left there, and opening + // it again from the Dock never got the person back (1.2.0-rc.5). + let refused = current + .as_ref() + .filter(|current| on_the_relays_refusal(app, current)); + if let Some(refused) = refused { + log::info!( + "[connect] the window was on the relay's refusal; it enters the relay again" + ); + let entry = state(app) + .connected + .live + .lock() + .unwrap() + .as_ref() + .map(|live| live.relay.entry_to(refused.path())) + .and_then(|entry| entry.parse::().ok()); + if let Some(entry) = entry { + let _ = window.navigate(entry); + } + } else if !already_showing { // Onto the relay through its entry, which hands the window its cookie on the way. let entry = relay_entry(app).and_then(|entry| entry.parse::().ok()); let _ = window.navigate(entry.unwrap_or(destination)); diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs index 8c3130ac48..6dc5403478 100644 --- a/desktop/src-tauri/src/main.rs +++ b/desktop/src-tauri/src/main.rs @@ -15480,6 +15480,13 @@ fn main() { payload.url(), payload.event() == tauri::webview::PageLoadEvent::Finished, ); + // Nor on the relay's refusal of its page: it enters the relay again + // (`desktop_connected::watch_relay_load`). + desktop_connected::watch_relay_load( + window.app_handle(), + payload.url(), + payload.event() == tauri::webview::PageLoadEvent::Finished, + ); match payload.event() { tauri::webview::PageLoadEvent::Started => { desktop_stall::page_loaded(window, page == WindowPage::Setup); diff --git a/desktop/src-tauri/src/window_ipc_tests.rs b/desktop/src-tauri/src/window_ipc_tests.rs index 84f567eaec..6ae5d122fa 100644 --- a/desktop/src-tauri/src/window_ipc_tests.rs +++ b/desktop/src-tauri/src/window_ipc_tests.rs @@ -739,3 +739,206 @@ fn an_older_openbot_and_a_sign_in_from_before_go_on_through_the_relay() { Some(address.as_str()) ); } + +/// What the relay answers a request it doesn't take to be from the OpenBot window. +const RELAY_REFUSAL: &str = "This relay is for the OpenBot window."; + +/// Shown through the relay, with a sign-in of the app's own from before, as a launch shows it: the +/// relay's origin, and the entry the window was sent to. +fn shown_through_the_relay(shell: &Connected, address: &str) -> (String, tauri::Url) { + shell.choose(choice::Mode::Connected, address, None); + shell + .store + .set(address, &format!("obr_before{}", "b".repeat(32))) + .unwrap(); + shell + .ask(SETUP, "show_connected") + .expect("shown through the relay"); + let origin = desktop_connected::relay_origin(shell.handle()).expect("the relay is up"); + let entry = shell.window.url().unwrap(); + assert_eq!( + entry.path(), + openbot_desktop_lib::connected::relay::ENTER_PATH + ); + (origin, entry) +} + +/// The window's WebKit: it enters at `entry` and keeps the cookie it is given (by name and value). +fn enter_the_relay(entry: &tauri::Url) -> String { + let entered = reqwest::blocking::Client::new() + .get(entry.as_str()) + .send() + .unwrap(); + assert_eq!(entered.status(), 200); + let set = entered.headers()["set-cookie"].to_str().unwrap().to_owned(); + set.split(';').next().unwrap().to_owned() +} + +/// A page load of the window's at `url`, as WebKit sends one (a reload of a page on the relay's own +/// origin), with the cookie or without it: its status and what the page says. +fn page_load(url: &str, cookie: Option<&str>) -> (u16, String) { + let mut request = reqwest::blocking::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .build() + .unwrap() + .get(url) + .header("accept", "text/html,application/xhtml+xml,*/*;q=0.8") + .header("sec-fetch-dest", "document") + .header("sec-fetch-mode", "navigate") + .header("sec-fetch-site", "same-origin"); + if let Some(cookie) = cookie { + request = request.header("cookie", cookie); + } + let answered = request.send().unwrap(); + (answered.status().as_u16(), answered.text().unwrap()) +} + +/** +Found in dogfooding, OpenBot Desktop connected to OpenBot Cloud through the relay: every time they +opened the window it showed only the relay's refusal, "This relay is for the OpenBot window.", with +no way to chat, until the app quit. The window's page had loaded without the run's cookie, which +the relay refuses, and Show Window (the Dock, the tray, a second launch) took a window anywhere on +the relay's origin to be showing OpenBot already, the refusal included, and left it there. The +refusal page has no script, so nothing on it could get back either. + +Opened again, a window the relay refused goes back through the entry at the page it was on, and the +entry hands it the cookie, so its page loads. +*/ +#[test] +fn a_window_the_relay_refused_goes_back_through_the_entry_when_it_is_opened_again() { + let stand = WindowStand::new(false); + let address = window_stand_in(stand.clone()); + let shell = window_shell(); + let (origin, entry) = shown_through_the_relay(&shell, &address); + let cookie = enter_the_relay(&entry); + let home = format!("{origin}/"); + assert_ne!(page_load(&home, Some(&cookie)).1, RELAY_REFUSAL); + + // WebKit no longer has the cookie, and the page's next load is refused: the white page. + assert_eq!(page_load(&home, None), (403, RELAY_REFUSAL.to_owned())); + shell.window.navigate(home.parse().unwrap()).unwrap(); + + // Opened again from the Dock. + desktop_connected::show_window(shell.handle()); + let now = shell.window.url().unwrap(); + assert_eq!( + now.path(), + openbot_desktop_lib::connected::relay::ENTER_PATH, + "left on the relay's refusal at {now}" + ); + assert_eq!(now.origin(), entry.origin()); + let given = enter_the_relay(&now); + assert_eq!(given, cookie, "the relay's own cookie for this run"); + assert_ne!(page_load(&home, Some(&given)).1, RELAY_REFUSAL); +} + +/** +The same, on screen: the window's page load is refused, and as it ends the window goes back through +the entry at that page by itself, nobody opening it again. Not over and over: a second refusal +straight after is left to the person, and opening the window again still enters. +*/ +#[test] +fn a_page_load_the_relay_refused_enters_the_relay_again_by_itself() { + let stand = WindowStand::new(false); + let address = window_stand_in(stand.clone()); + let shell = window_shell(); + let (origin, entry) = shown_through_the_relay(&shell, &address); + let cookie = enter_the_relay(&entry); + let page: tauri::Url = format!("{origin}/connections").parse().unwrap(); + + // A page that loads is left where it is. + assert_ne!(page_load(page.as_str(), Some(&cookie)).1, RELAY_REFUSAL); + shell.window.navigate(page.clone()).unwrap(); + desktop_connected::watch_relay_load(shell.handle(), &page, true); + assert_eq!(shell.window.url().unwrap(), page); + + // Refused, and the load ends on the refusal: back through the entry, to the same page. + assert_eq!(page_load(page.as_str(), None).1, RELAY_REFUSAL); + desktop_connected::watch_relay_load(shell.handle(), &page, false); + assert_eq!(shell.window.url().unwrap(), page, "not before the load ends"); + desktop_connected::watch_relay_load(shell.handle(), &page, true); + let again = shell.window.url().unwrap(); + assert_eq!(again.path(), openbot_desktop_lib::connected::relay::ENTER_PATH); + assert!(again.query().unwrap().ends_with("&to=/connections"), "{again}"); + assert_eq!(enter_the_relay(&again), cookie); + assert_ne!(page_load(page.as_str(), Some(&cookie)).1, RELAY_REFUSAL); + + // Refused again at once: left to the person, who opens the window again. + assert_eq!(page_load(page.as_str(), None).1, RELAY_REFUSAL); + shell.window.navigate(page.clone()).unwrap(); + desktop_connected::watch_relay_load(shell.handle(), &page, true); + assert_eq!(shell.window.url().unwrap(), page); + desktop_connected::show_window(shell.handle()); + assert_eq!( + shell.window.url().unwrap().path(), + openbot_desktop_lib::connected::relay::ENTER_PATH + ); +} + +/// The page on screen keeps asking, and its requests come without the cookie: the window goes back +/// through the entry at the page it shows, by itself. +#[test] +fn the_windows_page_asking_without_the_cookie_enters_the_relay_again() { + let stand = WindowStand::new(false); + let address = window_stand_in(stand.clone()); + let shell = window_shell(); + let (origin, entry) = shown_through_the_relay(&shell, &address); + let cookie = enter_the_relay(&entry); + let page: tauri::Url = format!("{origin}/connections").parse().unwrap(); + shell.window.navigate(page.clone()).unwrap(); + + let asked = reqwest::blocking::Client::new() + .get(format!("{origin}/api/v2/organizations/default/deployment")) + .header("sec-fetch-site", "same-origin") + .header("sec-fetch-dest", "empty") + .send() + .unwrap(); + assert_eq!(asked.status(), 403); + wait_until("the window entered the relay again", || { + shell.window.url().unwrap().path() == openbot_desktop_lib::connected::relay::ENTER_PATH + }); + let again = shell.window.url().unwrap(); + assert!(again.query().unwrap().ends_with("&to=/connections"), "{again}"); + assert_eq!(enter_the_relay(&again), cookie); +} + +/** +Quit, and the next launch, connected through the relay: the relay stops with the app, and the +launch starts one of its own, with a secret of its own, and sends the window through its entry, so +the window's first page load carries the new cookie and passes. The last run's cookie opens nothing. +What got the person back, where opening the window again had not. +*/ +#[test] +fn a_quit_and_the_next_launch_give_the_window_a_new_relay_it_enters() { + let stand = WindowStand::new(false); + let address = window_stand_in(stand.clone()); + let shell = window_shell(); + let (origin, entry) = shown_through_the_relay(&shell, &address); + let before = enter_the_relay(&entry); + assert_ne!(page_load(&format!("{origin}/"), Some(&before)).1, RELAY_REFUSAL); + + desktop_connected::quit(shell.handle()); + assert_eq!(desktop_connected::relay_origin(shell.handle()), None); + wait_until("the last run's relay stopped answering", || { + reqwest::blocking::Client::new() + .get(format!("{origin}/")) + .timeout(Duration::from_secs(2)) + .send() + .is_err() + }); + + // The next launch. + shell.ask(SETUP, "show_connected").expect("shown again"); + let origin = desktop_connected::relay_origin(shell.handle()).expect("a new relay"); + let entry_now = shell.window.url().unwrap(); + assert_eq!( + entry_now.path(), + openbot_desktop_lib::connected::relay::ENTER_PATH + ); + assert_ne!(entry_now, entry); + let home = format!("{origin}/"); + assert_eq!(page_load(&home, Some(&before)).1, RELAY_REFUSAL); + let now = enter_the_relay(&entry_now); + assert_ne!(now, before); + assert_ne!(page_load(&home, Some(&now)).1, RELAY_REFUSAL); +}