Cotton code
174 lines · 7.1 KB · RustRaw
//! A session's door to the browser broker: a loopback listener that admits//! only requests carrying THIS session's token.//!//! The pinned `chrome-devtools-mcp` can dial a WebSocket URL and send headers//! with it (`--wsEndpoint`, `--wsHeaders`), but not a Unix socket. So each//! `browser mcp` — one per hosted session — opens a listener on//! `127.0.0.1:0`, mints a random token, and hands the server both. A//! connection whose upgrade request does not carry `Authorization: Bearer//! <token>` is answered `401` and closed before anything reaches the broker;//! one that does is spliced, byte for byte, to the broker's Unix socket//! ([`crate::browser_broker`]), which is started if it is not running — this//! is where the browser starts lazily, on the first tool call.//!//! **The token never appears on a command line.** On macOS any user's `ps`//! reads every process's arguments (but not its environment), so the token//! travels in [`TOKEN_ENV`], and a small Cotton-written shim ([`SHIM`]) moves//! it into `--wsHeaders` inside the server's own process and deletes it from//! the environment its children would inherit.use std::io::{Read as _, Write as _};use std::net::{Ipv4Addr, Shutdown, SocketAddr, TcpListener, TcpStream};use std::os::unix::net::UnixStream;use std::path::Path;use std::sync::Arc;use std::time::Duration;/// The environment variable the token travels in.pub const TOKEN_ENV: &str = "COTTON_BROWSER_TOKEN";/// The shim `node` runs in front of the server's entry point: the entry is/// its first argument, the token its environment (module doc).pub const SHIM: &str = r#"// Written by cotton-session-host (browser_relay.rs). It moves this session's// token from the environment into --wsHeaders inside this process, so the token// is never on a command line another user's `ps` can read, and no child of the// server inherits it.import { pathToFileURL } from "node:url";const token = process.env.COTTON_BROWSER_TOKEN ?? "";delete process.env.COTTON_BROWSER_TOKEN;const [entry] = process.argv.splice(2, 1);process.argv.push("--wsHeaders", JSON.stringify({ Authorization: `Bearer ${token}` }));await import(pathToFileURL(entry).href);"#;/// The shim's file name, beside the checked package.pub const SHIM_FILE: &str = "cotton-connect.mjs";/// The most an upgrade request's head may be before it is refused.const HEAD_LIMIT: usize = 16 * 1024;/// What a refused request is answered.pub const REFUSAL: &str =    "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";/// Write [`SHIM`] into `dir`, owner-only.pub fn write_shim(dir: &Path) -> Result<std::path::PathBuf, String> {    use std::os::unix::fs::PermissionsExt as _;    let path = dir.join(SHIM_FILE);    std::fs::write(&path, SHIM)        .map_err(|error| format!("{} could not be written — {error}", path.display()))?;    std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))        .map_err(|error| format!("{} could not be made private — {error}", path.display()))?;    Ok(path)}/// A fresh token: 32 bytes from the OS generator, as hex.pub fn new_token() -> Result<String, String> {    use rand::RngCore as _;    let mut bytes = [0_u8; 32];    rand::rngs::OsRng        .try_fill_bytes(&mut bytes)        .map_err(|error| format!("no randomness for the browser token — {error}"))?;    Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())}/// Compare without stopping at the first difference, so the time a refusal/// takes says nothing about how much of a guess was right.fn same(a: &[u8], b: &[u8]) -> bool {    a.len() == b.len() && a.iter().zip(b).fold(0_u8, |acc, (x, y)| acc | (x ^ y)) == 0}/// Whether an upgrade request's head carries `Authorization: Bearer <token>`.pub fn authorized(head: &str, token: &str) -> bool {    if token.is_empty() {        return false;    }    let expected = format!("Bearer {token}");    head.split("\r\n").skip(1).any(|line| {        line.split_once(':').is_some_and(|(name, value)| {            name.trim().eq_ignore_ascii_case("authorization")                && same(value.trim().as_bytes(), expected.as_bytes())        })    })}/// Read a request's head — through the blank line — and whatever came after/// it in the same reads. `None` for a head that never ends, or is too long.fn read_head(stream: &mut TcpStream) -> Option<(String, Vec<u8>)> {    let mut bytes = Vec::new();    let mut chunk = [0_u8; 4096];    loop {        if let Some(end) = bytes.windows(4).position(|window| window == b"\r\n\r\n") {            let rest = bytes.split_off(end + 4);            return Some((String::from_utf8_lossy(&bytes).to_string(), rest));        }        if bytes.len() > HEAD_LIMIT {            return None;        }        match stream.read(&mut chunk) {            Ok(0) | Err(_) => return None,            Ok(read) => bytes.extend_from_slice(&chunk[..read]),        }    }}/// How the relay reaches the broker — started on demand by the real one.pub type Dial = dyn Fn() -> Result<UnixStream, String> + Send + Sync;/// Listen on 127.0.0.1:0 for this session; the port. Each connection is/// handled on its own thread for as long as it lasts.pub fn start(token: String, dial: Arc<Dial>) -> Result<u16, String> {    let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))        .map_err(|error| format!("the browser relay could not listen — {error}"))?;    let port = listener        .local_addr()        .map_err(|error| format!("the browser relay has no address — {error}"))?        .port();    let token = Arc::new(token);    std::thread::spawn(move || {        for stream in listener.incoming() {            let Ok(stream) = stream else { continue };            let (token, dial) = (token.clone(), dial.clone());            std::thread::spawn(move || relay(stream, &token, &*dial));        }    });    Ok(port)}fn relay(mut tcp: TcpStream, token: &str, dial: &Dial) {    let _ = tcp.set_read_timeout(Some(Duration::from_secs(10)));    let Some((head, rest)) = read_head(&mut tcp) else { return };    if !authorized(&head, token) {        let _ = tcp.write_all(REFUSAL.as_bytes());        let _ = tcp.shutdown(Shutdown::Both);        return;    }    let mut unix = match dial() {        Ok(unix) => unix,        Err(error) => {            eprintln!("cotton-browser: {error}");            let _ = tcp.write_all(                b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",            );            return;        }    };    let _ = tcp.set_read_timeout(None);    if unix.write_all(head.as_bytes()).and_then(|()| unix.write_all(&rest)).is_err() {        return;    }    let (Ok(mut tcp_back), Ok(mut unix_back)) = (tcp.try_clone(), unix.try_clone()) else {        return;    };    let upstream = std::thread::spawn(move || {        let _ = std::io::copy(&mut tcp, &mut unix);        let _ = unix.shutdown(Shutdown::Write);    });    let _ = std::io::copy(&mut unix_back, &mut tcp_back);    let _ = tcp_back.shutdown(Shutdown::Both);    let _ = upstream.join();}#[cfg(test)]#[path = "browser_relay_tests.rs"]mod browser_relay_tests;