//! The browser tool against a REAL Chrome, on a throwaway profile. //! //! Skipped — with a line saying so — on a machine with no Chrome in //! `/Applications` or `~/Applications` (every Linux lane). Chrome runs //! headless here so a test run opens no window; everything else is the path //! a session takes: the broker this binary runs, Chrome on the DevTools pipe, //! the broker's socket, and a session's token-gated relay. use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::Arc; use std::time::{Duration, Instant}; use futures_util::{SinkExt as _, StreamExt as _}; use serde_json::{json, Value}; use tokio_tungstenite::tungstenite::client::IntoClientRequest as _; use tokio_tungstenite::tungstenite::Message; use cotton_session_host::browser::{installed_chrome, parse_singleton_lock, SINGLETON_LOCK}; use cotton_session_host::browser_broker::{connect, ensure_broker, socket_path}; use cotton_session_host::browser_relay; use cotton_session_host::data_dir::Layout; const HOST: &str = env!("CARGO_BIN_EXE_cotton-session-host"); fn has_chrome() -> bool { let home = std::env::var("HOME").unwrap_or_default(); let found = installed_chrome(&home).is_some(); if !found { eprintln!("skipped: Google Chrome is not installed on this machine"); } found } fn headless() -> Vec { vec!["--headless=new".to_string()] } /// A throwaway data directory whose broker and Chrome are stopped however the /// test ends — a failed assertion must not leave a headless Chrome running on /// a deleted directory. struct Browser { _dir: tempfile::TempDir, layout: Layout, } impl Browser { fn new() -> Self { let dir = tempfile::tempdir().expect("a temp dir"); let layout = Layout::new(dir.path().to_path_buf()); Self { _dir: dir, layout } } fn start(&self) -> PathBuf { ensure_broker(&self.layout, "", Path::new(HOST), &headless()).expect("the broker starts") } /// Chrome's pid, once it has taken the profile — the broker answers on /// its socket before Chrome has finished starting. fn wait_for_chrome(&self) -> Option { let deadline = Instant::now() + Duration::from_secs(15); loop { let pid = self.chrome_pid(); if pid.is_some() || Instant::now() > deadline { return pid; } std::thread::sleep(Duration::from_millis(100)); } } fn chrome_pid(&self) -> Option { let target = std::fs::read_link(self.layout.browser_profile().join(SINGLETON_LOCK)).ok()?; let pid = parse_singleton_lock(&target.to_string_lossy())?; let pid = i32::try_from(pid).ok()?; // SAFETY: a signal-0 probe. (unsafe { libc::kill(pid, 0) } == 0).then_some(pid) } /// Quit Chrome, and wait until the broker has stopped answering. fn quit(&self) { if let Some(pid) = self.chrome_pid() { // SAFETY: this test's own Chrome, found by its own profile's lock. unsafe { libc::kill(pid, libc::SIGTERM) }; } let deadline = Instant::now() + Duration::from_secs(15); while connect(&self.layout).is_some() && Instant::now() < deadline { std::thread::sleep(Duration::from_millis(100)); } } } impl Drop for Browser { fn drop(&mut self) { self.quit(); // A Chrome still starting has no lock to be found by yet: stop it by // its throwaway profile, which only this test's Chrome carries. let profile = format!("--user-data-dir={}", self.layout.browser_profile().display()); let _ = Command::new("pkill").args(["-f", "--", &profile]).status(); } } type Socket = tokio_tungstenite::WebSocketStream; async fn client(socket: &Path) -> Socket { let stream = tokio::net::UnixStream::connect(socket).await.expect("the broker answers"); tokio_tungstenite::client_async("ws://localhost/devtools/browser", stream) .await .expect("the broker speaks WebSocket") .0 } /// Send one command and wait for its answer, skipping events. async fn call(socket: &mut tokio_tungstenite::WebSocketStream, command: Value) -> Value where S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, { let id = command["id"].clone(); socket.send(Message::text(command.to_string())).await.expect("sent"); loop { let next = tokio::time::timeout(Duration::from_secs(15), socket.next()) .await .expect("answered in time"); let Some(Ok(Message::Text(text))) = next else { panic!("closed: {next:?}") }; let message: Value = serde_json::from_str(&text).expect("JSON"); if message["id"] == id { return message; } } } /// The TCP sockets `pid` listens on. fn listening(pid: i32) -> String { let out = Command::new("lsof") .args(["-a", "-nP", "-p", &pid.to_string(), "-iTCP", "-sTCP:LISTEN"]) .output() .expect("lsof runs"); String::from_utf8_lossy(&out.stdout).to_string() } /// RULE: Cotton's Chrome listens on no TCP port; its only DevTools connection is the broker's pipe. /// /// A DevTools port is full control of a signed-in browser, and loopback is /// reachable by every process of every user on the Mac. This reads Chrome's /// listening sockets back from the kernel rather than trusting the argv, and /// proves the pipe carries DevTools by opening a tab through the broker. #[tokio::test] async fn cotton_s_chrome_listens_on_no_tcp_port() { if !has_chrome() { return; } let browser = Browser::new(); let socket = browser.start(); let pid = browser.wait_for_chrome().expect("Chrome runs on the profile"); assert_eq!(listening(pid), "", "Chrome (pid {pid}) listens on TCP"); // The one door is the owner's alone: the directory, and the socket in it. use std::os::unix::fs::PermissionsExt as _; let mode = |path: &Path| std::fs::metadata(path).expect("exists").permissions().mode() & 0o777; assert_eq!(mode(socket.parent().expect("the run directory")), 0o700); assert_eq!(mode(&socket), 0o600); let mut socket = client(&socket).await; let created = call( &mut socket, json!({ "id": 1, "method": "Target.createTarget", "params": { "url": "about:blank" } }), ) .await; assert!(created["result"]["targetId"].is_string(), "{created}"); } /// RULE: Through the browser broker, one client cannot use a session id another client holds, nor close the shared browser. #[tokio::test] async fn one_client_cannot_reach_another_s_page_or_close_the_browser() { if !has_chrome() { return; } let browser = Browser::new(); let socket = browser.start(); let (mut a, mut b) = (client(&socket).await, client(&socket).await); let created = call( &mut a, json!({ "id": 1, "method": "Target.createTarget", "params": { "url": "about:blank" } }), ) .await; let target = created["result"]["targetId"].clone(); let attached = call( &mut a, json!({ "id": 2, "method": "Target.attachToTarget", "params": { "targetId": target, "flatten": true } }), ) .await; let session = attached["result"]["sessionId"].as_str().expect("a session").to_string(); let evaluate = |id: u64| { json!({ "id": id, "sessionId": session, "method": "Runtime.evaluate", "params": { "expression": "6 * 7", "returnByValue": true } }) }; let own = call(&mut a, evaluate(3)).await; assert_eq!(own["result"]["result"]["value"], 42, "{own}"); let foreign = call(&mut b, evaluate(4)).await; assert_eq!(foreign["error"]["message"], "Session with given id not found.", "{foreign}"); let close = call(&mut b, json!({ "id": 5, "method": "Browser.close" })).await; assert!(close["error"].is_object(), "{close}"); let still = call(&mut a, evaluate(6)).await; assert_eq!(still["result"]["result"]["value"], 42, "the browser was closed: {still}"); } /// RULE: Browser-broker clients are separated, not isolated: a second client can list and attach to a tab the first opened, so no one may rely on per-session tab isolation. #[tokio::test] async fn clients_share_the_browser_s_tabs_by_design() { if !has_chrome() { return; } let browser = Browser::new(); let socket = browser.start(); let (mut a, mut b) = (client(&socket).await, client(&socket).await); let created = call( &mut a, json!({ "id": 1, "method": "Target.createTarget", "params": { "url": "about:blank" } }), ) .await; let target = created["result"]["targetId"].clone(); let listed = call(&mut b, json!({ "id": 2, "method": "Target.getTargets" })).await; let seen = listed["result"]["targetInfos"] .as_array() .is_some_and(|infos| infos.iter().any(|info| info["targetId"] == target)); assert!(seen, "b does not see a's tab: {listed}"); let attached = call( &mut b, json!({ "id": 3, "method": "Target.attachToTarget", "params": { "targetId": target, "flatten": true } }), ) .await; let session = attached["result"]["sessionId"].as_str().expect("b attached").to_string(); let read = call( &mut b, json!({ "id": 4, "sessionId": session, "method": "Runtime.evaluate", "params": { "expression": "location.href", "returnByValue": true } }), ) .await; assert_eq!(read["result"]["result"]["value"], "about:blank", "{read}"); } /// RULE: A session's browser relay admits a connection only with that session's token, and then reaches Chrome. #[tokio::test] async fn the_relay_reaches_chrome_only_with_the_session_s_token() { if !has_chrome() { return; } let browser = Browser::new(); let layout = browser.layout.clone(); let token = browser_relay::new_token().expect("a token"); let dial: Arc = Arc::new(move || { let socket = ensure_broker(&layout, "", Path::new(HOST), &headless())?; std::os::unix::net::UnixStream::connect(socket).map_err(|error| error.to_string()) }); let port = browser_relay::start(token.clone(), dial).expect("the relay listens"); let url = format!("ws://127.0.0.1:{port}/devtools/browser"); for header in [None, Some("Bearer not-the-token".to_string())] { let mut request = url.as_str().into_client_request().expect("a request"); if let Some(header) = &header { request.headers_mut().insert("Authorization", header.parse().expect("a header")); } let refused = tokio_tungstenite::connect_async(request).await; assert!(refused.is_err(), "{header:?} was admitted"); } assert!(connect(&browser.layout).is_none(), "a refused request started the broker"); let mut request = url.as_str().into_client_request().expect("a request"); request .headers_mut() .insert("Authorization", format!("Bearer {token}").parse().expect("a header")); let (mut socket, _) = tokio_tungstenite::connect_async(request).await.expect("admitted"); let version = call(&mut socket, json!({ "id": 1, "method": "Browser.getVersion" })).await; assert!(version["result"]["product"].as_str().is_some_and(|p| p.contains("Chrome")), "{version}"); } /// RULE: A quit Cotton Chrome ends its broker, and the next call starts both again. #[test] fn a_quit_chrome_ends_the_broker_and_the_next_call_starts_both() { if !has_chrome() { return; } let browser = Browser::new(); let socket = browser.start(); let first = browser.wait_for_chrome().expect("Chrome runs"); assert_eq!(browser.start(), socket, "a live broker is reused"); assert_eq!(browser.chrome_pid(), Some(first), "a live Chrome was launched a second time"); browser.quit(); assert!(connect(&browser.layout).is_none(), "the broker outlived its Chrome"); browser.start(); let back = browser.wait_for_chrome().expect("Chrome runs again"); assert_ne!(back, first); assert_eq!(socket_path(&browser.layout), socket); }