usesuper::*;const HOME: &str = "/Users/owner";const HOST: &str = "/Applications/CottonDB.app/Contents/Helpers/cotton-session-host";// RULE: Tool and account brokers inherit the session host's flavor; a broker launch cannot change which Cotton owns its data directory.#[test]fn both_broker_launches_preserve_the_host_flavor() {usecrate::browser_broker::{ensure_profile, Profile};usecrate::data_dir::{Flavor, FLAVOR_ENV};use std::os::unix::fs::PermissionsExtas _;use std::os::unix::net::UnixListener;use std::time::{Duration, Instant};let dir = tempfile::Builder::new().prefix("invented-broker-").tempdir_in("/tmp").unwrap();let host = dir.path().join("invented-host"); std::fs::write( &host,"#!/bin/sh\nprintf '%s\\n' \"${COTTON_FLAVOR-unset}\" > \"$COTTON_MAC_DATA_DIR/flavor\"\n", ).unwrap(); std::fs::set_permissions(&host, std::fs::Permissions::from_mode(0o700)).unwrap();let expected = Flavor::from_declared(std::env::var(FLAVOR_ENV).ok().as_deref());for account in [false, true] {let layout = Layout::new(dir.path().join(if account { "account" } else { "tool" }));let profile = if account {Profile::account(&layout, "instagram", "invented.harbor").unwrap() } else {Profile::tool(&layout) };let observed = layout.root().join("flavor");let socket = profile.socket();let (done, wait) = std::sync::mpsc::channel();let ready = std::thread::spawn(move || {let deadline = Instant::now() + Duration::from_secs(5);while std::fs::read_to_string(&observed).unwrap_or_default().is_empty() { assert!(Instant::now() < deadline, "fake broker never reported its flavor"); std::thread::sleep(Duration::from_millis(10)); }// A fake listening socket lets the production launch finish;// no Chrome, signed-in profile, or remote connection is opened.let _listener = UnixListener::bind(socket).unwrap();let _ = wait.recv_timeout(Duration::from_secs(15)); std::fs::read_to_string(observed).unwrap() });let result = ensure_profile(&layout, &profile, dir.path().to_str().unwrap(), &host, &[]);let _ = done.send(());let observed = ready.join().unwrap(); result.unwrap(); assert_eq!(Flavor::from_declared(Some(observed.trim())), expected); }}/// RULE: The browser tool's Chrome profile is Cotton's own directory, never Chrome's default one.////// Chrome 136 and later ignore the debugging switches on the default/// user-data directory and start anyway, so a profile that drifted onto it/// would be a browser tool that silently never connects — and a debugging/// channel on the everyday profile is what Chrome's change exists to prevent.#[test]fn the_profile_lives_in_the_data_dir_and_chrome_s_default_directory_is_refused() {let layout = Layout::new("/Users/owner/CottonDB");let profile = profile_dir(&layout); assert_eq!(profile, Path::new("/Users/owner/CottonDB/browser/chrome-profile")); assert!(profile.starts_with(layout.root())); assert_eq!(check_profile(&profile, HOME), Ok(()));let default = Path::new(HOME).join(DEFAULT_CHROME_DIR);for refused in [ default.clone(), default.join("Default"), default.join("Profile 1"),// A directory HOLDING the default one would be as bad.Path::new(HOME).join("Library/Application Support/Google"), ] {let said = check_profile(&refused, HOME).expect_err("the default profile was accepted"); assert!(said.contains("default profile"), "{said}"); } assert!(check_profile(Path::new("relative/profile"), HOME).is_err());}/// RULE: Cotton's Chrome is started with the DevTools pipe and never a DevTools port of any number.////// Chrome's DevTools port is unauthenticated: any process of any user on the/// Mac that can reach 127.0.0.1 could drive the signed-in browser. With/// `--remote-debugging-pipe` the only connection is two descriptors held by/// the broker that started it.#[test]fn chrome_is_started_with_the_pipe_and_no_port() {let exe = Path::new("/Applications/Google Chrome.app").join(CHROME_EXECUTABLE);let argv = crate::browser_broker::chrome_argv(&exe, Path::new("/p"), &[]); assert_eq!(argv[0], "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","the broker must be Chrome's parent to hand it the pipe — never `open`");let debugging: Vec<_> = argv.iter().filter(|arg| arg.contains("remote-debugging")).collect(); assert_eq!(debugging, vec!["--remote-debugging-pipe"]); assert!(argv.contains(&"--user-data-dir=/p".to_string()));}/// RULE: No argument handed to the browser broker can give Cotton's Chrome a DevTools port or address; only the pipe is ever passed.#[test]fn no_extra_argument_brings_a_devtools_port_back() {let exe = Path::new("/Applications/Google Chrome.app").join(CHROME_EXECUTABLE);let extra: Vec<String> = ["--headless=new","--remote-debugging-port=9222","--remote-debugging-address=0.0.0.0","-remote-debugging-port=0","--remote-debugging-pipe", ] .map(str::to_string) .to_vec();let argv = crate::browser_broker::chrome_argv(&exe, Path::new("/p"), &extra);let debugging: Vec<_> = argv.iter().filter(|arg| arg.contains("remote-debugging")).collect(); assert_eq!(debugging, vec!["--remote-debugging-pipe"], "{argv:?}"); assert!(argv.contains(&"--headless=new".to_string()), "an ordinary switch is kept: {argv:?}");}/// RULE: The browser broker stops an orphan only when the profile's lock names a running Google Chrome, never whatever process now has a stale lock's pid.#[test]fn a_stale_lock_s_pid_is_never_signalled_unless_it_is_chrome() {usecrate::processes::ProcessRow;let row = |pid, command: &str| ProcessRow { pid, ppid: 1, rss_kb: 0, cpu_pct: 0.0, command: command.to_string(), };let chrome = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";let rows = vec![ row(100, chrome), row(200, "/usr/bin/vim"), row(300, "/Applications/Google Chrome.app/Contents/Frameworks/Google Chrome Framework.framework/Helpers/Google Chrome Helper"), ];let orphan = crate::browser_broker::orphan_pid; assert_eq!(orphan("my-mac.local-100", &rows), Some(100)); assert_eq!(orphan("my-mac.local-200", &rows), None, "the owner's editor took a crashed Chrome's pid"); assert_eq!(orphan("my-mac.local-300", &rows), None, "a helper is not the browser"); assert_eq!(orphan("my-mac.local-400", &rows), None, "no such process"); assert_eq!(orphan("garbage", &rows), None);}/// RULE: The browser broker admits a connection only when the kernel says its peer is the broker's own user, and refuses one whose peer cannot be read.#[test]fn only_the_broker_s_own_user_is_admitted() {let admits = crate::browser_broker::admits; assert!(admits(Ok(501), 501)); assert!(!admits(Ok(502), 501), "another account on the Mac"); assert!(!admits(Ok(0), 501), "root is not the owner either"); assert!(!admits(Err(std::io::Error::other("no credentials")), 501));}#[test]fn the_broker_s_socket_lives_in_its_own_directory_under_the_browser_one() {let layout = Layout::new("/Users/owner/CottonDB"); assert_eq!(crate::browser_broker::socket_path(&layout),Path::new("/Users/owner/CottonDB/browser/run/broker.sock") ); assert_eq!(crate::browser_broker::run_dir(&layout), layout.browser_dir().join("run"));// The default data directory binds for any reasonable account name…let long_name = format!("/Users/{}/CottonDB", "a".repeat(40)); assert_eq!(crate::browser_broker::check_socket_path(&crate::browser_broker::socket_path( &Layout::new(long_name) )),Ok(()) );// …and one too deep to bind is refused by name, not waited on.let deep = Layout::new(format!("/Users/owner/{}", "d".repeat(80)));let said = crate::browser_broker::check_socket_path(&crate::browser_broker::socket_path(&deep)) .expect_err("a path no socket can bind was accepted"); assert!(said.contains("too deep"), "{said}");}/// RULE: The browser tool is offered only on a Mac where Chrome is installed and node is on the login PATH.////// A session handed a browser server that cannot run gets a tool that fails/// on its first call; a Mac without either gets sessions exactly as before.#[test]fn the_tool_is_offered_only_where_chrome_and_node_are() { assert_eq!(find_chrome(HOME, |_| false), None); assert_eq!( find_chrome(HOME, |_| true),Some(PathBuf::from("/Applications/Google Chrome.app")),"/Applications first" ); assert_eq!( find_chrome(HOME, |exe| exe.starts_with(HOME)),Some(PathBuf::from("/Users/owner/Applications/Google Chrome.app")) );// A login environment with no HOME and no PATH — a test host's — offers// nothing, whatever is installed on the machine running the test. assert_eq!(offer(&LoginEnv::default(), Path::new("/d"), Flavor::Dev), None);let no_node = LoginEnv::from_vars(BTreeMap::from([ ("HOME".to_string(), HOME.to_string()), ("PATH".to_string(), "/nonexistent".to_string()), ])); assert_eq!(offer(&no_node, Path::new("/d"), Flavor::Dev), None);}#[test]fn a_session_s_server_is_this_binary_pointed_at_this_host_s_data_dir() {let server = mcp_server(HOST, &Offer { data_dir: "/Users/owner/CottonDB".to_string(), flavor: Flavor::Real }); assert_eq!(server.name, "cotton-browser"); assert_eq!(server.command, HOST); assert_eq!(server.args, vec!["browser", "mcp"]); assert_eq!( server.env.get(DATA_DIR_ENV).map(String::as_str),Some("/Users/owner/CottonDB"),"the server must resolve the SAME profile as the host that offered it" );}/// RULE: The browser tool's server dials only its session's relay, and its token is never on its command line.////// Every user on a Mac can read every process's arguments with `ps`, so a/// token there would be a token for anyone; it travels in the environment.#[test]fn the_devtools_server_dials_the_relay_and_its_argv_holds_no_token() {let entry = Path::new("/d/browser").join(CHROME_DEVTOOLS_MCP).join(PACKAGE_ENTRY);let shim = Path::new("/d/browser").join(crate::browser_relay::SHIM_FILE);let argv = devtools_mcp_argv("/opt/homebrew/bin/node", &shim, &entry, 51234); assert_eq!(argv[0], "/opt/homebrew/bin/node"); assert_eq!(argv[1], "/d/browser/cotton-connect.mjs"); assert_eq!( argv[2],"/d/browser/chrome-devtools-mcp@1.10.1/package/build/src/bin/chrome-devtools-mcp.js" ); assert!(!argv.iter().any(|arg| arg.contains("npx")), "{argv:?}");let rest = argv[3..].join(" "); assert!(rest.contains("--wsEndpoint ws://127.0.0.1:51234/devtools/browser"), "{rest}"); assert!(rest.contains("--no-usage-statistics"), "{rest}"); assert!(rest.contains("--no-performance-crux"), "{rest}"); assert!(!rest.contains("wsHeaders") && !rest.contains("Bearer"), "{rest}"); assert!(DEVTOOLS_MCP_ENV.contains(&("CHROME_DEVTOOLS_MCP_NO_UPDATE_CHECKS", "1")));// It must never be told to LAUNCH a browser of its own, find one by its// profile, or dial a DevTools port directly.for never in ["--isolated", "--browserUrl", "--autoConnect", "--userDataDir"] { assert!(!rest.contains(never), "{never}: {rest}"); }}/// RULE: The browser tool's package is one exact version, fetched by URL and run only if its sha512 is the pinned one.////// `npx` resolves through the working directory's `.npmrc` and/// `node_modules`, so a repository a session opened could substitute the/// server that holds the signed-in browser. The digest is npm's own/// `integrity` string, and it must name the SAME version as the URL.#[test]fn the_package_is_pinned_by_version_and_by_digest() {let version = CHROME_DEVTOOLS_MCP.strip_prefix("chrome-devtools-mcp@").expect("the name"); assert!( version.split('.').count() == 3 && version.split('.').all(|part| part.parse::<u32>().is_ok()),"{version} is not an exact version" ); assert_eq!( PACKAGE_URL, format!("https://registry.npmjs.org/chrome-devtools-mcp/-/chrome-devtools-mcp-{version}.tgz") ); assert!(PACKAGE_SHA512.starts_with("sha512-") && PACKAGE_SHA512.len() == 7 + 88);// Synthetic bytes: the check is the hash, not the network.let bytes = b"not a tarball";let good = {use base64::Engineas _;use sha2::Digestas _; format!("sha512-{}", base64::engine::general_purpose::STANDARD.encode(sha2::Sha512::digest(bytes)) ) }; assert!(integrity_matches(bytes, &good)); assert!(!integrity_matches(b"not a tarbalL", &good)); assert!(!integrity_matches(bytes, &good.replace("sha512-", "sha256-"))); assert!(!integrity_matches(bytes, PACKAGE_SHA512)); assert!(!integrity_matches(bytes, ""));}/// RULE: Cotton's browser directory and Chrome profile are readable by the owner alone (0700).////// The data directory is world-readable, and a signed-in profile keeps its/// local storage and history in plain files; a directory an older build made/// at `0755` is tightened on the next start, not only a new one.#[test]fn the_browser_directories_are_the_owner_s_alone() {use std::os::unix::fs::PermissionsExtas _;let dir = tempfile::tempdir().expect("a temp dir");let made = dir.path().join("browser/chrome-profile"); private_dir(&made).expect("made");let mode = |path: &Path| std::fs::metadata(path).expect("exists").permissions().mode() & 0o777; assert_eq!(mode(&made), 0o700);let loose = dir.path().join("loose"); std::fs::create_dir(&loose).expect("made"); std::fs::set_permissions(&loose, std::fs::Permissions::from_mode(0o755)).expect("chmod"); private_dir(&loose).expect("tightened"); assert_eq!(mode(&loose), 0o700);}#[test]fn the_singleton_lock_names_the_pid_after_the_last_hyphen() { assert_eq!(parse_singleton_lock("mac-b.local-4242"), Some(4242)); assert_eq!(parse_singleton_lock("mac-d-2.local-17"), Some(17)); assert_eq!(parse_singleton_lock("mac-b.local-0"), None); assert_eq!(parse_singleton_lock("nohyphen"), None); assert_eq!(parse_singleton_lock("mac-b.local-abc"), None);}fn row(pid: u32, ppid: u32, rss_gb: f64) -> ProcessRow {ProcessRow { pid, ppid, rss_kb: (rss_gb * 1024.0 * 1024.0) as u64, cpu_pct: 0.0, command: "Google Chrome".to_string(), }}/// RULE: The budget holds back Chrome's cost for the browser tool, because Chrome belongs to no session's process tree.////// Chrome is launched by LaunchServices, so its parent is launchd and the/// per-session headroom never sees it. Without this, a Mac admits work/// against memory the next browser call is about to take.#[test]fn the_budget_counts_chrome_which_no_session_tree_holds() {// Running: its whole tree, the peak raised to it, and headroom up to the// larger of peak and the declared cost.let rows = [row(10, 1, 0.25), row(11, 10, 0.25), row(99, 1, 4.0)];let (peak, headroom) = budget(&rows, Some(10), true, 0.0); assert!((peak - 0.5).abs() < 1e-9, "{peak}"); assert!((headroom - (DECLARED_GB - 0.5)).abs() < 1e-9, "{headroom}");// Measured bigger than declared: the measured peak is what is held back.let (peak, headroom) = budget(&rows, Some(10), true, 2.0); assert!((peak - 2.0).abs() < 1e-9); assert!((headroom - 1.5).abs() < 1e-9);// Not running, but one tool call brings it back: the whole cost. assert_eq!(budget(&rows, None, true, 0.0), (0.0, DECLARED_GB)); assert_eq!(budget(&rows, None, true, 3.0), (3.0, 3.0));// Not running and no session holds the tool: nothing promised. assert_eq!(budget(&rows, None, false, 3.0), (3.0, 0.0));}#[test]fn a_lock_whose_chrome_is_gone_is_no_chrome() {let root = tempfile::tempdir().unwrap(); std::os::unix::fs::symlink("mac-b.local-4242", root.path().join(SINGLETON_LOCK)).unwrap(); assert_eq!(chrome_pid(root.path(), &[row(4242, 1, 0.1)]), Some(4242)); assert_eq!(chrome_pid(root.path(), &[row(7, 1, 0.1)]), None, "a crashed Chrome's lock"); assert_eq!(chrome_pid(&root.path().join("absent"), &[row(4242, 1, 0.1)]), None);}/// RULE: Each signed-in account the browser-session source reads has its own Chrome profile under `<dataDir>/browser-profiles/<site>/<account>/` and its own broker — never the agents' browser-tool profile, never another account's (owner ruling 7 Oct 2026: one profile per account; the profile stays on the serving Mac).#[test]fn an_account_s_profile_is_its_own_and_never_the_tool_s() {usecrate::browser_broker::Profile;let layout = Layout::new("/Users/owner/CottonDB");let wren = Profile::account(&layout, "instagram", "Wren.Dale").unwrap(); assert_eq!(wren.profile, Path::new("/Users/owner/CottonDB/browser-profiles/instagram/wren.dale/chrome")); assert_eq!(wren.account.as_deref(), Some("instagram/wren.dale"));let tool = Profile::tool(&layout);let other = Profile::account(&layout, "instagram", "ash_moor").unwrap();for (a, b) in [(&wren, &tool), (&wren, &other), (&other, &tool)] { assert_ne!(a.profile, b.profile); assert_ne!(a.socket(), b.socket()); assert!(!a.profile.starts_with(&b.profile) && !b.profile.starts_with(&a.profile)); } assert_eq!(Profile::parse(&layout, Some("instagram/wren.dale")).unwrap(), wren); assert_eq!(Profile::parse(&layout, None).unwrap(), tool); assert!(check_profile(&wren.profile, HOME).is_ok());}/// RULE: A site or account that is not a plain name is refused, so a profile can never be placed outside `browser-profiles` (no `..`, no slash, no hidden directory).#[test]fn an_account_name_cannot_climb_out_of_the_profiles() {usecrate::browser_broker::Profile;let layout = Layout::new("/Users/owner/CottonDB");for (site, account) in [("instagram", ".."), ("..", "x"), ("instagram", "a/b"), ("instagram", ""), ("instagram", "_run"), ("ig", ".hidden")] { assert!(Profile::account(&layout, site, account).is_err(), "{site}/{account}"); } assert!(Profile::parse(&layout, Some("no-slash")).is_err());}/// RULE: An account's broker socket binds whatever the handle's length (Instagram allows 30 characters) under any reasonable home, because its directory is a short digest of the site and account.#[test]fn an_account_s_socket_binds_for_the_longest_handle() {usecrate::browser_broker::{check_socket_path, Profile};let layout = Layout::new(format!("/Users/{}/CottonDev", "u".repeat(32)));let held = Profile::account(&layout, "instagram", &"h".repeat(30)).unwrap(); assert_eq!(check_socket_path(&held.socket()), Ok(()));}