From 9cf0ab8360462c455aa64ee2f0decf0dc10485cc Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 16:09:49 +0300 Subject: [PATCH 01/93] chore(handoff): preserve browser proxy work in progress --- crates/tinycomputer-browser/Cargo.toml | 2 +- crates/tinycomputer-browser/README.md | 19 +- crates/tinycomputer-browser/src/egress.rs | 590 ++++++++++++++++ .../tinycomputer-browser/src/egress_tests.rs | 629 ++++++++++++++++++ crates/tinycomputer-browser/src/lib.rs | 7 +- .../src/linked/linked_tests.rs | 377 ++++++++++- crates/tinycomputer-browser/src/linked/mod.rs | 220 +++++- .../browser_egress/browser_egress_tests.rs | 80 +++ .../src/browser_egress/mod.rs | 115 ++++ crates/tinycomputer-bus/src/lib.rs | 1 + crates/tinycomputer-bus/src/version/mod.rs | 4 +- .../src/version/version_tests.rs | 7 +- .../src/tinybus_module/browser_egress.rs | 154 +++++ .../tinybus_module/browser_egress_tests.rs | 185 ++++++ .../tinycomputer/src/tinybus_module/config.rs | 45 +- .../src/tinybus_module/dispatch/service.rs | 22 +- crates/tinycomputer/src/tinybus_module/mod.rs | 4 +- .../tinybus_module_tests/config_tests.rs | 9 + crates/tinycomputer/tests/public_api_tests.rs | 2 +- docs/crates/tinycomputer-bus/versioning.md | 12 +- docs/crates/tinycomputer/configuration.md | 25 +- 21 files changed, 2478 insertions(+), 31 deletions(-) create mode 100644 crates/tinycomputer-browser/src/egress.rs create mode 100644 crates/tinycomputer-browser/src/egress_tests.rs create mode 100644 crates/tinycomputer-bus/src/browser_egress/browser_egress_tests.rs create mode 100644 crates/tinycomputer-bus/src/browser_egress/mod.rs create mode 100644 crates/tinycomputer/src/tinybus_module/browser_egress.rs create mode 100644 crates/tinycomputer/src/tinybus_module/browser_egress_tests.rs diff --git a/crates/tinycomputer-browser/Cargo.toml b/crates/tinycomputer-browser/Cargo.toml index c699924eb..fc0e73967 100644 --- a/crates/tinycomputer-browser/Cargo.toml +++ b/crates/tinycomputer-browser/Cargo.toml @@ -36,7 +36,7 @@ tinycomputer-cursor = { workspace = true } url = { workspace = true } # Per-session locks held across engine calls; `rt` for the runtime handle a # blocking surface call runs the async browser on. -tokio = { workspace = true, features = ["sync", "rt", "time"] } +tokio = { workspace = true, features = ["sync", "rt", "time", "net", "io-util"] } # Whether the process a Chrome profile lock names is alive. sysinfo = { workspace = true } diff --git a/crates/tinycomputer-browser/README.md b/crates/tinycomputer-browser/README.md index a31fe4fa0..d644527c6 100644 --- a/crates/tinycomputer-browser/README.md +++ b/crates/tinycomputer-browser/README.md @@ -30,5 +30,20 @@ through `SessionOptions::endpoint` instead of launching one. Closing an attached session only disconnects. See `docs/technical/architecture.md` for how the surface compares with the desktop's. -Tests that launch Chromium run in the Docker lab (`docs/technical/docker-lab.md`), never -on the host. +When the compiled TinyComputer module receives a host-private `browser.egress` +scope, it selects `EnforcedAgentBrowser`: every session must be explicitly +launched by TinyComputer, attaches and caller launch overrides are refused, +and the process uses an authenticated per-session loopback proxy. The proxy +asks the host callback for TinySecurity's one-use, generation-bound dial +authorization and dials only the returned socket address. It periodically +validates active leases, including TLS CONNECT and WebSocket streams. HTTPS +contents remain opaque to the proxy and require TinySecurity's explicit +`OpaqueBrowserTraffic` classification. See +[`configuration.md`](../../docs/crates/tinycomputer/configuration.md#browser) +for the host contract and its privacy behavior. + +The Chromium egress fixture tests are ignored in the default suite because +they need an installed browser; run them explicitly with +`cargo test -p tinycomputer-browser --features agent-browser chromium_ -- --ignored`. +They use local fixtures only. Other browser integration tests run in the Docker +lab (`docs/technical/docker-lab.md`). diff --git a/crates/tinycomputer-browser/src/egress.rs b/crates/tinycomputer-browser/src/egress.rs new file mode 100644 index 000000000..ec7dd7347 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress.rs @@ -0,0 +1,590 @@ +//! Session-local browser HTTP proxy with destination authorization before each dial. +//! +//! The proxy accepts only browser HTTP proxy requests. It never resolves a name +//! locally: the authorizer returns a finite set of vetted socket addresses and +//! the proxy consumes the grant before dialing one exact address. + +use std::{future::Future, io, net::SocketAddr, pin::Pin, sync::Arc, time::Duration}; + +use base64::Engine as _; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt, copy_bidirectional}, + net::{TcpListener, TcpStream}, + task::JoinSet, +}; + +/// A destination parsed from the browser's actual proxy request. +#[derive(Clone, PartialEq, Eq)] +pub struct BrowserDialTarget { + /// `http` or `https`. + pub scheme: String, + /// Canonical host, without brackets for IPv6 literals. + pub hostname: String, + /// Effective destination port. + pub port: u16, + /// Opaque per-browser-session binding generated by `TinyComputer`. + pub session_id: String, +} + +impl std::fmt::Debug for BrowserDialTarget { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("BrowserDialTarget([REDACTED])") + } +} + +/// Opaque authorizer state plus the exact permitted sockets. +#[derive(Clone)] +pub struct DialGrant { + /// Opaque lease returned by the authenticated `TinySecurity` adapter. + pub lease: String, + /// Finite address set vetted by `TinySecurity`. + pub addresses: Vec, +} + +impl std::fmt::Debug for DialGrant { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("DialGrant([REDACTED])") + } +} + +/// The host adapter delegates every decision to `TinySecurity` over `TinyBus`. +pub trait EgressAuthorizer: Send + Sync + 'static { + /// Authorize the actual destination and return a one-use grant. + fn authorize( + &self, + target: BrowserDialTarget, + ) -> Pin> + Send>>; + /// Consume the grant before the selected socket is opened. + fn consume( + &self, + target: BrowserDialTarget, + grant: DialGrant, + address: SocketAddr, + ) -> Pin> + Send>>; + /// Revalidate an active tunnel lease. False or error closes the tunnel. + fn validate(&self, lease: String) -> Pin> + Send>>; +} + +/// An ephemeral loopback proxy owned by one browser session. +#[derive(Debug)] +pub struct EgressProxy { + address: SocketAddr, + task: tokio::task::JoinHandle<()>, +} + +impl EgressProxy { + /// Bind a private IPv4 loopback listener for one session. + /// + /// # Errors + /// + /// Returns an I/O error when the listener cannot bind or its address cannot + /// be read. + pub async fn bind( + authorizer: Arc, + session_id: String, + proxy_password: String, + ) -> io::Result { + let listener = TcpListener::bind(("127.0.0.1", 0)).await?; + let address = listener.local_addr()?; + let task = tokio::spawn(async move { + let mut connections = JoinSet::new(); + loop { + tokio::select! { + accepted = listener.accept(), if connections.len() < 64 => { + let Ok((stream, _)) = accepted else { break; }; + let auth = authorizer.clone(); + let session = session_id.clone(); + let password = proxy_password.clone(); + connections.spawn(async move { let _ = serve(stream, auth, session, password).await; }); + } + _ = connections.join_next(), if !connections.is_empty() => {} + } + } + }); + Ok(Self { address, task }) + } + + /// Chromium proxy URL; it contains no policy authority. + #[must_use] + pub fn url(&self) -> String { + format!("http://{}:{}", self.address.ip(), self.address.port()) + } +} + +impl Drop for EgressProxy { + fn drop(&mut self) { + self.task.abort(); + } +} + +async fn serve( + mut client: TcpStream, + auth: Arc, + session_id: String, + proxy_password: String, +) -> io::Result<()> { + let Some(mut request) = read_proxy_request(&mut client, &session_id, &proxy_password).await? + else { + return Ok(()); + }; + if !read_request_body(&mut client, &mut request).await? { + return refuse(&mut client).await; + } + let grant = match tokio::time::timeout( + Duration::from_secs(5), + auth.authorize(request.target.clone()), + ) + .await + { + Ok(Ok(g)) if !g.addresses.is_empty() && g.addresses.len() <= 64 => g, + _ => return refuse(&mut client).await, + }; + let Some(address) = grant.addresses.first().copied() else { + return refuse(&mut client).await; + }; + if !matches!( + tokio::time::timeout( + Duration::from_secs(5), + auth.consume(request.target.clone(), grant.clone(), address), + ) + .await, + Ok(Ok(())) + ) { + return refuse(&mut client).await; + } + let Ok(Ok(mut upstream)) = + tokio::time::timeout(Duration::from_secs(5), TcpStream::connect(address)).await + else { + return refuse(&mut client).await; + }; + let lease = grant.lease; + if !validate_lease(&auth, &lease).await? { + return Ok(()); + } + initialize_upstream(&mut client, &mut upstream, &request).await?; + if request.connect || request.has_upgrade { + tunnel_with_lease(&mut client, &mut upstream, &auth, lease).await?; + } else { + forward_response_with_lease(&mut client, &mut upstream, &auth, lease).await?; + } + Ok(()) +} + +struct ProxyRequest { + bytes: Vec, + split: usize, + lines: Vec, + method: String, + uri: String, + version: String, + target: BrowserDialTarget, + connect: bool, + body_len: usize, + has_upgrade: bool, +} + +async fn read_proxy_request( + client: &mut TcpStream, + session_id: &str, + proxy_password: &str, +) -> io::Result> { + let mut bytes = Vec::with_capacity(4096); + let mut chunk = [0u8; 1024]; + loop { + let n = tokio::time::timeout(Duration::from_secs(10), client.read(&mut chunk)) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy request timed out"))??; + if n == 0 { + return Ok(None); + } + bytes.extend_from_slice(&chunk[..n]); + if bytes.len() > 32 * 1024 { + refuse(client).await?; + return Ok(None); + } + if bytes.windows(4).any(|window| window == b"\r\n\r\n") { + break; + } + } + let Some(header_end) = bytes.windows(4).position(|window| window == b"\r\n\r\n") else { + refuse(client).await?; + return Ok(None); + }; + let split = header_end + 4; + let Ok(head) = std::str::from_utf8(&bytes[..split]) else { + refuse(client).await?; + return Ok(None); + }; + let lines: Vec = head.split("\r\n").map(str::to_owned).collect(); + let Some(request_line) = lines.first() else { + refuse(client).await?; + return Ok(None); + }; + let mut parts = request_line.split_ascii_whitespace(); + let method = parts.next().unwrap_or_default().to_owned(); + let uri = parts.next().unwrap_or_default().to_owned(); + let version = parts.next().unwrap_or_default().to_owned(); + if parts.next().is_some() || (version != "HTTP/1.1" && version != "HTTP/1.0") { + refuse(client).await?; + return Ok(None); + } + let Some(target) = proxy_target(&method, &uri, session_id) else { + refuse(client).await?; + return Ok(None); + }; + let connect = method.eq_ignore_ascii_case("CONNECT"); + let Some(headers) = parse_proxy_headers(&lines, &target, connect, session_id) else { + refuse(client).await?; + return Ok(None); + }; + if !has_proxy_auth(headers.proxy_authorization.as_deref(), proxy_password) { + write_all_bounded( + client, + b"HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm=\"tinycomputer-browser\"\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", + "browser proxy challenge timed out", + ) + .await?; + return Ok(None); + } + if connect && bytes.len() > split { + refuse(client).await?; + return Ok(None); + } + Ok(Some(ProxyRequest { + bytes, + split, + lines, + method, + uri, + version, + target, + connect, + body_len: headers.body_len, + has_upgrade: headers.has_upgrade, + })) +} + +fn proxy_target(method: &str, uri: &str, session_id: &str) -> Option { + if method.eq_ignore_ascii_case("CONNECT") { + return parse_authority(uri, "https", session_id).ok(); + } + let url = url::Url::parse(uri).ok()?; + if !matches!(url.scheme(), "http" | "ws") + || !url.username().is_empty() + || url.password().is_some() + || url.fragment().is_some() + { + return None; + } + Some(BrowserDialTarget { + scheme: "http".to_owned(), + hostname: url + .host_str()? + .trim_matches(['[', ']']) + .to_ascii_lowercase(), + port: url.port_or_known_default()?, + session_id: session_id.to_owned(), + }) +} + +struct ParsedHeaders { + body_len: usize, + has_upgrade: bool, + proxy_authorization: Option, +} + +fn parse_proxy_headers( + lines: &[String], + target: &BrowserDialTarget, + connect: bool, + session_id: &str, +) -> Option { + let mut body_len = 0usize; + let mut host_header = None; + let mut has_upgrade = false; + let mut connection_upgrade = false; + let mut proxy_authorization = None; + let mut saw_content_length = false; + for line in lines + .iter() + .skip(1) + .map(String::as_str) + .filter(|line| !line.is_empty()) + { + let (name, value) = line.split_once(':')?; + if name.eq_ignore_ascii_case("host") { + if host_header.replace(value.trim().to_owned()).is_some() { + return None; + } + } else if name.eq_ignore_ascii_case("content-length") { + if saw_content_length { + return None; + } + saw_content_length = true; + body_len = value.trim().parse().unwrap_or(usize::MAX); + } else if name.eq_ignore_ascii_case("transfer-encoding") + || name.eq_ignore_ascii_case("expect") + { + return None; + } else if name.eq_ignore_ascii_case("proxy-authorization") { + if proxy_authorization + .replace(value.trim().to_owned()) + .is_some() + { + return None; + } + } else if name.eq_ignore_ascii_case("upgrade") + && value.trim().eq_ignore_ascii_case("websocket") + { + has_upgrade = true; + } else if name.eq_ignore_ascii_case("connection") + && value + .split(',') + .any(|token| token.trim().eq_ignore_ascii_case("upgrade")) + { + connection_upgrade = true; + } + } + let host_matches = host_header.as_deref().is_some_and(|host| { + parse_authority(host, if connect { "https" } else { "http" }, session_id) + .is_ok_and(|parsed| parsed.hostname == target.hostname && parsed.port == target.port) + }); + if has_upgrade != connection_upgrade + || !host_matches + || (connect && body_len != 0) + || (!connect && (body_len > 1024 * 1024 || (has_upgrade && body_len != 0))) + { + return None; + } + Some(ParsedHeaders { + body_len, + has_upgrade, + proxy_authorization, + }) +} + +fn has_proxy_auth(proxy_authorization: Option<&str>, password: &str) -> bool { + let expected = format!( + "Basic {}", + base64::engine::general_purpose::STANDARD.encode(format!("tinycomputer:{password}")) + ); + proxy_authorization + .is_some_and(|actual| constant_time_eq(actual.as_bytes(), expected.as_bytes())) +} + +async fn initialize_upstream( + client: &mut TcpStream, + upstream: &mut TcpStream, + request: &ProxyRequest, +) -> io::Result<()> { + if request.connect { + write_all_bounded( + client, + b"HTTP/1.1 200 Connection Established\r\n\r\n", + "browser CONNECT response timed out", + ) + .await?; + if request.bytes.len() > request.split { + return write_all_bounded( + upstream, + &request.bytes[request.split..], + "browser CONNECT payload timed out", + ) + .await; + } + return Ok(()); + } + let url = url::Url::parse(&request.uri) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid HTTP proxy URL"))?; + let path = if let Some(query) = url.query() { + format!("{}?{query}", url.path()) + } else { + url.path().to_owned() + }; + let mut forwarded = format!("{} {path} {}\r\n", request.method, request.version); + for line in request + .lines + .iter() + .skip(1) + .map(String::as_str) + .filter(|line| !line.is_empty()) + { + let name = line.split_once(':').map_or("", |(name, _)| name); + if !name.eq_ignore_ascii_case("connection") + && !name.eq_ignore_ascii_case("proxy-connection") + && !name.eq_ignore_ascii_case("proxy-authorization") + { + forwarded.push_str(line); + forwarded.push_str("\r\n"); + } + } + if request.has_upgrade { + forwarded.push_str("Connection: Upgrade\r\n\r\n"); + } else { + forwarded.push_str("Connection: close\r\n\r\n"); + } + write_all_bounded( + upstream, + forwarded.as_bytes(), + "browser upstream request timed out", + ) + .await?; + write_all_bounded( + upstream, + &request.bytes[request.split..], + "browser upstream body timed out", + ) + .await +} + +async fn read_request_body(client: &mut TcpStream, request: &mut ProxyRequest) -> io::Result { + if request.has_upgrade || request.connect { + return Ok(true); + } + let received = request.bytes.len().saturating_sub(request.split); + if received > request.body_len { + return Ok(false); + } + let mut chunk = [0u8; 1024]; + while request.bytes.len().saturating_sub(request.split) < request.body_len { + let n = tokio::time::timeout(Duration::from_secs(10), client.read(&mut chunk)) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy body timed out"))??; + if n == 0 { + return Ok(false); + } + request.bytes.extend_from_slice(&chunk[..n]); + if request.bytes.len() > request.split + request.body_len { + return Ok(false); + } + } + Ok(true) +} + +fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { + let mut difference = left.len() ^ right.len(); + for index in 0..left.len().max(right.len()) { + difference |= usize::from( + left.get(index).copied().unwrap_or(0) ^ right.get(index).copied().unwrap_or(0), + ); + } + difference == 0 +} + +async fn tunnel_with_lease( + client: &mut TcpStream, + upstream: &mut TcpStream, + auth: &Arc, + lease: String, +) -> io::Result<()> { + let relay = copy_bidirectional(client, upstream); + tokio::pin!(relay); + let mut validations = validation_interval(); + loop { + tokio::select! { + biased; + _ = validations.tick() => { + if !validate_lease(auth, &lease).await? { return Ok(()); } + }, + result = &mut relay => { result?; return Ok(()); }, + } + } +} + +async fn forward_response_with_lease( + client: &mut TcpStream, + upstream: &mut TcpStream, + auth: &Arc, + lease: String, +) -> io::Result<()> { + let mut chunk = [0u8; 8192]; + let mut validations = validation_interval(); + loop { + tokio::select! { + biased; + _ = validations.tick() => { + if !validate_lease(auth, &lease).await? { return Ok(()); } + }, + result = upstream.read(&mut chunk) => { + let n = result?; + if n == 0 { return Ok(()); } + write_all_bounded(client, &chunk[..n], "browser response write timed out").await?; + }, + } + } +} + +fn validation_interval() -> tokio::time::Interval { + let period = Duration::from_secs(1); + let mut interval = tokio::time::interval_at(tokio::time::Instant::now() + period, period); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + interval +} + +async fn validate_lease(auth: &Arc, lease: &str) -> io::Result { + tokio::time::timeout(Duration::from_secs(2), auth.validate(lease.to_owned())) + .await + .map_err(|_| { + io::Error::new( + io::ErrorKind::TimedOut, + "browser lease validation timed out", + ) + })? +} + +pub(super) fn parse_authority( + value: &str, + scheme: &str, + session_id: &str, +) -> io::Result { + if value.contains("://") { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "authority form required", + )); + } + let authority = url::Url::parse(&format!("{scheme}://{value}/")) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid CONNECT authority"))?; + if authority.path() != "/" + || authority.query().is_some() + || authority.fragment().is_some() + || !authority.username().is_empty() + || authority.password().is_some() + { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid CONNECT authority", + )); + } + Ok(BrowserDialTarget { + scheme: scheme.to_owned(), + hostname: authority + .host_str() + .unwrap_or_default() + .trim_matches(['[', ']']) + .to_ascii_lowercase(), + port: authority + .port() + .unwrap_or(if scheme == "http" { 80 } else { 443 }), + session_id: session_id.to_owned(), + }) +} + +async fn refuse(client: &mut TcpStream) -> io::Result<()> { + write_all_bounded( + client, + b"HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", + "browser refusal response timed out", + ) + .await +} + +async fn write_all_bounded( + stream: &mut TcpStream, + bytes: &[u8], + message: &'static str, +) -> io::Result<()> { + tokio::time::timeout(Duration::from_secs(5), stream.write_all(bytes)) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, message))? +} diff --git a/crates/tinycomputer-browser/src/egress_tests.rs b/crates/tinycomputer-browser/src/egress_tests.rs new file mode 100644 index 000000000..6453a4629 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress_tests.rs @@ -0,0 +1,629 @@ +//! Local socket tests for browser proxy enforcement. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::{ + io, + net::SocketAddr, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, +}; + +use base64::Engine as _; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, +}; + +use crate::{BrowserDialTarget, DialGrant, EgressAuthorizer, EgressProxy, egress::parse_authority}; + +const FIXTURE_PASSWORD: &str = "fixture-proxy-secret"; + +fn proxy_authorization() -> String { + format!( + "Basic {}", + base64::engine::general_purpose::STANDARD + .encode(format!("tinycomputer:{FIXTURE_PASSWORD}")) + ) +} + +#[test] +fn browser_dial_target_debug_does_not_disclose_session_or_destination() { + let target = BrowserDialTarget { + scheme: "https".into(), + hostname: "private.example.test".into(), + port: 443, + session_id: "private-browser-session".into(), + }; + let debug = format!("{target:?}"); + assert!(!debug.contains("private.example.test")); + assert!(!debug.contains("private-browser-session")); + assert!(debug.contains("REDACTED")); +} + +#[test] +fn dial_grant_debug_does_not_disclose_lease_or_destination() { + let grant = DialGrant { + lease: "private-opaque-nonce".into(), + addresses: vec!["203.0.113.77:8443".parse().unwrap()], + }; + let debug = format!("{grant:?}"); + assert!(!debug.contains("private-opaque-nonce")); + assert!(!debug.contains("203.0.113.77")); + assert!(debug.contains("REDACTED")); +} + +#[test] +fn proxy_authority_uses_scheme_defaults_and_canonical_ipv6_literals() { + assert_eq!( + parse_authority("example.test", "http", "session") + .unwrap() + .port, + 80 + ); + assert_eq!( + parse_authority("example.test", "https", "session") + .unwrap() + .port, + 443 + ); + let ipv6 = parse_authority("[2001:4860:4860::8888]:443", "https", "session").unwrap(); + assert_eq!(ipv6.hostname, "2001:4860:4860::8888"); + assert!(parse_authority("https://example.test:443", "https", "session").is_err()); +} + +#[derive(Clone)] +struct FixtureAuthorizer { + address: SocketAddr, + allow: bool, + consumed: Arc, +} + +impl EgressAuthorizer for FixtureAuthorizer { + fn authorize( + &self, + _target: BrowserDialTarget, + ) -> std::pin::Pin> + Send>> { + let address = self.address; + let allow = self.allow; + Box::pin(async move { + if allow { + Ok(DialGrant { + lease: "fixture-lease".into(), + addresses: vec![address], + }) + } else { + Err(io::Error::new(io::ErrorKind::PermissionDenied, "denied")) + } + }) + } + fn consume( + &self, + _target: BrowserDialTarget, + _grant: DialGrant, + address: SocketAddr, + ) -> std::pin::Pin> + Send>> { + let expected = self.address; + let consumed = self.consumed.clone(); + Box::pin(async move { + if address == expected { + consumed.store(true, Ordering::SeqCst); + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "wrong address", + )) + } + }) + } + fn validate( + &self, + _lease: String, + ) -> std::pin::Pin> + Send>> { + Box::pin(async { Ok(true) }) + } +} + +#[tokio::test] +async fn approved_connect_reaches_only_the_consumed_socket() { + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let authorizer = Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }); + let proxy = EgressProxy::bind( + authorizer.clone(), + "test-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let ((), upstream_client) = tokio::join!( + async { + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "CONNECT example.test:{} HTTP/1.1\r\nHost: example.test:{}\r\nProxy-Authorization: {}\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = [0; 128]; + let n = client.read(&mut response).await.unwrap(); + assert!( + std::str::from_utf8(&response[..n]) + .unwrap() + .contains("200 Connection Established") + ); + client.write_all(b"ping").await.unwrap(); + }, + destination.accept() + ); + let (mut upstream_client, _) = upstream_client.unwrap(); + assert!(authorizer.consumed.load(Ordering::SeqCst)); + let mut payload = [0; 4]; + upstream_client.read_exact(&mut payload).await.unwrap(); + assert_eq!(&payload, b"ping"); +} + +#[tokio::test] +async fn denied_destination_never_connects_to_the_fixture() { + let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + destination.set_nonblocking(true).unwrap(); + let address = destination.local_addr().unwrap(); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: false, + consumed: Arc::new(AtomicBool::new(false)), + }), + "denied-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "CONNECT metadata.test:{} HTTP/1.1\r\nHost: metadata.test:{}\r\nProxy-Authorization: {}\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = [0; 128]; + let n = client.read(&mut response).await.unwrap(); + assert!( + std::str::from_utf8(&response[..n]) + .unwrap() + .contains("403 Forbidden") + ); + assert_eq!( + destination.accept().unwrap_err().kind(), + io::ErrorKind::WouldBlock + ); +} + +#[tokio::test] +async fn unauthenticated_local_clients_cannot_use_the_session_policy_broker() { + let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + destination.set_nonblocking(true).unwrap(); + let address = destination.local_addr().unwrap(); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }), + "protected-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "CONNECT public.example:{} HTTP/1.1\r\nHost: public.example:{}\r\n\r\n", + address.port(), + address.port() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = [0; 256]; + let n = client.read(&mut response).await.unwrap(); + let response = std::str::from_utf8(&response[..n]).unwrap(); + assert!(response.contains("407 Proxy Authentication Required")); + assert_eq!( + destination.accept().unwrap_err().kind(), + io::ErrorKind::WouldBlock + ); +} + +#[tokio::test] +async fn approved_http_request_is_rewritten_and_forwarded_to_approved_fixture() { + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 512]; + loop { + let n = socket.read(&mut chunk).await.unwrap(); + request.extend_from_slice(&chunk[..n]); + if request.windows(4).any(|window| window == b"\r\n\r\n") { + break; + } + } + let request = std::str::from_utf8(&request).unwrap(); + assert!(request.starts_with("GET /control?ready=1 HTTP/1.1\r\n")); + assert!(request.contains(&format!("Host: control.test:{}\r\n", address.port()))); + assert!(request.contains("Connection: close\r\n")); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + .await + .unwrap(); + }); + let authorizer = Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }); + let proxy = EgressProxy::bind( + authorizer.clone(), + "http-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "GET http://control.test:{}/control?ready=1 HTTP/1.1\r\nHost: control.test:{}\r\nProxy-Authorization: {}\r\nConnection: keep-alive\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = Vec::new(); + client.read_to_end(&mut response).await.unwrap(); + assert!( + std::str::from_utf8(&response) + .unwrap() + .ends_with("\r\n\r\nok") + ); + assert!(authorizer.consumed.load(Ordering::SeqCst)); + server.await.unwrap(); +} + +#[tokio::test] +async fn approved_http_request_body_is_forwarded_without_framing_changes() { + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 512]; + loop { + let n = socket.read(&mut chunk).await.unwrap(); + request.extend_from_slice(&chunk[..n]); + if let Some(split) = request.windows(4).position(|window| window == b"\r\n\r\n") + && request.len() >= split + 8 + { + break; + } + } + assert!(request.ends_with(b"data")); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + .await + .unwrap(); + }); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }), + "body-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "POST http://body.test:{}/submit HTTP/1.1\r\nHost: body.test:{}\r\nProxy-Authorization: {}\r\nContent-Length: 4\r\n\r\ndata", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = Vec::new(); + client.read_to_end(&mut response).await.unwrap(); + assert!( + std::str::from_utf8(&response) + .unwrap() + .ends_with("\r\n\r\nok") + ); + server.await.unwrap(); +} + +#[tokio::test] +async fn duplicate_lengths_and_pipelined_authorities_are_refused_before_dial() { + let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + destination.set_nonblocking(true).unwrap(); + let address = destination.local_addr().unwrap(); + for suffix in [ + "Content-Length: 0\r\nContent-Length: 0\r\n\r\n", + "Content-Length: 0\r\n\r\nGET http://other.test/ HTTP/1.1\r\nHost: other.test\r\n\r\n", + ] { + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }), + "malformed-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "GET http://one.test:{}/ HTTP/1.1\r\nHost: one.test:{}\r\nProxy-Authorization: {}\r\n{}", + address.port(), + address.port(), + proxy_authorization(), + suffix + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = [0; 128]; + let n = client.read(&mut response).await.unwrap(); + assert!( + std::str::from_utf8(&response[..n]) + .unwrap() + .contains("403 Forbidden") + ); + assert_eq!( + destination.accept().unwrap_err().kind(), + io::ErrorKind::WouldBlock + ); + } +} + +#[tokio::test] +async fn approved_websocket_upgrade_is_forwarded_and_tunneled() { + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 512]; + loop { + let n = socket.read(&mut chunk).await.unwrap(); + request.extend_from_slice(&chunk[..n]); + if request.windows(4).any(|window| window == b"\r\n\r\n") { + break; + } + } + let request = std::str::from_utf8(&request).unwrap(); + assert!(request.starts_with("GET /socket HTTP/1.1\r\n")); + assert!(request.contains("Connection: Upgrade\r\n")); + assert!(request.contains("Upgrade: websocket\r\n")); + socket + .write_all(b"HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n") + .await + .unwrap(); + let mut ping = [0; 4]; + socket.read_exact(&mut ping).await.unwrap(); + assert_eq!(&ping, b"ping"); + socket.write_all(b"pong").await.unwrap(); + }); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }), + "websocket-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "GET ws://socket.test:{}/socket HTTP/1.1\r\nHost: socket.test:{}\r\nProxy-Authorization: {}\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut handshake = [0; 256]; + let n = client.read(&mut handshake).await.unwrap(); + assert!( + std::str::from_utf8(&handshake[..n]) + .unwrap() + .contains("101 Switching Protocols") + ); + client.write_all(b"ping").await.unwrap(); + let mut pong = [0; 4]; + client.read_exact(&mut pong).await.unwrap(); + assert_eq!(&pong, b"pong"); + server.await.unwrap(); +} + +struct RevokingAuthorizer { + address: SocketAddr, + validations: Arc, +} + +impl EgressAuthorizer for RevokingAuthorizer { + fn authorize( + &self, + _target: BrowserDialTarget, + ) -> std::pin::Pin> + Send>> { + let address = self.address; + Box::pin(async move { + Ok(DialGrant { + lease: "revoked-during-stream".into(), + addresses: vec![address], + }) + }) + } + + fn consume( + &self, + _target: BrowserDialTarget, + _grant: DialGrant, + address: SocketAddr, + ) -> std::pin::Pin> + Send>> { + let expected = self.address; + Box::pin(async move { + if address == expected { + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "wrong address", + )) + } + }) + } + + fn validate( + &self, + _lease: String, + ) -> std::pin::Pin> + Send>> { + let validations = self.validations.clone(); + Box::pin(async move { + let call = validations.fetch_add(1, Ordering::SeqCst); + Ok(call == 0) + }) + } +} + +#[tokio::test] +async fn continuous_http_response_still_revalidates_and_closes_revoked_lease() { + use std::sync::atomic::AtomicUsize; + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + let mut request = [0; 2048]; + let _ = socket.read(&mut request).await.unwrap(); + for _ in 0..4096 { + if socket.write_all(&[b'x'; 1024]).await.is_err() { + return; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + }); + let validations = Arc::new(AtomicUsize::new(0)); + let proxy = EgressProxy::bind( + Arc::new(RevokingAuthorizer { + address, + validations: validations.clone(), + }), + "stream-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "GET http://stream.test:{}/ HTTP/1.1\r\nHost: stream.test:{}\r\nProxy-Authorization: {}\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = Vec::new(); + tokio::time::timeout( + std::time::Duration::from_secs(4), + client.read_to_end(&mut response), + ) + .await + .expect("revoked response stream should be closed promptly") + .unwrap(); + assert!(validations.load(Ordering::SeqCst) > 0); + assert!( + response.len() < 4096 * 1024, + "revoked response kept streaming" + ); + server.await.unwrap(); +} + +#[tokio::test] +async fn dropping_session_proxy_closes_its_listener() { + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address: destination.local_addr().unwrap(), + allow: false, + consumed: Arc::new(AtomicBool::new(false)), + }), + "closed-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let endpoint = proxy.url().replace("http://", ""); + drop(proxy); + tokio::task::yield_now().await; + assert!(TcpStream::connect(endpoint).await.is_err()); +} diff --git a/crates/tinycomputer-browser/src/lib.rs b/crates/tinycomputer-browser/src/lib.rs index f42cc376b..38675ad4d 100644 --- a/crates/tinycomputer-browser/src/lib.rs +++ b/crates/tinycomputer-browser/src/lib.rs @@ -31,6 +31,10 @@ mod convert; mod deep; +mod egress; +#[cfg(test)] +#[path = "egress_tests.rs"] +mod egress_tests; mod engine; mod error; #[cfg(test)] @@ -44,10 +48,11 @@ mod reply; mod sessions; mod surface; +pub use egress::{BrowserDialTarget, DialGrant, EgressAuthorizer, EgressProxy}; pub use engine::{Engine, Launcher, Reply}; pub use error::{Error, Result}; #[cfg(feature = "agent-browser")] -pub use linked::AgentBrowser; +pub use linked::{AgentBrowser, EnforcedAgentBrowser}; pub use outputs::SWEEP_INTERVAL; pub use profile_lock::{claim_profile, in_use as profile_in_use, release as release_profile}; pub use sessions::{Browser, MAX_SESSIONS}; diff --git a/crates/tinycomputer-browser/src/linked/linked_tests.rs b/crates/tinycomputer-browser/src/linked/linked_tests.rs index e19488e15..0d365c6c1 100644 --- a/crates/tinycomputer-browser/src/linked/linked_tests.rs +++ b/crates/tinycomputer-browser/src/linked/linked_tests.rs @@ -7,9 +7,52 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::json; +use std::{ + io, + net::SocketAddr, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, +}; -use super::AgentBrowser; -use crate::engine::Launcher; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpListener, +}; + +use super::{AgentBrowser, EnforcedAgentBrowser, Linked, enforce_launch, state_options}; +use crate::{ + BrowserDialTarget, DialGrant, EgressAuthorizer, + engine::{Engine, Launcher}, +}; +use agent_browser::DaemonState; + +#[derive(Debug)] +struct RejectAll; + +impl EgressAuthorizer for RejectAll { + fn authorize( + &self, + _: BrowserDialTarget, + ) -> std::pin::Pin> + Send>> { + Box::pin(async { Err(io::Error::new(io::ErrorKind::PermissionDenied, "denied")) }) + } + fn consume( + &self, + _: BrowserDialTarget, + _: DialGrant, + _: SocketAddr, + ) -> std::pin::Pin> + Send>> { + Box::pin(async { Err(io::Error::new(io::ErrorKind::PermissionDenied, "denied")) }) + } + fn validate( + &self, + _: String, + ) -> std::pin::Pin> + Send>> { + Box::pin(async { Ok(false) }) + } +} #[tokio::test] async fn an_empty_command_is_answered_without_launching_a_browser() { @@ -22,3 +65,333 @@ async fn an_empty_command_is_answered_without_launching_a_browser() { .is_some_and(|error| !error.is_empty()) ); } + +#[tokio::test] +async fn enforced_browser_refuses_implicit_launch_before_any_request() { + let mut engine = EnforcedAgentBrowser::new(Arc::new(RejectAll)).open("unit"); + let reply = engine + .execute(json!({"id":"navigate","action":"navigate","url":"http://127.0.0.1/"})) + .await; + assert_eq!(reply["success"], false); + assert!(reply["error"].as_str().unwrap().contains("enforced launch")); +} + +#[tokio::test] +async fn a_closed_or_lost_browser_cannot_implicitly_launch_without_the_proxy() { + let mut engine = Linked { + state: DaemonState::with_options(state_options("closed")), + egress_authorizer: Some(Arc::new(RejectAll)), + proxy: None, + proxy_session_id: "private-session-id".into(), + enforced_launch: true, + }; + let reply = engine + .execute(json!({"id":"navigate","action":"navigate","url":"http://public.example/"})) + .await; + assert_eq!(reply["success"], false); + assert!( + reply["error"] + .as_str() + .unwrap() + .contains("live browser session") + ); +} + +#[tokio::test] +#[ignore = "requires an installed Chromium; exercises its actual proxy behavior"] +async fn chromium_loopback_navigation_uses_the_authenticated_session_proxy() { + let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = fixture.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = fixture.accept().await.unwrap(); + let mut request = [0; 4096]; + let _ = socket.read(&mut request).await.unwrap(); + socket + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 22\r\nConnection: close\r\n\r\n

proxy fixture

", + ) + .await + .unwrap(); + }); + let authorizations = Arc::new(AtomicUsize::new(0)); + let mut browser = EnforcedAgentBrowser::new(Arc::new(RejectAllButFixture { + address, + authorizations: authorizations.clone(), + })) + .open("live-egress"); + let launch = browser + .execute(json!({"id":"launch","action":"launch","headless":true,"args":[]})) + .await; + assert_eq!(launch["success"], true, "{launch}"); + let navigation = browser + .execute(json!({ + "id":"navigate", + "action":"navigate", + "url":format!("http://127.0.0.1:{}/", address.port()) + })) + .await; + browser + .execute(json!({"id":"close","action":"close"})) + .await; + assert_eq!( + navigation["success"], + true, + "{navigation}; proxy authorizations: {}", + authorizations.load(Ordering::SeqCst) + ); + server.await.unwrap(); +} + +#[tokio::test] +#[ignore = "requires an installed Chromium; verifies denied subresource egress"] +async fn chromium_subresource_never_reaches_a_denied_destination() { + let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + denied.set_nonblocking(true).unwrap(); + let denied_address = denied.local_addr().unwrap(); + let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = fixture.local_addr().unwrap(); + let body = format!( + "", + denied_address.port() + ); + let fixture_server = tokio::spawn(async move { + let (mut socket, _) = fixture.accept().await.unwrap(); + let mut request = [0; 4096]; + let _ = socket.read(&mut request).await.unwrap(); + socket + .write_all( + format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), body + ) + .as_bytes(), + ) + .await + .unwrap(); + }); + let mut browser = EnforcedAgentBrowser::new(Arc::new(RejectAllButFixture { + address, + authorizations: Arc::new(AtomicUsize::new(0)), + })) + .open("live-egress-subresource"); + let launch = browser + .execute(json!({"id":"launch","action":"launch","headless":true,"args":[]})) + .await; + assert_eq!(launch["success"], true, "{launch}"); + let navigation = browser + .execute(json!({ + "id":"navigate", + "action":"navigate", + "url":format!("http://127.0.0.1:{}/", address.port()) + })) + .await; + browser + .execute(json!({"id":"close","action":"close"})) + .await; + assert_eq!(navigation["success"], true, "{navigation}"); + fixture_server.await.unwrap(); + assert_eq!( + denied.accept().unwrap_err().kind(), + io::ErrorKind::WouldBlock, + "the denied subresource destination must never receive a connection" + ); +} + +#[tokio::test] +#[ignore = "requires an installed Chromium; verifies denied redirect egress"] +async fn chromium_redirect_never_reaches_a_denied_destination() { + let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + denied.set_nonblocking(true).unwrap(); + let denied_address = denied.local_addr().unwrap(); + let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = fixture.local_addr().unwrap(); + let fixture_server = tokio::spawn(async move { + let (mut socket, _) = fixture.accept().await.unwrap(); + let mut request = [0; 4096]; + let _ = socket.read(&mut request).await.unwrap(); + socket + .write_all( + format!( + "HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:{}/private\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + denied_address.port() + ) + .as_bytes(), + ) + .await + .unwrap(); + }); + let mut browser = EnforcedAgentBrowser::new(Arc::new(RejectAllButFixture { + address, + authorizations: Arc::new(AtomicUsize::new(0)), + })) + .open("live-egress-redirect"); + let launch = browser + .execute(json!({"id":"launch","action":"launch","headless":true,"args":[]})) + .await; + assert_eq!(launch["success"], true, "{launch}"); + let navigation = browser + .execute(json!({ + "id":"navigate", + "action":"navigate", + "url":format!("http://127.0.0.1:{}/", address.port()) + })) + .await; + browser + .execute(json!({"id":"close","action":"close"})) + .await; + assert_eq!(navigation["success"], false, "{navigation}"); + fixture_server.await.unwrap(); + assert_eq!( + denied.accept().unwrap_err().kind(), + io::ErrorKind::WouldBlock, + "the denied redirect destination must never receive a connection" + ); +} + +#[tokio::test] +#[ignore = "requires an installed Chromium; verifies denied WebSocket egress"] +async fn chromium_websocket_never_reaches_a_denied_destination() { + let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + denied.set_nonblocking(true).unwrap(); + let denied_address = denied.local_addr().unwrap(); + let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = fixture.local_addr().unwrap(); + let body = format!( + "", + denied_address.port() + ); + let fixture_server = tokio::spawn(async move { + let (mut socket, _) = fixture.accept().await.unwrap(); + let mut request = [0; 4096]; + let _ = socket.read(&mut request).await.unwrap(); + socket + .write_all( + format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), body + ) + .as_bytes(), + ) + .await + .unwrap(); + }); + let mut browser = EnforcedAgentBrowser::new(Arc::new(RejectAllButFixture { + address, + authorizations: Arc::new(AtomicUsize::new(0)), + })) + .open("live-egress-websocket"); + let launch = browser + .execute(json!({"id":"launch","action":"launch","headless":true,"args":[]})) + .await; + assert_eq!(launch["success"], true, "{launch}"); + let navigation = browser + .execute(json!({ + "id":"navigate", + "action":"navigate", + "url":format!("http://127.0.0.1:{}/", address.port()) + })) + .await; + browser + .execute(json!({"id":"close","action":"close"})) + .await; + assert_eq!(navigation["success"], true, "{navigation}"); + fixture_server.await.unwrap(); + assert_eq!( + denied.accept().unwrap_err().kind(), + io::ErrorKind::WouldBlock, + "the denied WebSocket destination must never receive a connection" + ); +} + +#[derive(Debug)] +struct RejectAllButFixture { + address: SocketAddr, + authorizations: Arc, +} + +impl EgressAuthorizer for RejectAllButFixture { + fn authorize( + &self, + target: BrowserDialTarget, + ) -> std::pin::Pin> + Send>> { + let address = self.address; + self.authorizations.fetch_add(1, Ordering::SeqCst); + Box::pin(async move { + if target.hostname == "127.0.0.1" && target.port == address.port() { + Ok(DialGrant { + lease: "live-fixture-lease".into(), + addresses: vec![address], + }) + } else { + Err(io::Error::new(io::ErrorKind::PermissionDenied, "denied")) + } + }) + } + + fn consume( + &self, + _: BrowserDialTarget, + grant: DialGrant, + address: SocketAddr, + ) -> std::pin::Pin> + Send>> { + Box::pin(async move { + if grant.addresses.contains(&address) { + Ok(()) + } else { + Err(io::Error::new(io::ErrorKind::PermissionDenied, "denied")) + } + }) + } + + fn validate( + &self, + _: String, + ) -> std::pin::Pin> + Send>> { + Box::pin(async { Ok(true) }) + } +} + +#[test] +fn enforced_launch_uses_only_the_host_proxy_and_network_containment_flags() { + let launch = enforce_launch( + json!({"id":"launch","action":"launch","headless":true,"args":[]}), + "http://127.0.0.1:39123", + "session-secret", + ) + .expect("enforced launch"); + assert_eq!(launch["proxy"]["server"], "http://127.0.0.1:39123"); + assert_eq!(launch["proxy"]["bypass"], "<-loopback>"); + assert_eq!(launch["proxy"]["username"], "tinycomputer"); + assert_eq!(launch["proxy"]["password"], "session-secret"); + assert_eq!( + launch["args"], + json!([ + "--disable-quic", + "--disable-http2", + "--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1", + "--force-webrtc-ip-handling-policy=disable_non_proxied_udp" + ]) + ); +} + +#[test] +fn enforced_launch_refuses_external_cdp_and_caller_flags() { + let cdp = enforce_launch( + json!({"action":"launch","cdpUrl":"http://127.0.0.1:9222"}), + "http://127.0.0.1:39123", + "session-secret", + ); + assert!(cdp.is_err()); + let args = enforce_launch( + json!({"action":"launch","args":["--proxy-server=http://attacker.test"]}), + "http://127.0.0.1:39123", + "session-secret", + ); + assert!(args.is_err()); + let executable = enforce_launch( + json!({"action":"launch","executablePath":"/tmp/attacker-browser"}), + "http://127.0.0.1:39123", + "session-secret", + ); + assert!(executable.is_err()); +} diff --git a/crates/tinycomputer-browser/src/linked/mod.rs b/crates/tinycomputer-browser/src/linked/mod.rs index f570def6c..e1e26ce93 100644 --- a/crates/tinycomputer-browser/src/linked/mod.rs +++ b/crates/tinycomputer-browser/src/linked/mod.rs @@ -10,10 +10,13 @@ //! serialized through [`ENGINE`]. Calls on one session are already serialized //! by the session lock. +use crate::{ + egress::{EgressAuthorizer, EgressProxy}, + engine::{Engine, Launcher, Reply}, +}; use agent_browser::{DaemonState, StateOptions, execute_command}; -use serde_json::Value; - -use crate::engine::{Engine, Launcher, Reply}; +use serde_json::{Value, json}; +use std::sync::Arc; /// Serializes commands across sessions; see the module docs. static ENGINE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); @@ -22,31 +25,228 @@ static ENGINE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); #[derive(Debug, Clone, Copy, Default)] pub struct AgentBrowser; +/// A launcher that pins every owned Chromium process to a host-created proxy. +/// The proxy address is host control and cannot be selected by browser calls. +#[derive(Clone)] +pub struct EnforcedAgentBrowser { + authorizer: Arc, +} + +impl std::fmt::Debug for EnforcedAgentBrowser { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("EnforcedAgentBrowser([host authorizer])") + } +} + +impl EnforcedAgentBrowser { + /// Use the authenticated host callback for every launched session. + #[must_use] + pub fn new(authorizer: Arc) -> Self { + Self { authorizer } + } +} + impl Launcher for AgentBrowser { fn open(&self, session: &str) -> Box { Box::new(Linked { - state: DaemonState::with_options(StateOptions { - session_id: format!("tinycomputer-{}-{session}", std::process::id()), - ..StateOptions::default() - }), + state: DaemonState::with_options(state_options(session)), + egress_authorizer: None, + proxy: None, + proxy_session_id: String::new(), + enforced_launch: false, + }) + } +} + +impl Launcher for EnforcedAgentBrowser { + fn open(&self, session: &str) -> Box { + Box::new(Linked { + state: DaemonState::with_options(state_options(session)), + egress_authorizer: Some(self.authorizer.clone()), + proxy: None, + proxy_session_id: private_session_id(), + enforced_launch: false, }) } } struct Linked { state: DaemonState, + egress_authorizer: Option>, + proxy: Option, + proxy_session_id: String, + enforced_launch: bool, } impl Engine for Linked { fn execute(&mut self, command: Value) -> Reply<'_> { + let action = command + .get("action") + .and_then(Value::as_str) + .map(str::to_owned); + #[allow(clippy::redundant_closure_for_method_calls)] + let browser_unavailable = self + .state + .browser + .as_mut() + // BrowserManager is private in agent-browser, so its method cannot + // be named as a function item here. + .is_none_or(|browser| browser.has_process_exited()); + if self.egress_authorizer.is_some() + && action.as_deref() != Some("launch") + && (!self.enforced_launch || browser_unavailable) + { + self.enforced_launch = false; + self.proxy.take(); + return Box::pin(async move { + failure_reply( + &command, + "network policy requires an enforced launch with a live browser session", + ) + }); + } + let launch = self.egress_authorizer.is_some() && action.as_deref() == Some("launch"); Box::pin(async move { + let command = if launch { + if self.proxy_session_id.len() != 48 { + return failure_reply( + &command, + "network policy could not create a private session identity", + ); + } + let Some(authorizer) = self.egress_authorizer.clone() else { + return failure_reply(&command, "network policy has no host authorizer"); + }; + if self.proxy.is_none() { + match EgressProxy::bind( + authorizer, + self.proxy_session_id.clone(), + self.proxy_session_id.clone(), + ) + .await + { + Ok(proxy) => self.proxy = Some(proxy), + Err(_) => { + return failure_reply(&command, "network policy proxy could not start"); + } + } + } + let Some(proxy) = self.proxy.as_ref() else { + return failure_reply(&command, "network policy proxy could not start"); + }; + match enforce_launch(command.clone(), &proxy.url(), &self.proxy_session_id) { + Ok(command) => command, + Err(reason) => return failure_reply(&command, reason), + } + } else { + command + }; let _serialized = ENGINE.lock().await; - // The dispatcher's future is large (it spans every action), so it - // is boxed rather than held inline in this one. - Box::pin(execute_command(&command, &mut self.state)).await + let reply = Box::pin(execute_command(&command, &mut self.state)).await; + if launch && reply.get("success").and_then(Value::as_bool) == Some(true) { + self.enforced_launch = true; + } + if action.as_deref() == Some("close") + && reply.get("success").and_then(Value::as_bool) == Some(true) + { + self.enforced_launch = false; + self.proxy.take(); + } + reply }) } } +fn private_session_id() -> String { + let mut bytes = [0u8; 24]; + if getrandom::fill(&mut bytes).is_err() { + return String::new(); + } + bytes + .iter() + .fold(String::with_capacity(48), |mut output, byte| { + use std::fmt::Write as _; + let _ = write!(output, "{byte:02x}"); + output + }) +} + +fn state_options(session: &str) -> StateOptions { + StateOptions { + session_id: format!("tinycomputer-{}-{session}", std::process::id()), + ..StateOptions::default() + } +} + +fn failure_reply(command: &Value, reason: &str) -> Value { + json!({ + "id": command.get("id").cloned().unwrap_or(Value::Null), + "success": false, + "error": reason + }) +} + +fn enforce_launch( + mut command: Value, + proxy: &str, + proxy_password: &str, +) -> Result { + if command.get("action").and_then(Value::as_str) != Some("launch") { + return Ok(command); + } + if [ + "cdpUrl", + "cdpPort", + "autoConnect", + "provider", + "profile", + "storageState", + "restore", + "executablePath", + ] + .iter() + .any(|key| command.get(key).is_some()) + { + return Err("network policy refuses attached or externally managed browsers"); + } + if command + .get("args") + .and_then(Value::as_array) + .is_some_and(|args| !args.is_empty()) + { + return Err("network policy refuses caller-supplied browser launch arguments"); + } + if std::env::var_os("AGENT_BROWSER_CDP").is_some() + || std::env::var_os("AGENT_BROWSER_AUTO_CONNECT").is_some() + || std::env::var_os("AGENT_BROWSER_PROVIDER").is_some() + || std::env::var_os("AGENT_BROWSER_ENGINE").is_some() + || std::env::var_os("AGENT_BROWSER_EXECUTABLE_PATH").is_some() + || std::env::var_os("AGENT_BROWSER_PROXY").is_some() + || std::env::var_os("AGENT_BROWSER_PROXY_BYPASS").is_some() + || std::env::var_os("AGENT_BROWSER_PROXY_USERNAME").is_some() + || std::env::var_os("AGENT_BROWSER_PROXY_PASSWORD").is_some() + || std::env::var_os("AGENT_BROWSER_PROFILE").is_some() + || std::env::var_os("AGENT_BROWSER_RESTORE").is_some() + { + return Err("network policy refuses ambient external browser configuration"); + } + // Chromium's special <-loopback> token removes its implicit direct + // localhost bypass. Without this, loopback requests evade authorization. + command["proxy"] = json!({ + "server": proxy, + "bypass": "<-loopback>", + "username": "tinycomputer", + "password": proxy_password + }); + command["engine"] = json!("chrome"); + command["args"] = json!([ + "--disable-quic", + "--disable-http2", + "--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1", + "--force-webrtc-ip-handling-policy=disable_non_proxied_udp" + ]); + Ok(command) +} + #[cfg(test)] mod linked_tests; diff --git a/crates/tinycomputer-bus/src/browser_egress/browser_egress_tests.rs b/crates/tinycomputer-bus/src/browser_egress/browser_egress_tests.rs new file mode 100644 index 000000000..22bf01f6e --- /dev/null +++ b/crates/tinycomputer-bus/src/browser_egress/browser_egress_tests.rs @@ -0,0 +1,80 @@ +//! Browser egress callbacks carry destinations and opaque grants only. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::*; + +#[test] +fn browser_callback_contract_has_no_http_payload_or_caller_selected_addresses() { + let target = BrowserEgressTarget { + policy_id: "private-policy".into(), + expected_generation: 8, + session_id: "private-session".into(), + scheme: "https".into(), + hostname: "example.test".into(), + port: 443, + }; + let json = serde_json::to_value(&target).unwrap(); + assert!(json.get("method").is_none()); + assert!(json.get("headers").is_none()); + assert!(json.get("body").is_none()); + assert!(json.get("address").is_none()); + let grant = BrowserEgressGrant { + generation: 8, + authorization: "opaque serialized TinySecurity grant".into(), + addresses: vec!["203.0.113.8:443".into()], + }; + assert_eq!(grant.addresses.len(), 1); + assert_eq!(METHODS, ["Authorize", "Consume", "Validate"]); +} + +#[test] +fn callback_types_reject_unrecognized_fields() { + let malformed = serde_json::json!({ + "policy_id": "p", "expected_generation": 1, "session_id": "s", + "scheme": "https", "hostname": "example.test", "port": 443, + "headers": ["secret"] + }); + assert!(serde_json::from_value::(malformed).is_err()); +} + +#[test] +fn callback_debug_redacts_policy_destination_and_grant_material() { + let target = BrowserEgressTarget { + policy_id: "secret-subject-policy".into(), + expected_generation: 9, + session_id: "private-browser-session".into(), + scheme: "https".into(), + hostname: "private.example.test".into(), + port: 443, + }; + let grant = BrowserEgressGrant { + generation: 9, + authorization: "private-one-use-nonce".into(), + addresses: vec!["198.51.100.99:443".into()], + }; + assert!(format!("{target:?}").contains("REDACTED")); + let consume = BrowserEgressConsumeRequest { + target, + authorization: grant.authorization.clone(), + address: grant.addresses[0].clone(), + }; + let validate = BrowserEgressValidateRequest { + authorization: grant.authorization.clone(), + }; + for debug in [ + format!("{consume:?}"), + format!("{validate:?}"), + format!("{grant:?}"), + ] { + for private in [ + "secret-subject-policy", + "private-browser-session", + "private.example.test", + "private-one-use-nonce", + "198.51.100.99", + ] { + assert!(!debug.contains(private)); + } + assert!(debug.contains("REDACTED")); + } +} diff --git a/crates/tinycomputer-bus/src/browser_egress/mod.rs b/crates/tinycomputer-bus/src/browser_egress/mod.rs new file mode 100644 index 000000000..5b1c76429 --- /dev/null +++ b/crates/tinycomputer-bus/src/browser_egress/mod.rs @@ -0,0 +1,115 @@ +//! The private browser-network callback used by the compiled `TinyComputer` +//! module. The authenticated host adapter translates these requests to +//! `TinySecurity`'s destination-only browser-dial contract; it must not make +//! policy decisions or resolve destinations itself. +//! +//! The module owns browser proxy parsing, exact approved-address dialing, and +//! live-lease enforcement. These callbacks carry only destination authority, +//! opaque `TinySecurity` grants, and a session ID generated by the module. They +//! never carry browser methods, headers, body bytes, or page/model claims. + +use serde::{Deserialize, Serialize}; + +/// Host interface implemented by an authenticated adapter to `TinySecurity`. +pub const INTERFACE: &str = "ai.tinyhumans.tinycomputer.BrowserEgressHost"; +/// Object path for [`INTERFACE`]. +pub const OBJECT_PATH: &str = "/ai/tinyhumans/tinycomputer/BrowserEgressHost"; + +/// Callback member names. +pub mod methods { + /// Ask `TinySecurity` to resolve and authorize the actual browser destination. + pub const AUTHORIZE: &str = "Authorize"; + /// Consume a one-use `TinySecurity` grant before the socket dial. + pub const CONSUME: &str = "Consume"; + /// Validate an active HTTPS or WebSocket tunnel lease. + pub const VALIDATE: &str = "Validate"; +} + +/// Callback names in dispatch order. +pub const METHODS: [&str; 3] = [methods::AUTHORIZE, methods::CONSUME, methods::VALIDATE]; + +/// Destination parsed from the browser's real HTTP proxy request. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BrowserEgressTarget { + /// Immutable host-provided policy identifier. + pub policy_id: String, + /// Expected `TinySecurity` generation captured at browser session creation. + pub expected_generation: u64, + /// Unpredictable browser-proxy session ID generated by `TinyComputer`. + pub session_id: String, + /// Canonical `http` or `https` scheme (WS maps to corresponding HTTP scheme). + pub scheme: String, + /// Canonical DNS hostname or IP literal. + pub hostname: String, + /// Effective destination port. + pub port: u16, +} + +impl std::fmt::Debug for BrowserEgressTarget { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("BrowserEgressTarget([REDACTED])") + } +} + +/// `Authorize`: `TinySecurity`'s opaque one-use grant and vetted addresses. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BrowserEgressGrant { + /// Active generation; mismatch causes refusal before a socket is opened. + pub generation: u64, + /// Opaque serialized `TinySecurity` authorization; module treats it as data. + pub authorization: String, + /// Exact vetted socket addresses; no hostname resolution occurs in module. + pub addresses: Vec, +} + +impl std::fmt::Debug for BrowserEgressGrant { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("BrowserEgressGrant([REDACTED])") + } +} + +/// `Consume`: exact socket selected from the returned grant. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BrowserEgressConsumeRequest { + /// Destination used for `Authorize`. + pub target: BrowserEgressTarget, + /// Opaque unmodified `TinySecurity` authorization returned by `Authorize`. + pub authorization: String, + /// One exact member of `BrowserEgressGrant.addresses`. + pub address: String, +} + +impl std::fmt::Debug for BrowserEgressConsumeRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("BrowserEgressConsumeRequest([REDACTED])") + } +} + +/// `Validate`: lease for an already consumed tunnel. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BrowserEgressValidateRequest { + /// Opaque unmodified `TinySecurity` authorization returned by `Authorize`. + pub authorization: String, +} + +impl std::fmt::Debug for BrowserEgressValidateRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("BrowserEgressValidateRequest([REDACTED])") + } +} + +/// Result for `Consume` and `Validate`; anything other than `allowed: true` +/// closes or refuses the connection. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BrowserEgressDecision { + /// Whether `TinySecurity` accepted the exact request or live lease. + pub allowed: bool, +} + +#[cfg(test)] +mod browser_egress_tests; diff --git a/crates/tinycomputer-bus/src/lib.rs b/crates/tinycomputer-bus/src/lib.rs index c35f152c5..b1fac0100 100644 --- a/crates/tinycomputer-bus/src/lib.rs +++ b/crates/tinycomputer-bus/src/lib.rs @@ -117,6 +117,7 @@ pub mod agent; pub mod agentic; pub mod apps; pub mod browser; +pub mod browser_egress; pub mod catalogue; pub mod clipboard; pub mod consequence_host; diff --git a/crates/tinycomputer-bus/src/version/mod.rs b/crates/tinycomputer-bus/src/version/mod.rs index ad675d3e4..df0cfe38d 100644 --- a/crates/tinycomputer-bus/src/version/mod.rs +++ b/crates/tinycomputer-bus/src/version/mod.rs @@ -8,7 +8,7 @@ //! release workflow bumps, which tracks the shipped artifact. /// The wire contract version this crate defines. -pub const CONTRACT_VERSION: (u32, u32) = (2, 19); +pub const CONTRACT_VERSION: (u32, u32) = (2, 20); /// Returns whether a host holding [`CONTRACT_VERSION`] can bind to a module /// reporting `module`. @@ -22,7 +22,7 @@ pub const CONTRACT_VERSION: (u32, u32) = (2, 19); /// ``` /// # use tinycomputer_bus::{is_compatible, CONTRACT_VERSION}; /// assert!(is_compatible(CONTRACT_VERSION)); -/// assert!(is_compatible((2, 19))); +/// assert!(is_compatible((2, 20))); /// assert!(!is_compatible((2, 11))); /// assert!(!is_compatible((1, 8))); /// ``` diff --git a/crates/tinycomputer-bus/src/version/version_tests.rs b/crates/tinycomputer-bus/src/version/version_tests.rs index 1be61cc7d..6e56ab05a 100644 --- a/crates/tinycomputer-bus/src/version/version_tests.rs +++ b/crates/tinycomputer-bus/src/version/version_tests.rs @@ -6,7 +6,7 @@ use super::{CONTRACT_VERSION, binds, is_compatible}; #[test] fn the_shipped_contract_version_is_pinned() { - assert_eq!(CONTRACT_VERSION, (2, 19)); + assert_eq!(CONTRACT_VERSION, (2, 20)); } #[test] @@ -16,7 +16,7 @@ fn the_contract_binds_to_itself() { #[test] fn a_newer_minor_on_the_module_side_binds() { - assert!(is_compatible((2, 19))); + assert!(is_compatible((2, 20))); assert!(is_compatible((2, 97))); // 2.12 adds replayable GlobeRead and joined terminal GlobeShutdown. // A 2.11 module does not implement those members. @@ -35,6 +35,9 @@ fn a_newer_minor_on_the_module_side_binds() { // 2.19 adds the ConsequenceHost host-callback interface (Review): a 2.19 // host serves it, which a 2.18 module does not call, so its approvals // would never reach the host's policy. + // 2.20 adds BrowserEgressHost (Authorize/Consume/Validate): a 2.20 host + // serves it, while a 2.19 module cannot enforce per-destination browser dials. + assert!(!is_compatible((2, 19))); assert!(!is_compatible((2, 18))); assert!(!is_compatible((2, 17))); assert!(!is_compatible((2, 16))); diff --git a/crates/tinycomputer/src/tinybus_module/browser_egress.rs b/crates/tinycomputer/src/tinybus_module/browser_egress.rs new file mode 100644 index 000000000..cc153309c --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/browser_egress.rs @@ -0,0 +1,154 @@ +//! Browser network callback adapter. Policy and DNS decisions live in the +//! authenticated host callback, which delegates to `TinySecurity`; this module +//! only forwards requests and enforces the returned exact sockets. + +use std::{future::Future, io, net::SocketAddr, pin::Pin}; + +use tinybus::Connection; +use tinycomputer_browser::{BrowserDialTarget, DialGrant, EgressAuthorizer}; +use tinycomputer_bus::browser_egress::{ + self as contract, BrowserEgressConsumeRequest, BrowserEgressTarget, + BrowserEgressValidateRequest, +}; + +const CALLBACK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); + +/// Authenticated callback adapter to the host's `TinySecurity` bus bridge. +#[derive(Clone)] +pub(super) struct BusAuthorizer { + connection: Connection, + policy_id: String, + generation: u64, +} + +impl std::fmt::Debug for BusAuthorizer { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("BusAuthorizer") + .finish_non_exhaustive() + } +} + +impl BusAuthorizer { + pub(super) fn new(connection: Connection, policy_id: String, generation: u64) -> Self { + Self { + connection, + policy_id, + generation, + } + } + + fn proxy(&self) -> io::Result { + self.connection + .proxy( + contract::INTERFACE, + contract::OBJECT_PATH, + contract::INTERFACE, + ) + .map(|proxy| proxy.with_timeout(CALLBACK_TIMEOUT)) + .map_err(denied) + } + + fn target(&self, target: BrowserDialTarget) -> BrowserEgressTarget { + BrowserEgressTarget { + policy_id: self.policy_id.clone(), + expected_generation: self.generation, + session_id: target.session_id, + scheme: target.scheme, + hostname: target.hostname, + port: target.port, + } + } +} + +impl EgressAuthorizer for BusAuthorizer { + fn authorize( + &self, + target: BrowserDialTarget, + ) -> Pin> + Send>> { + let this = self.clone(); + Box::pin(async move { + let expected_port = target.port; + let request = this.target(target); + let response: contract::BrowserEgressGrant = this + .proxy()? + .call(contract::methods::AUTHORIZE, (request,)) + .await + .map_err(denied)?; + if response.generation != this.generation + || response.authorization.is_empty() + || response.addresses.is_empty() + || response.addresses.len() > 64 + { + return Err(denied("host returned a stale or empty browser grant")); + } + let addresses = response + .addresses + .iter() + .map(|address| address.parse::().map_err(denied)) + .collect::>>()?; + if addresses + .iter() + .any(|address| address.port() != expected_port) + { + return Err(denied("host returned an address for a different port")); + } + Ok(DialGrant { + lease: response.authorization, + addresses, + }) + }) + } + + fn consume( + &self, + target: BrowserDialTarget, + grant: DialGrant, + address: SocketAddr, + ) -> Pin> + Send>> { + let this = self.clone(); + Box::pin(async move { + if !grant.addresses.contains(&address) { + return Err(denied("socket address was not in the host grant")); + } + let request = BrowserEgressConsumeRequest { + target: this.target(target), + authorization: grant.lease, + address: address.to_string(), + }; + let decision: contract::BrowserEgressDecision = this + .proxy()? + .call(contract::methods::CONSUME, (request,)) + .await + .map_err(denied)?; + if decision.allowed { + Ok(()) + } else { + Err(denied("TinySecurity refused browser socket grant")) + } + }) + } + + fn validate(&self, lease: String) -> Pin> + Send>> { + let this = self.clone(); + Box::pin(async move { + let request = BrowserEgressValidateRequest { + authorization: lease, + }; + let decision: contract::BrowserEgressDecision = this + .proxy()? + .call(contract::methods::VALIDATE, (request,)) + .await + .map_err(denied)?; + Ok(decision.allowed) + }) + } +} + +fn denied(error: impl std::fmt::Display) -> io::Error { + io::Error::new(io::ErrorKind::PermissionDenied, error.to_string()) +} + +#[cfg(test)] +#[path = "browser_egress_tests.rs"] +mod tests; diff --git a/crates/tinycomputer/src/tinybus_module/browser_egress_tests.rs b/crates/tinycomputer/src/tinybus_module/browser_egress_tests.rs new file mode 100644 index 000000000..79fb35a25 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/browser_egress_tests.rs @@ -0,0 +1,185 @@ +//! Tests for the mechanical TinyBus-to-TinySecurity browser egress adapter. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +#![allow(clippy::unused_async)] // TinyBus interface methods must be async. + +use super::*; +use std::sync::{Arc, Mutex}; +use tinybus::{Connection, broker::Broker, transport::memory::MemoryBus}; +use tinycomputer_bus::browser_egress::{ + self as contract, BrowserEgressConsumeRequest, BrowserEgressDecision, BrowserEgressGrant, + BrowserEgressTarget, BrowserEgressValidateRequest, +}; + +#[derive(Clone)] +struct Host { + addresses: Vec, + generation: u64, + consume_allowed: bool, + validate_allowed: bool, + seen: Arc>>, +} + +#[tinybus::interface(name = "ai.tinyhumans.tinycomputer.BrowserEgressHost")] +impl Host { + async fn authorize(&self, request: BrowserEgressTarget) -> tinybus::Result { + self.seen.lock().unwrap().push(format!( + "authorize:{}:{}:{}:{}:{}:{}", + request.policy_id, + request.expected_generation, + request.session_id, + request.scheme, + request.hostname, + request.port + )); + Ok(BrowserEgressGrant { + generation: self.generation, + authorization: "secret-lease".into(), + addresses: self.addresses.clone(), + }) + } + + async fn consume( + &self, + request: BrowserEgressConsumeRequest, + ) -> tinybus::Result { + self.seen.lock().unwrap().push(format!( + "consume:{}:{}:{}:{}:{}:{}", + request.target.policy_id, + request.target.expected_generation, + request.target.session_id, + request.target.scheme, + request.target.hostname, + request.address + )); + Ok(BrowserEgressDecision { + allowed: self.consume_allowed, + }) + } + + async fn validate( + &self, + request: BrowserEgressValidateRequest, + ) -> tinybus::Result { + self.seen + .lock() + .unwrap() + .push(format!("validate:{}", request.authorization)); + Ok(BrowserEgressDecision { + allowed: self.validate_allowed, + }) + } +} + +async fn connect_host(host: Host) -> tinybus::Result<(BusAuthorizer, Connection)> { + let bus = MemoryBus::new(); + Broker::new().spawn(bus.clone()); + let connection = Connection::connect(bus.connect().await?).await?; + connection + .serve_at(contract::OBJECT_PATH.try_into()?, host) + .await?; + connection.request_name(contract::INTERFACE).await?; + let module = Connection::connect(bus.connect().await?).await?; + Ok(( + BusAuthorizer::new(module, "policy-private".into(), 7), + connection, + )) +} + +fn dial_target() -> BrowserDialTarget { + BrowserDialTarget { + scheme: "https".into(), + hostname: "example.test".into(), + port: 443, + session_id: "session-private".into(), + } +} + +fn host(addresses: Vec) -> Host { + Host { + addresses, + generation: 7, + consume_allowed: true, + validate_allowed: true, + seen: Arc::new(Mutex::new(Vec::new())), + } +} + +#[tokio::test] +async fn bus_adapter_delegates_exact_target_and_checks_the_fixed_socket() -> tinybus::Result<()> { + let host = host(vec!["8.8.8.8:443".into()]); + let seen = host.seen.clone(); + let (authorizer, _host_connection) = connect_host(host).await?; + let target = dial_target(); + let grant = authorizer.authorize(target.clone()).await?; + let address = grant.addresses[0]; + authorizer.consume(target, grant.clone(), address).await?; + assert!(authorizer.validate(grant.lease).await?); + let calls = seen.lock().unwrap(); + assert_eq!(calls.len(), 3); + assert!(calls[0].contains("policy-private:7:session-private:https:example.test:443")); + assert!(calls[1].contains("policy-private:7:session-private:https:example.test:8.8.8.8:443")); + assert!(calls[2].contains("validate:secret-lease")); + Ok(()) +} + +#[tokio::test] +async fn bus_adapter_rejects_wrong_generation_port_and_ungranted_socket() -> tinybus::Result<()> { + let (wrong_generation, _wrong_generation_connection) = connect_host(Host { + generation: 8, + ..host(vec!["8.8.8.8:443".into()]) + }) + .await?; + assert!(wrong_generation.authorize(dial_target()).await.is_err()); + + let (wrong_port, _wrong_port_connection) = + connect_host(host(vec!["8.8.8.8:80".into()])).await?; + assert!(wrong_port.authorize(dial_target()).await.is_err()); + + let host = host(vec!["8.8.8.8:443".into()]); + let seen = host.seen.clone(); + let (authorizer, _host_connection) = connect_host(host).await?; + let target = dial_target(); + let grant = authorizer.authorize(target.clone()).await?; + assert!( + authorizer + .consume( + target, + grant, + std::net::SocketAddr::from(([1, 1, 1, 1], 443)), + ) + .await + .is_err() + ); + assert_eq!(seen.lock().unwrap().len(), 1); + Ok(()) +} + +#[tokio::test] +async fn bus_adapter_refuses_host_denials_and_malformed_grants() -> tinybus::Result<()> { + let denied_host = Host { + consume_allowed: false, + validate_allowed: false, + ..host(vec!["8.8.8.8:443".into()]) + }; + let (authorizer, _denied_host_connection) = connect_host(denied_host).await?; + let target = dial_target(); + let grant = authorizer.authorize(target.clone()).await?; + let address = grant.addresses[0]; + assert!( + authorizer + .consume(target, grant.clone(), address) + .await + .is_err() + ); + assert!(!authorizer.validate(grant.lease).await?); + + for addresses in [ + vec![], + (0..65).map(|_| "8.8.8.8:443".into()).collect(), + vec!["not-a-socket".into()], + ] { + let (malformed, _malformed_connection) = connect_host(host(addresses)).await?; + assert!(malformed.authorize(dial_target()).await.is_err()); + } + Ok(()) +} diff --git a/crates/tinycomputer/src/tinybus_module/config.rs b/crates/tinycomputer/src/tinybus_module/config.rs index b1ae35aee..c8d3e4060 100644 --- a/crates/tinycomputer/src/tinybus_module/config.rs +++ b/crates/tinycomputer/src/tinybus_module/config.rs @@ -29,6 +29,21 @@ pub(crate) struct BrowserDefaults { /// drafted (the default), at the one web address the task's text names /// if it names one, rather than at its first step. pub(crate) prelaunch: bool, + /// Immutable `TinySecurity` scope captured from host-private configuration. + pub(crate) egress: Option, +} + +/// Host-selected policy identity and generation; never an agent argument. +#[derive(Clone, PartialEq, Eq)] +pub(crate) struct BrowserEgressConfig { + pub(crate) policy_id: String, + pub(crate) generation: u64, +} + +impl std::fmt::Debug for BrowserEgressConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("BrowserEgressConfig([REDACTED])") + } } impl Default for BrowserDefaults { @@ -40,6 +55,7 @@ impl Default for BrowserDefaults { perception: Perception::default(), settle: Settle::default(), prelaunch: true, + egress: None, } } } @@ -63,7 +79,7 @@ impl BrowserDefaults { field: "browser", expected: "an object with optional `executable` and `user_agent` strings, an `args` \ array of strings, a `perception` of sight or tree, a `settle` of \ - prompt or steady, and a `prelaunch` boolean", + prompt or steady, a `prelaunch` boolean, and optional private `egress` policy", }; let browser = browser.as_object().ok_or_else(invalid)?; let text = |name: &str| match browser.get(name) { @@ -99,6 +115,32 @@ impl BrowserDefaults { Some(serde_json::Value::Bool(prelaunch)) => *prelaunch, Some(_) => return Err(invalid()), }; + defaults.egress = match browser.get("egress") { + None => None, + Some(serde_json::Value::Object(egress)) => { + let policy_id = egress + .get("policy_id") + .and_then(serde_json::Value::as_str) + .filter(|id| !id.is_empty() && id.len() <= 64) + .ok_or_else(invalid)?; + let generation = egress + .get("generation") + .and_then(serde_json::Value::as_u64) + .filter(|generation| *generation > 0) + .ok_or_else(invalid)?; + if egress.len() != 2 + || browser.contains_key("args") + || browser.contains_key("executable") + { + return Err(invalid()); + } + Some(BrowserEgressConfig { + policy_id: policy_id.to_owned(), + generation, + }) + } + Some(_) => return Err(invalid()), + }; if browser.keys().any(|key| { ![ "executable", @@ -107,6 +149,7 @@ impl BrowserDefaults { "perception", "settle", "prelaunch", + "egress", ] .contains(&key.as_str()) }) { diff --git a/crates/tinycomputer/src/tinybus_module/dispatch/service.rs b/crates/tinycomputer/src/tinybus_module/dispatch/service.rs index f4d1847ba..0fc700dcf 100644 --- a/crates/tinycomputer/src/tinybus_module/dispatch/service.rs +++ b/crates/tinycomputer/src/tinybus_module/dispatch/service.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use tinybus::{Error as TinyBusError, Result as TinyBusResult}; -use tinycomputer_browser::{AgentBrowser, Browser}; +use tinycomputer_browser::{AgentBrowser, Browser, EnforcedAgentBrowser}; use tinycomputer_bus::agent::{ AgentResponse, ContinueTaskRequest, StartTaskRequest, SurfaceAvailability, SurfaceKind, TaskStatus, TaskView, @@ -13,6 +13,7 @@ use tinycomputer_bus::{DesktopResponse, JevConfig}; use tinycomputer_engine as agentic; use super::DesktopService; +use crate::tinybus_module::browser_egress::BusAuthorizer; use crate::tinybus_module::config::{BrowserDefaults, cursor_config}; use crate::tinybus_module::consequence_gate::{ConsequenceLink, ConsequencePort}; use crate::tinybus_module::runner::WorkspaceRunner; @@ -25,10 +26,29 @@ impl DesktopService { /// # Errors /// /// Propagates whatever [`Desktop::from_config`] rejects. + #[cfg(test)] pub(crate) fn from_config(config: &serde_json::Value) -> Result { Self::with_browser(config, Arc::new(Browser::new(Arc::new(AgentBrowser)))) } + /// Builds the service with the authenticated host callback available on + /// the module connection. A configured egress scope always selects the + /// enforced browser launcher. + pub(crate) fn from_config_with_connection( + config: &serde_json::Value, + connection: tinybus::Connection, + ) -> Result { + let defaults = BrowserDefaults::from_config(config)?; + let browser = if let Some(egress) = defaults.egress { + Arc::new(Browser::new(Arc::new(EnforcedAgentBrowser::new(Arc::new( + BusAuthorizer::new(connection, egress.policy_id, egress.generation), + ))))) + } else { + Arc::new(Browser::new(Arc::new(AgentBrowser))) + }; + Self::with_browser(config, browser) + } + /// Builds the service from the module configuration blob, opening browser /// sessions on `browser`. /// diff --git a/crates/tinycomputer/src/tinybus_module/mod.rs b/crates/tinycomputer/src/tinybus_module/mod.rs index 7fd82e399..72f6ad0a8 100644 --- a/crates/tinycomputer/src/tinybus_module/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/mod.rs @@ -19,6 +19,7 @@ //! call — nothing platform-specific has to cross a thread boundary or survive //! an `await`. +mod browser_egress; mod config; mod consequence_gate; mod dispatch; @@ -38,7 +39,7 @@ pub(crate) use dispatch::DesktopService; /// silently ignoring the session it was told to join would allocate refs /// nothing else can spend. async fn setup(connection: Connection, config: Value) -> TinyBusResult<()> { - let service = DesktopService::from_config(&config) + let service = DesktopService::from_config_with_connection(&config, connection.clone()) .map_err(|error| tinybus::Error::failed(error.to_string()))?; // The host's per-site memory; a host that does not serve it only costs // tasks what earlier ones learned. @@ -94,6 +95,7 @@ tinybus_module::module_export_optional_static! { optional = [ "ai.tinyhumans.tinycomputer.SiteMemoryHost", "ai.tinyhumans.tinycomputer.ConsequenceHost", + "ai.tinyhumans.tinycomputer.BrowserEgressHost", ], lazy = false, } diff --git a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs index 38f6d41d5..9f273023a 100644 --- a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs @@ -175,6 +175,12 @@ fn the_browser_configuration_is_read_or_refused() { assert_eq!(defaults.perception, Perception::Tree); assert_eq!(defaults.settle, Settle::Steady); assert!(!defaults.prelaunch); + let egress = BrowserDefaults::from_config(&json!({"browser": { + "egress": {"policy_id": "host-policy", "generation": 7} + }})) + .unwrap(); + assert_eq!(egress.egress.as_ref().unwrap().policy_id, "host-policy"); + assert_eq!(egress.egress.as_ref().unwrap().generation, 7); // Settling promptly and opening the browser early are on unless turned // off. let unset = BrowserDefaults::default(); @@ -196,6 +202,9 @@ fn the_browser_configuration_is_read_or_refused() { json!({"browser": {"settle": "fast"}}), json!({"browser": {"prelaunch": "yes"}}), json!({"browser": {"useragent": "typo"}}), + json!({"browser": {"egress": {"policy_id": "", "generation": 0}}}), + json!({"browser": {"egress": {"policy_id": "p", "generation": 1, "extra": true}}}), + json!({"browser": {"egress": {"policy_id": "p", "generation": 1}, "args": ["--proxy-server=bad"]}}), ] { assert!(BrowserDefaults::from_config(&invalid).is_err(), "{invalid}"); assert!(DesktopService::from_config(&invalid).is_err(), "{invalid}"); diff --git a/crates/tinycomputer/tests/public_api_tests.rs b/crates/tinycomputer/tests/public_api_tests.rs index 5856950e1..e13461a87 100644 --- a/crates/tinycomputer/tests/public_api_tests.rs +++ b/crates/tinycomputer/tests/public_api_tests.rs @@ -34,7 +34,7 @@ fn the_crate_re_exports_the_contract_rather_than_redefining_it() { #[test] fn the_shipped_contract_binds_to_itself() { assert!(is_compatible(CONTRACT_VERSION)); - assert_eq!(CONTRACT_VERSION, (2, 19)); + assert_eq!(CONTRACT_VERSION, (2, 20)); } #[test] diff --git a/docs/crates/tinycomputer-bus/versioning.md b/docs/crates/tinycomputer-bus/versioning.md index c6d9ede83..b8229e67b 100644 --- a/docs/crates/tinycomputer-bus/versioning.md +++ b/docs/crates/tinycomputer-bus/versioning.md @@ -9,7 +9,7 @@ code, so this page exists mostly to keep them apart. ## `CONTRACT_VERSION`: does this host understand this module ```rust,ignore -pub const CONTRACT_VERSION: (u32, u32) = (2, 19); +pub const CONTRACT_VERSION: (u32, u32) = (2, 20); ``` This describes the *vocabulary*: the member set and the payload shapes, @@ -45,15 +45,15 @@ Two conditions, both necessary: relies on changed shape or disappeared, so a mismatched major is refused outright, in either direction. 2. **The module must be at least as new, minor-wise, as the host.** A host - built against `(2, 19)` expects at least the members and fields that - existed at `(2, 19)`. A module reporting `(2, 11)` might be missing one of - them, so it is rejected. A module reporting `(2, 19)` has everything the + built against `(2, 20)` expects at least the members and fields that + existed at `(2, 20)`. A module reporting `(2, 11)` might be missing one of + them, so it is rejected. A module reporting `(2, 20)` has everything the host expects, plus something newer the host simply does not use yet, so it is accepted. ```rust,ignore -assert!(is_compatible(CONTRACT_VERSION)); // (2, 19), the exact version this crate ships -assert!(is_compatible((2, 19))); // a newer, still-compatible module +assert!(is_compatible(CONTRACT_VERSION)); // (2, 20), the exact version this crate ships +assert!(is_compatible((2, 20))); // a newer, still-compatible module assert!(!is_compatible((2, 11))); // an older module, missing something assert!(!is_compatible((1, 10))); // a different major, all bets off ``` diff --git a/docs/crates/tinycomputer/configuration.md b/docs/crates/tinycomputer/configuration.md index 328d2ac12..a3c037e2f 100644 --- a/docs/crates/tinycomputer/configuration.md +++ b/docs/crates/tinycomputer/configuration.md @@ -222,7 +222,11 @@ never sent to a provider it was not given for: "args": ["--disable-blink-features=AutomationControlled"], "perception": "sight", "settle": "prompt", - "prelaunch": true + "prelaunch": true, + "egress": { + "policy_id": "host-selected-policy", + "generation": 4 + } } } ``` @@ -240,6 +244,25 @@ optional: | `perception` | how a task reads a page: `sight` (the default) reads the rendered page as a person sees it, `tree` the accessibility tree alone ([`browser-sight.md`](../../technical/specs/browser-sight.md)) | | `settle` | how a task lets a page settle after an action before reading it again: `prompt` (the default) counts the network's 500 ms of quiet from the start, counting only requests that can change the page and for at most 1 s, and then waits only while the page is still changing (at most 400 ms), so an idle page is read again after about 0.6 s; `steady` waits for the network to go idle, at least about 1.1 s, then 400 ms more | | `prelaunch` | `true` (the default) opens a browser-only task's browser while `StartTask` plans it (a `task` with no `flow`), so the first step does not wait for the launch, and loads in it the one web address the task's text names, if it names one, so a first step that browses there does not wait for the page either; `false` opens it at the first step | +| `egress` | Host-private TinySecurity scope. When present, `policy_id` and `generation` are required; browser arguments, an executable override, attached DevTools endpoints, and caller-supplied launch flags are refused. The scope is never a browser or task argument. | + +With `egress`, every launched browser session uses a private, authenticated +loopback proxy. TinyComputer parses each HTTP request, asks the authenticated +host callback to delegate destination authorization to TinySecurity, consumes +a one-use grant, then connects only to one of the exact approved socket +addresses. HTTP redirects and subresources produce their own requests; +HTTPS uses CONNECT, so TinySecurity classifies its encrypted contents as +`OpaqueBrowserTraffic` and does not claim to inspect methods, headers, or +bodies. Active tunnels are closed when lease validation fails, the policy +generation changes, or its deadline expires. WebSocket upgrades use the same +destination path. Failed, missing, timed-out, or malformed callbacks refuse +the connection before the destination socket is opened. + +The enforced Chromium launch disables QUIC and HTTP/2, blocks ordinary browser +DNS resolution, and disables non-proxied WebRTC UDP. These browser settings +keep supported web traffic on the policy proxy; OS-level network isolation is +still required to contain direct sockets from browser features or other +processes. Most installs never need any of this: leave `browser` out entirely and the linked `agent-browser` engine looks for Chrome itself. An unknown key under From 36668e17993d7a21a59ef6ec56633c4c6468c42c Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 14:19:42 +0000 Subject: [PATCH 02/93] test(bus): avoid float equality lint Co-authored-by: Medulla --- crates/tinycomputer-bus/src/browser/session/session_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinycomputer-bus/src/browser/session/session_tests.rs b/crates/tinycomputer-bus/src/browser/session/session_tests.rs index 85122f10c..55c25757d 100644 --- a/crates/tinycomputer-bus/src/browser/session/session_tests.rs +++ b/crates/tinycomputer-bus/src/browser/session/session_tests.rs @@ -182,7 +182,7 @@ fn a_minimal_metadata_and_screen_fill_their_defaults() { assert_eq!(metadata.platform, "Windows"); assert_eq!(metadata.platform_version, ""); assert!(!metadata.mobile); - assert_eq!(options.screen.expect("screen").device_scale_factor, 1.0); + assert!((options.screen.expect("screen").device_scale_factor - 1.0).abs() <= f64::EPSILON); } #[test] From 98b4ca16a8f4ed3d96d36715261b7449c6a06399 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 14:40:14 +0000 Subject: [PATCH 03/93] test(tinycomputer): keep browser egress host async Co-authored-by: Medulla --- .../tinycomputer/src/tinybus_module/browser_egress_tests.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/tinycomputer/src/tinybus_module/browser_egress_tests.rs b/crates/tinycomputer/src/tinybus_module/browser_egress_tests.rs index 79fb35a25..5e385e679 100644 --- a/crates/tinycomputer/src/tinybus_module/browser_egress_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/browser_egress_tests.rs @@ -1,7 +1,5 @@ //! Tests for the mechanical TinyBus-to-TinySecurity browser egress adapter. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -#![allow(clippy::unused_async)] // TinyBus interface methods must be async. - use super::*; use std::sync::{Arc, Mutex}; use tinybus::{Connection, broker::Broker, transport::memory::MemoryBus}; @@ -22,6 +20,7 @@ struct Host { #[tinybus::interface(name = "ai.tinyhumans.tinycomputer.BrowserEgressHost")] impl Host { async fn authorize(&self, request: BrowserEgressTarget) -> tinybus::Result { + tokio::task::yield_now().await; self.seen.lock().unwrap().push(format!( "authorize:{}:{}:{}:{}:{}:{}", request.policy_id, @@ -42,6 +41,7 @@ impl Host { &self, request: BrowserEgressConsumeRequest, ) -> tinybus::Result { + tokio::task::yield_now().await; self.seen.lock().unwrap().push(format!( "consume:{}:{}:{}:{}:{}:{}", request.target.policy_id, @@ -60,6 +60,7 @@ impl Host { &self, request: BrowserEgressValidateRequest, ) -> tinybus::Result { + tokio::task::yield_now().await; self.seen .lock() .unwrap() From d7d1bf1b26d0b79164b41cb7a441a5cfb1f7bfdb Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 16:34:25 +0000 Subject: [PATCH 04/93] fix(browser): try later authorized egress addresses Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress.rs | 64 ++++++++----- .../tinycomputer-browser/src/egress_tests.rs | 94 +++++++++++++++++++ 2 files changed, 135 insertions(+), 23 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress.rs b/crates/tinycomputer-browser/src/egress.rs index ec7dd7347..d677defb9 100644 --- a/crates/tinycomputer-browser/src/egress.rs +++ b/crates/tinycomputer-browser/src/egress.rs @@ -130,34 +130,42 @@ async fn serve( if !read_request_body(&mut client, &mut request).await? { return refuse(&mut client).await; } - let grant = match tokio::time::timeout( - Duration::from_secs(5), - auth.authorize(request.target.clone()), - ) - .await - { - Ok(Ok(g)) if !g.addresses.is_empty() && g.addresses.len() <= 64 => g, - _ => return refuse(&mut client).await, - }; - let Some(address) = grant.addresses.first().copied() else { + let Some(first_grant) = authorize(&auth, &request.target).await else { return refuse(&mut client).await; }; - if !matches!( - tokio::time::timeout( - Duration::from_secs(5), - auth.consume(request.target.clone(), grant.clone(), address), - ) - .await, - Ok(Ok(())) - ) { - return refuse(&mut client).await; + let addresses = first_grant.addresses.clone(); + let mut connected = None; + for (index, address) in addresses.into_iter().enumerate() { + // A consume call spends its one-use grant. Reauthorize every later + // candidate so a failed dial cannot reuse a spent authorization. + let grant = if index == 0 { + first_grant.clone() + } else { + match authorize(&auth, &request.target).await { + Some(grant) if grant.addresses.contains(&address) => grant, + _ => continue, + } + }; + if !matches!( + tokio::time::timeout( + Duration::from_secs(5), + auth.consume(request.target.clone(), grant.clone(), address), + ) + .await, + Ok(Ok(())) + ) { + return refuse(&mut client).await; + } + if let Ok(Ok(upstream)) = + tokio::time::timeout(Duration::from_secs(5), TcpStream::connect(address)).await + { + connected = Some((upstream, grant.lease)); + break; + } } - let Ok(Ok(mut upstream)) = - tokio::time::timeout(Duration::from_secs(5), TcpStream::connect(address)).await - else { + let Some((mut upstream, lease)) = connected else { return refuse(&mut client).await; }; - let lease = grant.lease; if !validate_lease(&auth, &lease).await? { return Ok(()); } @@ -170,6 +178,16 @@ async fn serve( Ok(()) } +async fn authorize( + auth: &Arc, + target: &BrowserDialTarget, +) -> Option { + match tokio::time::timeout(Duration::from_secs(5), auth.authorize(target.clone())).await { + Ok(Ok(grant)) if !grant.addresses.is_empty() && grant.addresses.len() <= 64 => Some(grant), + _ => None, + } +} + struct ProxyRequest { bytes: Vec, split: usize, diff --git a/crates/tinycomputer-browser/src/egress_tests.rs b/crates/tinycomputer-browser/src/egress_tests.rs index 6453a4629..259e1ef15 100644 --- a/crates/tinycomputer-browser/src/egress_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests.rs @@ -177,6 +177,100 @@ async fn approved_connect_reaches_only_the_consumed_socket() { assert_eq!(&payload, b"ping"); } +#[tokio::test] +async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachable() { + let unreachable = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let first_address = unreachable.local_addr().unwrap(); + drop(unreachable); + + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let second_address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + .await + .unwrap(); + }); + let authorizer = Arc::new(MultiAddressAuthorizer { + addresses: vec![first_address, second_address], + }); + let proxy = EgressProxy::bind( + authorizer, + "multi-address-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "GET http://control.test:{}/ HTTP/1.1\r\nHost: control.test:{}\r\nProxy-Authorization: {}\r\n\r\n", + second_address.port(), + second_address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = Vec::new(); + client.read_to_end(&mut response).await.unwrap(); + assert!( + std::str::from_utf8(&response) + .unwrap() + .ends_with("\r\n\r\nok") + ); + server.await.unwrap(); +} + +struct MultiAddressAuthorizer { + addresses: Vec, +} + +impl EgressAuthorizer for MultiAddressAuthorizer { + fn authorize( + &self, + _target: BrowserDialTarget, + ) -> std::pin::Pin> + Send>> { + let addresses = self.addresses.clone(); + Box::pin(async move { + Ok(DialGrant { + lease: "multi-address-lease".into(), + addresses, + }) + }) + } + + fn consume( + &self, + _target: BrowserDialTarget, + grant: DialGrant, + address: SocketAddr, + ) -> std::pin::Pin> + Send>> { + Box::pin(async move { + if grant.addresses.contains(&address) { + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "wrong address", + )) + } + }) + } + + fn validate( + &self, + _lease: String, + ) -> std::pin::Pin> + Send>> { + Box::pin(async { Ok(true) }) + } +} + #[tokio::test] async fn denied_destination_never_connects_to_the_fixture() { let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); From c49e951665146dddee1a3a968d8fe950e51b0f19 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 16:36:00 +0000 Subject: [PATCH 05/93] chore(deps): refresh rustls and yoke lock entries Co-authored-by: Medulla --- Cargo.lock | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 96628891a..003ea2368 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1029,7 +1029,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] @@ -2094,7 +2094,7 @@ dependencies = [ "wasm-bindgen-futures", "wasm-streams", "web-sys", - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] @@ -2176,9 +2176,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "log", "once_cell", @@ -2201,9 +2201,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "ring", "rustls-pki-types", @@ -3108,7 +3108,7 @@ dependencies = [ "rustls-pki-types", "ureq-proto", "utf8-zero", - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] @@ -3295,14 +3295,14 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] name = "webpki-roots" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" dependencies = [ "rustls-pki-types", ] @@ -3785,9 +3785,9 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", From 525c4e77b8fe335b8601249d312af1f01725a87c Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 16:36:15 +0000 Subject: [PATCH 06/93] fix(bus): bump contract for browser egress host Co-authored-by: Medulla --- crates/tinycomputer-bus/src/version/mod.rs | 4 ++-- crates/tinycomputer-bus/src/version/version_tests.rs | 10 ++++++---- crates/tinycomputer/tests/public_api_tests.rs | 2 +- docs/crates/tinycomputer-bus/versioning.md | 12 ++++++------ docs/technical/specs/desktop-module-contract.md | 10 ++++++++++ 5 files changed, 25 insertions(+), 13 deletions(-) diff --git a/crates/tinycomputer-bus/src/version/mod.rs b/crates/tinycomputer-bus/src/version/mod.rs index df0cfe38d..c26022e07 100644 --- a/crates/tinycomputer-bus/src/version/mod.rs +++ b/crates/tinycomputer-bus/src/version/mod.rs @@ -8,7 +8,7 @@ //! release workflow bumps, which tracks the shipped artifact. /// The wire contract version this crate defines. -pub const CONTRACT_VERSION: (u32, u32) = (2, 20); +pub const CONTRACT_VERSION: (u32, u32) = (2, 21); /// Returns whether a host holding [`CONTRACT_VERSION`] can bind to a module /// reporting `module`. @@ -22,7 +22,7 @@ pub const CONTRACT_VERSION: (u32, u32) = (2, 20); /// ``` /// # use tinycomputer_bus::{is_compatible, CONTRACT_VERSION}; /// assert!(is_compatible(CONTRACT_VERSION)); -/// assert!(is_compatible((2, 20))); +/// assert!(is_compatible((2, 21))); /// assert!(!is_compatible((2, 11))); /// assert!(!is_compatible((1, 8))); /// ``` diff --git a/crates/tinycomputer-bus/src/version/version_tests.rs b/crates/tinycomputer-bus/src/version/version_tests.rs index 6e56ab05a..cbafcdefd 100644 --- a/crates/tinycomputer-bus/src/version/version_tests.rs +++ b/crates/tinycomputer-bus/src/version/version_tests.rs @@ -6,7 +6,7 @@ use super::{CONTRACT_VERSION, binds, is_compatible}; #[test] fn the_shipped_contract_version_is_pinned() { - assert_eq!(CONTRACT_VERSION, (2, 20)); + assert_eq!(CONTRACT_VERSION, (2, 21)); } #[test] @@ -16,7 +16,7 @@ fn the_contract_binds_to_itself() { #[test] fn a_newer_minor_on_the_module_side_binds() { - assert!(is_compatible((2, 20))); + assert!(is_compatible((2, 21))); assert!(is_compatible((2, 97))); // 2.12 adds replayable GlobeRead and joined terminal GlobeShutdown. // A 2.11 module does not implement those members. @@ -35,8 +35,10 @@ fn a_newer_minor_on_the_module_side_binds() { // 2.19 adds the ConsequenceHost host-callback interface (Review): a 2.19 // host serves it, which a 2.18 module does not call, so its approvals // would never reach the host's policy. - // 2.20 adds BrowserEgressHost (Authorize/Consume/Validate): a 2.20 host - // serves it, while a 2.19 module cannot enforce per-destination browser dials. + // 2.21 adds BrowserEgressHost (Authorize/Consume/Validate): a 2.21 host + // serves it, while a 2.20 module cannot enforce per-destination browser dials. + // 2.20 adds SessionOptions' optional browser identity and fingerprint fields. + assert!(!is_compatible((2, 20))); assert!(!is_compatible((2, 19))); assert!(!is_compatible((2, 18))); assert!(!is_compatible((2, 17))); diff --git a/crates/tinycomputer/tests/public_api_tests.rs b/crates/tinycomputer/tests/public_api_tests.rs index e13461a87..04065f627 100644 --- a/crates/tinycomputer/tests/public_api_tests.rs +++ b/crates/tinycomputer/tests/public_api_tests.rs @@ -34,7 +34,7 @@ fn the_crate_re_exports_the_contract_rather_than_redefining_it() { #[test] fn the_shipped_contract_binds_to_itself() { assert!(is_compatible(CONTRACT_VERSION)); - assert_eq!(CONTRACT_VERSION, (2, 20)); + assert_eq!(CONTRACT_VERSION, (2, 21)); } #[test] diff --git a/docs/crates/tinycomputer-bus/versioning.md b/docs/crates/tinycomputer-bus/versioning.md index b8229e67b..f2e1d389c 100644 --- a/docs/crates/tinycomputer-bus/versioning.md +++ b/docs/crates/tinycomputer-bus/versioning.md @@ -9,7 +9,7 @@ code, so this page exists mostly to keep them apart. ## `CONTRACT_VERSION`: does this host understand this module ```rust,ignore -pub const CONTRACT_VERSION: (u32, u32) = (2, 20); +pub const CONTRACT_VERSION: (u32, u32) = (2, 21); ``` This describes the *vocabulary*: the member set and the payload shapes, @@ -45,15 +45,15 @@ Two conditions, both necessary: relies on changed shape or disappeared, so a mismatched major is refused outright, in either direction. 2. **The module must be at least as new, minor-wise, as the host.** A host - built against `(2, 20)` expects at least the members and fields that - existed at `(2, 20)`. A module reporting `(2, 11)` might be missing one of - them, so it is rejected. A module reporting `(2, 20)` has everything the + built against `(2, 21)` expects at least the members and fields that + existed at `(2, 21)`. A module reporting `(2, 11)` might be missing one of + them, so it is rejected. A module reporting `(2, 21)` has everything the host expects, plus something newer the host simply does not use yet, so it is accepted. ```rust,ignore -assert!(is_compatible(CONTRACT_VERSION)); // (2, 20), the exact version this crate ships -assert!(is_compatible((2, 20))); // a newer, still-compatible module +assert!(is_compatible(CONTRACT_VERSION)); // (2, 21), the exact version this crate ships +assert!(is_compatible((2, 21))); // a newer, still-compatible module assert!(!is_compatible((2, 11))); // an older module, missing something assert!(!is_compatible((1, 10))); // a different major, all bets off ``` diff --git a/docs/technical/specs/desktop-module-contract.md b/docs/technical/specs/desktop-module-contract.md index 41774150c..e587146ce 100644 --- a/docs/technical/specs/desktop-module-contract.md +++ b/docs/technical/specs/desktop-module-contract.md @@ -89,6 +89,16 @@ serves the interface and fails to answer, turns the approval into a decline, so the task never takes the action. A host that serves nothing leaves the pause as the only gate. A payment checkpoint is never continuable and needs no review. +Browser egress (2.21): a host may serve the optional +`ai.tinyhumans.tinycomputer.BrowserEgressHost` interface +(`tinycomputer_bus::browser_egress`) with `Authorize`, `Consume`, and +`Validate`. Before a browser proxy request is dialed, the module asks the host +to authorize its actual destination and receives vetted socket addresses plus +an opaque lease. It consumes a one-use grant for an exact address before +dialing, and reauthorizes before trying another address if a connection fails. +The lease is revalidated while the tunnel or response remains active. A 2.20 +module cannot enforce these host decisions. + Session identity (2.20): `SessionOptions` takes the optional `timezone`, `locale`, `accept_language`, `user_agent_metadata`, `screen`, `init_scripts` and `stealth`. A client that sends none gets the defaults; a 2.19 module ignores From 52a0507690c10f1500182f5a30da9eea2138f7bd Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:05:07 +0000 Subject: [PATCH 07/93] Address browser egress review feedback Co-authored-by: Medulla --- crates/tinycomputer-browser/Cargo.toml | 2 ++ crates/tinycomputer-browser/README.md | 6 ++-- .../src/linked/linked_tests.rs | 16 +++++----- docs/technical/specs/process-containment.md | 32 +++++++++++-------- 4 files changed, 32 insertions(+), 24 deletions(-) diff --git a/crates/tinycomputer-browser/Cargo.toml b/crates/tinycomputer-browser/Cargo.toml index fc0e73967..3c6846122 100644 --- a/crates/tinycomputer-browser/Cargo.toml +++ b/crates/tinycomputer-browser/Cargo.toml @@ -48,6 +48,8 @@ agent-browser = { workspace = true, optional = true } default = [] # Link agent-browser in-process and provide `AgentBrowser`, its `Launcher`. agent-browser = ["dep:agent-browser"] +# Run browser egress integration tests against an installed Chromium. +live-tests = [] [dev-dependencies] tokio = { workspace = true } diff --git a/crates/tinycomputer-browser/README.md b/crates/tinycomputer-browser/README.md index d644527c6..be3bf05c5 100644 --- a/crates/tinycomputer-browser/README.md +++ b/crates/tinycomputer-browser/README.md @@ -42,8 +42,8 @@ contents remain opaque to the proxy and require TinySecurity's explicit [`configuration.md`](../../docs/crates/tinycomputer/configuration.md#browser) for the host contract and its privacy behavior. -The Chromium egress fixture tests are ignored in the default suite because -they need an installed browser; run them explicitly with -`cargo test -p tinycomputer-browser --features agent-browser chromium_ -- --ignored`. +The Chromium egress fixture tests are excluded from the default suite because +they need an installed browser; run them with +`cargo test -p tinycomputer-browser --features 'agent-browser live-tests' live_`. They use local fixtures only. Other browser integration tests run in the Docker lab (`docs/technical/docker-lab.md`). diff --git a/crates/tinycomputer-browser/src/linked/linked_tests.rs b/crates/tinycomputer-browser/src/linked/linked_tests.rs index 0d365c6c1..0f1ac430e 100644 --- a/crates/tinycomputer-browser/src/linked/linked_tests.rs +++ b/crates/tinycomputer-browser/src/linked/linked_tests.rs @@ -98,8 +98,8 @@ async fn a_closed_or_lost_browser_cannot_implicitly_launch_without_the_proxy() { } #[tokio::test] -#[ignore = "requires an installed Chromium; exercises its actual proxy behavior"] -async fn chromium_loopback_navigation_uses_the_authenticated_session_proxy() { +#[cfg(feature = "live-tests")] +async fn live_chromium_loopback_navigation_uses_the_authenticated_session_proxy() { let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = fixture.local_addr().unwrap(); let server = tokio::spawn(async move { @@ -143,8 +143,8 @@ async fn chromium_loopback_navigation_uses_the_authenticated_session_proxy() { } #[tokio::test] -#[ignore = "requires an installed Chromium; verifies denied subresource egress"] -async fn chromium_subresource_never_reaches_a_denied_destination() { +#[cfg(feature = "live-tests")] +async fn live_chromium_subresource_never_reaches_a_denied_destination() { let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); denied.set_nonblocking(true).unwrap(); let denied_address = denied.local_addr().unwrap(); @@ -198,8 +198,8 @@ async fn chromium_subresource_never_reaches_a_denied_destination() { } #[tokio::test] -#[ignore = "requires an installed Chromium; verifies denied redirect egress"] -async fn chromium_redirect_never_reaches_a_denied_destination() { +#[cfg(feature = "live-tests")] +async fn live_chromium_redirect_never_reaches_a_denied_destination() { let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); denied.set_nonblocking(true).unwrap(); let denied_address = denied.local_addr().unwrap(); @@ -249,8 +249,8 @@ async fn chromium_redirect_never_reaches_a_denied_destination() { } #[tokio::test] -#[ignore = "requires an installed Chromium; verifies denied WebSocket egress"] -async fn chromium_websocket_never_reaches_a_denied_destination() { +#[cfg(feature = "live-tests")] +async fn live_chromium_websocket_never_reaches_a_denied_destination() { let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); denied.set_nonblocking(true).unwrap(); let denied_address = denied.local_addr().unwrap(); diff --git a/docs/technical/specs/process-containment.md b/docs/technical/specs/process-containment.md index add5d8898..460e68fe1 100644 --- a/docs/technical/specs/process-containment.md +++ b/docs/technical/specs/process-containment.md @@ -14,11 +14,15 @@ skipped looks contained when it is not. tinycomputer is a native module loaded into the host process. It drives the user's real desktop and a real Chrome, so it cannot run inside a jail that -hides those. This module therefore **does not expose a sandbox, proxy or egress -contract**: none of it is enforceable from inside the module, and a contract -that is not enforced is worse than none. The host treats the whole module as -unsandboxed-by-design and gates it at the member level (approval, payment stop, -`POLICY_DENIED`). This document is the explicit list of what is not contained. +hides those. The host treats the module as unsandboxed-by-design and gates it +at the member level (approval, payment stop, `POLICY_DENIED`). For browser +sessions, the host may also provide the module's `BrowserEgressHost` contract: +the module routes HTTP, CONNECT, and WebSocket traffic through a per-session +authenticated proxy, and the host authorizes each dial and supplies the exact +socket address. This constrains only browser traffic that uses the configured +proxy. It does not contain the module process, prevent other direct sockets, +or inspect HTTPS contents; the host still needs OS-level process isolation for +those guarantees. ## Process inventory @@ -27,7 +31,7 @@ unsandboxed-by-design and gates it at the member level (approval, payment stop, | Process | Spawned from | Contract | | --- | --- | --- | -| Chrome (browser sessions) | agent-browser (`vendor/agent-browser`, `native/cdp/chrome.rs`), started by an explicit `launch` | Unsupported. Runs as the user with their network. agent-browser can take a `proxy` launch option, but this module does not set or forward one, so egress is not enforceable here. Xvfb and certutil helpers are agent-browser's. | +| Chrome (browser sessions) | agent-browser (`vendor/agent-browser`, `native/cdp/chrome.rs`), started by an explicit `launch` | Runs as the user. When the host provides `BrowserEgressHost`, the module sets an authenticated per-session proxy and all browser dials pass through host authorization and address consumption. Without that host contract, normal agent-browser egress behavior applies. This is not process containment. Xvfb and certutil helpers are agent-browser's. | | Cursor overlay helper (`tinycomputer-cursor-overlay`) | `crates/tinycomputer-cursor/src/screen/process.rs` | Unsupported. Draws on screen, reads commands on stdin, opens no network. Optional; absent means no drawn cursor. | | Accessibility helper (Swift, macOS) | `crates/tinycomputer-accessibility/src/helper/process.rs`, `globe.rs`, `build.rs` | Unsupported. Needs the macOS accessibility grant of the host app, so it cannot be jailed. Opens no network. | | `osascript`, `open`, `cmd`, `xcrun`, `swiftc` | `crates/tinycomputer-accessibility/src/{focus,paste,permissions}.rs`, `helper/process.rs` | Unsupported. Fixed argv, no model-supplied command line. Local desktop actions only. | @@ -37,13 +41,15 @@ unsandboxed-by-design and gates it at the member level (approval, payment stop, The module's own outbound traffic is the decision model, planner, rescue and output model calls (the `jev`, `planner` config routes), made from the host -process, plus whatever sites the browser is told to open. Host-side egress -policy applies to the first. The second is user-directed browsing and is not -restricted by the module (`origins` checks classify pages, they do not block -network). +process. Browser traffic goes through the host-provided proxy when the +`BrowserEgressHost` is configured; the host authorizes every destination and +provides the socket address used for the dial. The module does not proxy its +own model calls, enforce policy on other sockets opened by the process, or +inspect encrypted browser payloads. `origins` checks classify pages; they do +not block network access. ## Revisit when -agent-browser or the module can pass a launch-time proxy or network namespace -and the module can verify it took effect. Only then add a contract member, in -`tinycomputer-bus`, with a test that the browser's traffic goes through it. +The remaining containment gaps are closed only when the host supplies +OS-level process isolation that the module can verify. Keep the browser egress +contract and tests aligned with `BrowserEgressHost` in `tinycomputer-bus`. From 25afb0ba602656c066da94a4a425618156a88eec Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:07:28 +0000 Subject: [PATCH 08/93] Make unreachable proxy test deterministic Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress_tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress_tests.rs b/crates/tinycomputer-browser/src/egress_tests.rs index 259e1ef15..182e85806 100644 --- a/crates/tinycomputer-browser/src/egress_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests.rs @@ -179,9 +179,9 @@ async fn approved_connect_reaches_only_the_consumed_socket() { #[tokio::test] async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachable() { - let unreachable = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let first_address = unreachable.local_addr().unwrap(); - drop(unreachable); + // Port zero is never a listening destination, unlike a recently freed + // ephemeral port that another parallel test could claim before we dial. + let first_address = SocketAddr::from(([127, 0, 0, 1], 0)); let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); let second_address = destination.local_addr().unwrap(); From 8b2d7b4e18c08b81bf968c988ad88329f02351d7 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:12:52 +0000 Subject: [PATCH 09/93] Bump vendored browser and bus security fixes Co-authored-by: Medulla --- Cargo.lock | 74 +++++++++++++------------------------------- vendor/agent-browser | 2 +- vendor/tinybus | 2 +- 3 files changed, 24 insertions(+), 54 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 003ea2368..95e8999b9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -83,7 +83,7 @@ dependencies = [ "urlencoding", "uuid", "windows-sys 0.52.0", - "zip 8.6.0", + "zip", ] [[package]] @@ -181,15 +181,6 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" -[[package]] -name = "arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] - [[package]] name = "arboard" version = "3.6.1" @@ -395,7 +386,7 @@ version = "5.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a68fa787550392a9d58f44c21a3022cfb3ea3e2458b7f85d3b399d0ceeccf409" dependencies = [ - "nix", + "nix 0.27.1", "winapi", ] @@ -529,12 +520,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "crossbeam-utils" -version = "0.8.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" - [[package]] name = "crypto-common" version = "0.1.7" @@ -582,17 +567,6 @@ version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" -[[package]] -name = "derive_arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "digest" version = "0.10.7" @@ -1465,6 +1439,18 @@ dependencies = [ "libc", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "ntapi" version = "0.4.3" @@ -2572,7 +2558,7 @@ dependencies = [ [[package]] name = "tinybus" -version = "0.1.5" +version = "0.1.6" dependencies = [ "async-trait", "flate2", @@ -2588,12 +2574,12 @@ dependencies = [ "toml", "tracing", "ureq", - "zip 2.4.2", + "zip", ] [[package]] name = "tinybus-macros" -version = "0.1.5" +version = "0.1.6" dependencies = [ "proc-macro2", "quote", @@ -2602,7 +2588,7 @@ dependencies = [ [[package]] name = "tinybus-module" -version = "0.1.5" +version = "0.1.6" dependencies = [ "async-trait", "serde", @@ -3329,7 +3315,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.48.0", ] [[package]] @@ -3877,31 +3863,15 @@ dependencies = [ [[package]] name = "zip" -version = "2.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" -dependencies = [ - "arbitrary", - "crc32fast", - "crossbeam-utils", - "displaydoc", - "flate2", - "indexmap", - "memchr", - "thiserror 2.0.20", - "zopfli", -] - -[[package]] -name = "zip" -version = "8.6.0" +version = "9.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +checksum = "6e04976da629d3b04204ba8105b396a193af8ad2583b2c79bfb3ab8af580a11e" dependencies = [ "crc32fast", "flate2", "indexmap", "memchr", + "nix 0.31.3", "typed-path", "zopfli", ] diff --git a/vendor/agent-browser b/vendor/agent-browser index f98d5fef6..4027616bc 160000 --- a/vendor/agent-browser +++ b/vendor/agent-browser @@ -1 +1 @@ -Subproject commit f98d5fef6a57b6067e6c5710e6f0ea6fb0b3bd47 +Subproject commit 4027616bc202356a35661d2329154ac6607d6233 diff --git a/vendor/tinybus b/vendor/tinybus index eb5cf7270..0c98b57c9 160000 --- a/vendor/tinybus +++ b/vendor/tinybus @@ -1 +1 @@ -Subproject commit eb5cf727071a6eb12f9efa3db8ec59e54039f336 +Subproject commit 0c98b57c91cb47c65d7f93f7c950b0f3ca5673b4 From 69346e5a4d1980b8b56421dbc998122c7b0e6c7b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:18:58 +0000 Subject: [PATCH 10/93] fix(tinycomputer-browser): recheck browser liveness after acquiring engine lock The enforced-launch liveness check ran before the engine lock was taken, so a browser that exited while a call waited on the lock could still be used. The check now runs inside the lock, and the live Chromium tests are gated on a `live_browser_tests` cfg set by the build script instead of a `live-tests` feature. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/Cargo.toml | 2 - crates/tinycomputer-browser/README.md | 2 +- crates/tinycomputer-browser/build.rs | 10 +++++ .../src/linked/linked_tests.rs | 39 +++++++++++++++--- crates/tinycomputer-browser/src/linked/mod.rs | 40 +++++++++---------- 5 files changed, 64 insertions(+), 29 deletions(-) create mode 100644 crates/tinycomputer-browser/build.rs diff --git a/crates/tinycomputer-browser/Cargo.toml b/crates/tinycomputer-browser/Cargo.toml index 3c6846122..fc0e73967 100644 --- a/crates/tinycomputer-browser/Cargo.toml +++ b/crates/tinycomputer-browser/Cargo.toml @@ -48,8 +48,6 @@ agent-browser = { workspace = true, optional = true } default = [] # Link agent-browser in-process and provide `AgentBrowser`, its `Launcher`. agent-browser = ["dep:agent-browser"] -# Run browser egress integration tests against an installed Chromium. -live-tests = [] [dev-dependencies] tokio = { workspace = true } diff --git a/crates/tinycomputer-browser/README.md b/crates/tinycomputer-browser/README.md index be3bf05c5..ee59a67f0 100644 --- a/crates/tinycomputer-browser/README.md +++ b/crates/tinycomputer-browser/README.md @@ -44,6 +44,6 @@ for the host contract and its privacy behavior. The Chromium egress fixture tests are excluded from the default suite because they need an installed browser; run them with -`cargo test -p tinycomputer-browser --features 'agent-browser live-tests' live_`. +`TINYCOMPUTER_LIVE_BROWSER_TESTS=1 cargo test -p tinycomputer-browser --features agent-browser live_`. They use local fixtures only. Other browser integration tests run in the Docker lab (`docs/technical/docker-lab.md`). diff --git a/crates/tinycomputer-browser/build.rs b/crates/tinycomputer-browser/build.rs new file mode 100644 index 000000000..26c793c02 --- /dev/null +++ b/crates/tinycomputer-browser/build.rs @@ -0,0 +1,10 @@ +//! Selects opt-in browser tests at compile time. + +fn main() { + println!("cargo:rustc-check-cfg=cfg(live_browser_tests)"); + println!("cargo:rerun-if-env-changed=TINYCOMPUTER_LIVE_BROWSER_TESTS"); + + if std::env::var_os("TINYCOMPUTER_LIVE_BROWSER_TESTS").is_some() { + println!("cargo:rustc-cfg=live_browser_tests"); + } +} diff --git a/crates/tinycomputer-browser/src/linked/linked_tests.rs b/crates/tinycomputer-browser/src/linked/linked_tests.rs index 0f1ac430e..8a4cdf4a0 100644 --- a/crates/tinycomputer-browser/src/linked/linked_tests.rs +++ b/crates/tinycomputer-browser/src/linked/linked_tests.rs @@ -21,7 +21,7 @@ use tokio::{ net::TcpListener, }; -use super::{AgentBrowser, EnforcedAgentBrowser, Linked, enforce_launch, state_options}; +use super::{AgentBrowser, EnforcedAgentBrowser, Linked, ENGINE, enforce_launch, state_options}; use crate::{ BrowserDialTarget, DialGrant, EgressAuthorizer, engine::{Engine, Launcher}, @@ -98,7 +98,36 @@ async fn a_closed_or_lost_browser_cannot_implicitly_launch_without_the_proxy() { } #[tokio::test] -#[cfg(feature = "live-tests")] +async fn enforced_browser_rechecks_liveness_after_waiting_for_engine_lock() { + let engine = Linked { + state: DaemonState::with_options(state_options("closed-after-lock")), + egress_authorizer: Some(Arc::new(RejectAll)), + proxy: None, + proxy_session_id: "private-session-id".into(), + enforced_launch: true, + }; + let serialized = ENGINE.lock().await; + let pending = tokio::spawn(async move { + let mut engine = engine; + engine + .execute(json!({ + "id":"navigate", + "action":"navigate", + "url":"http://public.example/" + })) + .await + }); + tokio::task::yield_now().await; + assert!(!pending.is_finished(), "the call should wait for ENGINE"); + drop(serialized); + + let reply = pending.await.unwrap(); + assert_eq!(reply["success"], false); + assert!(reply["error"].as_str().unwrap().contains("live browser session")); +} + +#[tokio::test] +#[cfg(live_browser_tests)] async fn live_chromium_loopback_navigation_uses_the_authenticated_session_proxy() { let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = fixture.local_addr().unwrap(); @@ -143,7 +172,7 @@ async fn live_chromium_loopback_navigation_uses_the_authenticated_session_proxy( } #[tokio::test] -#[cfg(feature = "live-tests")] +#[cfg(live_browser_tests)] async fn live_chromium_subresource_never_reaches_a_denied_destination() { let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); denied.set_nonblocking(true).unwrap(); @@ -198,7 +227,7 @@ async fn live_chromium_subresource_never_reaches_a_denied_destination() { } #[tokio::test] -#[cfg(feature = "live-tests")] +#[cfg(live_browser_tests)] async fn live_chromium_redirect_never_reaches_a_denied_destination() { let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); denied.set_nonblocking(true).unwrap(); @@ -249,7 +278,7 @@ async fn live_chromium_redirect_never_reaches_a_denied_destination() { } #[tokio::test] -#[cfg(feature = "live-tests")] +#[cfg(live_browser_tests)] async fn live_chromium_websocket_never_reaches_a_denied_destination() { let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); denied.set_nonblocking(true).unwrap(); diff --git a/crates/tinycomputer-browser/src/linked/mod.rs b/crates/tinycomputer-browser/src/linked/mod.rs index e1e26ce93..56e327769 100644 --- a/crates/tinycomputer-browser/src/linked/mod.rs +++ b/crates/tinycomputer-browser/src/linked/mod.rs @@ -84,27 +84,6 @@ impl Engine for Linked { .get("action") .and_then(Value::as_str) .map(str::to_owned); - #[allow(clippy::redundant_closure_for_method_calls)] - let browser_unavailable = self - .state - .browser - .as_mut() - // BrowserManager is private in agent-browser, so its method cannot - // be named as a function item here. - .is_none_or(|browser| browser.has_process_exited()); - if self.egress_authorizer.is_some() - && action.as_deref() != Some("launch") - && (!self.enforced_launch || browser_unavailable) - { - self.enforced_launch = false; - self.proxy.take(); - return Box::pin(async move { - failure_reply( - &command, - "network policy requires an enforced launch with a live browser session", - ) - }); - } let launch = self.egress_authorizer.is_some() && action.as_deref() == Some("launch"); Box::pin(async move { let command = if launch { @@ -142,6 +121,25 @@ impl Engine for Linked { command }; let _serialized = ENGINE.lock().await; + #[allow(clippy::redundant_closure_for_method_calls)] + let browser_unavailable = self + .state + .browser + .as_mut() + // BrowserManager is private in agent-browser, so its method cannot + // be named as a function item here. + .is_none_or(|browser| browser.has_process_exited()); + if self.egress_authorizer.is_some() + && !launch + && (!self.enforced_launch || browser_unavailable) + { + self.enforced_launch = false; + self.proxy.take(); + return failure_reply( + &command, + "network policy requires an enforced launch with a live browser session", + ); + } let reply = Box::pin(execute_command(&command, &mut self.state)).await; if launch && reply.get("success").and_then(Value::as_bool) == Some(true) { self.enforced_launch = true; From e1b4de04c154b138ca1dfbc5d8545a9fe2204da6 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:19:35 +0000 Subject: [PATCH 11/93] test(linked): gate live browser test helpers behind cfg The live-browser test fixtures and their tokio and atomic imports are now compiled only when the live_browser_tests cfg is enabled, so the default test build no longer pulls in unused networking helpers. Import ordering and one assertion were also reformatted. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/linked/linked_tests.rs | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/crates/tinycomputer-browser/src/linked/linked_tests.rs b/crates/tinycomputer-browser/src/linked/linked_tests.rs index 8a4cdf4a0..a5fd1790b 100644 --- a/crates/tinycomputer-browser/src/linked/linked_tests.rs +++ b/crates/tinycomputer-browser/src/linked/linked_tests.rs @@ -7,21 +7,17 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::json; -use std::{ - io, - net::SocketAddr, - sync::{ - Arc, - atomic::{AtomicUsize, Ordering}, - }, -}; +use std::{io, net::SocketAddr, sync::Arc}; +#[cfg(live_browser_tests)] +use std::sync::atomic::{AtomicUsize, Ordering}; +#[cfg(live_browser_tests)] use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::TcpListener, }; -use super::{AgentBrowser, EnforcedAgentBrowser, Linked, ENGINE, enforce_launch, state_options}; +use super::{AgentBrowser, ENGINE, EnforcedAgentBrowser, Linked, enforce_launch, state_options}; use crate::{ BrowserDialTarget, DialGrant, EgressAuthorizer, engine::{Engine, Launcher}, @@ -123,7 +119,12 @@ async fn enforced_browser_rechecks_liveness_after_waiting_for_engine_lock() { let reply = pending.await.unwrap(); assert_eq!(reply["success"], false); - assert!(reply["error"].as_str().unwrap().contains("live browser session")); + assert!( + reply["error"] + .as_str() + .unwrap() + .contains("live browser session") + ); } #[tokio::test] @@ -332,12 +333,14 @@ async fn live_chromium_websocket_never_reaches_a_denied_destination() { ); } +#[cfg(live_browser_tests)] #[derive(Debug)] struct RejectAllButFixture { address: SocketAddr, authorizations: Arc, } +#[cfg(live_browser_tests)] impl EgressAuthorizer for RejectAllButFixture { fn authorize( &self, From 655f002a45ce07e36a5f400c822a2b3e96148f6b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:22:47 +0000 Subject: [PATCH 12/93] test(egress): split proxy tests into per-protocol modules The monolithic egress test file was broken up into separate modules for authority parsing, connect, http, lease, lifecycle, retry, websocket, and shared simulator fixtures, with the root file reduced to module declarations. This keeps each protocol path's tests self-contained and easier to navigate as coverage grows. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinycomputer-browser/src/egress_tests.rs | 739 +----------------- .../src/egress_tests/authority_tests.rs | 54 ++ .../src/egress_tests/connect_tests.rs | 58 ++ .../src/egress_tests/http_tests.rs | 261 +++++++ .../src/egress_tests/lease_tests.rs | 65 ++ .../src/egress_tests/lifecycle_tests.rs | 27 + .../src/egress_tests/retry_tests.rs | 57 ++ .../src/egress_tests/simulator.rs | 158 ++++ .../src/egress_tests/websocket_tests.rs | 75 ++ 9 files changed, 773 insertions(+), 721 deletions(-) create mode 100644 crates/tinycomputer-browser/src/egress_tests/authority_tests.rs create mode 100644 crates/tinycomputer-browser/src/egress_tests/connect_tests.rs create mode 100644 crates/tinycomputer-browser/src/egress_tests/http_tests.rs create mode 100644 crates/tinycomputer-browser/src/egress_tests/lease_tests.rs create mode 100644 crates/tinycomputer-browser/src/egress_tests/lifecycle_tests.rs create mode 100644 crates/tinycomputer-browser/src/egress_tests/retry_tests.rs create mode 100644 crates/tinycomputer-browser/src/egress_tests/simulator.rs create mode 100644 crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs diff --git a/crates/tinycomputer-browser/src/egress_tests.rs b/crates/tinycomputer-browser/src/egress_tests.rs index 182e85806..2e48d981b 100644 --- a/crates/tinycomputer-browser/src/egress_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests.rs @@ -1,723 +1,20 @@ -//! Local socket tests for browser proxy enforcement. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - -use std::{ - io, - net::SocketAddr, - sync::{ - Arc, - atomic::{AtomicBool, Ordering}, - }, -}; - -use base64::Engine as _; -use tokio::{ - io::{AsyncReadExt, AsyncWriteExt}, - net::{TcpListener, TcpStream}, -}; - -use crate::{BrowserDialTarget, DialGrant, EgressAuthorizer, EgressProxy, egress::parse_authority}; - -const FIXTURE_PASSWORD: &str = "fixture-proxy-secret"; - -fn proxy_authorization() -> String { - format!( - "Basic {}", - base64::engine::general_purpose::STANDARD - .encode(format!("tinycomputer:{FIXTURE_PASSWORD}")) - ) -} - -#[test] -fn browser_dial_target_debug_does_not_disclose_session_or_destination() { - let target = BrowserDialTarget { - scheme: "https".into(), - hostname: "private.example.test".into(), - port: 443, - session_id: "private-browser-session".into(), - }; - let debug = format!("{target:?}"); - assert!(!debug.contains("private.example.test")); - assert!(!debug.contains("private-browser-session")); - assert!(debug.contains("REDACTED")); -} - -#[test] -fn dial_grant_debug_does_not_disclose_lease_or_destination() { - let grant = DialGrant { - lease: "private-opaque-nonce".into(), - addresses: vec!["203.0.113.77:8443".parse().unwrap()], - }; - let debug = format!("{grant:?}"); - assert!(!debug.contains("private-opaque-nonce")); - assert!(!debug.contains("203.0.113.77")); - assert!(debug.contains("REDACTED")); -} - -#[test] -fn proxy_authority_uses_scheme_defaults_and_canonical_ipv6_literals() { - assert_eq!( - parse_authority("example.test", "http", "session") - .unwrap() - .port, - 80 - ); - assert_eq!( - parse_authority("example.test", "https", "session") - .unwrap() - .port, - 443 - ); - let ipv6 = parse_authority("[2001:4860:4860::8888]:443", "https", "session").unwrap(); - assert_eq!(ipv6.hostname, "2001:4860:4860::8888"); - assert!(parse_authority("https://example.test:443", "https", "session").is_err()); -} - -#[derive(Clone)] -struct FixtureAuthorizer { - address: SocketAddr, - allow: bool, - consumed: Arc, -} - -impl EgressAuthorizer for FixtureAuthorizer { - fn authorize( - &self, - _target: BrowserDialTarget, - ) -> std::pin::Pin> + Send>> { - let address = self.address; - let allow = self.allow; - Box::pin(async move { - if allow { - Ok(DialGrant { - lease: "fixture-lease".into(), - addresses: vec![address], - }) - } else { - Err(io::Error::new(io::ErrorKind::PermissionDenied, "denied")) - } - }) - } - fn consume( - &self, - _target: BrowserDialTarget, - _grant: DialGrant, - address: SocketAddr, - ) -> std::pin::Pin> + Send>> { - let expected = self.address; - let consumed = self.consumed.clone(); - Box::pin(async move { - if address == expected { - consumed.store(true, Ordering::SeqCst); - Ok(()) - } else { - Err(io::Error::new( - io::ErrorKind::PermissionDenied, - "wrong address", - )) - } - }) - } - fn validate( - &self, - _lease: String, - ) -> std::pin::Pin> + Send>> { - Box::pin(async { Ok(true) }) - } -} - -#[tokio::test] -async fn approved_connect_reaches_only_the_consumed_socket() { - let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = destination.local_addr().unwrap(); - let authorizer = Arc::new(FixtureAuthorizer { - address, - allow: true, - consumed: Arc::new(AtomicBool::new(false)), - }); - let proxy = EgressProxy::bind( - authorizer.clone(), - "test-session".into(), - FIXTURE_PASSWORD.into(), - ) - .await - .unwrap(); - let ((), upstream_client) = tokio::join!( - async { - let mut client = TcpStream::connect(proxy.url().replace("http://", "")) - .await - .unwrap(); - client - .write_all( - format!( - "CONNECT example.test:{} HTTP/1.1\r\nHost: example.test:{}\r\nProxy-Authorization: {}\r\n\r\n", - address.port(), - address.port(), - proxy_authorization() - ) - .as_bytes(), - ) - .await - .unwrap(); - let mut response = [0; 128]; - let n = client.read(&mut response).await.unwrap(); - assert!( - std::str::from_utf8(&response[..n]) - .unwrap() - .contains("200 Connection Established") - ); - client.write_all(b"ping").await.unwrap(); - }, - destination.accept() - ); - let (mut upstream_client, _) = upstream_client.unwrap(); - assert!(authorizer.consumed.load(Ordering::SeqCst)); - let mut payload = [0; 4]; - upstream_client.read_exact(&mut payload).await.unwrap(); - assert_eq!(&payload, b"ping"); -} - -#[tokio::test] -async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachable() { - // Port zero is never a listening destination, unlike a recently freed - // ephemeral port that another parallel test could claim before we dial. - let first_address = SocketAddr::from(([127, 0, 0, 1], 0)); - - let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let second_address = destination.local_addr().unwrap(); - let server = tokio::spawn(async move { - let (mut socket, _) = destination.accept().await.unwrap(); - socket - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") - .await - .unwrap(); - }); - let authorizer = Arc::new(MultiAddressAuthorizer { - addresses: vec![first_address, second_address], - }); - let proxy = EgressProxy::bind( - authorizer, - "multi-address-session".into(), - FIXTURE_PASSWORD.into(), - ) - .await - .unwrap(); - let mut client = TcpStream::connect(proxy.url().replace("http://", "")) - .await - .unwrap(); - client - .write_all( - format!( - "GET http://control.test:{}/ HTTP/1.1\r\nHost: control.test:{}\r\nProxy-Authorization: {}\r\n\r\n", - second_address.port(), - second_address.port(), - proxy_authorization() - ) - .as_bytes(), - ) - .await - .unwrap(); - let mut response = Vec::new(); - client.read_to_end(&mut response).await.unwrap(); - assert!( - std::str::from_utf8(&response) - .unwrap() - .ends_with("\r\n\r\nok") - ); - server.await.unwrap(); -} - -struct MultiAddressAuthorizer { - addresses: Vec, -} +//! Egress proxy tests, grouped by protocol path and lifecycle behavior. -impl EgressAuthorizer for MultiAddressAuthorizer { - fn authorize( - &self, - _target: BrowserDialTarget, - ) -> std::pin::Pin> + Send>> { - let addresses = self.addresses.clone(); - Box::pin(async move { - Ok(DialGrant { - lease: "multi-address-lease".into(), - addresses, - }) - }) - } - - fn consume( - &self, - _target: BrowserDialTarget, - grant: DialGrant, - address: SocketAddr, - ) -> std::pin::Pin> + Send>> { - Box::pin(async move { - if grant.addresses.contains(&address) { - Ok(()) - } else { - Err(io::Error::new( - io::ErrorKind::PermissionDenied, - "wrong address", - )) - } - }) - } - - fn validate( - &self, - _lease: String, - ) -> std::pin::Pin> + Send>> { - Box::pin(async { Ok(true) }) - } -} - -#[tokio::test] -async fn denied_destination_never_connects_to_the_fixture() { - let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - destination.set_nonblocking(true).unwrap(); - let address = destination.local_addr().unwrap(); - let proxy = EgressProxy::bind( - Arc::new(FixtureAuthorizer { - address, - allow: false, - consumed: Arc::new(AtomicBool::new(false)), - }), - "denied-session".into(), - FIXTURE_PASSWORD.into(), - ) - .await - .unwrap(); - let mut client = TcpStream::connect(proxy.url().replace("http://", "")) - .await - .unwrap(); - client - .write_all( - format!( - "CONNECT metadata.test:{} HTTP/1.1\r\nHost: metadata.test:{}\r\nProxy-Authorization: {}\r\n\r\n", - address.port(), - address.port(), - proxy_authorization() - ) - .as_bytes(), - ) - .await - .unwrap(); - let mut response = [0; 128]; - let n = client.read(&mut response).await.unwrap(); - assert!( - std::str::from_utf8(&response[..n]) - .unwrap() - .contains("403 Forbidden") - ); - assert_eq!( - destination.accept().unwrap_err().kind(), - io::ErrorKind::WouldBlock - ); -} - -#[tokio::test] -async fn unauthenticated_local_clients_cannot_use_the_session_policy_broker() { - let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - destination.set_nonblocking(true).unwrap(); - let address = destination.local_addr().unwrap(); - let proxy = EgressProxy::bind( - Arc::new(FixtureAuthorizer { - address, - allow: true, - consumed: Arc::new(AtomicBool::new(false)), - }), - "protected-session".into(), - FIXTURE_PASSWORD.into(), - ) - .await - .unwrap(); - let mut client = TcpStream::connect(proxy.url().replace("http://", "")) - .await - .unwrap(); - client - .write_all( - format!( - "CONNECT public.example:{} HTTP/1.1\r\nHost: public.example:{}\r\n\r\n", - address.port(), - address.port() - ) - .as_bytes(), - ) - .await - .unwrap(); - let mut response = [0; 256]; - let n = client.read(&mut response).await.unwrap(); - let response = std::str::from_utf8(&response[..n]).unwrap(); - assert!(response.contains("407 Proxy Authentication Required")); - assert_eq!( - destination.accept().unwrap_err().kind(), - io::ErrorKind::WouldBlock - ); -} - -#[tokio::test] -async fn approved_http_request_is_rewritten_and_forwarded_to_approved_fixture() { - let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = destination.local_addr().unwrap(); - let server = tokio::spawn(async move { - let (mut socket, _) = destination.accept().await.unwrap(); - let mut request = Vec::new(); - let mut chunk = [0; 512]; - loop { - let n = socket.read(&mut chunk).await.unwrap(); - request.extend_from_slice(&chunk[..n]); - if request.windows(4).any(|window| window == b"\r\n\r\n") { - break; - } - } - let request = std::str::from_utf8(&request).unwrap(); - assert!(request.starts_with("GET /control?ready=1 HTTP/1.1\r\n")); - assert!(request.contains(&format!("Host: control.test:{}\r\n", address.port()))); - assert!(request.contains("Connection: close\r\n")); - socket - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") - .await - .unwrap(); - }); - let authorizer = Arc::new(FixtureAuthorizer { - address, - allow: true, - consumed: Arc::new(AtomicBool::new(false)), - }); - let proxy = EgressProxy::bind( - authorizer.clone(), - "http-session".into(), - FIXTURE_PASSWORD.into(), - ) - .await - .unwrap(); - let mut client = TcpStream::connect(proxy.url().replace("http://", "")) - .await - .unwrap(); - client - .write_all( - format!( - "GET http://control.test:{}/control?ready=1 HTTP/1.1\r\nHost: control.test:{}\r\nProxy-Authorization: {}\r\nConnection: keep-alive\r\n\r\n", - address.port(), - address.port(), - proxy_authorization() - ) - .as_bytes(), - ) - .await - .unwrap(); - let mut response = Vec::new(); - client.read_to_end(&mut response).await.unwrap(); - assert!( - std::str::from_utf8(&response) - .unwrap() - .ends_with("\r\n\r\nok") - ); - assert!(authorizer.consumed.load(Ordering::SeqCst)); - server.await.unwrap(); -} - -#[tokio::test] -async fn approved_http_request_body_is_forwarded_without_framing_changes() { - let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = destination.local_addr().unwrap(); - let server = tokio::spawn(async move { - let (mut socket, _) = destination.accept().await.unwrap(); - let mut request = Vec::new(); - let mut chunk = [0; 512]; - loop { - let n = socket.read(&mut chunk).await.unwrap(); - request.extend_from_slice(&chunk[..n]); - if let Some(split) = request.windows(4).position(|window| window == b"\r\n\r\n") - && request.len() >= split + 8 - { - break; - } - } - assert!(request.ends_with(b"data")); - socket - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") - .await - .unwrap(); - }); - let proxy = EgressProxy::bind( - Arc::new(FixtureAuthorizer { - address, - allow: true, - consumed: Arc::new(AtomicBool::new(false)), - }), - "body-session".into(), - FIXTURE_PASSWORD.into(), - ) - .await - .unwrap(); - let mut client = TcpStream::connect(proxy.url().replace("http://", "")) - .await - .unwrap(); - client - .write_all( - format!( - "POST http://body.test:{}/submit HTTP/1.1\r\nHost: body.test:{}\r\nProxy-Authorization: {}\r\nContent-Length: 4\r\n\r\ndata", - address.port(), - address.port(), - proxy_authorization() - ) - .as_bytes(), - ) - .await - .unwrap(); - let mut response = Vec::new(); - client.read_to_end(&mut response).await.unwrap(); - assert!( - std::str::from_utf8(&response) - .unwrap() - .ends_with("\r\n\r\nok") - ); - server.await.unwrap(); -} - -#[tokio::test] -async fn duplicate_lengths_and_pipelined_authorities_are_refused_before_dial() { - let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - destination.set_nonblocking(true).unwrap(); - let address = destination.local_addr().unwrap(); - for suffix in [ - "Content-Length: 0\r\nContent-Length: 0\r\n\r\n", - "Content-Length: 0\r\n\r\nGET http://other.test/ HTTP/1.1\r\nHost: other.test\r\n\r\n", - ] { - let proxy = EgressProxy::bind( - Arc::new(FixtureAuthorizer { - address, - allow: true, - consumed: Arc::new(AtomicBool::new(false)), - }), - "malformed-session".into(), - FIXTURE_PASSWORD.into(), - ) - .await - .unwrap(); - let mut client = TcpStream::connect(proxy.url().replace("http://", "")) - .await - .unwrap(); - client - .write_all( - format!( - "GET http://one.test:{}/ HTTP/1.1\r\nHost: one.test:{}\r\nProxy-Authorization: {}\r\n{}", - address.port(), - address.port(), - proxy_authorization(), - suffix - ) - .as_bytes(), - ) - .await - .unwrap(); - let mut response = [0; 128]; - let n = client.read(&mut response).await.unwrap(); - assert!( - std::str::from_utf8(&response[..n]) - .unwrap() - .contains("403 Forbidden") - ); - assert_eq!( - destination.accept().unwrap_err().kind(), - io::ErrorKind::WouldBlock - ); - } -} - -#[tokio::test] -async fn approved_websocket_upgrade_is_forwarded_and_tunneled() { - let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = destination.local_addr().unwrap(); - let server = tokio::spawn(async move { - let (mut socket, _) = destination.accept().await.unwrap(); - let mut request = Vec::new(); - let mut chunk = [0; 512]; - loop { - let n = socket.read(&mut chunk).await.unwrap(); - request.extend_from_slice(&chunk[..n]); - if request.windows(4).any(|window| window == b"\r\n\r\n") { - break; - } - } - let request = std::str::from_utf8(&request).unwrap(); - assert!(request.starts_with("GET /socket HTTP/1.1\r\n")); - assert!(request.contains("Connection: Upgrade\r\n")); - assert!(request.contains("Upgrade: websocket\r\n")); - socket - .write_all(b"HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n") - .await - .unwrap(); - let mut ping = [0; 4]; - socket.read_exact(&mut ping).await.unwrap(); - assert_eq!(&ping, b"ping"); - socket.write_all(b"pong").await.unwrap(); - }); - let proxy = EgressProxy::bind( - Arc::new(FixtureAuthorizer { - address, - allow: true, - consumed: Arc::new(AtomicBool::new(false)), - }), - "websocket-session".into(), - FIXTURE_PASSWORD.into(), - ) - .await - .unwrap(); - let mut client = TcpStream::connect(proxy.url().replace("http://", "")) - .await - .unwrap(); - client - .write_all( - format!( - "GET ws://socket.test:{}/socket HTTP/1.1\r\nHost: socket.test:{}\r\nProxy-Authorization: {}\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n", - address.port(), - address.port(), - proxy_authorization() - ) - .as_bytes(), - ) - .await - .unwrap(); - let mut handshake = [0; 256]; - let n = client.read(&mut handshake).await.unwrap(); - assert!( - std::str::from_utf8(&handshake[..n]) - .unwrap() - .contains("101 Switching Protocols") - ); - client.write_all(b"ping").await.unwrap(); - let mut pong = [0; 4]; - client.read_exact(&mut pong).await.unwrap(); - assert_eq!(&pong, b"pong"); - server.await.unwrap(); -} - -struct RevokingAuthorizer { - address: SocketAddr, - validations: Arc, -} - -impl EgressAuthorizer for RevokingAuthorizer { - fn authorize( - &self, - _target: BrowserDialTarget, - ) -> std::pin::Pin> + Send>> { - let address = self.address; - Box::pin(async move { - Ok(DialGrant { - lease: "revoked-during-stream".into(), - addresses: vec![address], - }) - }) - } - - fn consume( - &self, - _target: BrowserDialTarget, - _grant: DialGrant, - address: SocketAddr, - ) -> std::pin::Pin> + Send>> { - let expected = self.address; - Box::pin(async move { - if address == expected { - Ok(()) - } else { - Err(io::Error::new( - io::ErrorKind::PermissionDenied, - "wrong address", - )) - } - }) - } - - fn validate( - &self, - _lease: String, - ) -> std::pin::Pin> + Send>> { - let validations = self.validations.clone(); - Box::pin(async move { - let call = validations.fetch_add(1, Ordering::SeqCst); - Ok(call == 0) - }) - } -} - -#[tokio::test] -async fn continuous_http_response_still_revalidates_and_closes_revoked_lease() { - use std::sync::atomic::AtomicUsize; - let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = destination.local_addr().unwrap(); - let server = tokio::spawn(async move { - let (mut socket, _) = destination.accept().await.unwrap(); - let mut request = [0; 2048]; - let _ = socket.read(&mut request).await.unwrap(); - for _ in 0..4096 { - if socket.write_all(&[b'x'; 1024]).await.is_err() { - return; - } - tokio::time::sleep(std::time::Duration::from_millis(20)).await; - } - }); - let validations = Arc::new(AtomicUsize::new(0)); - let proxy = EgressProxy::bind( - Arc::new(RevokingAuthorizer { - address, - validations: validations.clone(), - }), - "stream-session".into(), - FIXTURE_PASSWORD.into(), - ) - .await - .unwrap(); - let mut client = TcpStream::connect(proxy.url().replace("http://", "")) - .await - .unwrap(); - client - .write_all( - format!( - "GET http://stream.test:{}/ HTTP/1.1\r\nHost: stream.test:{}\r\nProxy-Authorization: {}\r\n\r\n", - address.port(), - address.port(), - proxy_authorization() - ) - .as_bytes(), - ) - .await - .unwrap(); - let mut response = Vec::new(); - tokio::time::timeout( - std::time::Duration::from_secs(4), - client.read_to_end(&mut response), - ) - .await - .expect("revoked response stream should be closed promptly") - .unwrap(); - assert!(validations.load(Ordering::SeqCst) > 0); - assert!( - response.len() < 4096 * 1024, - "revoked response kept streaming" - ); - server.await.unwrap(); -} +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -#[tokio::test] -async fn dropping_session_proxy_closes_its_listener() { - let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let proxy = EgressProxy::bind( - Arc::new(FixtureAuthorizer { - address: destination.local_addr().unwrap(), - allow: false, - consumed: Arc::new(AtomicBool::new(false)), - }), - "closed-session".into(), - FIXTURE_PASSWORD.into(), - ) - .await - .unwrap(); - let endpoint = proxy.url().replace("http://", ""); - drop(proxy); - tokio::task::yield_now().await; - assert!(TcpStream::connect(endpoint).await.is_err()); -} +#[path = "egress_tests/authority_tests.rs"] +mod authority_tests; +#[path = "egress_tests/connect_tests.rs"] +mod connect_tests; +#[path = "egress_tests/http_tests.rs"] +mod http_tests; +#[path = "egress_tests/lease_tests.rs"] +mod lease_tests; +#[path = "egress_tests/lifecycle_tests.rs"] +mod lifecycle_tests; +#[path = "egress_tests/retry_tests.rs"] +mod retry_tests; +#[path = "egress_tests/simulator.rs"] +mod simulator; +#[path = "egress_tests/websocket_tests.rs"] +mod websocket_tests; diff --git a/crates/tinycomputer-browser/src/egress_tests/authority_tests.rs b/crates/tinycomputer-browser/src/egress_tests/authority_tests.rs new file mode 100644 index 000000000..c4cbd50ad --- /dev/null +++ b/crates/tinycomputer-browser/src/egress_tests/authority_tests.rs @@ -0,0 +1,54 @@ +//! Focused browser egress proxy tests. + +use super::simulator::*; +use crate::{BrowserDialTarget, DialGrant, EgressProxy, egress::parse_authority}; +use serde_json::json; +use std::{io, net::*, sync::*}; +use tokio::{io::*, net::*}; + +#[test] +fn browser_dial_target_debug_does_not_disclose_session_or_destination() { + let target = BrowserDialTarget { + scheme: "https".into(), + hostname: "private.example.test".into(), + port: 443, + session_id: "private-browser-session".into(), + }; + let debug = format!("{target:?}"); + assert!(!debug.contains("private.example.test")); + assert!(!debug.contains("private-browser-session")); + assert!(debug.contains("REDACTED")); +} + +#[test] +fn dial_grant_debug_does_not_disclose_lease_or_destination() { + let grant = DialGrant { + lease: "private-opaque-nonce".into(), + addresses: vec!["203.0.113.77:8443".parse().unwrap()], + }; + let debug = format!("{grant:?}"); + assert!(!debug.contains("private-opaque-nonce")); + assert!(!debug.contains("203.0.113.77")); + assert!(debug.contains("REDACTED")); +} + +#[test] +fn proxy_authority_uses_scheme_defaults_and_canonical_ipv6_literals() { + assert_eq!( + parse_authority("example.test", "http", "session") + .unwrap() + .port, + 80 + ); + assert_eq!( + parse_authority("example.test", "https", "session") + .unwrap() + .port, + 443 + ); + let ipv6 = parse_authority("[2001:4860:4860::8888]:443", "https", "session").unwrap(); + assert_eq!(ipv6.hostname, "2001:4860:4860::8888"); + assert!(parse_authority("https://example.test:443", "https", "session").is_err()); +} + +#[derive(Clone)] diff --git a/crates/tinycomputer-browser/src/egress_tests/connect_tests.rs b/crates/tinycomputer-browser/src/egress_tests/connect_tests.rs new file mode 100644 index 000000000..887dc82b9 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress_tests/connect_tests.rs @@ -0,0 +1,58 @@ +//! Focused browser egress proxy tests. + +use super::simulator::*; +use crate::{BrowserDialTarget, DialGrant, EgressProxy, egress::parse_authority}; +use serde_json::json; +use std::{io, net::*, sync::*}; +use tokio::{io::*, net::*}; + +#[tokio::test] +async fn approved_connect_reaches_only_the_consumed_socket() { + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let authorizer = Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }); + let proxy = EgressProxy::bind( + authorizer.clone(), + "test-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let ((), upstream_client) = tokio::join!( + async { + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "CONNECT example.test:{} HTTP/1.1\r\nHost: example.test:{}\r\nProxy-Authorization: {}\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = [0; 128]; + let n = client.read(&mut response).await.unwrap(); + assert!( + std::str::from_utf8(&response[..n]) + .unwrap() + .contains("200 Connection Established") + ); + client.write_all(b"ping").await.unwrap(); + }, + destination.accept() + ); + let (mut upstream_client, _) = upstream_client.unwrap(); + assert!(authorizer.consumed.load(Ordering::SeqCst)); + let mut payload = [0; 4]; + upstream_client.read_exact(&mut payload).await.unwrap(); + assert_eq!(&payload, b"ping"); +} diff --git a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs new file mode 100644 index 000000000..712fd4334 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs @@ -0,0 +1,261 @@ +//! Focused browser egress proxy tests. + +use super::simulator::*; +use crate::{BrowserDialTarget, DialGrant, EgressProxy, egress::parse_authority}; +use serde_json::json; +use std::{io, net::*, sync::*}; +use tokio::{io::*, net::*}; + +#[tokio::test] +async fn denied_destination_never_connects_to_the_fixture() { + let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + destination.set_nonblocking(true).unwrap(); + let address = destination.local_addr().unwrap(); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: false, + consumed: Arc::new(AtomicBool::new(false)), + }), + "denied-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "CONNECT metadata.test:{} HTTP/1.1\r\nHost: metadata.test:{}\r\nProxy-Authorization: {}\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = [0; 128]; + let n = client.read(&mut response).await.unwrap(); + assert!( + std::str::from_utf8(&response[..n]) + .unwrap() + .contains("403 Forbidden") + ); + assert_eq!( + destination.accept().unwrap_err().kind(), + io::ErrorKind::WouldBlock + ); +} +#[tokio::test] +async fn unauthenticated_local_clients_cannot_use_the_session_policy_broker() { + let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + destination.set_nonblocking(true).unwrap(); + let address = destination.local_addr().unwrap(); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }), + "protected-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "CONNECT public.example:{} HTTP/1.1\r\nHost: public.example:{}\r\n\r\n", + address.port(), + address.port() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = [0; 256]; + let n = client.read(&mut response).await.unwrap(); + let response = std::str::from_utf8(&response[..n]).unwrap(); + assert!(response.contains("407 Proxy Authentication Required")); + assert_eq!( + destination.accept().unwrap_err().kind(), + io::ErrorKind::WouldBlock + ); +} + +#[tokio::test] +async fn approved_http_request_is_rewritten_and_forwarded_to_approved_fixture() { + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 512]; + loop { + let n = socket.read(&mut chunk).await.unwrap(); + request.extend_from_slice(&chunk[..n]); + if request.windows(4).any(|window| window == b"\r\n\r\n") { + break; + } + } + let request = std::str::from_utf8(&request).unwrap(); + assert!(request.starts_with("GET /control?ready=1 HTTP/1.1\r\n")); + assert!(request.contains(&format!("Host: control.test:{}\r\n", address.port()))); + assert!(request.contains("Connection: close\r\n")); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + .await + .unwrap(); + }); + let authorizer = Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }); + let proxy = EgressProxy::bind( + authorizer.clone(), + "http-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "GET http://control.test:{}/control?ready=1 HTTP/1.1\r\nHost: control.test:{}\r\nProxy-Authorization: {}\r\nConnection: keep-alive\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = Vec::new(); + client.read_to_end(&mut response).await.unwrap(); + assert!( + std::str::from_utf8(&response) + .unwrap() + .ends_with("\r\n\r\nok") + ); + assert!(authorizer.consumed.load(Ordering::SeqCst)); + server.await.unwrap(); +} + +#[tokio::test] +async fn approved_http_request_body_is_forwarded_without_framing_changes() { + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 512]; + loop { + let n = socket.read(&mut chunk).await.unwrap(); + request.extend_from_slice(&chunk[..n]); + if let Some(split) = request.windows(4).position(|window| window == b"\r\n\r\n") + && request.len() >= split + 8 + { + break; + } + } + assert!(request.ends_with(b"data")); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + .await + .unwrap(); + }); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }), + "body-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "POST http://body.test:{}/submit HTTP/1.1\r\nHost: body.test:{}\r\nProxy-Authorization: {}\r\nContent-Length: 4\r\n\r\ndata", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = Vec::new(); + client.read_to_end(&mut response).await.unwrap(); + assert!( + std::str::from_utf8(&response) + .unwrap() + .ends_with("\r\n\r\nok") + ); + server.await.unwrap(); +} + +#[tokio::test] +async fn duplicate_lengths_and_pipelined_authorities_are_refused_before_dial() { + let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + destination.set_nonblocking(true).unwrap(); + let address = destination.local_addr().unwrap(); + for suffix in [ + "Content-Length: 0\r\nContent-Length: 0\r\n\r\n", + "Content-Length: 0\r\n\r\nGET http://other.test/ HTTP/1.1\r\nHost: other.test\r\n\r\n", + ] { + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }), + "malformed-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "GET http://one.test:{}/ HTTP/1.1\r\nHost: one.test:{}\r\nProxy-Authorization: {}\r\n{}", + address.port(), + address.port(), + proxy_authorization(), + suffix + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = [0; 128]; + let n = client.read(&mut response).await.unwrap(); + assert!( + std::str::from_utf8(&response[..n]) + .unwrap() + .contains("403 Forbidden") + ); + assert_eq!( + destination.accept().unwrap_err().kind(), + io::ErrorKind::WouldBlock + ); + } +} diff --git a/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs b/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs new file mode 100644 index 000000000..a09b908ca --- /dev/null +++ b/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs @@ -0,0 +1,65 @@ +//! Focused browser egress proxy tests. + +use super::simulator::*; +use crate::{BrowserDialTarget, DialGrant, EgressProxy, egress::parse_authority}; +use serde_json::json; +use std::{io, net::*, sync::*}; +use tokio::{io::*, net::*}; + +#[tokio::test] +async fn continuous_http_response_still_revalidates_and_closes_revoked_lease() { + use std::sync::atomic::AtomicUsize; + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + let mut request = [0; 2048]; + let _ = socket.read(&mut request).await.unwrap(); + for _ in 0..4096 { + if socket.write_all(&[b'x'; 1024]).await.is_err() { + return; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + }); + let validations = Arc::new(AtomicUsize::new(0)); + let proxy = EgressProxy::bind( + Arc::new(RevokingAuthorizer { + address, + validations: validations.clone(), + }), + "stream-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "GET http://stream.test:{}/ HTTP/1.1\r\nHost: stream.test:{}\r\nProxy-Authorization: {}\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = Vec::new(); + tokio::time::timeout( + std::time::Duration::from_secs(4), + client.read_to_end(&mut response), + ) + .await + .expect("revoked response stream should be closed promptly") + .unwrap(); + assert!(validations.load(Ordering::SeqCst) > 0); + assert!( + response.len() < 4096 * 1024, + "revoked response kept streaming" + ); + server.await.unwrap(); +} diff --git a/crates/tinycomputer-browser/src/egress_tests/lifecycle_tests.rs b/crates/tinycomputer-browser/src/egress_tests/lifecycle_tests.rs new file mode 100644 index 000000000..63b4440a2 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress_tests/lifecycle_tests.rs @@ -0,0 +1,27 @@ +//! Focused browser egress proxy tests. + +use super::simulator::*; +use crate::{BrowserDialTarget, DialGrant, EgressProxy, egress::parse_authority}; +use serde_json::json; +use std::{io, net::*, sync::*}; +use tokio::{io::*, net::*}; + +#[tokio::test] +async fn dropping_session_proxy_closes_its_listener() { + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address: destination.local_addr().unwrap(), + allow: false, + consumed: Arc::new(AtomicBool::new(false)), + }), + "closed-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let endpoint = proxy.url().replace("http://", ""); + drop(proxy); + tokio::task::yield_now().await; + assert!(TcpStream::connect(endpoint).await.is_err()); +} diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs new file mode 100644 index 000000000..64754da05 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -0,0 +1,57 @@ +//! Focused browser egress proxy tests. + +use super::simulator::*; +use crate::{BrowserDialTarget, DialGrant, EgressProxy, egress::parse_authority}; +use serde_json::json; +use std::{io, net::*, sync::*}; +use tokio::{io::*, net::*}; + +#[tokio::test] +async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachable() { + // Port zero is never a listening destination, unlike a recently freed + // ephemeral port that another parallel test could claim before we dial. + let first_address = SocketAddr::from(([127, 0, 0, 1], 0)); + + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let second_address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + .await + .unwrap(); + }); + let authorizer = Arc::new(MultiAddressAuthorizer { + addresses: vec![first_address, second_address], + }); + let proxy = EgressProxy::bind( + authorizer, + "multi-address-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "GET http://control.test:{}/ HTTP/1.1\r\nHost: control.test:{}\r\nProxy-Authorization: {}\r\n\r\n", + second_address.port(), + second_address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = Vec::new(); + client.read_to_end(&mut response).await.unwrap(); + assert!( + std::str::from_utf8(&response) + .unwrap() + .ends_with("\r\n\r\nok") + ); + server.await.unwrap(); +} diff --git a/crates/tinycomputer-browser/src/egress_tests/simulator.rs b/crates/tinycomputer-browser/src/egress_tests/simulator.rs new file mode 100644 index 000000000..5c62e5614 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress_tests/simulator.rs @@ -0,0 +1,158 @@ +//! Local authorizers and fixture helpers shared by egress tests. + +use crate::{BrowserDialTarget, DialGrant, EgressAuthorizer}; +use std::{io, net::SocketAddr, sync::{Arc, atomic::{AtomicUsize, Ordering}}}; + +fn proxy_authorization() -> String { + format!( + "Basic {}", + base64::engine::general_purpose::STANDARD + .encode(format!("tinycomputer:{FIXTURE_PASSWORD}")) + ) +} + +struct FixtureAuthorizer { + address: SocketAddr, + allow: bool, + consumed: Arc, +} + +impl EgressAuthorizer for FixtureAuthorizer { + fn authorize( + &self, + _target: BrowserDialTarget, + ) -> std::pin::Pin> + Send>> { + let address = self.address; + let allow = self.allow; + Box::pin(async move { + if allow { + Ok(DialGrant { + lease: "fixture-lease".into(), + addresses: vec![address], + }) + } else { + Err(io::Error::new(io::ErrorKind::PermissionDenied, "denied")) + } + }) + } + fn consume( + &self, + _target: BrowserDialTarget, + _grant: DialGrant, + address: SocketAddr, + ) -> std::pin::Pin> + Send>> { + let expected = self.address; + let consumed = self.consumed.clone(); + Box::pin(async move { + if address == expected { + consumed.store(true, Ordering::SeqCst); + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "wrong address", + )) + } + }) + } + fn validate( + &self, + _lease: String, + ) -> std::pin::Pin> + Send>> { + Box::pin(async { Ok(true) }) + } +} + +struct MultiAddressAuthorizer { + addresses: Vec, +} + +impl EgressAuthorizer for MultiAddressAuthorizer { + fn authorize( + &self, + _target: BrowserDialTarget, + ) -> std::pin::Pin> + Send>> { + let addresses = self.addresses.clone(); + Box::pin(async move { + Ok(DialGrant { + lease: "multi-address-lease".into(), + addresses, + }) + }) + } + + fn consume( + &self, + _target: BrowserDialTarget, + grant: DialGrant, + address: SocketAddr, + ) -> std::pin::Pin> + Send>> { + Box::pin(async move { + if grant.addresses.contains(&address) { + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "wrong address", + )) + } + }) + } + + fn validate( + &self, + _lease: String, + ) -> std::pin::Pin> + Send>> { + Box::pin(async { Ok(true) }) + } +} + +struct RevokingAuthorizer { + address: SocketAddr, + validations: Arc, +} + +impl EgressAuthorizer for RevokingAuthorizer { + fn authorize( + &self, + _target: BrowserDialTarget, + ) -> std::pin::Pin> + Send>> { + let address = self.address; + Box::pin(async move { + Ok(DialGrant { + lease: "revoked-during-stream".into(), + addresses: vec![address], + }) + }) + } + + fn consume( + &self, + _target: BrowserDialTarget, + _grant: DialGrant, + address: SocketAddr, + ) -> std::pin::Pin> + Send>> { + let expected = self.address; + Box::pin(async move { + if address == expected { + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "wrong address", + )) + } + }) + } + + fn validate( + &self, + _lease: String, + ) -> std::pin::Pin> + Send>> { + let validations = self.validations.clone(); + Box::pin(async move { + let call = validations.fetch_add(1, Ordering::SeqCst); + Ok(call == 0) + }) + } +} diff --git a/crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs b/crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs new file mode 100644 index 000000000..b668459a7 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs @@ -0,0 +1,75 @@ +//! Focused browser egress proxy tests. + +use super::simulator::*; +use crate::{BrowserDialTarget, DialGrant, EgressProxy, egress::parse_authority}; +use serde_json::json; +use std::{io, net::*, sync::*}; +use tokio::{io::*, net::*}; + +#[tokio::test] +async fn approved_websocket_upgrade_is_forwarded_and_tunneled() { + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 512]; + loop { + let n = socket.read(&mut chunk).await.unwrap(); + request.extend_from_slice(&chunk[..n]); + if request.windows(4).any(|window| window == b"\r\n\r\n") { + break; + } + } + let request = std::str::from_utf8(&request).unwrap(); + assert!(request.starts_with("GET /socket HTTP/1.1\r\n")); + assert!(request.contains("Connection: Upgrade\r\n")); + assert!(request.contains("Upgrade: websocket\r\n")); + socket + .write_all(b"HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n") + .await + .unwrap(); + let mut ping = [0; 4]; + socket.read_exact(&mut ping).await.unwrap(); + assert_eq!(&ping, b"ping"); + socket.write_all(b"pong").await.unwrap(); + }); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }), + "websocket-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "GET ws://socket.test:{}/socket HTTP/1.1\r\nHost: socket.test:{}\r\nProxy-Authorization: {}\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut handshake = [0; 256]; + let n = client.read(&mut handshake).await.unwrap(); + assert!( + std::str::from_utf8(&handshake[..n]) + .unwrap() + .contains("101 Switching Protocols") + ); + client.write_all(b"ping").await.unwrap(); + let mut pong = [0; 4]; + client.read_exact(&mut pong).await.unwrap(); + assert_eq!(&pong, b"pong"); + server.await.unwrap(); +} From 9d1da132089b7ada081a7f98dfc6e3785c01ffd1 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:23:12 +0000 Subject: [PATCH 13/93] refactor(egress): split browser proxy into submodules The single egress module was broken up into forward, request, serve, and mod submodules so the proxy's request parsing, upstream forwarding, and connection serving logic can be maintained separately. No behaviour changes. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress.rs | 608 ------------------ .../src/egress/forward.rs | 161 +++++ crates/tinycomputer-browser/src/egress/mod.rs | 119 ++++ .../src/egress/request.rs | 270 ++++++++ .../tinycomputer-browser/src/egress/serve.rs | 82 +++ 5 files changed, 632 insertions(+), 608 deletions(-) delete mode 100644 crates/tinycomputer-browser/src/egress.rs create mode 100644 crates/tinycomputer-browser/src/egress/forward.rs create mode 100644 crates/tinycomputer-browser/src/egress/mod.rs create mode 100644 crates/tinycomputer-browser/src/egress/request.rs create mode 100644 crates/tinycomputer-browser/src/egress/serve.rs diff --git a/crates/tinycomputer-browser/src/egress.rs b/crates/tinycomputer-browser/src/egress.rs deleted file mode 100644 index d677defb9..000000000 --- a/crates/tinycomputer-browser/src/egress.rs +++ /dev/null @@ -1,608 +0,0 @@ -//! Session-local browser HTTP proxy with destination authorization before each dial. -//! -//! The proxy accepts only browser HTTP proxy requests. It never resolves a name -//! locally: the authorizer returns a finite set of vetted socket addresses and -//! the proxy consumes the grant before dialing one exact address. - -use std::{future::Future, io, net::SocketAddr, pin::Pin, sync::Arc, time::Duration}; - -use base64::Engine as _; -use tokio::{ - io::{AsyncReadExt, AsyncWriteExt, copy_bidirectional}, - net::{TcpListener, TcpStream}, - task::JoinSet, -}; - -/// A destination parsed from the browser's actual proxy request. -#[derive(Clone, PartialEq, Eq)] -pub struct BrowserDialTarget { - /// `http` or `https`. - pub scheme: String, - /// Canonical host, without brackets for IPv6 literals. - pub hostname: String, - /// Effective destination port. - pub port: u16, - /// Opaque per-browser-session binding generated by `TinyComputer`. - pub session_id: String, -} - -impl std::fmt::Debug for BrowserDialTarget { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("BrowserDialTarget([REDACTED])") - } -} - -/// Opaque authorizer state plus the exact permitted sockets. -#[derive(Clone)] -pub struct DialGrant { - /// Opaque lease returned by the authenticated `TinySecurity` adapter. - pub lease: String, - /// Finite address set vetted by `TinySecurity`. - pub addresses: Vec, -} - -impl std::fmt::Debug for DialGrant { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("DialGrant([REDACTED])") - } -} - -/// The host adapter delegates every decision to `TinySecurity` over `TinyBus`. -pub trait EgressAuthorizer: Send + Sync + 'static { - /// Authorize the actual destination and return a one-use grant. - fn authorize( - &self, - target: BrowserDialTarget, - ) -> Pin> + Send>>; - /// Consume the grant before the selected socket is opened. - fn consume( - &self, - target: BrowserDialTarget, - grant: DialGrant, - address: SocketAddr, - ) -> Pin> + Send>>; - /// Revalidate an active tunnel lease. False or error closes the tunnel. - fn validate(&self, lease: String) -> Pin> + Send>>; -} - -/// An ephemeral loopback proxy owned by one browser session. -#[derive(Debug)] -pub struct EgressProxy { - address: SocketAddr, - task: tokio::task::JoinHandle<()>, -} - -impl EgressProxy { - /// Bind a private IPv4 loopback listener for one session. - /// - /// # Errors - /// - /// Returns an I/O error when the listener cannot bind or its address cannot - /// be read. - pub async fn bind( - authorizer: Arc, - session_id: String, - proxy_password: String, - ) -> io::Result { - let listener = TcpListener::bind(("127.0.0.1", 0)).await?; - let address = listener.local_addr()?; - let task = tokio::spawn(async move { - let mut connections = JoinSet::new(); - loop { - tokio::select! { - accepted = listener.accept(), if connections.len() < 64 => { - let Ok((stream, _)) = accepted else { break; }; - let auth = authorizer.clone(); - let session = session_id.clone(); - let password = proxy_password.clone(); - connections.spawn(async move { let _ = serve(stream, auth, session, password).await; }); - } - _ = connections.join_next(), if !connections.is_empty() => {} - } - } - }); - Ok(Self { address, task }) - } - - /// Chromium proxy URL; it contains no policy authority. - #[must_use] - pub fn url(&self) -> String { - format!("http://{}:{}", self.address.ip(), self.address.port()) - } -} - -impl Drop for EgressProxy { - fn drop(&mut self) { - self.task.abort(); - } -} - -async fn serve( - mut client: TcpStream, - auth: Arc, - session_id: String, - proxy_password: String, -) -> io::Result<()> { - let Some(mut request) = read_proxy_request(&mut client, &session_id, &proxy_password).await? - else { - return Ok(()); - }; - if !read_request_body(&mut client, &mut request).await? { - return refuse(&mut client).await; - } - let Some(first_grant) = authorize(&auth, &request.target).await else { - return refuse(&mut client).await; - }; - let addresses = first_grant.addresses.clone(); - let mut connected = None; - for (index, address) in addresses.into_iter().enumerate() { - // A consume call spends its one-use grant. Reauthorize every later - // candidate so a failed dial cannot reuse a spent authorization. - let grant = if index == 0 { - first_grant.clone() - } else { - match authorize(&auth, &request.target).await { - Some(grant) if grant.addresses.contains(&address) => grant, - _ => continue, - } - }; - if !matches!( - tokio::time::timeout( - Duration::from_secs(5), - auth.consume(request.target.clone(), grant.clone(), address), - ) - .await, - Ok(Ok(())) - ) { - return refuse(&mut client).await; - } - if let Ok(Ok(upstream)) = - tokio::time::timeout(Duration::from_secs(5), TcpStream::connect(address)).await - { - connected = Some((upstream, grant.lease)); - break; - } - } - let Some((mut upstream, lease)) = connected else { - return refuse(&mut client).await; - }; - if !validate_lease(&auth, &lease).await? { - return Ok(()); - } - initialize_upstream(&mut client, &mut upstream, &request).await?; - if request.connect || request.has_upgrade { - tunnel_with_lease(&mut client, &mut upstream, &auth, lease).await?; - } else { - forward_response_with_lease(&mut client, &mut upstream, &auth, lease).await?; - } - Ok(()) -} - -async fn authorize( - auth: &Arc, - target: &BrowserDialTarget, -) -> Option { - match tokio::time::timeout(Duration::from_secs(5), auth.authorize(target.clone())).await { - Ok(Ok(grant)) if !grant.addresses.is_empty() && grant.addresses.len() <= 64 => Some(grant), - _ => None, - } -} - -struct ProxyRequest { - bytes: Vec, - split: usize, - lines: Vec, - method: String, - uri: String, - version: String, - target: BrowserDialTarget, - connect: bool, - body_len: usize, - has_upgrade: bool, -} - -async fn read_proxy_request( - client: &mut TcpStream, - session_id: &str, - proxy_password: &str, -) -> io::Result> { - let mut bytes = Vec::with_capacity(4096); - let mut chunk = [0u8; 1024]; - loop { - let n = tokio::time::timeout(Duration::from_secs(10), client.read(&mut chunk)) - .await - .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy request timed out"))??; - if n == 0 { - return Ok(None); - } - bytes.extend_from_slice(&chunk[..n]); - if bytes.len() > 32 * 1024 { - refuse(client).await?; - return Ok(None); - } - if bytes.windows(4).any(|window| window == b"\r\n\r\n") { - break; - } - } - let Some(header_end) = bytes.windows(4).position(|window| window == b"\r\n\r\n") else { - refuse(client).await?; - return Ok(None); - }; - let split = header_end + 4; - let Ok(head) = std::str::from_utf8(&bytes[..split]) else { - refuse(client).await?; - return Ok(None); - }; - let lines: Vec = head.split("\r\n").map(str::to_owned).collect(); - let Some(request_line) = lines.first() else { - refuse(client).await?; - return Ok(None); - }; - let mut parts = request_line.split_ascii_whitespace(); - let method = parts.next().unwrap_or_default().to_owned(); - let uri = parts.next().unwrap_or_default().to_owned(); - let version = parts.next().unwrap_or_default().to_owned(); - if parts.next().is_some() || (version != "HTTP/1.1" && version != "HTTP/1.0") { - refuse(client).await?; - return Ok(None); - } - let Some(target) = proxy_target(&method, &uri, session_id) else { - refuse(client).await?; - return Ok(None); - }; - let connect = method.eq_ignore_ascii_case("CONNECT"); - let Some(headers) = parse_proxy_headers(&lines, &target, connect, session_id) else { - refuse(client).await?; - return Ok(None); - }; - if !has_proxy_auth(headers.proxy_authorization.as_deref(), proxy_password) { - write_all_bounded( - client, - b"HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm=\"tinycomputer-browser\"\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", - "browser proxy challenge timed out", - ) - .await?; - return Ok(None); - } - if connect && bytes.len() > split { - refuse(client).await?; - return Ok(None); - } - Ok(Some(ProxyRequest { - bytes, - split, - lines, - method, - uri, - version, - target, - connect, - body_len: headers.body_len, - has_upgrade: headers.has_upgrade, - })) -} - -fn proxy_target(method: &str, uri: &str, session_id: &str) -> Option { - if method.eq_ignore_ascii_case("CONNECT") { - return parse_authority(uri, "https", session_id).ok(); - } - let url = url::Url::parse(uri).ok()?; - if !matches!(url.scheme(), "http" | "ws") - || !url.username().is_empty() - || url.password().is_some() - || url.fragment().is_some() - { - return None; - } - Some(BrowserDialTarget { - scheme: "http".to_owned(), - hostname: url - .host_str()? - .trim_matches(['[', ']']) - .to_ascii_lowercase(), - port: url.port_or_known_default()?, - session_id: session_id.to_owned(), - }) -} - -struct ParsedHeaders { - body_len: usize, - has_upgrade: bool, - proxy_authorization: Option, -} - -fn parse_proxy_headers( - lines: &[String], - target: &BrowserDialTarget, - connect: bool, - session_id: &str, -) -> Option { - let mut body_len = 0usize; - let mut host_header = None; - let mut has_upgrade = false; - let mut connection_upgrade = false; - let mut proxy_authorization = None; - let mut saw_content_length = false; - for line in lines - .iter() - .skip(1) - .map(String::as_str) - .filter(|line| !line.is_empty()) - { - let (name, value) = line.split_once(':')?; - if name.eq_ignore_ascii_case("host") { - if host_header.replace(value.trim().to_owned()).is_some() { - return None; - } - } else if name.eq_ignore_ascii_case("content-length") { - if saw_content_length { - return None; - } - saw_content_length = true; - body_len = value.trim().parse().unwrap_or(usize::MAX); - } else if name.eq_ignore_ascii_case("transfer-encoding") - || name.eq_ignore_ascii_case("expect") - { - return None; - } else if name.eq_ignore_ascii_case("proxy-authorization") { - if proxy_authorization - .replace(value.trim().to_owned()) - .is_some() - { - return None; - } - } else if name.eq_ignore_ascii_case("upgrade") - && value.trim().eq_ignore_ascii_case("websocket") - { - has_upgrade = true; - } else if name.eq_ignore_ascii_case("connection") - && value - .split(',') - .any(|token| token.trim().eq_ignore_ascii_case("upgrade")) - { - connection_upgrade = true; - } - } - let host_matches = host_header.as_deref().is_some_and(|host| { - parse_authority(host, if connect { "https" } else { "http" }, session_id) - .is_ok_and(|parsed| parsed.hostname == target.hostname && parsed.port == target.port) - }); - if has_upgrade != connection_upgrade - || !host_matches - || (connect && body_len != 0) - || (!connect && (body_len > 1024 * 1024 || (has_upgrade && body_len != 0))) - { - return None; - } - Some(ParsedHeaders { - body_len, - has_upgrade, - proxy_authorization, - }) -} - -fn has_proxy_auth(proxy_authorization: Option<&str>, password: &str) -> bool { - let expected = format!( - "Basic {}", - base64::engine::general_purpose::STANDARD.encode(format!("tinycomputer:{password}")) - ); - proxy_authorization - .is_some_and(|actual| constant_time_eq(actual.as_bytes(), expected.as_bytes())) -} - -async fn initialize_upstream( - client: &mut TcpStream, - upstream: &mut TcpStream, - request: &ProxyRequest, -) -> io::Result<()> { - if request.connect { - write_all_bounded( - client, - b"HTTP/1.1 200 Connection Established\r\n\r\n", - "browser CONNECT response timed out", - ) - .await?; - if request.bytes.len() > request.split { - return write_all_bounded( - upstream, - &request.bytes[request.split..], - "browser CONNECT payload timed out", - ) - .await; - } - return Ok(()); - } - let url = url::Url::parse(&request.uri) - .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid HTTP proxy URL"))?; - let path = if let Some(query) = url.query() { - format!("{}?{query}", url.path()) - } else { - url.path().to_owned() - }; - let mut forwarded = format!("{} {path} {}\r\n", request.method, request.version); - for line in request - .lines - .iter() - .skip(1) - .map(String::as_str) - .filter(|line| !line.is_empty()) - { - let name = line.split_once(':').map_or("", |(name, _)| name); - if !name.eq_ignore_ascii_case("connection") - && !name.eq_ignore_ascii_case("proxy-connection") - && !name.eq_ignore_ascii_case("proxy-authorization") - { - forwarded.push_str(line); - forwarded.push_str("\r\n"); - } - } - if request.has_upgrade { - forwarded.push_str("Connection: Upgrade\r\n\r\n"); - } else { - forwarded.push_str("Connection: close\r\n\r\n"); - } - write_all_bounded( - upstream, - forwarded.as_bytes(), - "browser upstream request timed out", - ) - .await?; - write_all_bounded( - upstream, - &request.bytes[request.split..], - "browser upstream body timed out", - ) - .await -} - -async fn read_request_body(client: &mut TcpStream, request: &mut ProxyRequest) -> io::Result { - if request.has_upgrade || request.connect { - return Ok(true); - } - let received = request.bytes.len().saturating_sub(request.split); - if received > request.body_len { - return Ok(false); - } - let mut chunk = [0u8; 1024]; - while request.bytes.len().saturating_sub(request.split) < request.body_len { - let n = tokio::time::timeout(Duration::from_secs(10), client.read(&mut chunk)) - .await - .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy body timed out"))??; - if n == 0 { - return Ok(false); - } - request.bytes.extend_from_slice(&chunk[..n]); - if request.bytes.len() > request.split + request.body_len { - return Ok(false); - } - } - Ok(true) -} - -fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { - let mut difference = left.len() ^ right.len(); - for index in 0..left.len().max(right.len()) { - difference |= usize::from( - left.get(index).copied().unwrap_or(0) ^ right.get(index).copied().unwrap_or(0), - ); - } - difference == 0 -} - -async fn tunnel_with_lease( - client: &mut TcpStream, - upstream: &mut TcpStream, - auth: &Arc, - lease: String, -) -> io::Result<()> { - let relay = copy_bidirectional(client, upstream); - tokio::pin!(relay); - let mut validations = validation_interval(); - loop { - tokio::select! { - biased; - _ = validations.tick() => { - if !validate_lease(auth, &lease).await? { return Ok(()); } - }, - result = &mut relay => { result?; return Ok(()); }, - } - } -} - -async fn forward_response_with_lease( - client: &mut TcpStream, - upstream: &mut TcpStream, - auth: &Arc, - lease: String, -) -> io::Result<()> { - let mut chunk = [0u8; 8192]; - let mut validations = validation_interval(); - loop { - tokio::select! { - biased; - _ = validations.tick() => { - if !validate_lease(auth, &lease).await? { return Ok(()); } - }, - result = upstream.read(&mut chunk) => { - let n = result?; - if n == 0 { return Ok(()); } - write_all_bounded(client, &chunk[..n], "browser response write timed out").await?; - }, - } - } -} - -fn validation_interval() -> tokio::time::Interval { - let period = Duration::from_secs(1); - let mut interval = tokio::time::interval_at(tokio::time::Instant::now() + period, period); - interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - interval -} - -async fn validate_lease(auth: &Arc, lease: &str) -> io::Result { - tokio::time::timeout(Duration::from_secs(2), auth.validate(lease.to_owned())) - .await - .map_err(|_| { - io::Error::new( - io::ErrorKind::TimedOut, - "browser lease validation timed out", - ) - })? -} - -pub(super) fn parse_authority( - value: &str, - scheme: &str, - session_id: &str, -) -> io::Result { - if value.contains("://") { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "authority form required", - )); - } - let authority = url::Url::parse(&format!("{scheme}://{value}/")) - .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid CONNECT authority"))?; - if authority.path() != "/" - || authority.query().is_some() - || authority.fragment().is_some() - || !authority.username().is_empty() - || authority.password().is_some() - { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "invalid CONNECT authority", - )); - } - Ok(BrowserDialTarget { - scheme: scheme.to_owned(), - hostname: authority - .host_str() - .unwrap_or_default() - .trim_matches(['[', ']']) - .to_ascii_lowercase(), - port: authority - .port() - .unwrap_or(if scheme == "http" { 80 } else { 443 }), - session_id: session_id.to_owned(), - }) -} - -async fn refuse(client: &mut TcpStream) -> io::Result<()> { - write_all_bounded( - client, - b"HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", - "browser refusal response timed out", - ) - .await -} - -async fn write_all_bounded( - stream: &mut TcpStream, - bytes: &[u8], - message: &'static str, -) -> io::Result<()> { - tokio::time::timeout(Duration::from_secs(5), stream.write_all(bytes)) - .await - .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, message))? -} diff --git a/crates/tinycomputer-browser/src/egress/forward.rs b/crates/tinycomputer-browser/src/egress/forward.rs new file mode 100644 index 000000000..ae34a8a4f --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/forward.rs @@ -0,0 +1,161 @@ +//! Forwards authorized proxy traffic and keeps active streams tied to their lease. + +use std::{io, sync::Arc, time::Duration}; + +use base64::Engine as _; +use tokio::{io::{AsyncReadExt, AsyncWriteExt, copy_bidirectional}, net::TcpStream}; + +use super::{EgressAuthorizer, request::ProxyRequest}; + +pub(super) async fn initialize_upstream( + client: &mut TcpStream, + upstream: &mut TcpStream, + request: &ProxyRequest, +) -> io::Result<()> { + if request.connect { + write_all_bounded( + client, + b"HTTP/1.1 200 Connection Established\r\n\r\n", + "browser CONNECT response timed out", + ) + .await?; + if request.bytes.len() > request.split { + return write_all_bounded( + upstream, + &request.bytes[request.split..], + "browser CONNECT payload timed out", + ) + .await; + } + return Ok(()); + } + let url = url::Url::parse(&request.uri) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid HTTP proxy URL"))?; + let path = if let Some(query) = url.query() { + format!("{}?{query}", url.path()) + } else { + url.path().to_owned() + }; + let mut forwarded = format!("{} {path} {}\r\n", request.method, request.version); + for line in request + .lines + .iter() + .skip(1) + .map(String::as_str) + .filter(|line| !line.is_empty()) + { + let name = line.split_once(':').map_or("", |(name, _)| name); + if !name.eq_ignore_ascii_case("connection") + && !name.eq_ignore_ascii_case("proxy-connection") + && !name.eq_ignore_ascii_case("proxy-authorization") + { + forwarded.push_str(line); + forwarded.push_str("\r\n"); + } + } + if request.has_upgrade { + forwarded.push_str("Connection: Upgrade\r\n\r\n"); + } else { + forwarded.push_str("Connection: close\r\n\r\n"); + } + write_all_bounded( + upstream, + forwarded.as_bytes(), + "browser upstream request timed out", + ) + .await?; + write_all_bounded( + upstream, + &request.bytes[request.split..], + "browser upstream body timed out", + ) + .await +} +fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { + let mut difference = left.len() ^ right.len(); + for index in 0..left.len().max(right.len()) { + difference |= usize::from( + left.get(index).copied().unwrap_or(0) ^ right.get(index).copied().unwrap_or(0), + ); + } + difference == 0 +} + +pub(super) async fn tunnel_with_lease( + client: &mut TcpStream, + upstream: &mut TcpStream, + auth: &Arc, + lease: String, +) -> io::Result<()> { + let relay = copy_bidirectional(client, upstream); + tokio::pin!(relay); + let mut validations = validation_interval(); + loop { + tokio::select! { + biased; + _ = validations.tick() => { + if !validate_lease(auth, &lease).await? { return Ok(()); } + }, + result = &mut relay => { result?; return Ok(()); }, + } + } +} + +pub(super) async fn forward_response_with_lease( + client: &mut TcpStream, + upstream: &mut TcpStream, + auth: &Arc, + lease: String, +) -> io::Result<()> { + let mut chunk = [0u8; 8192]; + let mut validations = validation_interval(); + loop { + tokio::select! { + biased; + _ = validations.tick() => { + if !validate_lease(auth, &lease).await? { return Ok(()); } + }, + result = upstream.read(&mut chunk) => { + let n = result?; + if n == 0 { return Ok(()); } + write_all_bounded(client, &chunk[..n], "browser response write timed out").await?; + }, + } + } +} + +fn validation_interval() -> tokio::time::Interval { + let period = Duration::from_secs(1); + let mut interval = tokio::time::interval_at(tokio::time::Instant::now() + period, period); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + interval +} + +pub(super) async fn validate_lease(auth: &Arc, lease: &str) -> io::Result { + tokio::time::timeout(Duration::from_secs(2), auth.validate(lease.to_owned())) + .await + .map_err(|_| { + io::Error::new( + io::ErrorKind::TimedOut, + "browser lease validation timed out", + ) + })? +} +pub(super) async fn refuse(client: &mut TcpStream) -> io::Result<()> { + write_all_bounded( + client, + b"HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", + "browser refusal response timed out", + ) + .await +} + +pub(super) async fn write_all_bounded( + stream: &mut TcpStream, + bytes: &[u8], + message: &'static str, +) -> io::Result<()> { + tokio::time::timeout(Duration::from_secs(5), stream.write_all(bytes)) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, message))? +} diff --git a/crates/tinycomputer-browser/src/egress/mod.rs b/crates/tinycomputer-browser/src/egress/mod.rs new file mode 100644 index 000000000..3912e8b96 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/mod.rs @@ -0,0 +1,119 @@ +//! Session-local browser HTTP proxy with destination authorization before each dial. +//! +//! The proxy accepts only browser HTTP proxy requests. It never resolves a name +//! locally: the authorizer returns a finite set of vetted socket addresses and +//! the proxy consumes the grant before dialing one exact address. + +use std::{future::Future, io, net::SocketAddr, pin::Pin, sync::Arc}; + +use tokio::{net::TcpListener, task::JoinSet}; + +mod forward; +mod request; +mod serve; + +pub(super) use request::parse_authority; + +/// A destination parsed from the browser's actual proxy request. +#[derive(Clone, PartialEq, Eq)] +pub struct BrowserDialTarget { + /// `http` or `https`. + pub scheme: String, + /// Canonical host, without brackets for IPv6 literals. + pub hostname: String, + /// Effective destination port. + pub port: u16, + /// Opaque per-browser-session binding generated by `TinyComputer`. + pub session_id: String, +} + +impl std::fmt::Debug for BrowserDialTarget { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("BrowserDialTarget([REDACTED])") + } +} + +/// Opaque authorizer state plus the exact permitted sockets. +#[derive(Clone)] +pub struct DialGrant { + /// Opaque lease returned by the authenticated `TinySecurity` adapter. + pub lease: String, + /// Finite address set vetted by `TinySecurity`. + pub addresses: Vec, +} + +impl std::fmt::Debug for DialGrant { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("DialGrant([REDACTED])") + } +} + +/// The host adapter delegates every decision to `TinySecurity` over `TinyBus`. +pub trait EgressAuthorizer: Send + Sync + 'static { + /// Authorize the actual destination and return a one-use grant. + fn authorize( + &self, + target: BrowserDialTarget, + ) -> Pin> + Send>>; + /// Consume the grant before the selected socket is opened. + fn consume( + &self, + target: BrowserDialTarget, + grant: DialGrant, + address: SocketAddr, + ) -> Pin> + Send>>; + /// Revalidate an active tunnel lease. False or error closes the tunnel. + fn validate(&self, lease: String) -> Pin> + Send>>; +} + +/// An ephemeral loopback proxy owned by one browser session. +#[derive(Debug)] +pub struct EgressProxy { + address: SocketAddr, + task: tokio::task::JoinHandle<()>, +} + +impl EgressProxy { + /// Bind a private IPv4 loopback listener for one session. + /// + /// # Errors + /// + /// Returns an I/O error when the listener cannot bind or its address cannot + /// be read. + pub async fn bind( + authorizer: Arc, + session_id: String, + proxy_password: String, + ) -> io::Result { + let listener = TcpListener::bind(("127.0.0.1", 0)).await?; + let address = listener.local_addr()?; + let task = tokio::spawn(async move { + let mut connections = JoinSet::new(); + loop { + tokio::select! { + accepted = listener.accept(), if connections.len() < 64 => { + let Ok((stream, _)) = accepted else { break; }; + let auth = authorizer.clone(); + let session = session_id.clone(); + let password = proxy_password.clone(); + connections.spawn(async move { let _ = serve::serve(stream, auth, session, password).await; }); + } + _ = connections.join_next(), if !connections.is_empty() => {} + } + } + }); + Ok(Self { address, task }) + } + + /// Chromium proxy URL; it contains no policy authority. + #[must_use] + pub fn url(&self) -> String { + format!("http://{}:{}", self.address.ip(), self.address.port()) + } +} + +impl Drop for EgressProxy { + fn drop(&mut self) { + self.task.abort(); + } +} diff --git a/crates/tinycomputer-browser/src/egress/request.rs b/crates/tinycomputer-browser/src/egress/request.rs new file mode 100644 index 000000000..0c16f62ba --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/request.rs @@ -0,0 +1,270 @@ +//! Parses and validates browser proxy requests before a destination is authorized. + +use std::{io, net::SocketAddr, time::Duration}; + +use base64::Engine as _; +use tokio::{io::AsyncReadExt, net::TcpStream}; + +use super::{BrowserDialTarget, forward::{refuse, write_all_bounded}}; + +struct ProxyRequest { + pub(super) bytes: Vec, + pub(super) split: usize, + pub(super) lines: Vec, + pub(super) method: String, + pub(super) uri: String, + pub(super) version: String, + pub(super) target: BrowserDialTarget, + pub(super) connect: bool, + pub(super) body_len: usize, + pub(super) has_upgrade: bool, +} + +pub(super) async fn read_proxy_request( + client: &mut TcpStream, + session_id: &str, + proxy_password: &str, +) -> io::Result> { + let mut bytes = Vec::with_capacity(4096); + let mut chunk = [0u8; 1024]; + loop { + let n = tokio::time::timeout(Duration::from_secs(10), client.read(&mut chunk)) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy request timed out"))??; + if n == 0 { + return Ok(None); + } + bytes.extend_from_slice(&chunk[..n]); + if bytes.len() > 32 * 1024 { + refuse(client).await?; + return Ok(None); + } + if bytes.windows(4).any(|window| window == b"\r\n\r\n") { + break; + } + } + let Some(header_end) = bytes.windows(4).position(|window| window == b"\r\n\r\n") else { + refuse(client).await?; + return Ok(None); + }; + let split = header_end + 4; + let Ok(head) = std::str::from_utf8(&bytes[..split]) else { + refuse(client).await?; + return Ok(None); + }; + let lines: Vec = head.split("\r\n").map(str::to_owned).collect(); + let Some(request_line) = lines.first() else { + refuse(client).await?; + return Ok(None); + }; + let mut parts = request_line.split_ascii_whitespace(); + let method = parts.next().unwrap_or_default().to_owned(); + let uri = parts.next().unwrap_or_default().to_owned(); + let version = parts.next().unwrap_or_default().to_owned(); + if parts.next().is_some() || (version != "HTTP/1.1" && version != "HTTP/1.0") { + refuse(client).await?; + return Ok(None); + } + let Some(target) = proxy_target(&method, &uri, session_id) else { + refuse(client).await?; + return Ok(None); + }; + let connect = method.eq_ignore_ascii_case("CONNECT"); + let Some(headers) = parse_proxy_headers(&lines, &target, connect, session_id) else { + refuse(client).await?; + return Ok(None); + }; + if !has_proxy_auth(headers.proxy_authorization.as_deref(), proxy_password) { + write_all_bounded( + client, + b"HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm=\"tinycomputer-browser\"\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", + "browser proxy challenge timed out", + ) + .await?; + return Ok(None); + } + if connect && bytes.len() > split { + refuse(client).await?; + return Ok(None); + } + Ok(Some(ProxyRequest { + bytes, + split, + lines, + method, + uri, + version, + target, + connect, + body_len: headers.body_len, + has_upgrade: headers.has_upgrade, + })) +} + +fn proxy_target(method: &str, uri: &str, session_id: &str) -> Option { + if method.eq_ignore_ascii_case("CONNECT") { + return parse_authority(uri, "https", session_id).ok(); + } + let url = url::Url::parse(uri).ok()?; + if !matches!(url.scheme(), "http" | "ws") + || !url.username().is_empty() + || url.password().is_some() + || url.fragment().is_some() + { + return None; + } + Some(BrowserDialTarget { + scheme: "http".to_owned(), + hostname: url + .host_str()? + .trim_matches(['[', ']']) + .to_ascii_lowercase(), + port: url.port_or_known_default()?, + session_id: session_id.to_owned(), + }) +} + +struct ParsedHeaders { + body_len: usize, + has_upgrade: bool, + proxy_authorization: Option, +} + +fn parse_proxy_headers( + lines: &[String], + target: &BrowserDialTarget, + connect: bool, + session_id: &str, +) -> Option { + let mut body_len = 0usize; + let mut host_header = None; + let mut has_upgrade = false; + let mut connection_upgrade = false; + let mut proxy_authorization = None; + let mut saw_content_length = false; + for line in lines + .iter() + .skip(1) + .map(String::as_str) + .filter(|line| !line.is_empty()) + { + let (name, value) = line.split_once(':')?; + if name.eq_ignore_ascii_case("host") { + if host_header.replace(value.trim().to_owned()).is_some() { + return None; + } + } else if name.eq_ignore_ascii_case("content-length") { + if saw_content_length { + return None; + } + saw_content_length = true; + body_len = value.trim().parse().unwrap_or(usize::MAX); + } else if name.eq_ignore_ascii_case("transfer-encoding") + || name.eq_ignore_ascii_case("expect") + { + return None; + } else if name.eq_ignore_ascii_case("proxy-authorization") { + if proxy_authorization + .replace(value.trim().to_owned()) + .is_some() + { + return None; + } + } else if name.eq_ignore_ascii_case("upgrade") + && value.trim().eq_ignore_ascii_case("websocket") + { + has_upgrade = true; + } else if name.eq_ignore_ascii_case("connection") + && value + .split(',') + .any(|token| token.trim().eq_ignore_ascii_case("upgrade")) + { + connection_upgrade = true; + } + } + let host_matches = host_header.as_deref().is_some_and(|host| { + parse_authority(host, if connect { "https" } else { "http" }, session_id) + .is_ok_and(|parsed| parsed.hostname == target.hostname && parsed.port == target.port) + }); + if has_upgrade != connection_upgrade + || !host_matches + || (connect && body_len != 0) + || (!connect && (body_len > 1024 * 1024 || (has_upgrade && body_len != 0))) + { + return None; + } + Some(ParsedHeaders { + body_len, + has_upgrade, + proxy_authorization, + }) +} + +fn has_proxy_auth(proxy_authorization: Option<&str>, password: &str) -> bool { + let expected = format!( + "Basic {}", + base64::engine::general_purpose::STANDARD.encode(format!("tinycomputer:{password}")) + ); + proxy_authorization + .is_some_and(|actual| constant_time_eq(actual.as_bytes(), expected.as_bytes())) +} +pub(super) async fn read_request_body(client: &mut TcpStream, request: &mut ProxyRequest) -> io::Result { + if request.has_upgrade || request.connect { + return Ok(true); + } + let received = request.bytes.len().saturating_sub(request.split); + if received > request.body_len { + return Ok(false); + } + let mut chunk = [0u8; 1024]; + while request.bytes.len().saturating_sub(request.split) < request.body_len { + let n = tokio::time::timeout(Duration::from_secs(10), client.read(&mut chunk)) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy body timed out"))??; + if n == 0 { + return Ok(false); + } + request.bytes.extend_from_slice(&chunk[..n]); + if request.bytes.len() > request.split + request.body_len { + return Ok(false); + } + } + Ok(true) +} +pub(super) fn parse_authority( + value: &str, + scheme: &str, + session_id: &str, +) -> io::Result { + if value.contains("://") { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "authority form required", + )); + } + let authority = url::Url::parse(&format!("{scheme}://{value}/")) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid CONNECT authority"))?; + if authority.path() != "/" + || authority.query().is_some() + || authority.fragment().is_some() + || !authority.username().is_empty() + || authority.password().is_some() + { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid CONNECT authority", + )); + } + Ok(BrowserDialTarget { + scheme: scheme.to_owned(), + hostname: authority + .host_str() + .unwrap_or_default() + .trim_matches(['[', ']']) + .to_ascii_lowercase(), + port: authority + .port() + .unwrap_or(if scheme == "http" { 80 } else { 443 }), + session_id: session_id.to_owned(), + }) +} diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs new file mode 100644 index 000000000..be430bdd7 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -0,0 +1,82 @@ +//! Authorizes requests and consumes grants before dialing approved addresses. + +use std::{io, sync::Arc, time::Duration}; + +use tokio::net::TcpStream; + +use super::{ + BrowserDialTarget, DialGrant, EgressAuthorizer, + forward::{forward_response_with_lease, initialize_upstream, refuse, tunnel_with_lease, validate_lease}, + request::{ProxyRequest, read_proxy_request, read_request_body}, +}; + +async fn serve( + mut client: TcpStream, + auth: Arc, + session_id: String, + proxy_password: String, +) -> io::Result<()> { + let Some(mut request) = read_proxy_request(&mut client, &session_id, &proxy_password).await? + else { + return Ok(()); + }; + if !read_request_body(&mut client, &mut request).await? { + return refuse(&mut client).await; + } + let Some(first_grant) = authorize(&auth, &request.target).await else { + return refuse(&mut client).await; + }; + let addresses = first_grant.addresses.clone(); + let mut connected = None; + for (index, address) in addresses.into_iter().enumerate() { + // A consume call spends its one-use grant. Reauthorize every later + // candidate so a failed dial cannot reuse a spent authorization. + let grant = if index == 0 { + first_grant.clone() + } else { + match authorize(&auth, &request.target).await { + Some(grant) if grant.addresses.contains(&address) => grant, + _ => continue, + } + }; + if !matches!( + tokio::time::timeout( + Duration::from_secs(5), + auth.consume(request.target.clone(), grant.clone(), address), + ) + .await, + Ok(Ok(())) + ) { + return refuse(&mut client).await; + } + if let Ok(Ok(upstream)) = + tokio::time::timeout(Duration::from_secs(5), TcpStream::connect(address)).await + { + connected = Some((upstream, grant.lease)); + break; + } + } + let Some((mut upstream, lease)) = connected else { + return refuse(&mut client).await; + }; + if !validate_lease(&auth, &lease).await? { + return Ok(()); + } + initialize_upstream(&mut client, &mut upstream, &request).await?; + if request.connect || request.has_upgrade { + tunnel_with_lease(&mut client, &mut upstream, &auth, lease).await?; + } else { + forward_response_with_lease(&mut client, &mut upstream, &auth, lease).await?; + } + Ok(()) +} + +async fn authorize( + auth: &Arc, + target: &BrowserDialTarget, +) -> Option { + match tokio::time::timeout(Duration::from_secs(5), auth.authorize(target.clone())).await { + Ok(Ok(grant)) if !grant.addresses.is_empty() && grant.addresses.len() <= 64 => Some(grant), + _ => None, + } +} From 6491e7575ed789bbfb5c6e8d30d452f607133931 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:23:38 +0000 Subject: [PATCH 14/93] docs(tinycomputer): drop browser executable and args from config example The browser configuration example no longer shows the executable and args fields, since those options are not part of the documented configuration. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- docs/crates/tinycomputer/configuration.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/crates/tinycomputer/configuration.md b/docs/crates/tinycomputer/configuration.md index a3c037e2f..af0baa7a1 100644 --- a/docs/crates/tinycomputer/configuration.md +++ b/docs/crates/tinycomputer/configuration.md @@ -217,9 +217,7 @@ never sent to a provider it was not given for: ```json { "browser": { - "executable": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36", - "args": ["--disable-blink-features=AutomationControlled"], "perception": "sight", "settle": "prompt", "prelaunch": true, From 8a30d619aa0d0793a680ff7b79b6bf95ba0c214a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:24:16 +0000 Subject: [PATCH 15/93] test(egress): add shared fixture authorizer helpers Move the Clone derive onto the fixture authorizer in the simulator module and add a base64 engine import plus a fixture password constant so the shared test helpers can build proxy credentials. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress_tests/authority_tests.rs | 2 -- .../src/egress_tests/simulator.rs | 13 ++++++++++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/authority_tests.rs b/crates/tinycomputer-browser/src/egress_tests/authority_tests.rs index c4cbd50ad..69af49d64 100644 --- a/crates/tinycomputer-browser/src/egress_tests/authority_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/authority_tests.rs @@ -50,5 +50,3 @@ fn proxy_authority_uses_scheme_defaults_and_canonical_ipv6_literals() { assert_eq!(ipv6.hostname, "2001:4860:4860::8888"); assert!(parse_authority("https://example.test:443", "https", "session").is_err()); } - -#[derive(Clone)] diff --git a/crates/tinycomputer-browser/src/egress_tests/simulator.rs b/crates/tinycomputer-browser/src/egress_tests/simulator.rs index 5c62e5614..a629d8e4b 100644 --- a/crates/tinycomputer-browser/src/egress_tests/simulator.rs +++ b/crates/tinycomputer-browser/src/egress_tests/simulator.rs @@ -1,7 +1,17 @@ //! Local authorizers and fixture helpers shared by egress tests. use crate::{BrowserDialTarget, DialGrant, EgressAuthorizer}; -use std::{io, net::SocketAddr, sync::{Arc, atomic::{AtomicUsize, Ordering}}}; +use std::{ + io, + net::SocketAddr, + sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, +}; +use base64::Engine as _; + +const FIXTURE_PASSWORD: &str = "fixture-proxy-secret"; fn proxy_authorization() -> String { format!( @@ -11,6 +21,7 @@ fn proxy_authorization() -> String { ) } +#[derive(Clone)] struct FixtureAuthorizer { address: SocketAddr, allow: bool, From ca05bad673eb8c7bbe85d325aa0ec32f7a8a366d Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:24:27 +0000 Subject: [PATCH 16/93] refactor(egress-tests): widen simulator fixture visibility to super The egress test simulator's fixture authorizers, their fields, and the proxy authorization helper are now visible to the parent module so sibling test modules can reuse them. No behaviour changes. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress_tests/simulator.rs | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/simulator.rs b/crates/tinycomputer-browser/src/egress_tests/simulator.rs index a629d8e4b..faa7b1ca3 100644 --- a/crates/tinycomputer-browser/src/egress_tests/simulator.rs +++ b/crates/tinycomputer-browser/src/egress_tests/simulator.rs @@ -11,9 +11,9 @@ use std::{ }; use base64::Engine as _; -const FIXTURE_PASSWORD: &str = "fixture-proxy-secret"; +pub(super) const FIXTURE_PASSWORD: &str = "fixture-proxy-secret"; -fn proxy_authorization() -> String { +pub(super) fn proxy_authorization() -> String { format!( "Basic {}", base64::engine::general_purpose::STANDARD @@ -22,10 +22,10 @@ fn proxy_authorization() -> String { } #[derive(Clone)] -struct FixtureAuthorizer { - address: SocketAddr, - allow: bool, - consumed: Arc, +pub(super) struct FixtureAuthorizer { + pub(super) address: SocketAddr, + pub(super) allow: bool, + pub(super) consumed: Arc, } impl EgressAuthorizer for FixtureAuthorizer { @@ -74,8 +74,8 @@ impl EgressAuthorizer for FixtureAuthorizer { } } -struct MultiAddressAuthorizer { - addresses: Vec, +pub(super) struct MultiAddressAuthorizer { + pub(super) addresses: Vec, } impl EgressAuthorizer for MultiAddressAuthorizer { @@ -118,9 +118,9 @@ impl EgressAuthorizer for MultiAddressAuthorizer { } } -struct RevokingAuthorizer { - address: SocketAddr, - validations: Arc, +pub(super) struct RevokingAuthorizer { + pub(super) address: SocketAddr, + pub(super) validations: Arc, } impl EgressAuthorizer for RevokingAuthorizer { From f313e14cc8ab3785e4e719b67dbcf0751e0ba8f9 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:24:50 +0000 Subject: [PATCH 17/93] style: format egress imports and signatures Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/forward.rs | 10 ++++++++-- crates/tinycomputer-browser/src/egress/request.rs | 10 ++++++++-- crates/tinycomputer-browser/src/egress/serve.rs | 4 +++- .../tinycomputer-browser/src/egress_tests/simulator.rs | 2 +- 4 files changed, 20 insertions(+), 6 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/forward.rs b/crates/tinycomputer-browser/src/egress/forward.rs index ae34a8a4f..d91f3e9ee 100644 --- a/crates/tinycomputer-browser/src/egress/forward.rs +++ b/crates/tinycomputer-browser/src/egress/forward.rs @@ -3,7 +3,10 @@ use std::{io, sync::Arc, time::Duration}; use base64::Engine as _; -use tokio::{io::{AsyncReadExt, AsyncWriteExt, copy_bidirectional}, net::TcpStream}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt, copy_bidirectional}, + net::TcpStream, +}; use super::{EgressAuthorizer, request::ProxyRequest}; @@ -131,7 +134,10 @@ fn validation_interval() -> tokio::time::Interval { interval } -pub(super) async fn validate_lease(auth: &Arc, lease: &str) -> io::Result { +pub(super) async fn validate_lease( + auth: &Arc, + lease: &str, +) -> io::Result { tokio::time::timeout(Duration::from_secs(2), auth.validate(lease.to_owned())) .await .map_err(|_| { diff --git a/crates/tinycomputer-browser/src/egress/request.rs b/crates/tinycomputer-browser/src/egress/request.rs index 0c16f62ba..2efaa98ac 100644 --- a/crates/tinycomputer-browser/src/egress/request.rs +++ b/crates/tinycomputer-browser/src/egress/request.rs @@ -5,7 +5,10 @@ use std::{io, net::SocketAddr, time::Duration}; use base64::Engine as _; use tokio::{io::AsyncReadExt, net::TcpStream}; -use super::{BrowserDialTarget, forward::{refuse, write_all_bounded}}; +use super::{ + BrowserDialTarget, + forward::{refuse, write_all_bounded}, +}; struct ProxyRequest { pub(super) bytes: Vec, @@ -208,7 +211,10 @@ fn has_proxy_auth(proxy_authorization: Option<&str>, password: &str) -> bool { proxy_authorization .is_some_and(|actual| constant_time_eq(actual.as_bytes(), expected.as_bytes())) } -pub(super) async fn read_request_body(client: &mut TcpStream, request: &mut ProxyRequest) -> io::Result { +pub(super) async fn read_request_body( + client: &mut TcpStream, + request: &mut ProxyRequest, +) -> io::Result { if request.has_upgrade || request.connect { return Ok(true); } diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index be430bdd7..443c14ab2 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -6,7 +6,9 @@ use tokio::net::TcpStream; use super::{ BrowserDialTarget, DialGrant, EgressAuthorizer, - forward::{forward_response_with_lease, initialize_upstream, refuse, tunnel_with_lease, validate_lease}, + forward::{ + forward_response_with_lease, initialize_upstream, refuse, tunnel_with_lease, validate_lease, + }, request::{ProxyRequest, read_proxy_request, read_request_body}, }; diff --git a/crates/tinycomputer-browser/src/egress_tests/simulator.rs b/crates/tinycomputer-browser/src/egress_tests/simulator.rs index faa7b1ca3..86e8007cc 100644 --- a/crates/tinycomputer-browser/src/egress_tests/simulator.rs +++ b/crates/tinycomputer-browser/src/egress_tests/simulator.rs @@ -1,6 +1,7 @@ //! Local authorizers and fixture helpers shared by egress tests. use crate::{BrowserDialTarget, DialGrant, EgressAuthorizer}; +use base64::Engine as _; use std::{ io, net::SocketAddr, @@ -9,7 +10,6 @@ use std::{ atomic::{AtomicBool, AtomicUsize, Ordering}, }, }; -use base64::Engine as _; pub(super) const FIXTURE_PASSWORD: &str = "fixture-proxy-secret"; From cf2e63d198bef889447479ce2984e5d2c1ffd96e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:25:10 +0000 Subject: [PATCH 18/93] test(egress): narrow test imports to what each module uses Trimmed the shared egress test imports so each module only pulls in the symbols it actually references, and gave the authority tests a doc comment matching their contents. This removes unused-import noise without changing any test behaviour. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress_tests/authority_tests.rs | 8 ++------ .../src/egress_tests/connect_tests.rs | 4 ++-- .../tinycomputer-browser/src/egress_tests/http_tests.rs | 4 ++-- .../tinycomputer-browser/src/egress_tests/lease_tests.rs | 4 ++-- .../src/egress_tests/lifecycle_tests.rs | 4 ++-- .../tinycomputer-browser/src/egress_tests/retry_tests.rs | 4 ++-- .../src/egress_tests/websocket_tests.rs | 4 ++-- 7 files changed, 14 insertions(+), 18 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/authority_tests.rs b/crates/tinycomputer-browser/src/egress_tests/authority_tests.rs index 69af49d64..546651d50 100644 --- a/crates/tinycomputer-browser/src/egress_tests/authority_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/authority_tests.rs @@ -1,10 +1,6 @@ -//! Focused browser egress proxy tests. +//! Authority parsing and redaction tests. -use super::simulator::*; -use crate::{BrowserDialTarget, DialGrant, EgressProxy, egress::parse_authority}; -use serde_json::json; -use std::{io, net::*, sync::*}; -use tokio::{io::*, net::*}; +use crate::{BrowserDialTarget, DialGrant, egress::parse_authority}; #[test] fn browser_dial_target_debug_does_not_disclose_session_or_destination() { diff --git a/crates/tinycomputer-browser/src/egress_tests/connect_tests.rs b/crates/tinycomputer-browser/src/egress_tests/connect_tests.rs index 887dc82b9..f35acf1a7 100644 --- a/crates/tinycomputer-browser/src/egress_tests/connect_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/connect_tests.rs @@ -1,9 +1,9 @@ //! Focused browser egress proxy tests. use super::simulator::*; -use crate::{BrowserDialTarget, DialGrant, EgressProxy, egress::parse_authority}; +use crate::EgressProxy; use serde_json::json; -use std::{io, net::*, sync::*}; +use std::{io, net::SocketAddr, sync::*}; use tokio::{io::*, net::*}; #[tokio::test] diff --git a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs index 712fd4334..9bcaa320d 100644 --- a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs @@ -1,9 +1,9 @@ //! Focused browser egress proxy tests. use super::simulator::*; -use crate::{BrowserDialTarget, DialGrant, EgressProxy, egress::parse_authority}; +use crate::EgressProxy; use serde_json::json; -use std::{io, net::*, sync::*}; +use std::{io, net::SocketAddr, sync::*}; use tokio::{io::*, net::*}; #[tokio::test] diff --git a/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs b/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs index a09b908ca..2ca763e59 100644 --- a/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs @@ -1,9 +1,9 @@ //! Focused browser egress proxy tests. use super::simulator::*; -use crate::{BrowserDialTarget, DialGrant, EgressProxy, egress::parse_authority}; +use crate::EgressProxy; use serde_json::json; -use std::{io, net::*, sync::*}; +use std::{io, net::SocketAddr, sync::*}; use tokio::{io::*, net::*}; #[tokio::test] diff --git a/crates/tinycomputer-browser/src/egress_tests/lifecycle_tests.rs b/crates/tinycomputer-browser/src/egress_tests/lifecycle_tests.rs index 63b4440a2..fd93854fb 100644 --- a/crates/tinycomputer-browser/src/egress_tests/lifecycle_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/lifecycle_tests.rs @@ -1,9 +1,9 @@ //! Focused browser egress proxy tests. use super::simulator::*; -use crate::{BrowserDialTarget, DialGrant, EgressProxy, egress::parse_authority}; +use crate::EgressProxy; use serde_json::json; -use std::{io, net::*, sync::*}; +use std::{io, net::SocketAddr, sync::*}; use tokio::{io::*, net::*}; #[tokio::test] diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index 64754da05..386af9298 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -1,9 +1,9 @@ //! Focused browser egress proxy tests. use super::simulator::*; -use crate::{BrowserDialTarget, DialGrant, EgressProxy, egress::parse_authority}; +use crate::EgressProxy; use serde_json::json; -use std::{io, net::*, sync::*}; +use std::{io, net::SocketAddr, sync::*}; use tokio::{io::*, net::*}; #[tokio::test] diff --git a/crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs b/crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs index b668459a7..675374c77 100644 --- a/crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs @@ -1,9 +1,9 @@ //! Focused browser egress proxy tests. use super::simulator::*; -use crate::{BrowserDialTarget, DialGrant, EgressProxy, egress::parse_authority}; +use crate::EgressProxy; use serde_json::json; -use std::{io, net::*, sync::*}; +use std::{io, net::SocketAddr, sync::*}; use tokio::{io::*, net::*}; #[tokio::test] From 86aed71ecb6784f7944c99c7d4b9b7ca6111fdc9 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:26:16 +0000 Subject: [PATCH 19/93] refactor(egress): widen visibility of proxy request helpers Several items in the egress module were made visible to the wider crate so they can be reused outside the module, and an unused import was dropped. No behaviour changes. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/forward.rs | 3 +-- crates/tinycomputer-browser/src/egress/mod.rs | 2 +- crates/tinycomputer-browser/src/egress/request.rs | 8 ++++---- crates/tinycomputer-browser/src/egress/serve.rs | 2 +- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/forward.rs b/crates/tinycomputer-browser/src/egress/forward.rs index d91f3e9ee..fb0a493ed 100644 --- a/crates/tinycomputer-browser/src/egress/forward.rs +++ b/crates/tinycomputer-browser/src/egress/forward.rs @@ -2,7 +2,6 @@ use std::{io, sync::Arc, time::Duration}; -use base64::Engine as _; use tokio::{ io::{AsyncReadExt, AsyncWriteExt, copy_bidirectional}, net::TcpStream, @@ -74,7 +73,7 @@ pub(super) async fn initialize_upstream( ) .await } -fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { +pub(super) fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { let mut difference = left.len() ^ right.len(); for index in 0..left.len().max(right.len()) { difference |= usize::from( diff --git a/crates/tinycomputer-browser/src/egress/mod.rs b/crates/tinycomputer-browser/src/egress/mod.rs index 3912e8b96..ef8fd6691 100644 --- a/crates/tinycomputer-browser/src/egress/mod.rs +++ b/crates/tinycomputer-browser/src/egress/mod.rs @@ -12,7 +12,7 @@ mod forward; mod request; mod serve; -pub(super) use request::parse_authority; +pub(crate) use request::parse_authority; /// A destination parsed from the browser's actual proxy request. #[derive(Clone, PartialEq, Eq)] diff --git a/crates/tinycomputer-browser/src/egress/request.rs b/crates/tinycomputer-browser/src/egress/request.rs index 2efaa98ac..1f4554e0a 100644 --- a/crates/tinycomputer-browser/src/egress/request.rs +++ b/crates/tinycomputer-browser/src/egress/request.rs @@ -1,16 +1,16 @@ //! Parses and validates browser proxy requests before a destination is authorized. -use std::{io, net::SocketAddr, time::Duration}; +use std::{io, time::Duration}; use base64::Engine as _; use tokio::{io::AsyncReadExt, net::TcpStream}; use super::{ BrowserDialTarget, - forward::{refuse, write_all_bounded}, + forward::{constant_time_eq, refuse, write_all_bounded}, }; -struct ProxyRequest { +pub(super) struct ProxyRequest { pub(super) bytes: Vec, pub(super) split: usize, pub(super) lines: Vec, @@ -237,7 +237,7 @@ pub(super) async fn read_request_body( } Ok(true) } -pub(super) fn parse_authority( +pub(crate) fn parse_authority( value: &str, scheme: &str, session_id: &str, diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index 443c14ab2..c77aced95 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -12,7 +12,7 @@ use super::{ request::{ProxyRequest, read_proxy_request, read_request_body}, }; -async fn serve( +pub(super) async fn serve( mut client: TcpStream, auth: Arc, session_id: String, From d871d691e82b5d67b87c69fe82d326c49904b985 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:26:48 +0000 Subject: [PATCH 20/93] test(egress): give each egress test module a specific doc comment Replace the shared "Focused browser egress proxy tests" header in each egress test module with a description of the behaviour that module covers, and narrow the glob imports to the specific items each file uses. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinycomputer-browser/src/egress_tests/connect_tests.rs | 7 +++---- crates/tinycomputer-browser/src/egress_tests/http_tests.rs | 7 +++---- .../tinycomputer-browser/src/egress_tests/lease_tests.rs | 7 +++---- .../src/egress_tests/lifecycle_tests.rs | 7 +++---- .../tinycomputer-browser/src/egress_tests/retry_tests.rs | 7 +++---- .../src/egress_tests/websocket_tests.rs | 7 +++---- 6 files changed, 18 insertions(+), 24 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/connect_tests.rs b/crates/tinycomputer-browser/src/egress_tests/connect_tests.rs index f35acf1a7..a03c77b80 100644 --- a/crates/tinycomputer-browser/src/egress_tests/connect_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/connect_tests.rs @@ -1,10 +1,9 @@ -//! Focused browser egress proxy tests. +//! CONNECT proxy tests. use super::simulator::*; use crate::EgressProxy; -use serde_json::json; -use std::{io, net::SocketAddr, sync::*}; -use tokio::{io::*, net::*}; +use std::sync::{Arc, atomic::{AtomicBool, Ordering}}; +use tokio::{io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}}; #[tokio::test] async fn approved_connect_reaches_only_the_consumed_socket() { diff --git a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs index 9bcaa320d..f13eceeb0 100644 --- a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs @@ -1,10 +1,9 @@ -//! Focused browser egress proxy tests. +//! HTTP request, body, authentication, and refusal tests. use super::simulator::*; use crate::EgressProxy; -use serde_json::json; -use std::{io, net::SocketAddr, sync::*}; -use tokio::{io::*, net::*}; +use std::{io, sync::{Arc, atomic::{AtomicBool, Ordering}}}; +use tokio::{io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}}; #[tokio::test] async fn denied_destination_never_connects_to_the_fixture() { diff --git a/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs b/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs index 2ca763e59..8050de4f3 100644 --- a/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs @@ -1,10 +1,9 @@ -//! Focused browser egress proxy tests. +//! Lease validation and revocation tests for active streams. use super::simulator::*; use crate::EgressProxy; -use serde_json::json; -use std::{io, net::SocketAddr, sync::*}; -use tokio::{io::*, net::*}; +use std::sync::{Arc, atomic::Ordering}; +use tokio::{io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}}; #[tokio::test] async fn continuous_http_response_still_revalidates_and_closes_revoked_lease() { diff --git a/crates/tinycomputer-browser/src/egress_tests/lifecycle_tests.rs b/crates/tinycomputer-browser/src/egress_tests/lifecycle_tests.rs index fd93854fb..74acaf4c9 100644 --- a/crates/tinycomputer-browser/src/egress_tests/lifecycle_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/lifecycle_tests.rs @@ -1,10 +1,9 @@ -//! Focused browser egress proxy tests. +//! Session proxy listener lifecycle tests. use super::simulator::*; use crate::EgressProxy; -use serde_json::json; -use std::{io, net::SocketAddr, sync::*}; -use tokio::{io::*, net::*}; +use std::sync::{Arc, atomic::AtomicBool}; +use tokio::net::{TcpListener, TcpStream}; #[tokio::test] async fn dropping_session_proxy_closes_its_listener() { diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index 386af9298..27cce4109 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -1,10 +1,9 @@ -//! Focused browser egress proxy tests. +//! Proxy retry behavior for multiple approved addresses. use super::simulator::*; use crate::EgressProxy; -use serde_json::json; -use std::{io, net::SocketAddr, sync::*}; -use tokio::{io::*, net::*}; +use std::sync::Arc; +use tokio::{io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}}; #[tokio::test] async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachable() { diff --git a/crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs b/crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs index 675374c77..2d1bd51a9 100644 --- a/crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs @@ -1,10 +1,9 @@ -//! Focused browser egress proxy tests. +//! WebSocket upgrade forwarding tests. use super::simulator::*; use crate::EgressProxy; -use serde_json::json; -use std::{io, net::SocketAddr, sync::*}; -use tokio::{io::*, net::*}; +use std::sync::{Arc, atomic::AtomicBool}; +use tokio::{io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}}; #[tokio::test] async fn approved_websocket_upgrade_is_forwarded_and_tunneled() { From 4313f2902f822026883525ea4166bd49671ec319 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:27:06 +0000 Subject: [PATCH 21/93] refactor(egress): tidy imports and gate test-only re-export Reformatted the egress test imports into grouped blocks and dropped an unused ProxyRequest import from serve.rs. The parse_authority re-export is now behind cfg(test) since only the tests use it, and the simulator's AtomicUsize path is shortened via an existing import. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/mod.rs | 1 + crates/tinycomputer-browser/src/egress/serve.rs | 2 +- .../src/egress_tests/connect_tests.rs | 10 ++++++++-- .../src/egress_tests/http_tests.rs | 13 +++++++++++-- .../src/egress_tests/lease_tests.rs | 5 ++++- .../src/egress_tests/retry_tests.rs | 5 ++++- .../src/egress_tests/simulator.rs | 2 +- .../src/egress_tests/websocket_tests.rs | 5 ++++- 8 files changed, 34 insertions(+), 9 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/mod.rs b/crates/tinycomputer-browser/src/egress/mod.rs index ef8fd6691..af00ec15c 100644 --- a/crates/tinycomputer-browser/src/egress/mod.rs +++ b/crates/tinycomputer-browser/src/egress/mod.rs @@ -12,6 +12,7 @@ mod forward; mod request; mod serve; +#[cfg(test)] pub(crate) use request::parse_authority; /// A destination parsed from the browser's actual proxy request. diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index c77aced95..4e5eb042a 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -9,7 +9,7 @@ use super::{ forward::{ forward_response_with_lease, initialize_upstream, refuse, tunnel_with_lease, validate_lease, }, - request::{ProxyRequest, read_proxy_request, read_request_body}, + request::{read_proxy_request, read_request_body}, }; pub(super) async fn serve( diff --git a/crates/tinycomputer-browser/src/egress_tests/connect_tests.rs b/crates/tinycomputer-browser/src/egress_tests/connect_tests.rs index a03c77b80..9d2ccd4ce 100644 --- a/crates/tinycomputer-browser/src/egress_tests/connect_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/connect_tests.rs @@ -2,8 +2,14 @@ use super::simulator::*; use crate::EgressProxy; -use std::sync::{Arc, atomic::{AtomicBool, Ordering}}; -use tokio::{io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}}; +use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, +}; #[tokio::test] async fn approved_connect_reaches_only_the_consumed_socket() { diff --git a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs index f13eceeb0..c7d3f7ccf 100644 --- a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs @@ -2,8 +2,17 @@ use super::simulator::*; use crate::EgressProxy; -use std::{io, sync::{Arc, atomic::{AtomicBool, Ordering}}}; -use tokio::{io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}}; +use std::{ + io, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, +}; #[tokio::test] async fn denied_destination_never_connects_to_the_fixture() { diff --git a/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs b/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs index 8050de4f3..37f3f40cc 100644 --- a/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs @@ -3,7 +3,10 @@ use super::simulator::*; use crate::EgressProxy; use std::sync::{Arc, atomic::Ordering}; -use tokio::{io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, +}; #[tokio::test] async fn continuous_http_response_still_revalidates_and_closes_revoked_lease() { diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index 27cce4109..a793e435f 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -3,7 +3,10 @@ use super::simulator::*; use crate::EgressProxy; use std::sync::Arc; -use tokio::{io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, +}; #[tokio::test] async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachable() { diff --git a/crates/tinycomputer-browser/src/egress_tests/simulator.rs b/crates/tinycomputer-browser/src/egress_tests/simulator.rs index 86e8007cc..0dbf8d2c1 100644 --- a/crates/tinycomputer-browser/src/egress_tests/simulator.rs +++ b/crates/tinycomputer-browser/src/egress_tests/simulator.rs @@ -120,7 +120,7 @@ impl EgressAuthorizer for MultiAddressAuthorizer { pub(super) struct RevokingAuthorizer { pub(super) address: SocketAddr, - pub(super) validations: Arc, + pub(super) validations: Arc, } impl EgressAuthorizer for RevokingAuthorizer { diff --git a/crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs b/crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs index 2d1bd51a9..a1542d3d0 100644 --- a/crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs @@ -3,7 +3,10 @@ use super::simulator::*; use crate::EgressProxy; use std::sync::{Arc, atomic::AtomicBool}; -use tokio::{io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, +}; #[tokio::test] async fn approved_websocket_upgrade_is_forwarded_and_tunneled() { From 72ed1b6ab881b1b4fab20aeba0af41e03290b033 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:28:05 +0000 Subject: [PATCH 22/93] test(egress): import SocketAddr in retry tests Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress_tests/retry_tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index a793e435f..66eb59293 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -2,6 +2,7 @@ use super::simulator::*; use crate::EgressProxy; +use std::net::SocketAddr; use std::sync::Arc; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, From 86920e6aae95f9f4964f47ca25d46d8a6467ca70 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:29:36 +0000 Subject: [PATCH 23/93] fix(browser-egress): stream request bodies to upstream instead of buffering Request bodies are now forwarded to the upstream as they arrive rather than being accumulated in memory, and a body that ends early or exceeds its declared content length is rejected instead of being silently truncated or accepted. The proxy header check no longer caps bodies at 1 MiB, and the callback contract test now asserts the exact serialized shape of the egress types. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress/request.rs | 52 +++++++++++----- .../tinycomputer-browser/src/egress/serve.rs | 11 +++- .../browser_egress/browser_egress_tests.rs | 62 +++++++++++++++++-- 3 files changed, 102 insertions(+), 23 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/request.rs b/crates/tinycomputer-browser/src/egress/request.rs index 1f4554e0a..601497b49 100644 --- a/crates/tinycomputer-browser/src/egress/request.rs +++ b/crates/tinycomputer-browser/src/egress/request.rs @@ -161,7 +161,7 @@ fn parse_proxy_headers( return None; } saw_content_length = true; - body_len = value.trim().parse().unwrap_or(usize::MAX); + body_len = value.trim().parse().ok()?; } else if name.eq_ignore_ascii_case("transfer-encoding") || name.eq_ignore_ascii_case("expect") { @@ -192,7 +192,7 @@ fn parse_proxy_headers( if has_upgrade != connection_upgrade || !host_matches || (connect && body_len != 0) - || (!connect && (body_len > 1024 * 1024 || (has_upgrade && body_len != 0))) + || (!connect && has_upgrade && body_len != 0) { return None; } @@ -211,31 +211,53 @@ fn has_proxy_auth(proxy_authorization: Option<&str>, password: &str) -> bool { proxy_authorization .is_some_and(|actual| constant_time_eq(actual.as_bytes(), expected.as_bytes())) } -pub(super) async fn read_request_body( - client: &mut TcpStream, - request: &mut ProxyRequest, -) -> io::Result { +pub(super) fn has_valid_buffered_body(request: &ProxyRequest) -> bool { if request.has_upgrade || request.connect { - return Ok(true); + return true; } let received = request.bytes.len().saturating_sub(request.split); - if received > request.body_len { - return Ok(false); + received <= request.body_len +} + +pub(super) fn buffered_body_len(request: &ProxyRequest) -> usize { + if request.has_upgrade || request.connect { + 0 + } else { + request.bytes.len().saturating_sub(request.split) + } +} + +pub(super) async fn read_request_body( + client: &mut TcpStream, + upstream: &mut TcpStream, + request: &ProxyRequest, + mut received: usize, +) -> io::Result<()> { + if request.has_upgrade || request.connect { + return Ok(()); } let mut chunk = [0u8; 1024]; - while request.bytes.len().saturating_sub(request.split) < request.body_len { + while received < request.body_len { let n = tokio::time::timeout(Duration::from_secs(10), client.read(&mut chunk)) .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy body timed out"))??; if n == 0 { - return Ok(false); + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "browser request body ended early", + )); } - request.bytes.extend_from_slice(&chunk[..n]); - if request.bytes.len() > request.split + request.body_len { - return Ok(false); + let remaining = request.body_len - received; + if n > remaining { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "browser request body exceeded content length", + )); } + write_all_bounded(upstream, &chunk[..n], "browser upstream body timed out").await?; + received += n; } - Ok(true) + Ok(()) } pub(crate) fn parse_authority( value: &str, diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index 4e5eb042a..de2da0791 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -9,7 +9,7 @@ use super::{ forward::{ forward_response_with_lease, initialize_upstream, refuse, tunnel_with_lease, validate_lease, }, - request::{read_proxy_request, read_request_body}, + request::{buffered_body_len, has_valid_buffered_body, read_proxy_request, read_request_body}, }; pub(super) async fn serve( @@ -22,7 +22,7 @@ pub(super) async fn serve( else { return Ok(()); }; - if !read_request_body(&mut client, &mut request).await? { + if !has_valid_buffered_body(&request) { return refuse(&mut client).await; } let Some(first_grant) = authorize(&auth, &request.target).await else { @@ -68,6 +68,13 @@ pub(super) async fn serve( if request.connect || request.has_upgrade { tunnel_with_lease(&mut client, &mut upstream, &auth, lease).await?; } else { + read_request_body( + &mut client, + &mut upstream, + &request, + buffered_body_len(&request), + ) + .await?; forward_response_with_lease(&mut client, &mut upstream, &auth, lease).await?; } Ok(()) diff --git a/crates/tinycomputer-bus/src/browser_egress/browser_egress_tests.rs b/crates/tinycomputer-bus/src/browser_egress/browser_egress_tests.rs index 22bf01f6e..7025c070e 100644 --- a/crates/tinycomputer-bus/src/browser_egress/browser_egress_tests.rs +++ b/crates/tinycomputer-bus/src/browser_egress/browser_egress_tests.rs @@ -13,17 +13,67 @@ fn browser_callback_contract_has_no_http_payload_or_caller_selected_addresses() hostname: "example.test".into(), port: 443, }; - let json = serde_json::to_value(&target).unwrap(); - assert!(json.get("method").is_none()); - assert!(json.get("headers").is_none()); - assert!(json.get("body").is_none()); - assert!(json.get("address").is_none()); + assert_eq!( + serde_json::to_value(&target).unwrap(), + serde_json::json!({ + "policy_id": "private-policy", + "expected_generation": 8, + "session_id": "private-session", + "scheme": "https", + "hostname": "example.test", + "port": 443 + }) + ); let grant = BrowserEgressGrant { generation: 8, authorization: "opaque serialized TinySecurity grant".into(), addresses: vec!["203.0.113.8:443".into()], }; - assert_eq!(grant.addresses.len(), 1); + assert_eq!( + serde_json::to_value(&grant).unwrap(), + serde_json::json!({ + "generation": 8, + "authorization": "opaque serialized TinySecurity grant", + "addresses": ["203.0.113.8:443"] + }) + ); + let consume = BrowserEgressConsumeRequest { + target: target.clone(), + authorization: "opaque serialized TinySecurity grant".into(), + address: "203.0.113.8:443".into(), + }; + assert_eq!( + serde_json::to_value(&consume).unwrap(), + serde_json::json!({ + "target": { + "policy_id": "private-policy", + "expected_generation": 8, + "session_id": "private-session", + "scheme": "https", + "hostname": "example.test", + "port": 443 + }, + "authorization": "opaque serialized TinySecurity grant", + "address": "203.0.113.8:443" + }) + ); + let validate = BrowserEgressValidateRequest { + authorization: "opaque serialized TinySecurity grant".into(), + }; + assert_eq!( + serde_json::to_value(&validate).unwrap(), + serde_json::json!({ "authorization": "opaque serialized TinySecurity grant" }) + ); + let decision = BrowserEgressDecision { allowed: true }; + assert_eq!( + serde_json::to_value(decision).unwrap(), + serde_json::json!({ "allowed": true }) + ); + assert_eq!(serde_json::from_value::(serde_json::to_value(&target).unwrap()).unwrap(), target); + assert_eq!(serde_json::from_value::(serde_json::to_value(&grant).unwrap()).unwrap(), grant); + assert_eq!(serde_json::from_value::(serde_json::to_value(&consume).unwrap()).unwrap(), consume); + assert_eq!(serde_json::from_value::(serde_json::to_value(&validate).unwrap()).unwrap(), validate); + assert_eq!(serde_json::from_value::(serde_json::to_value(decision).unwrap()).unwrap(), decision); assert_eq!(METHODS, ["Authorize", "Consume", "Validate"]); } From e2d64fac392ff630fefda70d24d641fa784816a7 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:30:19 +0000 Subject: [PATCH 24/93] test(browser-egress): cover large request bodies and tidy round-trip assertions Add a proxy test that streams a request body larger than one mebibyte to confirm approved uploads are forwarded intact. Reformat the browser egress round-trip assertions for readability without changing what they check. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress_tests/http_tests.rs | 68 +++++++++++++++++++ .../browser_egress/browser_egress_tests.rs | 34 ++++++++-- 2 files changed, 97 insertions(+), 5 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs index c7d3f7ccf..b2a4ed11b 100644 --- a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs @@ -218,6 +218,74 @@ async fn approved_http_request_body_is_forwarded_without_framing_changes() { server.await.unwrap(); } +#[tokio::test] +async fn approved_http_request_streams_bodies_larger_than_one_mibibyte() { + const BODY_LENGTH: usize = 1536 * 1024; + let expected_body = vec![b'x'; BODY_LENGTH]; + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 8192]; + let split = loop { + let n = socket.read(&mut chunk).await.unwrap(); + assert_ne!(n, 0); + request.extend_from_slice(&chunk[..n]); + if let Some(split) = request.windows(4).position(|window| window == b"\r\n\r\n") { + break split + 4; + } + }; + let mut body = request.split_off(split); + let received = body.len(); + assert!(received <= BODY_LENGTH); + body.resize(BODY_LENGTH, 0); + if received < BODY_LENGTH { + socket.read_exact(&mut body[received..]).await.unwrap(); + } + assert_eq!(body, vec![b'x'; BODY_LENGTH]); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + .await + .unwrap(); + }); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }), + "large-body-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "POST http://body.test:{}/upload HTTP/1.1\r\nHost: body.test:{}\r\nProxy-Authorization: {}\r\nContent-Length: {BODY_LENGTH}\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + client.write_all(&expected_body).await.unwrap(); + let mut response = Vec::new(); + client.read_to_end(&mut response).await.unwrap(); + assert!( + std::str::from_utf8(&response) + .unwrap() + .ends_with("\r\n\r\nok") + ); + server.await.unwrap(); +} + #[tokio::test] async fn duplicate_lengths_and_pipelined_authorities_are_refused_before_dial() { let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); diff --git a/crates/tinycomputer-bus/src/browser_egress/browser_egress_tests.rs b/crates/tinycomputer-bus/src/browser_egress/browser_egress_tests.rs index 7025c070e..bef43c76c 100644 --- a/crates/tinycomputer-bus/src/browser_egress/browser_egress_tests.rs +++ b/crates/tinycomputer-bus/src/browser_egress/browser_egress_tests.rs @@ -69,11 +69,35 @@ fn browser_callback_contract_has_no_http_payload_or_caller_selected_addresses() serde_json::to_value(decision).unwrap(), serde_json::json!({ "allowed": true }) ); - assert_eq!(serde_json::from_value::(serde_json::to_value(&target).unwrap()).unwrap(), target); - assert_eq!(serde_json::from_value::(serde_json::to_value(&grant).unwrap()).unwrap(), grant); - assert_eq!(serde_json::from_value::(serde_json::to_value(&consume).unwrap()).unwrap(), consume); - assert_eq!(serde_json::from_value::(serde_json::to_value(&validate).unwrap()).unwrap(), validate); - assert_eq!(serde_json::from_value::(serde_json::to_value(decision).unwrap()).unwrap(), decision); + assert_eq!( + serde_json::from_value::(serde_json::to_value(&target).unwrap()) + .unwrap(), + target + ); + assert_eq!( + serde_json::from_value::(serde_json::to_value(&grant).unwrap()) + .unwrap(), + grant + ); + assert_eq!( + serde_json::from_value::( + serde_json::to_value(&consume).unwrap() + ) + .unwrap(), + consume + ); + assert_eq!( + serde_json::from_value::( + serde_json::to_value(&validate).unwrap() + ) + .unwrap(), + validate + ); + assert_eq!( + serde_json::from_value::(serde_json::to_value(decision).unwrap()) + .unwrap(), + decision + ); assert_eq!(METHODS, ["Authorize", "Consume", "Validate"]); } From 8870e0b5f005e66b2247a9a18cca4acafe4896b8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:30:42 +0000 Subject: [PATCH 25/93] refactor(egress): drop unused mut on proxy request binding Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/serve.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index de2da0791..12b487757 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -18,7 +18,7 @@ pub(super) async fn serve( session_id: String, proxy_password: String, ) -> io::Result<()> { - let Some(mut request) = read_proxy_request(&mut client, &session_id, &proxy_password).await? + let Some(request) = read_proxy_request(&mut client, &session_id, &proxy_password).await? else { return Ok(()); }; From 32e1080871695361a029fb64718ba43a6e718a7a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:31:06 +0000 Subject: [PATCH 26/93] refactor(egress): collapse let-else onto one line Reformatted the let-else binding in the proxy serve function so the else clause sits on the same line as the pattern. No behaviour change. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/serve.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index 12b487757..4ea0e5645 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -18,8 +18,7 @@ pub(super) async fn serve( session_id: String, proxy_password: String, ) -> io::Result<()> { - let Some(request) = read_proxy_request(&mut client, &session_id, &proxy_password).await? - else { + let Some(request) = read_proxy_request(&mut client, &session_id, &proxy_password).await? else { return Ok(()); }; if !has_valid_buffered_body(&request) { From 5d8f3350cf117533c2087dbd455e6160de315f50 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:31:30 +0000 Subject: [PATCH 27/93] fix(egress): correct proxy header validation condition The condition guarding proxy header parsing was malformed, mixing upgrade and body length checks in a way that could reject valid requests. It now correctly requires a zero body length for CONNECT requests and for upgrade requests. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/request.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/request.rs b/crates/tinycomputer-browser/src/egress/request.rs index 601497b49..7f1033ed0 100644 --- a/crates/tinycomputer-browser/src/egress/request.rs +++ b/crates/tinycomputer-browser/src/egress/request.rs @@ -191,8 +191,7 @@ fn parse_proxy_headers( }); if has_upgrade != connection_upgrade || !host_matches - || (connect && body_len != 0) - || (!connect && has_upgrade && body_len != 0) + || ((connect || has_upgrade) && body_len != 0) { return None; } From 98ed10487466e90e0db1d79691710f5a5263d281 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:31:46 +0000 Subject: [PATCH 28/93] Document live browser test toggle Co-authored-by: Medulla --- .env.example | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.env.example b/.env.example index c3ccee456..58ad77e21 100644 --- a/.env.example +++ b/.env.example @@ -103,3 +103,5 @@ TINYCOMPUTER_LAB_SELF_EMAIL= # TASK_SURFACE=desktop # Opt-in live browser runs (see docs/technical/specs/unified-agent.md). # TINYCOMPUTER_LIVE_BROWSER=1 +# Compile and run the linked browser egress tests against installed Chromium. +# TINYCOMPUTER_LIVE_BROWSER_TESTS=1 From 8356f04aeb751a7ede2ef2636a2dc38fd3a35a88 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:33:22 +0000 Subject: [PATCH 29/93] test(linked): cover enforced browser rejecting process-side reads with a url Add a test asserting that an enforced browser refuses a process-side read that carries a URL, verifying the rejection message is surfaced to the caller. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/linked/linked_tests.rs | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/crates/tinycomputer-browser/src/linked/linked_tests.rs b/crates/tinycomputer-browser/src/linked/linked_tests.rs index a5fd1790b..65b00dc9f 100644 --- a/crates/tinycomputer-browser/src/linked/linked_tests.rs +++ b/crates/tinycomputer-browser/src/linked/linked_tests.rs @@ -93,6 +93,31 @@ async fn a_closed_or_lost_browser_cannot_implicitly_launch_without_the_proxy() { ); } +#[tokio::test] +async fn enforced_browser_refuses_process_side_reads_with_a_url() { + let mut engine = Linked { + state: DaemonState::with_options(state_options("process-read")), + egress_authorizer: Some(Arc::new(RejectAll)), + proxy: None, + proxy_session_id: "private-session-id".into(), + enforced_launch: true, + }; + let reply = engine + .execute(json!({ + "id":"read", + "action":"read", + "url":"http://public.example/" + })) + .await; + assert_eq!(reply["success"], false); + assert!( + reply["error"] + .as_str() + .unwrap() + .contains("process-side reads with a URL") + ); +} + #[tokio::test] async fn enforced_browser_rechecks_liveness_after_waiting_for_engine_lock() { let engine = Linked { From 33645075bd2121520575c5f047ab0eeea188b2f9 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:34:02 +0000 Subject: [PATCH 30/93] fix(browser): reject process-side reads with a url under egress policy The linked engine now returns a failure reply when an egress authorizer is configured and a read command carries a url, closing a path where network policy could be bypassed. The versioning doc example was updated to a still-compatible newer module version. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/linked/mod.rs | 9 +++++++++ docs/crates/tinycomputer-bus/versioning.md | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/tinycomputer-browser/src/linked/mod.rs b/crates/tinycomputer-browser/src/linked/mod.rs index 56e327769..67eaeb8cf 100644 --- a/crates/tinycomputer-browser/src/linked/mod.rs +++ b/crates/tinycomputer-browser/src/linked/mod.rs @@ -121,6 +121,15 @@ impl Engine for Linked { command }; let _serialized = ENGINE.lock().await; + if self.egress_authorizer.is_some() + && action.as_deref() == Some("read") + && command.get("url").and_then(Value::as_str).is_some() + { + return failure_reply( + &command, + "network policy refuses process-side reads with a URL", + ); + } #[allow(clippy::redundant_closure_for_method_calls)] let browser_unavailable = self .state diff --git a/docs/crates/tinycomputer-bus/versioning.md b/docs/crates/tinycomputer-bus/versioning.md index f2e1d389c..042c9d05c 100644 --- a/docs/crates/tinycomputer-bus/versioning.md +++ b/docs/crates/tinycomputer-bus/versioning.md @@ -53,7 +53,7 @@ Two conditions, both necessary: ```rust,ignore assert!(is_compatible(CONTRACT_VERSION)); // (2, 21), the exact version this crate ships -assert!(is_compatible((2, 21))); // a newer, still-compatible module +assert!(is_compatible((2, 22))); // a newer, still-compatible module assert!(!is_compatible((2, 11))); // an older module, missing something assert!(!is_compatible((1, 10))); // a different major, all bets off ``` From f9476cd40a0c18e0536507904900449e95bb100f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:34:23 +0000 Subject: [PATCH 31/93] docs(tinycomputer-bus): clarify minor version compatibility example The versioning guide now separates the exact-match case from the newer-minor case when explaining why a module at or above the host's minor version is accepted. The previous wording conflated the two, making it unclear that a module reporting the same version is accepted because it matches exactly rather than because it carries extra members. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- docs/crates/tinycomputer-bus/versioning.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/crates/tinycomputer-bus/versioning.md b/docs/crates/tinycomputer-bus/versioning.md index 042c9d05c..68665eb88 100644 --- a/docs/crates/tinycomputer-bus/versioning.md +++ b/docs/crates/tinycomputer-bus/versioning.md @@ -47,9 +47,10 @@ Two conditions, both necessary: 2. **The module must be at least as new, minor-wise, as the host.** A host built against `(2, 21)` expects at least the members and fields that existed at `(2, 21)`. A module reporting `(2, 11)` might be missing one of - them, so it is rejected. A module reporting `(2, 21)` has everything the - host expects, plus something newer the host simply does not use yet, so - it is accepted. + them, so it is rejected. A module reporting `(2, 21)` is an exact match + and is accepted. A module reporting `(2, 22)` has everything the host + expects, plus something newer the host simply does not use yet, so it is + accepted. ```rust,ignore assert!(is_compatible(CONTRACT_VERSION)); // (2, 21), the exact version this crate ships From c33fb4b1c4985b0632b259bc3fc729d4955fae77 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:38:04 +0000 Subject: [PATCH 32/93] fix(egress): validate lease while forwarding request bodies Request bodies were streamed to the upstream without rechecking the lease, so a lease revoked mid-upload went unnoticed until the response phase. The body forwarding now runs under the same periodic lease validation as the response path and aborts the connection when the lease is no longer valid. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress/forward.rs | 31 ++++++++++++++++++- .../tinycomputer-browser/src/egress/serve.rs | 15 ++++++--- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/forward.rs b/crates/tinycomputer-browser/src/egress/forward.rs index fb0a493ed..7257032f4 100644 --- a/crates/tinycomputer-browser/src/egress/forward.rs +++ b/crates/tinycomputer-browser/src/egress/forward.rs @@ -7,7 +7,10 @@ use tokio::{ net::TcpStream, }; -use super::{EgressAuthorizer, request::ProxyRequest}; +use super::{ + EgressAuthorizer, + request::{ProxyRequest, buffered_body_len, read_request_body}, +}; pub(super) async fn initialize_upstream( client: &mut TcpStream, @@ -126,6 +129,32 @@ pub(super) async fn forward_response_with_lease( } } +pub(super) async fn forward_request_body_with_lease( + client: &mut TcpStream, + upstream: &mut TcpStream, + request: &ProxyRequest, + auth: &Arc, + lease: &str, +) -> io::Result { + let body = read_request_body( + client, + upstream, + request, + buffered_body_len(request), + ); + tokio::pin!(body); + let mut validations = validation_interval(); + loop { + tokio::select! { + biased; + _ = validations.tick() => { + if !validate_lease(auth, lease).await? { return Ok(false); } + }, + result = &mut body => { result?; return Ok(true); }, + } + } +} + fn validation_interval() -> tokio::time::Interval { let period = Duration::from_secs(1); let mut interval = tokio::time::interval_at(tokio::time::Instant::now() + period, period); diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index 4ea0e5645..34fdd7313 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -7,9 +7,10 @@ use tokio::net::TcpStream; use super::{ BrowserDialTarget, DialGrant, EgressAuthorizer, forward::{ - forward_response_with_lease, initialize_upstream, refuse, tunnel_with_lease, validate_lease, + forward_request_body_with_lease, forward_response_with_lease, initialize_upstream, refuse, + tunnel_with_lease, validate_lease, }, - request::{buffered_body_len, has_valid_buffered_body, read_proxy_request, read_request_body}, + request::{has_valid_buffered_body, read_proxy_request}, }; pub(super) async fn serve( @@ -67,13 +68,17 @@ pub(super) async fn serve( if request.connect || request.has_upgrade { tunnel_with_lease(&mut client, &mut upstream, &auth, lease).await?; } else { - read_request_body( + if !forward_request_body_with_lease( &mut client, &mut upstream, &request, - buffered_body_len(&request), + &auth, + &lease, ) - .await?; + .await? + { + return Ok(()); + } forward_response_with_lease(&mut client, &mut upstream, &auth, lease).await?; } Ok(()) From f7a15146ccb4d0d9e94b5c8a74f6c37acedf86e5 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:38:40 +0000 Subject: [PATCH 33/93] refactor(browser): make ambient browser config check injectable Split the ambient browser configuration check out of enforce_launch into a has_ambient_browser_config helper and an enforce_launch_with_config variant that takes the result as a parameter, so tests can exercise launch enforcement without depending on process environment. Added a test covering that a revoked lease closes a large in-flight request upload. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress_tests/lease_tests.rs | 58 +++++++++++++++++++ crates/tinycomputer-browser/src/linked/mod.rs | 45 ++++++++++---- 2 files changed, 91 insertions(+), 12 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs b/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs index 37f3f40cc..b9588c6ce 100644 --- a/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs @@ -65,3 +65,61 @@ async fn continuous_http_response_still_revalidates_and_closes_revoked_lease() { ); server.await.unwrap(); } + +#[tokio::test] +async fn a_revoked_lease_closes_a_large_request_upload() { + use std::sync::atomic::AtomicUsize; + const BODY_LENGTH: usize = 10 * 1024 * 1024; + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + let mut received = Vec::new(); + socket.read_to_end(&mut received).await.unwrap(); + received + }); + let validations = Arc::new(AtomicUsize::new(0)); + let proxy = EgressProxy::bind( + Arc::new(RevokingAuthorizer { + address, + validations: validations.clone(), + }), + "upload-revocation-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "POST http://upload.test:{}/ HTTP/1.1\r\nHost: upload.test:{}\r\nProxy-Authorization: {}\r\nContent-Length: {BODY_LENGTH}\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let chunk = [b'x'; 1024]; + for _ in 0..BODY_LENGTH / chunk.len() { + if client.write_all(&chunk).await.is_err() { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + let mut response = Vec::new(); + tokio::time::timeout( + std::time::Duration::from_secs(4), + client.read_to_end(&mut response), + ) + .await + .expect("revoked upload should be closed promptly") + .unwrap(); + let received = server.await.unwrap(); + assert!(validations.load(Ordering::SeqCst) > 1); + assert!(received.len() < BODY_LENGTH); +} diff --git a/crates/tinycomputer-browser/src/linked/mod.rs b/crates/tinycomputer-browser/src/linked/mod.rs index 67eaeb8cf..baf4f212c 100644 --- a/crates/tinycomputer-browser/src/linked/mod.rs +++ b/crates/tinycomputer-browser/src/linked/mod.rs @@ -194,9 +194,26 @@ fn failure_reply(command: &Value, reason: &str) -> Value { } fn enforce_launch( + command: Value, + proxy: &str, + proxy_password: &str, +) -> Result { + let has_ambient_browser_config = command.get("action").and_then(Value::as_str) + == Some("launch") + && has_ambient_browser_config(); + enforce_launch_with_config( + command, + proxy, + proxy_password, + has_ambient_browser_config, + ) +} + +fn enforce_launch_with_config( mut command: Value, proxy: &str, proxy_password: &str, + has_ambient_browser_config: bool, ) -> Result { if command.get("action").and_then(Value::as_str) != Some("launch") { return Ok(command); @@ -223,18 +240,7 @@ fn enforce_launch( { return Err("network policy refuses caller-supplied browser launch arguments"); } - if std::env::var_os("AGENT_BROWSER_CDP").is_some() - || std::env::var_os("AGENT_BROWSER_AUTO_CONNECT").is_some() - || std::env::var_os("AGENT_BROWSER_PROVIDER").is_some() - || std::env::var_os("AGENT_BROWSER_ENGINE").is_some() - || std::env::var_os("AGENT_BROWSER_EXECUTABLE_PATH").is_some() - || std::env::var_os("AGENT_BROWSER_PROXY").is_some() - || std::env::var_os("AGENT_BROWSER_PROXY_BYPASS").is_some() - || std::env::var_os("AGENT_BROWSER_PROXY_USERNAME").is_some() - || std::env::var_os("AGENT_BROWSER_PROXY_PASSWORD").is_some() - || std::env::var_os("AGENT_BROWSER_PROFILE").is_some() - || std::env::var_os("AGENT_BROWSER_RESTORE").is_some() - { + if has_ambient_browser_config { return Err("network policy refuses ambient external browser configuration"); } // Chromium's special <-loopback> token removes its implicit direct @@ -255,5 +261,20 @@ fn enforce_launch( Ok(command) } +fn has_ambient_browser_config() -> bool { + std::env::var_os("AGENT_BROWSER_CDP").is_some() + || std::env::var_os("AGENT_BROWSER_AUTO_CONNECT").is_some() + || std::env::var_os("AGENT_BROWSER_PROVIDER").is_some() + || std::env::var_os("AGENT_BROWSER_ENGINE").is_some() + || std::env::var_os("AGENT_BROWSER_EXECUTABLE_PATH").is_some() + || std::env::var_os("AGENT_BROWSER_PROXY").is_some() + || std::env::var_os("AGENT_BROWSER_PROXY_BYPASS").is_some() + || std::env::var_os("AGENT_BROWSER_PROXY_USERNAME").is_some() + || std::env::var_os("AGENT_BROWSER_PROXY_PASSWORD").is_some() + || std::env::var_os("AGENT_BROWSER_PROFILE").is_some() + || std::env::var_os("AGENT_BROWSER_RESTORE").is_some() +} +} + #[cfg(test)] mod linked_tests; From 4b399e36daf5b9f037ce9166e4f8688109679435 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:40:03 +0000 Subject: [PATCH 34/93] feat(egress): forward chunked request bodies to upstream The proxy now accepts Transfer-Encoding: chunked requests and streams their bodies to the upstream instead of rejecting them, validating chunk sizes, endings, and trailers along the way. Chunked requests are treated like upgrade and connect requests for buffering purposes, and a chunked body combined with Content-Length is refused. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress/forward.rs | 23 +-- .../src/egress/request.rs | 189 +++++++++++++++++- .../tinycomputer-browser/src/egress/serve.rs | 10 +- .../src/egress_tests/http_tests.rs | 58 ++++++ .../src/linked/linked_tests.rs | 23 ++- crates/tinycomputer-browser/src/linked/mod.rs | 8 +- 6 files changed, 273 insertions(+), 38 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/forward.rs b/crates/tinycomputer-browser/src/egress/forward.rs index 7257032f4..0bd884606 100644 --- a/crates/tinycomputer-browser/src/egress/forward.rs +++ b/crates/tinycomputer-browser/src/egress/forward.rs @@ -69,12 +69,16 @@ pub(super) async fn initialize_upstream( "browser upstream request timed out", ) .await?; - write_all_bounded( - upstream, - &request.bytes[request.split..], - "browser upstream body timed out", - ) - .await + if request.chunked { + Ok(()) + } else { + write_all_bounded( + upstream, + &request.bytes[request.split..], + "browser upstream body timed out", + ) + .await + } } pub(super) fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { let mut difference = left.len() ^ right.len(); @@ -136,12 +140,7 @@ pub(super) async fn forward_request_body_with_lease( auth: &Arc, lease: &str, ) -> io::Result { - let body = read_request_body( - client, - upstream, - request, - buffered_body_len(request), - ); + let body = read_request_body(client, upstream, request, buffered_body_len(request)); tokio::pin!(body); let mut validations = validation_interval(); loop { diff --git a/crates/tinycomputer-browser/src/egress/request.rs b/crates/tinycomputer-browser/src/egress/request.rs index 7f1033ed0..3d2774521 100644 --- a/crates/tinycomputer-browser/src/egress/request.rs +++ b/crates/tinycomputer-browser/src/egress/request.rs @@ -20,6 +20,7 @@ pub(super) struct ProxyRequest { pub(super) target: BrowserDialTarget, pub(super) connect: bool, pub(super) body_len: usize, + pub(super) chunked: bool, pub(super) has_upgrade: bool, } @@ -100,6 +101,7 @@ pub(super) async fn read_proxy_request( target, connect, body_len: headers.body_len, + chunked: headers.chunked, has_upgrade: headers.has_upgrade, })) } @@ -129,6 +131,7 @@ fn proxy_target(method: &str, uri: &str, session_id: &str) -> Option, } @@ -145,6 +148,8 @@ fn parse_proxy_headers( let mut connection_upgrade = false; let mut proxy_authorization = None; let mut saw_content_length = false; + let mut chunked = false; + let mut saw_transfer_encoding = false; for line in lines .iter() .skip(1) @@ -162,9 +167,13 @@ fn parse_proxy_headers( } saw_content_length = true; body_len = value.trim().parse().ok()?; - } else if name.eq_ignore_ascii_case("transfer-encoding") - || name.eq_ignore_ascii_case("expect") - { + } else if name.eq_ignore_ascii_case("transfer-encoding") { + if saw_transfer_encoding || !value.trim().eq_ignore_ascii_case("chunked") { + return None; + } + saw_transfer_encoding = true; + chunked = true; + } else if name.eq_ignore_ascii_case("expect") { return None; } else if name.eq_ignore_ascii_case("proxy-authorization") { if proxy_authorization @@ -191,12 +200,14 @@ fn parse_proxy_headers( }); if has_upgrade != connection_upgrade || !host_matches - || ((connect || has_upgrade) && body_len != 0) + || (saw_content_length && chunked) + || ((connect || has_upgrade) && (body_len != 0 || chunked)) { return None; } Some(ParsedHeaders { body_len, + chunked, has_upgrade, proxy_authorization, }) @@ -211,7 +222,7 @@ fn has_proxy_auth(proxy_authorization: Option<&str>, password: &str) -> bool { .is_some_and(|actual| constant_time_eq(actual.as_bytes(), expected.as_bytes())) } pub(super) fn has_valid_buffered_body(request: &ProxyRequest) -> bool { - if request.has_upgrade || request.connect { + if request.has_upgrade || request.connect || request.chunked { return true; } let received = request.bytes.len().saturating_sub(request.split); @@ -219,7 +230,7 @@ pub(super) fn has_valid_buffered_body(request: &ProxyRequest) -> bool { } pub(super) fn buffered_body_len(request: &ProxyRequest) -> usize { - if request.has_upgrade || request.connect { + if request.has_upgrade || request.connect || request.chunked { 0 } else { request.bytes.len().saturating_sub(request.split) @@ -235,6 +246,10 @@ pub(super) async fn read_request_body( if request.has_upgrade || request.connect { return Ok(()); } + if request.chunked { + return forward_chunked_request_body(client, upstream, &request.bytes[request.split..]) + .await; + } let mut chunk = [0u8; 1024]; while received < request.body_len { let n = tokio::time::timeout(Duration::from_secs(10), client.read(&mut chunk)) @@ -258,6 +273,168 @@ pub(super) async fn read_request_body( } Ok(()) } + +async fn forward_chunked_request_body( + client: &mut TcpStream, + upstream: &mut TcpStream, + initial: &[u8], +) -> io::Result<()> { + let mut pending = initial.to_vec(); + let mut offset = 0; + let mut trailer_bytes = 0; + loop { + let line = read_chunk_line(client, &mut pending, &mut offset).await?; + let size_text = std::str::from_utf8(&line[..line.len() - 2]) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid chunk size"))?; + let size_text = size_text.split(';').next().unwrap_or_default(); + if size_text.is_empty() || !size_text.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid chunk size", + )); + } + let size = usize::from_str_radix(size_text, 16) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid chunk size"))?; + write_all_bounded(upstream, &line, "browser upstream body timed out").await?; + if size == 0 { + loop { + let trailer = read_chunk_line(client, &mut pending, &mut offset).await?; + trailer_bytes += trailer.len(); + let trailer_line = &trailer[..trailer.len() - 2]; + let forbidden_trailer = std::str::from_utf8(trailer_line) + .ok() + .and_then(|line| line.split_once(':')) + .is_some_and(|(name, _)| { + name.is_empty() + || name.eq_ignore_ascii_case("content-length") + || name.eq_ignore_ascii_case("transfer-encoding") + || name.eq_ignore_ascii_case("host") + }); + if trailer_bytes > 32 * 1024 + || (trailer != b"\r\n" && (!trailer_line.contains(&b':') || forbidden_trailer)) + { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid chunk trailer", + )); + } + write_all_bounded(upstream, &trailer, "browser upstream body timed out").await?; + if trailer == b"\r\n" { + if offset != pending.len() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "bytes after chunked request body", + )); + } + return Ok(()); + } + } + } + let mut remaining = size; + let mut chunk = [0u8; 8192]; + while remaining > 0 { + let buffered = pending.len().saturating_sub(offset); + let n = if buffered > 0 { + let n = buffered.min(remaining).min(chunk.len()); + chunk[..n].copy_from_slice(&pending[offset..offset + n]); + offset += n; + n + } else { + let n = tokio::time::timeout( + Duration::from_secs(10), + client.read(&mut chunk[..remaining.min(chunk.len())]), + ) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy body timed out"))??; + if n == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "browser request body ended early", + )); + } + n + }; + write_all_bounded(upstream, &chunk[..n], "browser upstream body timed out").await?; + remaining -= n; + } + let ending = read_body_bytes(client, &mut pending, &mut offset, 2).await?; + if ending != b"\r\n" { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid chunk ending", + )); + } + write_all_bounded(upstream, &ending, "browser upstream body timed out").await?; + } +} + +async fn read_chunk_line( + client: &mut TcpStream, + pending: &mut Vec, + offset: &mut usize, +) -> io::Result> { + loop { + if let Some(end) = pending[*offset..] + .windows(2) + .position(|window| window == b"\r\n") + { + let end = *offset + end + 2; + let line = pending[*offset..end].to_vec(); + *offset = end; + return Ok(line); + } + if pending.len().saturating_sub(*offset) > 8192 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "chunk line is too long", + )); + } + if *offset > 8192 { + pending.drain(..*offset); + *offset = 0; + } + let mut chunk = [0u8; 1024]; + let n = tokio::time::timeout(Duration::from_secs(10), client.read(&mut chunk)) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy body timed out"))??; + if n == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "browser request body ended early", + )); + } + pending.extend_from_slice(&chunk[..n]); + } +} + +async fn read_body_bytes( + client: &mut TcpStream, + pending: &mut Vec, + offset: &mut usize, + length: usize, +) -> io::Result> { + while pending.len().saturating_sub(*offset) < length { + if *offset > 8192 { + pending.drain(..*offset); + *offset = 0; + } + let mut chunk = [0u8; 1024]; + let n = tokio::time::timeout(Duration::from_secs(10), client.read(&mut chunk)) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy body timed out"))??; + if n == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "browser request body ended early", + )); + } + pending.extend_from_slice(&chunk[..n]); + } + let end = *offset + length; + let bytes = pending[*offset..end].to_vec(); + *offset = end; + Ok(bytes) +} pub(crate) fn parse_authority( value: &str, scheme: &str, diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index 34fdd7313..450495d90 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -68,14 +68,8 @@ pub(super) async fn serve( if request.connect || request.has_upgrade { tunnel_with_lease(&mut client, &mut upstream, &auth, lease).await?; } else { - if !forward_request_body_with_lease( - &mut client, - &mut upstream, - &request, - &auth, - &lease, - ) - .await? + if !forward_request_body_with_lease(&mut client, &mut upstream, &request, &auth, &lease) + .await? { return Ok(()); } diff --git a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs index b2a4ed11b..cc0803416 100644 --- a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs @@ -286,6 +286,64 @@ async fn approved_http_request_streams_bodies_larger_than_one_mibibyte() { server.await.unwrap(); } +#[tokio::test] +async fn approved_http_request_forwards_chunked_uploads() { + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 1024]; + loop { + let n = socket.read(&mut chunk).await.unwrap(); + assert_ne!(n, 0); + request.extend_from_slice(&chunk[..n]); + if request.windows(5).any(|window| window == b"0\r\n\r\n") { + break; + } + } + assert!(request.windows(4).any(|window| window == b"4\r\ndata")); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + .await + .unwrap(); + }); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }), + "chunked-body-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "POST http://body.test:{}/stream HTTP/1.1\r\nHost: body.test:{}\r\nProxy-Authorization: {}\r\nTransfer-Encoding: chunked\r\n\r\n4\r\ndata\r\n0\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = Vec::new(); + client.read_to_end(&mut response).await.unwrap(); + assert!( + std::str::from_utf8(&response) + .unwrap() + .ends_with("\r\n\r\nok") + ); + server.await.unwrap(); +} + #[tokio::test] async fn duplicate_lengths_and_pipelined_authorities_are_refused_before_dial() { let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); diff --git a/crates/tinycomputer-browser/src/linked/linked_tests.rs b/crates/tinycomputer-browser/src/linked/linked_tests.rs index 65b00dc9f..a4c46d6cc 100644 --- a/crates/tinycomputer-browser/src/linked/linked_tests.rs +++ b/crates/tinycomputer-browser/src/linked/linked_tests.rs @@ -17,7 +17,9 @@ use tokio::{ net::TcpListener, }; -use super::{AgentBrowser, ENGINE, EnforcedAgentBrowser, Linked, enforce_launch, state_options}; +use super::{ + AgentBrowser, ENGINE, EnforcedAgentBrowser, Linked, enforce_launch_with_config, state_options, +}; use crate::{ BrowserDialTarget, DialGrant, EgressAuthorizer, engine::{Engine, Launcher}, @@ -410,10 +412,11 @@ impl EgressAuthorizer for RejectAllButFixture { #[test] fn enforced_launch_uses_only_the_host_proxy_and_network_containment_flags() { - let launch = enforce_launch( + let launch = enforce_launch_with_config( json!({"id":"launch","action":"launch","headless":true,"args":[]}), "http://127.0.0.1:39123", "session-secret", + false, ) .expect("enforced launch"); assert_eq!(launch["proxy"]["server"], "http://127.0.0.1:39123"); @@ -433,22 +436,32 @@ fn enforced_launch_uses_only_the_host_proxy_and_network_containment_flags() { #[test] fn enforced_launch_refuses_external_cdp_and_caller_flags() { - let cdp = enforce_launch( + let cdp = enforce_launch_with_config( json!({"action":"launch","cdpUrl":"http://127.0.0.1:9222"}), "http://127.0.0.1:39123", "session-secret", + false, ); assert!(cdp.is_err()); - let args = enforce_launch( + let args = enforce_launch_with_config( json!({"action":"launch","args":["--proxy-server=http://attacker.test"]}), "http://127.0.0.1:39123", "session-secret", + false, ); assert!(args.is_err()); - let executable = enforce_launch( + let executable = enforce_launch_with_config( json!({"action":"launch","executablePath":"/tmp/attacker-browser"}), "http://127.0.0.1:39123", "session-secret", + false, ); assert!(executable.is_err()); + let ambient = enforce_launch_with_config( + json!({"action":"launch"}), + "http://127.0.0.1:39123", + "session-secret", + true, + ); + assert!(ambient.is_err()); } diff --git a/crates/tinycomputer-browser/src/linked/mod.rs b/crates/tinycomputer-browser/src/linked/mod.rs index baf4f212c..be50a14e6 100644 --- a/crates/tinycomputer-browser/src/linked/mod.rs +++ b/crates/tinycomputer-browser/src/linked/mod.rs @@ -201,12 +201,7 @@ fn enforce_launch( let has_ambient_browser_config = command.get("action").and_then(Value::as_str) == Some("launch") && has_ambient_browser_config(); - enforce_launch_with_config( - command, - proxy, - proxy_password, - has_ambient_browser_config, - ) + enforce_launch_with_config(command, proxy, proxy_password, has_ambient_browser_config) } fn enforce_launch_with_config( @@ -274,7 +269,6 @@ fn has_ambient_browser_config() -> bool { || std::env::var_os("AGENT_BROWSER_PROFILE").is_some() || std::env::var_os("AGENT_BROWSER_RESTORE").is_some() } -} #[cfg(test)] mod linked_tests; From 6436247bbe0b4c8d1bcd16c2f4bf94f8cc956272 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:40:24 +0000 Subject: [PATCH 35/93] fix(egress): hoist chunk read length out of timeout future The slice length for the chunked body read was computed inside the timeout future, so the borrow of `chunk` was held across the await. Computing `read_length` beforehand keeps the borrow short and lets the future stay `Send`. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/request.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/tinycomputer-browser/src/egress/request.rs b/crates/tinycomputer-browser/src/egress/request.rs index 3d2774521..e1fb310d4 100644 --- a/crates/tinycomputer-browser/src/egress/request.rs +++ b/crates/tinycomputer-browser/src/egress/request.rs @@ -340,9 +340,10 @@ async fn forward_chunked_request_body( offset += n; n } else { + let read_length = remaining.min(chunk.len()); let n = tokio::time::timeout( Duration::from_secs(10), - client.read(&mut chunk[..remaining.min(chunk.len())]), + client.read(&mut chunk[..read_length]), ) .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy body timed out"))??; From e4d9682d2f7a5f8a0e0ed7ebea331603e3f313d8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:40:47 +0000 Subject: [PATCH 36/93] test(egress): fix chunked upload assertion window size The assertion compared a four-byte window against the seven-byte needle `4\r\ndata`, so it could never match. Widening the window to seven bytes lets the test actually verify the forwarded chunked upload body. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress_tests/http_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs index cc0803416..e7eb33584 100644 --- a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs @@ -302,7 +302,7 @@ async fn approved_http_request_forwards_chunked_uploads() { break; } } - assert!(request.windows(4).any(|window| window == b"4\r\ndata")); + assert!(request.windows(7).any(|window| window == b"4\r\ndata")); socket .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") .await From 10db35d89f024366ebec27e39d7fca9c83f5cdc2 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:45:08 +0000 Subject: [PATCH 37/93] docs(egress): add README for the egress module Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinycomputer-browser/src/egress/README.md | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 crates/tinycomputer-browser/src/egress/README.md diff --git a/crates/tinycomputer-browser/src/egress/README.md b/crates/tinycomputer-browser/src/egress/README.md new file mode 100644 index 000000000..ecdb599b0 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/README.md @@ -0,0 +1,35 @@ +# Browser egress proxy + +This module gives an explicitly launched Chromium session a private HTTP proxy +whose destination decisions come from the TinyComputer host callback. It keeps +the engine adapter (`EgressAuthorizer`) small: the host authorizes the parsed +destination, returns a one-use grant and exact socket addresses, consumes a +grant before each dial, and revalidates active leases. + +## Structure + +- `mod.rs` defines the public `BrowserDialTarget`, `DialGrant`, + `EgressAuthorizer`, and `EgressProxy` surface and owns the loopback listener. +- `request.rs` authenticates each local proxy client, parses HTTP proxy + requests, validates authorities and framing, and streams fixed-length and + chunked request bodies with bounded buffers. +- `forward.rs` writes sanitized upstream headers and forwards request and + response data while checking active leases. +- `serve.rs` sequences authorization, grant consumption, exact-address + connection, request forwarding, and response handling for one connection. + +## Operational constraints + +The proxy binds IPv4 loopback and requires Basic authentication with a random +per-session password. It never resolves destination names; it dials only an +address returned by the host and consumes the matching one-use grant first. +Only absolute `http` proxy requests, CONNECT requests, WebSocket upgrades, +fixed-length uploads, and valid HTTP/1.1 chunked uploads are accepted. Ambiguous +framing, caller-selected transfer encodings, unauthenticated clients, malformed +chunk framing, and bytes following a framed request body are refused. + +HTTPS payloads remain opaque after CONNECT. The proxy checks the lease at least +once per second while uploading, tunneling, or receiving a response, and closes +the connection when validation is denied or fails. Do not add a direct-dial +fallback or locally resolve a host here: destination policy belongs to the +authenticated host callback. From 956342cfccaee50fbc2789eb9b1bbd89e44457cc Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:45:31 +0000 Subject: [PATCH 38/93] refactor(tinycomputer-browser): split linked tests into launch and live modules The launch enforcement and live Chromium egress tests were moved out of the monolithic linked_tests module into dedicated launch_tests and live_tests submodules, leaving the shared test scaffolding behind. The README now points at the egress internals documentation. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/README.md | 3 + .../src/linked/linked_tests.rs | 324 +----------------- .../src/linked/linked_tests/launch_tests.rs | 61 ++++ .../src/linked/linked_tests/live_tests.rs | 275 +++++++++++++++ 4 files changed, 342 insertions(+), 321 deletions(-) create mode 100644 crates/tinycomputer-browser/src/linked/linked_tests/launch_tests.rs create mode 100644 crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs diff --git a/crates/tinycomputer-browser/README.md b/crates/tinycomputer-browser/README.md index ee59a67f0..4ee4cbb59 100644 --- a/crates/tinycomputer-browser/README.md +++ b/crates/tinycomputer-browser/README.md @@ -42,6 +42,9 @@ contents remain opaque to the proxy and require TinySecurity's explicit [`configuration.md`](../../docs/crates/tinycomputer/configuration.md#browser) for the host contract and its privacy behavior. +The proxy internals and request-framing constraints are described in +[`src/egress/README.md`](src/egress/README.md). + The Chromium egress fixture tests are excluded from the default suite because they need an installed browser; run them with `TINYCOMPUTER_LIVE_BROWSER_TESTS=1 cargo test -p tinycomputer-browser --features agent-browser live_`. diff --git a/crates/tinycomputer-browser/src/linked/linked_tests.rs b/crates/tinycomputer-browser/src/linked/linked_tests.rs index a4c46d6cc..06a0d6e0c 100644 --- a/crates/tinycomputer-browser/src/linked/linked_tests.rs +++ b/crates/tinycomputer-browser/src/linked/linked_tests.rs @@ -9,17 +9,7 @@ use serde_json::json; use std::{io, net::SocketAddr, sync::Arc}; -#[cfg(live_browser_tests)] -use std::sync::atomic::{AtomicUsize, Ordering}; -#[cfg(live_browser_tests)] -use tokio::{ - io::{AsyncReadExt, AsyncWriteExt}, - net::TcpListener, -}; - -use super::{ - AgentBrowser, ENGINE, EnforcedAgentBrowser, Linked, enforce_launch_with_config, state_options, -}; +use super::{AgentBrowser, ENGINE, EnforcedAgentBrowser, Linked, state_options}; use crate::{ BrowserDialTarget, DialGrant, EgressAuthorizer, engine::{Engine, Launcher}, @@ -154,314 +144,6 @@ async fn enforced_browser_rechecks_liveness_after_waiting_for_engine_lock() { ); } -#[tokio::test] -#[cfg(live_browser_tests)] -async fn live_chromium_loopback_navigation_uses_the_authenticated_session_proxy() { - let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = fixture.local_addr().unwrap(); - let server = tokio::spawn(async move { - let (mut socket, _) = fixture.accept().await.unwrap(); - let mut request = [0; 4096]; - let _ = socket.read(&mut request).await.unwrap(); - socket - .write_all( - b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 22\r\nConnection: close\r\n\r\n

proxy fixture

", - ) - .await - .unwrap(); - }); - let authorizations = Arc::new(AtomicUsize::new(0)); - let mut browser = EnforcedAgentBrowser::new(Arc::new(RejectAllButFixture { - address, - authorizations: authorizations.clone(), - })) - .open("live-egress"); - let launch = browser - .execute(json!({"id":"launch","action":"launch","headless":true,"args":[]})) - .await; - assert_eq!(launch["success"], true, "{launch}"); - let navigation = browser - .execute(json!({ - "id":"navigate", - "action":"navigate", - "url":format!("http://127.0.0.1:{}/", address.port()) - })) - .await; - browser - .execute(json!({"id":"close","action":"close"})) - .await; - assert_eq!( - navigation["success"], - true, - "{navigation}; proxy authorizations: {}", - authorizations.load(Ordering::SeqCst) - ); - server.await.unwrap(); -} - -#[tokio::test] -#[cfg(live_browser_tests)] -async fn live_chromium_subresource_never_reaches_a_denied_destination() { - let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - denied.set_nonblocking(true).unwrap(); - let denied_address = denied.local_addr().unwrap(); - let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = fixture.local_addr().unwrap(); - let body = format!( - "", - denied_address.port() - ); - let fixture_server = tokio::spawn(async move { - let (mut socket, _) = fixture.accept().await.unwrap(); - let mut request = [0; 4096]; - let _ = socket.read(&mut request).await.unwrap(); - socket - .write_all( - format!( - "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", - body.len(), body - ) - .as_bytes(), - ) - .await - .unwrap(); - }); - let mut browser = EnforcedAgentBrowser::new(Arc::new(RejectAllButFixture { - address, - authorizations: Arc::new(AtomicUsize::new(0)), - })) - .open("live-egress-subresource"); - let launch = browser - .execute(json!({"id":"launch","action":"launch","headless":true,"args":[]})) - .await; - assert_eq!(launch["success"], true, "{launch}"); - let navigation = browser - .execute(json!({ - "id":"navigate", - "action":"navigate", - "url":format!("http://127.0.0.1:{}/", address.port()) - })) - .await; - browser - .execute(json!({"id":"close","action":"close"})) - .await; - assert_eq!(navigation["success"], true, "{navigation}"); - fixture_server.await.unwrap(); - assert_eq!( - denied.accept().unwrap_err().kind(), - io::ErrorKind::WouldBlock, - "the denied subresource destination must never receive a connection" - ); -} - -#[tokio::test] -#[cfg(live_browser_tests)] -async fn live_chromium_redirect_never_reaches_a_denied_destination() { - let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - denied.set_nonblocking(true).unwrap(); - let denied_address = denied.local_addr().unwrap(); - let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = fixture.local_addr().unwrap(); - let fixture_server = tokio::spawn(async move { - let (mut socket, _) = fixture.accept().await.unwrap(); - let mut request = [0; 4096]; - let _ = socket.read(&mut request).await.unwrap(); - socket - .write_all( - format!( - "HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:{}/private\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", - denied_address.port() - ) - .as_bytes(), - ) - .await - .unwrap(); - }); - let mut browser = EnforcedAgentBrowser::new(Arc::new(RejectAllButFixture { - address, - authorizations: Arc::new(AtomicUsize::new(0)), - })) - .open("live-egress-redirect"); - let launch = browser - .execute(json!({"id":"launch","action":"launch","headless":true,"args":[]})) - .await; - assert_eq!(launch["success"], true, "{launch}"); - let navigation = browser - .execute(json!({ - "id":"navigate", - "action":"navigate", - "url":format!("http://127.0.0.1:{}/", address.port()) - })) - .await; - browser - .execute(json!({"id":"close","action":"close"})) - .await; - assert_eq!(navigation["success"], false, "{navigation}"); - fixture_server.await.unwrap(); - assert_eq!( - denied.accept().unwrap_err().kind(), - io::ErrorKind::WouldBlock, - "the denied redirect destination must never receive a connection" - ); -} - -#[tokio::test] +mod launch_tests; #[cfg(live_browser_tests)] -async fn live_chromium_websocket_never_reaches_a_denied_destination() { - let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - denied.set_nonblocking(true).unwrap(); - let denied_address = denied.local_addr().unwrap(); - let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = fixture.local_addr().unwrap(); - let body = format!( - "", - denied_address.port() - ); - let fixture_server = tokio::spawn(async move { - let (mut socket, _) = fixture.accept().await.unwrap(); - let mut request = [0; 4096]; - let _ = socket.read(&mut request).await.unwrap(); - socket - .write_all( - format!( - "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", - body.len(), body - ) - .as_bytes(), - ) - .await - .unwrap(); - }); - let mut browser = EnforcedAgentBrowser::new(Arc::new(RejectAllButFixture { - address, - authorizations: Arc::new(AtomicUsize::new(0)), - })) - .open("live-egress-websocket"); - let launch = browser - .execute(json!({"id":"launch","action":"launch","headless":true,"args":[]})) - .await; - assert_eq!(launch["success"], true, "{launch}"); - let navigation = browser - .execute(json!({ - "id":"navigate", - "action":"navigate", - "url":format!("http://127.0.0.1:{}/", address.port()) - })) - .await; - browser - .execute(json!({"id":"close","action":"close"})) - .await; - assert_eq!(navigation["success"], true, "{navigation}"); - fixture_server.await.unwrap(); - assert_eq!( - denied.accept().unwrap_err().kind(), - io::ErrorKind::WouldBlock, - "the denied WebSocket destination must never receive a connection" - ); -} - -#[cfg(live_browser_tests)] -#[derive(Debug)] -struct RejectAllButFixture { - address: SocketAddr, - authorizations: Arc, -} - -#[cfg(live_browser_tests)] -impl EgressAuthorizer for RejectAllButFixture { - fn authorize( - &self, - target: BrowserDialTarget, - ) -> std::pin::Pin> + Send>> { - let address = self.address; - self.authorizations.fetch_add(1, Ordering::SeqCst); - Box::pin(async move { - if target.hostname == "127.0.0.1" && target.port == address.port() { - Ok(DialGrant { - lease: "live-fixture-lease".into(), - addresses: vec![address], - }) - } else { - Err(io::Error::new(io::ErrorKind::PermissionDenied, "denied")) - } - }) - } - - fn consume( - &self, - _: BrowserDialTarget, - grant: DialGrant, - address: SocketAddr, - ) -> std::pin::Pin> + Send>> { - Box::pin(async move { - if grant.addresses.contains(&address) { - Ok(()) - } else { - Err(io::Error::new(io::ErrorKind::PermissionDenied, "denied")) - } - }) - } - - fn validate( - &self, - _: String, - ) -> std::pin::Pin> + Send>> { - Box::pin(async { Ok(true) }) - } -} - -#[test] -fn enforced_launch_uses_only_the_host_proxy_and_network_containment_flags() { - let launch = enforce_launch_with_config( - json!({"id":"launch","action":"launch","headless":true,"args":[]}), - "http://127.0.0.1:39123", - "session-secret", - false, - ) - .expect("enforced launch"); - assert_eq!(launch["proxy"]["server"], "http://127.0.0.1:39123"); - assert_eq!(launch["proxy"]["bypass"], "<-loopback>"); - assert_eq!(launch["proxy"]["username"], "tinycomputer"); - assert_eq!(launch["proxy"]["password"], "session-secret"); - assert_eq!( - launch["args"], - json!([ - "--disable-quic", - "--disable-http2", - "--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1", - "--force-webrtc-ip-handling-policy=disable_non_proxied_udp" - ]) - ); -} - -#[test] -fn enforced_launch_refuses_external_cdp_and_caller_flags() { - let cdp = enforce_launch_with_config( - json!({"action":"launch","cdpUrl":"http://127.0.0.1:9222"}), - "http://127.0.0.1:39123", - "session-secret", - false, - ); - assert!(cdp.is_err()); - let args = enforce_launch_with_config( - json!({"action":"launch","args":["--proxy-server=http://attacker.test"]}), - "http://127.0.0.1:39123", - "session-secret", - false, - ); - assert!(args.is_err()); - let executable = enforce_launch_with_config( - json!({"action":"launch","executablePath":"/tmp/attacker-browser"}), - "http://127.0.0.1:39123", - "session-secret", - false, - ); - assert!(executable.is_err()); - let ambient = enforce_launch_with_config( - json!({"action":"launch"}), - "http://127.0.0.1:39123", - "session-secret", - true, - ); - assert!(ambient.is_err()); -} +mod live_tests; diff --git a/crates/tinycomputer-browser/src/linked/linked_tests/launch_tests.rs b/crates/tinycomputer-browser/src/linked/linked_tests/launch_tests.rs new file mode 100644 index 000000000..04fc3cdf5 --- /dev/null +++ b/crates/tinycomputer-browser/src/linked/linked_tests/launch_tests.rs @@ -0,0 +1,61 @@ +//! Tests for browser launch command rewriting and policy refusal. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::super::enforce_launch_with_config; +use serde_json::json; + +#[test] +fn enforced_launch_uses_only_the_host_proxy_and_network_containment_flags() { + let launch = enforce_launch_with_config( + json!({"id":"launch","action":"launch","headless":true,"args":[]}), + "http://127.0.0.1:39123", + "session-secret", + false, + ) + .expect("enforced launch"); + assert_eq!(launch["proxy"]["server"], "http://127.0.0.1:39123"); + assert_eq!(launch["proxy"]["bypass"], "<-loopback>"); + assert_eq!(launch["proxy"]["username"], "tinycomputer"); + assert_eq!(launch["proxy"]["password"], "session-secret"); + assert_eq!( + launch["args"], + json!([ + "--disable-quic", + "--disable-http2", + "--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1", + "--force-webrtc-ip-handling-policy=disable_non_proxied_udp" + ]) + ); +} + +#[test] +fn enforced_launch_refuses_external_cdp_and_caller_flags() { + let cdp = enforce_launch_with_config( + json!({"action":"launch","cdpUrl":"http://127.0.0.1:9222"}), + "http://127.0.0.1:39123", + "session-secret", + false, + ); + assert!(cdp.is_err()); + let args = enforce_launch_with_config( + json!({"action":"launch","args":["--proxy-server=http://attacker.test"]}), + "http://127.0.0.1:39123", + "session-secret", + false, + ); + assert!(args.is_err()); + let executable = enforce_launch_with_config( + json!({"action":"launch","executablePath":"/tmp/attacker-browser"}), + "http://127.0.0.1:39123", + "session-secret", + false, + ); + assert!(executable.is_err()); + let ambient = enforce_launch_with_config( + json!({"action":"launch"}), + "http://127.0.0.1:39123", + "session-secret", + true, + ); + assert!(ambient.is_err()); +} diff --git a/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs b/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs new file mode 100644 index 000000000..221679527 --- /dev/null +++ b/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs @@ -0,0 +1,275 @@ +//! Live Chromium egress tests that use local HTTP and WebSocket fixtures. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::RejectAll; +use super::{AgentBrowser, EnforcedAgentBrowser}; +use crate::{BrowserDialTarget, DialGrant, EgressAuthorizer}; +use serde_json::json; +use std::{ + io, + net::SocketAddr, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpListener, +}; + +#[tokio::test] +#[cfg(live_browser_tests)] +async fn live_chromium_loopback_navigation_uses_the_authenticated_session_proxy() { + let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = fixture.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = fixture.accept().await.unwrap(); + let mut request = [0; 4096]; + let _ = socket.read(&mut request).await.unwrap(); + socket + .write_all( + b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 22\r\nConnection: close\r\n\r\n

proxy fixture

", + ) + .await + .unwrap(); + }); + let authorizations = Arc::new(AtomicUsize::new(0)); + let mut browser = EnforcedAgentBrowser::new(Arc::new(RejectAllButFixture { + address, + authorizations: authorizations.clone(), + })) + .open("live-egress"); + let launch = browser + .execute(json!({"id":"launch","action":"launch","headless":true,"args":[]})) + .await; + assert_eq!(launch["success"], true, "{launch}"); + let navigation = browser + .execute(json!({ + "id":"navigate", + "action":"navigate", + "url":format!("http://127.0.0.1:{}/", address.port()) + })) + .await; + browser + .execute(json!({"id":"close","action":"close"})) + .await; + assert_eq!( + navigation["success"], + true, + "{navigation}; proxy authorizations: {}", + authorizations.load(Ordering::SeqCst) + ); + server.await.unwrap(); +} + +#[tokio::test] +#[cfg(live_browser_tests)] +async fn live_chromium_subresource_never_reaches_a_denied_destination() { + let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + denied.set_nonblocking(true).unwrap(); + let denied_address = denied.local_addr().unwrap(); + let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = fixture.local_addr().unwrap(); + let body = format!( + "", + denied_address.port() + ); + let fixture_server = tokio::spawn(async move { + let (mut socket, _) = fixture.accept().await.unwrap(); + let mut request = [0; 4096]; + let _ = socket.read(&mut request).await.unwrap(); + socket + .write_all( + format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), body + ) + .as_bytes(), + ) + .await + .unwrap(); + }); + let mut browser = EnforcedAgentBrowser::new(Arc::new(RejectAllButFixture { + address, + authorizations: Arc::new(AtomicUsize::new(0)), + })) + .open("live-egress-subresource"); + let launch = browser + .execute(json!({"id":"launch","action":"launch","headless":true,"args":[]})) + .await; + assert_eq!(launch["success"], true, "{launch}"); + let navigation = browser + .execute(json!({ + "id":"navigate", + "action":"navigate", + "url":format!("http://127.0.0.1:{}/", address.port()) + })) + .await; + browser + .execute(json!({"id":"close","action":"close"})) + .await; + assert_eq!(navigation["success"], true, "{navigation}"); + fixture_server.await.unwrap(); + assert_eq!( + denied.accept().unwrap_err().kind(), + io::ErrorKind::WouldBlock, + "the denied subresource destination must never receive a connection" + ); +} + +#[tokio::test] +#[cfg(live_browser_tests)] +async fn live_chromium_redirect_never_reaches_a_denied_destination() { + let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + denied.set_nonblocking(true).unwrap(); + let denied_address = denied.local_addr().unwrap(); + let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = fixture.local_addr().unwrap(); + let fixture_server = tokio::spawn(async move { + let (mut socket, _) = fixture.accept().await.unwrap(); + let mut request = [0; 4096]; + let _ = socket.read(&mut request).await.unwrap(); + socket + .write_all( + format!( + "HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:{}/private\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + denied_address.port() + ) + .as_bytes(), + ) + .await + .unwrap(); + }); + let mut browser = EnforcedAgentBrowser::new(Arc::new(RejectAllButFixture { + address, + authorizations: Arc::new(AtomicUsize::new(0)), + })) + .open("live-egress-redirect"); + let launch = browser + .execute(json!({"id":"launch","action":"launch","headless":true,"args":[]})) + .await; + assert_eq!(launch["success"], true, "{launch}"); + let navigation = browser + .execute(json!({ + "id":"navigate", + "action":"navigate", + "url":format!("http://127.0.0.1:{}/", address.port()) + })) + .await; + browser + .execute(json!({"id":"close","action":"close"})) + .await; + assert_eq!(navigation["success"], false, "{navigation}"); + fixture_server.await.unwrap(); + assert_eq!( + denied.accept().unwrap_err().kind(), + io::ErrorKind::WouldBlock, + "the denied redirect destination must never receive a connection" + ); +} + +#[tokio::test] +#[cfg(live_browser_tests)] +async fn live_chromium_websocket_never_reaches_a_denied_destination() { + let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + denied.set_nonblocking(true).unwrap(); + let denied_address = denied.local_addr().unwrap(); + let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = fixture.local_addr().unwrap(); + let body = format!( + "", + denied_address.port() + ); + let fixture_server = tokio::spawn(async move { + let (mut socket, _) = fixture.accept().await.unwrap(); + let mut request = [0; 4096]; + let _ = socket.read(&mut request).await.unwrap(); + socket + .write_all( + format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), body + ) + .as_bytes(), + ) + .await + .unwrap(); + }); + let mut browser = EnforcedAgentBrowser::new(Arc::new(RejectAllButFixture { + address, + authorizations: Arc::new(AtomicUsize::new(0)), + })) + .open("live-egress-websocket"); + let launch = browser + .execute(json!({"id":"launch","action":"launch","headless":true,"args":[]})) + .await; + assert_eq!(launch["success"], true, "{launch}"); + let navigation = browser + .execute(json!({ + "id":"navigate", + "action":"navigate", + "url":format!("http://127.0.0.1:{}/", address.port()) + })) + .await; + browser + .execute(json!({"id":"close","action":"close"})) + .await; + assert_eq!(navigation["success"], true, "{navigation}"); + fixture_server.await.unwrap(); + assert_eq!( + denied.accept().unwrap_err().kind(), + io::ErrorKind::WouldBlock, + "the denied WebSocket destination must never receive a connection" + ); +} + +#[cfg(live_browser_tests)] +#[derive(Debug)] +struct RejectAllButFixture { + address: SocketAddr, + authorizations: Arc, +} + +#[cfg(live_browser_tests)] +impl EgressAuthorizer for RejectAllButFixture { + fn authorize( + &self, + target: BrowserDialTarget, + ) -> std::pin::Pin> + Send>> { + let address = self.address; + self.authorizations.fetch_add(1, Ordering::SeqCst); + Box::pin(async move { + if target.hostname == "127.0.0.1" && target.port == address.port() { + Ok(DialGrant { + lease: "live-fixture-lease".into(), + addresses: vec![address], + }) + } else { + Err(io::Error::new(io::ErrorKind::PermissionDenied, "denied")) + } + }) + } + + fn consume( + &self, + _: BrowserDialTarget, + grant: DialGrant, + address: SocketAddr, + ) -> std::pin::Pin> + Send>> { + Box::pin(async move { + if grant.addresses.contains(&address) { + Ok(()) + } else { + Err(io::Error::new(io::ErrorKind::PermissionDenied, "denied")) + } + }) + } + + fn validate( + &self, + _: String, + ) -> std::pin::Pin> + Send>> { + Box::pin(async { Ok(true) }) + } +} From b6a757c6894b26b72a5c2a9c5f98c4c2a2b745ec Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:45:42 +0000 Subject: [PATCH 39/93] refactor(egress): extract chunked request body handling The logic for forwarding chunked request bodies has been extracted into a new module and function for better organization. This separates the complex chunked body parsing from the main request reading flow. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress/request.rs | 172 +----------------- .../src/egress/request/chunked.rs | 170 +++++++++++++++++ 2 files changed, 178 insertions(+), 164 deletions(-) create mode 100644 crates/tinycomputer-browser/src/egress/request/chunked.rs diff --git a/crates/tinycomputer-browser/src/egress/request.rs b/crates/tinycomputer-browser/src/egress/request.rs index e1fb310d4..cca32dafa 100644 --- a/crates/tinycomputer-browser/src/egress/request.rs +++ b/crates/tinycomputer-browser/src/egress/request.rs @@ -2,6 +2,8 @@ use std::{io, time::Duration}; +mod chunked; + use base64::Engine as _; use tokio::{io::AsyncReadExt, net::TcpStream}; @@ -247,8 +249,12 @@ pub(super) async fn read_request_body( return Ok(()); } if request.chunked { - return forward_chunked_request_body(client, upstream, &request.bytes[request.split..]) - .await; + return chunked::forward_chunked_request_body( + client, + upstream, + &request.bytes[request.split..], + ) + .await; } let mut chunk = [0u8; 1024]; while received < request.body_len { @@ -274,168 +280,6 @@ pub(super) async fn read_request_body( Ok(()) } -async fn forward_chunked_request_body( - client: &mut TcpStream, - upstream: &mut TcpStream, - initial: &[u8], -) -> io::Result<()> { - let mut pending = initial.to_vec(); - let mut offset = 0; - let mut trailer_bytes = 0; - loop { - let line = read_chunk_line(client, &mut pending, &mut offset).await?; - let size_text = std::str::from_utf8(&line[..line.len() - 2]) - .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid chunk size"))?; - let size_text = size_text.split(';').next().unwrap_or_default(); - if size_text.is_empty() || !size_text.bytes().all(|byte| byte.is_ascii_hexdigit()) { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "invalid chunk size", - )); - } - let size = usize::from_str_radix(size_text, 16) - .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid chunk size"))?; - write_all_bounded(upstream, &line, "browser upstream body timed out").await?; - if size == 0 { - loop { - let trailer = read_chunk_line(client, &mut pending, &mut offset).await?; - trailer_bytes += trailer.len(); - let trailer_line = &trailer[..trailer.len() - 2]; - let forbidden_trailer = std::str::from_utf8(trailer_line) - .ok() - .and_then(|line| line.split_once(':')) - .is_some_and(|(name, _)| { - name.is_empty() - || name.eq_ignore_ascii_case("content-length") - || name.eq_ignore_ascii_case("transfer-encoding") - || name.eq_ignore_ascii_case("host") - }); - if trailer_bytes > 32 * 1024 - || (trailer != b"\r\n" && (!trailer_line.contains(&b':') || forbidden_trailer)) - { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "invalid chunk trailer", - )); - } - write_all_bounded(upstream, &trailer, "browser upstream body timed out").await?; - if trailer == b"\r\n" { - if offset != pending.len() { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "bytes after chunked request body", - )); - } - return Ok(()); - } - } - } - let mut remaining = size; - let mut chunk = [0u8; 8192]; - while remaining > 0 { - let buffered = pending.len().saturating_sub(offset); - let n = if buffered > 0 { - let n = buffered.min(remaining).min(chunk.len()); - chunk[..n].copy_from_slice(&pending[offset..offset + n]); - offset += n; - n - } else { - let read_length = remaining.min(chunk.len()); - let n = tokio::time::timeout( - Duration::from_secs(10), - client.read(&mut chunk[..read_length]), - ) - .await - .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy body timed out"))??; - if n == 0 { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "browser request body ended early", - )); - } - n - }; - write_all_bounded(upstream, &chunk[..n], "browser upstream body timed out").await?; - remaining -= n; - } - let ending = read_body_bytes(client, &mut pending, &mut offset, 2).await?; - if ending != b"\r\n" { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "invalid chunk ending", - )); - } - write_all_bounded(upstream, &ending, "browser upstream body timed out").await?; - } -} - -async fn read_chunk_line( - client: &mut TcpStream, - pending: &mut Vec, - offset: &mut usize, -) -> io::Result> { - loop { - if let Some(end) = pending[*offset..] - .windows(2) - .position(|window| window == b"\r\n") - { - let end = *offset + end + 2; - let line = pending[*offset..end].to_vec(); - *offset = end; - return Ok(line); - } - if pending.len().saturating_sub(*offset) > 8192 { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "chunk line is too long", - )); - } - if *offset > 8192 { - pending.drain(..*offset); - *offset = 0; - } - let mut chunk = [0u8; 1024]; - let n = tokio::time::timeout(Duration::from_secs(10), client.read(&mut chunk)) - .await - .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy body timed out"))??; - if n == 0 { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "browser request body ended early", - )); - } - pending.extend_from_slice(&chunk[..n]); - } -} - -async fn read_body_bytes( - client: &mut TcpStream, - pending: &mut Vec, - offset: &mut usize, - length: usize, -) -> io::Result> { - while pending.len().saturating_sub(*offset) < length { - if *offset > 8192 { - pending.drain(..*offset); - *offset = 0; - } - let mut chunk = [0u8; 1024]; - let n = tokio::time::timeout(Duration::from_secs(10), client.read(&mut chunk)) - .await - .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy body timed out"))??; - if n == 0 { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "browser request body ended early", - )); - } - pending.extend_from_slice(&chunk[..n]); - } - let end = *offset + length; - let bytes = pending[*offset..end].to_vec(); - *offset = end; - Ok(bytes) -} pub(crate) fn parse_authority( value: &str, scheme: &str, diff --git a/crates/tinycomputer-browser/src/egress/request/chunked.rs b/crates/tinycomputer-browser/src/egress/request/chunked.rs new file mode 100644 index 000000000..aad09d54a --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/request/chunked.rs @@ -0,0 +1,170 @@ +//! Bounded HTTP/1.1 chunk framing validation and forwarding. + +use std::{io, time::Duration}; + +use tokio::{io::AsyncReadExt, net::TcpStream}; + +use crate::egress::forward::write_all_bounded; + +pub(super) async fn forward_chunked_request_body( + client: &mut TcpStream, + upstream: &mut TcpStream, + initial: &[u8], +) -> io::Result<()> { + let mut pending = initial.to_vec(); + let mut offset = 0; + let mut trailer_bytes = 0; + loop { + let line = read_chunk_line(client, &mut pending, &mut offset).await?; + let size_text = std::str::from_utf8(&line[..line.len() - 2]) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid chunk size"))?; + let size_text = size_text.split(';').next().unwrap_or_default(); + if size_text.is_empty() || !size_text.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid chunk size", + )); + } + let size = usize::from_str_radix(size_text, 16) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid chunk size"))?; + write_all_bounded(upstream, &line, "browser upstream body timed out").await?; + if size == 0 { + loop { + let trailer = read_chunk_line(client, &mut pending, &mut offset).await?; + trailer_bytes += trailer.len(); + let trailer_line = &trailer[..trailer.len() - 2]; + let forbidden_trailer = std::str::from_utf8(trailer_line) + .ok() + .and_then(|line| line.split_once(':')) + .is_some_and(|(name, _)| { + name.is_empty() + || name.eq_ignore_ascii_case("content-length") + || name.eq_ignore_ascii_case("transfer-encoding") + || name.eq_ignore_ascii_case("host") + }); + if trailer_bytes > 32 * 1024 + || (trailer != b"\r\n" && (!trailer_line.contains(&b':') || forbidden_trailer)) + { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid chunk trailer", + )); + } + write_all_bounded(upstream, &trailer, "browser upstream body timed out").await?; + if trailer == b"\r\n" { + if offset != pending.len() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "bytes after chunked request body", + )); + } + return Ok(()); + } + } + } + let mut remaining = size; + let mut chunk = [0u8; 8192]; + while remaining > 0 { + let buffered = pending.len().saturating_sub(offset); + let n = if buffered > 0 { + let n = buffered.min(remaining).min(chunk.len()); + chunk[..n].copy_from_slice(&pending[offset..offset + n]); + offset += n; + n + } else { + let read_length = remaining.min(chunk.len()); + let n = tokio::time::timeout( + Duration::from_secs(10), + client.read(&mut chunk[..read_length]), + ) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy body timed out"))??; + if n == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "browser request body ended early", + )); + } + n + }; + write_all_bounded(upstream, &chunk[..n], "browser upstream body timed out").await?; + remaining -= n; + } + let ending = read_body_bytes(client, &mut pending, &mut offset, 2).await?; + if ending != b"\r\n" { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid chunk ending", + )); + } + write_all_bounded(upstream, &ending, "browser upstream body timed out").await?; + } +} + +async fn read_chunk_line( + client: &mut TcpStream, + pending: &mut Vec, + offset: &mut usize, +) -> io::Result> { + loop { + if let Some(end) = pending[*offset..] + .windows(2) + .position(|window| window == b"\r\n") + { + let end = *offset + end + 2; + let line = pending[*offset..end].to_vec(); + *offset = end; + return Ok(line); + } + if pending.len().saturating_sub(*offset) > 8192 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "chunk line is too long", + )); + } + if *offset > 8192 { + pending.drain(..*offset); + *offset = 0; + } + let mut chunk = [0u8; 1024]; + let n = tokio::time::timeout(Duration::from_secs(10), client.read(&mut chunk)) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy body timed out"))??; + if n == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "browser request body ended early", + )); + } + pending.extend_from_slice(&chunk[..n]); + } +} + +async fn read_body_bytes( + client: &mut TcpStream, + pending: &mut Vec, + offset: &mut usize, + length: usize, +) -> io::Result> { + while pending.len().saturating_sub(*offset) < length { + if *offset > 8192 { + pending.drain(..*offset); + *offset = 0; + } + let mut chunk = [0u8; 1024]; + let n = tokio::time::timeout(Duration::from_secs(10), client.read(&mut chunk)) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy body timed out"))??; + if n == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "browser request body ended early", + )); + } + pending.extend_from_slice(&chunk[..n]); + } + let end = *offset + length; + let bytes = pending[*offset..end].to_vec(); + *offset = end; + Ok(bytes) +} From 22e42b583c1c0a85b0924343a009468bd171e890 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:47:29 +0000 Subject: [PATCH 40/93] refactor(egress): genericize forwarding over async read and write The egress forwarding helpers now accept any AsyncRead or AsyncWrite stream instead of concrete TcpStreams, so the same code can serve non-TCP transports and be exercised with in-memory test doubles. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress/forward.rs | 28 ++++++++++++------- .../src/egress/request.rs | 12 +++++--- .../src/egress/request/chunked.rs | 22 +++++++++------ 3 files changed, 39 insertions(+), 23 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/forward.rs b/crates/tinycomputer-browser/src/egress/forward.rs index 0bd884606..be170214b 100644 --- a/crates/tinycomputer-browser/src/egress/forward.rs +++ b/crates/tinycomputer-browser/src/egress/forward.rs @@ -110,12 +110,16 @@ pub(super) async fn tunnel_with_lease( } } -pub(super) async fn forward_response_with_lease( - client: &mut TcpStream, - upstream: &mut TcpStream, +pub(super) async fn forward_response_with_lease( + client: &mut C, + upstream: &mut U, auth: &Arc, lease: String, -) -> io::Result<()> { +) -> io::Result<()> +where + C: tokio::io::AsyncWrite + Unpin, + U: tokio::io::AsyncRead + Unpin, +{ let mut chunk = [0u8; 8192]; let mut validations = validation_interval(); loop { @@ -133,13 +137,17 @@ pub(super) async fn forward_response_with_lease( } } -pub(super) async fn forward_request_body_with_lease( - client: &mut TcpStream, - upstream: &mut TcpStream, +pub(super) async fn forward_request_body_with_lease( + client: &mut C, + upstream: &mut U, request: &ProxyRequest, auth: &Arc, lease: &str, -) -> io::Result { +) -> io::Result +where + C: tokio::io::AsyncRead + Unpin, + U: tokio::io::AsyncWrite + Unpin, +{ let body = read_request_body(client, upstream, request, buffered_body_len(request)); tokio::pin!(body); let mut validations = validation_interval(); @@ -183,8 +191,8 @@ pub(super) async fn refuse(client: &mut TcpStream) -> io::Result<()> { .await } -pub(super) async fn write_all_bounded( - stream: &mut TcpStream, +pub(super) async fn write_all_bounded( + stream: &mut W, bytes: &[u8], message: &'static str, ) -> io::Result<()> { diff --git a/crates/tinycomputer-browser/src/egress/request.rs b/crates/tinycomputer-browser/src/egress/request.rs index cca32dafa..07de55d59 100644 --- a/crates/tinycomputer-browser/src/egress/request.rs +++ b/crates/tinycomputer-browser/src/egress/request.rs @@ -239,12 +239,16 @@ pub(super) fn buffered_body_len(request: &ProxyRequest) -> usize { } } -pub(super) async fn read_request_body( - client: &mut TcpStream, - upstream: &mut TcpStream, +pub(super) async fn read_request_body( + client: &mut C, + upstream: &mut U, request: &ProxyRequest, mut received: usize, -) -> io::Result<()> { +) -> io::Result<()> +where + C: tokio::io::AsyncRead + Unpin, + U: tokio::io::AsyncWrite + Unpin, +{ if request.has_upgrade || request.connect { return Ok(()); } diff --git a/crates/tinycomputer-browser/src/egress/request/chunked.rs b/crates/tinycomputer-browser/src/egress/request/chunked.rs index aad09d54a..413505a72 100644 --- a/crates/tinycomputer-browser/src/egress/request/chunked.rs +++ b/crates/tinycomputer-browser/src/egress/request/chunked.rs @@ -2,15 +2,19 @@ use std::{io, time::Duration}; -use tokio::{io::AsyncReadExt, net::TcpStream}; +use tokio::io::AsyncReadExt; use crate::egress::forward::write_all_bounded; -pub(super) async fn forward_chunked_request_body( - client: &mut TcpStream, - upstream: &mut TcpStream, +pub(super) async fn forward_chunked_request_body( + client: &mut C, + upstream: &mut U, initial: &[u8], -) -> io::Result<()> { +) -> io::Result<()> +where + C: tokio::io::AsyncRead + Unpin, + U: tokio::io::AsyncWrite + Unpin, +{ let mut pending = initial.to_vec(); let mut offset = 0; let mut trailer_bytes = 0; @@ -101,8 +105,8 @@ pub(super) async fn forward_chunked_request_body( } } -async fn read_chunk_line( - client: &mut TcpStream, +async fn read_chunk_line( + client: &mut C, pending: &mut Vec, offset: &mut usize, ) -> io::Result> { @@ -140,8 +144,8 @@ async fn read_chunk_line( } } -async fn read_body_bytes( - client: &mut TcpStream, +async fn read_body_bytes( + client: &mut C, pending: &mut Vec, offset: &mut usize, length: usize, From c763e13a5f5b4405ab9790278826b173e659d3a4 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:48:05 +0000 Subject: [PATCH 41/93] fix(egress): forward early upstream responses during uploads The non-tunnel path now splits the client and upstream streams and races the request upload against the response read, so an upstream rejection such as a 413 reaches the browser without waiting for a large body to finish uploading. A test covers the early-rejection case. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinycomputer-browser/src/egress/serve.rs | 30 +++++++-- .../src/egress_tests/http_tests.rs | 62 +++++++++++++++++++ 2 files changed, 87 insertions(+), 5 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index 450495d90..bd2782d6d 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -68,12 +68,32 @@ pub(super) async fn serve( if request.connect || request.has_upgrade { tunnel_with_lease(&mut client, &mut upstream, &auth, lease).await?; } else { - if !forward_request_body_with_lease(&mut client, &mut upstream, &request, &auth, &lease) - .await? - { - return Ok(()); + let (mut client_reader, mut client_writer) = client.into_split(); + let (mut upstream_reader, mut upstream_writer) = upstream.into_split(); + tokio::select! { + result = forward_response_with_lease( + &mut client_writer, + &mut upstream_reader, + &auth, + lease.clone(), + ) => result?, + upload = forward_request_body_with_lease( + &mut client_reader, + &mut upstream_writer, + &request, + &auth, + &lease, + ) => { + if upload? { + forward_response_with_lease( + &mut client_writer, + &mut upstream_reader, + &auth, + lease, + ).await?; + } + } } - forward_response_with_lease(&mut client, &mut upstream, &auth, lease).await?; } Ok(()) } diff --git a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs index e7eb33584..f0aa3d99a 100644 --- a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs @@ -344,6 +344,68 @@ async fn approved_http_request_forwards_chunked_uploads() { server.await.unwrap(); } +#[tokio::test] +async fn an_early_upstream_rejection_is_forwarded_before_upload_completion() { + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 1024]; + while !request.windows(4).any(|window| window == b"\r\n\r\n") { + let n = socket.read(&mut chunk).await.unwrap(); + assert_ne!(n, 0); + request.extend_from_slice(&chunk[..n]); + } + socket + .write_all( + b"HTTP/1.1 413 Payload Too Large\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ) + .await + .unwrap(); + }); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }), + "early-rejection-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "POST http://body.test:{}/upload HTTP/1.1\r\nHost: body.test:{}\r\nProxy-Authorization: {}\r\nContent-Length: 10485760\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = Vec::new(); + tokio::time::timeout( + std::time::Duration::from_secs(2), + client.read_to_end(&mut response), + ) + .await + .expect("the early upstream response should reach the browser") + .unwrap(); + assert!( + std::str::from_utf8(&response) + .unwrap() + .starts_with("HTTP/1.1 413") + ); + server.await.unwrap(); +} + #[tokio::test] async fn duplicate_lengths_and_pipelined_authorities_are_refused_before_dial() { let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); From 43be533b5288a217f93979e2df73a1dfef39b932 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:48:44 +0000 Subject: [PATCH 42/93] test(egress): move request body tests into their own module The body forwarding, large upload, chunked upload, and early rejection tests were extracted from the HTTP test module into a dedicated body_tests module and registered in the egress test tree. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinycomputer-browser/src/egress_tests.rs | 2 + .../src/egress_tests/body_tests.rs | 256 ++++++++++++++++++ .../src/egress_tests/http_tests.rs | 247 ----------------- 3 files changed, 258 insertions(+), 247 deletions(-) create mode 100644 crates/tinycomputer-browser/src/egress_tests/body_tests.rs diff --git a/crates/tinycomputer-browser/src/egress_tests.rs b/crates/tinycomputer-browser/src/egress_tests.rs index 2e48d981b..864ffd19c 100644 --- a/crates/tinycomputer-browser/src/egress_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests.rs @@ -4,6 +4,8 @@ #[path = "egress_tests/authority_tests.rs"] mod authority_tests; +#[path = "egress_tests/body_tests.rs"] +mod body_tests; #[path = "egress_tests/connect_tests.rs"] mod connect_tests; #[path = "egress_tests/http_tests.rs"] diff --git a/crates/tinycomputer-browser/src/egress_tests/body_tests.rs b/crates/tinycomputer-browser/src/egress_tests/body_tests.rs new file mode 100644 index 000000000..796d4c556 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress_tests/body_tests.rs @@ -0,0 +1,256 @@ +//! Fixed-length and chunked HTTP upload forwarding tests. + +use super::simulator::*; +use crate::EgressProxy; +use std::sync::{Arc, atomic::AtomicBool}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, +}; + +#[tokio::test] +async fn approved_http_request_body_is_forwarded_without_framing_changes() { + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 512]; + loop { + let n = socket.read(&mut chunk).await.unwrap(); + request.extend_from_slice(&chunk[..n]); + if let Some(split) = request.windows(4).position(|window| window == b"\r\n\r\n") + && request.len() >= split + 8 + { + break; + } + } + assert!(request.ends_with(b"data")); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + .await + .unwrap(); + }); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }), + "body-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "POST http://body.test:{}/submit HTTP/1.1\r\nHost: body.test:{}\r\nProxy-Authorization: {}\r\nContent-Length: 4\r\n\r\ndata", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = Vec::new(); + client.read_to_end(&mut response).await.unwrap(); + assert!( + std::str::from_utf8(&response) + .unwrap() + .ends_with("\r\n\r\nok") + ); + server.await.unwrap(); +} + +#[tokio::test] +async fn approved_http_request_streams_bodies_larger_than_one_mibibyte() { + const BODY_LENGTH: usize = 1536 * 1024; + let expected_body = vec![b'x'; BODY_LENGTH]; + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 8192]; + let split = loop { + let n = socket.read(&mut chunk).await.unwrap(); + assert_ne!(n, 0); + request.extend_from_slice(&chunk[..n]); + if let Some(split) = request.windows(4).position(|window| window == b"\r\n\r\n") { + break split + 4; + } + }; + let mut body = request.split_off(split); + let received = body.len(); + assert!(received <= BODY_LENGTH); + body.resize(BODY_LENGTH, 0); + if received < BODY_LENGTH { + socket.read_exact(&mut body[received..]).await.unwrap(); + } + assert_eq!(body, vec![b'x'; BODY_LENGTH]); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + .await + .unwrap(); + }); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }), + "large-body-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "POST http://body.test:{}/upload HTTP/1.1\r\nHost: body.test:{}\r\nProxy-Authorization: {}\r\nContent-Length: {BODY_LENGTH}\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + client.write_all(&expected_body).await.unwrap(); + let mut response = Vec::new(); + client.read_to_end(&mut response).await.unwrap(); + assert!( + std::str::from_utf8(&response) + .unwrap() + .ends_with("\r\n\r\nok") + ); + server.await.unwrap(); +} + +#[tokio::test] +async fn approved_http_request_forwards_chunked_uploads() { + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 1024]; + loop { + let n = socket.read(&mut chunk).await.unwrap(); + assert_ne!(n, 0); + request.extend_from_slice(&chunk[..n]); + if request.windows(5).any(|window| window == b"0\r\n\r\n") { + break; + } + } + assert!(request.windows(7).any(|window| window == b"4\r\ndata")); + socket + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + .await + .unwrap(); + }); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }), + "chunked-body-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "POST http://body.test:{}/stream HTTP/1.1\r\nHost: body.test:{}\r\nProxy-Authorization: {}\r\nTransfer-Encoding: chunked\r\n\r\n4\r\ndata\r\n0\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = Vec::new(); + client.read_to_end(&mut response).await.unwrap(); + assert!( + std::str::from_utf8(&response) + .unwrap() + .ends_with("\r\n\r\nok") + ); + server.await.unwrap(); +} + +#[tokio::test] +async fn an_early_upstream_rejection_is_forwarded_before_upload_completion() { + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 1024]; + while !request.windows(4).any(|window| window == b"\r\n\r\n") { + let n = socket.read(&mut chunk).await.unwrap(); + assert_ne!(n, 0); + request.extend_from_slice(&chunk[..n]); + } + socket + .write_all( + b"HTTP/1.1 413 Payload Too Large\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ) + .await + .unwrap(); + }); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }), + "early-rejection-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "POST http://body.test:{}/upload HTTP/1.1\r\nHost: body.test:{}\r\nProxy-Authorization: {}\r\nContent-Length: 10485760\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let mut response = Vec::new(); + tokio::time::timeout( + std::time::Duration::from_secs(2), + client.read_to_end(&mut response), + ) + .await + .expect("the early upstream response should reach the browser") + .unwrap(); + assert!( + std::str::from_utf8(&response) + .unwrap() + .starts_with("HTTP/1.1 413") + ); + server.await.unwrap(); +} diff --git a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs index f0aa3d99a..575451b22 100644 --- a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/http_tests.rs @@ -159,253 +159,6 @@ async fn approved_http_request_is_rewritten_and_forwarded_to_approved_fixture() server.await.unwrap(); } -#[tokio::test] -async fn approved_http_request_body_is_forwarded_without_framing_changes() { - let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = destination.local_addr().unwrap(); - let server = tokio::spawn(async move { - let (mut socket, _) = destination.accept().await.unwrap(); - let mut request = Vec::new(); - let mut chunk = [0; 512]; - loop { - let n = socket.read(&mut chunk).await.unwrap(); - request.extend_from_slice(&chunk[..n]); - if let Some(split) = request.windows(4).position(|window| window == b"\r\n\r\n") - && request.len() >= split + 8 - { - break; - } - } - assert!(request.ends_with(b"data")); - socket - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") - .await - .unwrap(); - }); - let proxy = EgressProxy::bind( - Arc::new(FixtureAuthorizer { - address, - allow: true, - consumed: Arc::new(AtomicBool::new(false)), - }), - "body-session".into(), - FIXTURE_PASSWORD.into(), - ) - .await - .unwrap(); - let mut client = TcpStream::connect(proxy.url().replace("http://", "")) - .await - .unwrap(); - client - .write_all( - format!( - "POST http://body.test:{}/submit HTTP/1.1\r\nHost: body.test:{}\r\nProxy-Authorization: {}\r\nContent-Length: 4\r\n\r\ndata", - address.port(), - address.port(), - proxy_authorization() - ) - .as_bytes(), - ) - .await - .unwrap(); - let mut response = Vec::new(); - client.read_to_end(&mut response).await.unwrap(); - assert!( - std::str::from_utf8(&response) - .unwrap() - .ends_with("\r\n\r\nok") - ); - server.await.unwrap(); -} - -#[tokio::test] -async fn approved_http_request_streams_bodies_larger_than_one_mibibyte() { - const BODY_LENGTH: usize = 1536 * 1024; - let expected_body = vec![b'x'; BODY_LENGTH]; - let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = destination.local_addr().unwrap(); - let server = tokio::spawn(async move { - let (mut socket, _) = destination.accept().await.unwrap(); - let mut request = Vec::new(); - let mut chunk = [0; 8192]; - let split = loop { - let n = socket.read(&mut chunk).await.unwrap(); - assert_ne!(n, 0); - request.extend_from_slice(&chunk[..n]); - if let Some(split) = request.windows(4).position(|window| window == b"\r\n\r\n") { - break split + 4; - } - }; - let mut body = request.split_off(split); - let received = body.len(); - assert!(received <= BODY_LENGTH); - body.resize(BODY_LENGTH, 0); - if received < BODY_LENGTH { - socket.read_exact(&mut body[received..]).await.unwrap(); - } - assert_eq!(body, vec![b'x'; BODY_LENGTH]); - socket - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") - .await - .unwrap(); - }); - let proxy = EgressProxy::bind( - Arc::new(FixtureAuthorizer { - address, - allow: true, - consumed: Arc::new(AtomicBool::new(false)), - }), - "large-body-session".into(), - FIXTURE_PASSWORD.into(), - ) - .await - .unwrap(); - let mut client = TcpStream::connect(proxy.url().replace("http://", "")) - .await - .unwrap(); - client - .write_all( - format!( - "POST http://body.test:{}/upload HTTP/1.1\r\nHost: body.test:{}\r\nProxy-Authorization: {}\r\nContent-Length: {BODY_LENGTH}\r\n\r\n", - address.port(), - address.port(), - proxy_authorization() - ) - .as_bytes(), - ) - .await - .unwrap(); - client.write_all(&expected_body).await.unwrap(); - let mut response = Vec::new(); - client.read_to_end(&mut response).await.unwrap(); - assert!( - std::str::from_utf8(&response) - .unwrap() - .ends_with("\r\n\r\nok") - ); - server.await.unwrap(); -} - -#[tokio::test] -async fn approved_http_request_forwards_chunked_uploads() { - let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = destination.local_addr().unwrap(); - let server = tokio::spawn(async move { - let (mut socket, _) = destination.accept().await.unwrap(); - let mut request = Vec::new(); - let mut chunk = [0; 1024]; - loop { - let n = socket.read(&mut chunk).await.unwrap(); - assert_ne!(n, 0); - request.extend_from_slice(&chunk[..n]); - if request.windows(5).any(|window| window == b"0\r\n\r\n") { - break; - } - } - assert!(request.windows(7).any(|window| window == b"4\r\ndata")); - socket - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") - .await - .unwrap(); - }); - let proxy = EgressProxy::bind( - Arc::new(FixtureAuthorizer { - address, - allow: true, - consumed: Arc::new(AtomicBool::new(false)), - }), - "chunked-body-session".into(), - FIXTURE_PASSWORD.into(), - ) - .await - .unwrap(); - let mut client = TcpStream::connect(proxy.url().replace("http://", "")) - .await - .unwrap(); - client - .write_all( - format!( - "POST http://body.test:{}/stream HTTP/1.1\r\nHost: body.test:{}\r\nProxy-Authorization: {}\r\nTransfer-Encoding: chunked\r\n\r\n4\r\ndata\r\n0\r\n\r\n", - address.port(), - address.port(), - proxy_authorization() - ) - .as_bytes(), - ) - .await - .unwrap(); - let mut response = Vec::new(); - client.read_to_end(&mut response).await.unwrap(); - assert!( - std::str::from_utf8(&response) - .unwrap() - .ends_with("\r\n\r\nok") - ); - server.await.unwrap(); -} - -#[tokio::test] -async fn an_early_upstream_rejection_is_forwarded_before_upload_completion() { - let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = destination.local_addr().unwrap(); - let server = tokio::spawn(async move { - let (mut socket, _) = destination.accept().await.unwrap(); - let mut request = Vec::new(); - let mut chunk = [0; 1024]; - while !request.windows(4).any(|window| window == b"\r\n\r\n") { - let n = socket.read(&mut chunk).await.unwrap(); - assert_ne!(n, 0); - request.extend_from_slice(&chunk[..n]); - } - socket - .write_all( - b"HTTP/1.1 413 Payload Too Large\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", - ) - .await - .unwrap(); - }); - let proxy = EgressProxy::bind( - Arc::new(FixtureAuthorizer { - address, - allow: true, - consumed: Arc::new(AtomicBool::new(false)), - }), - "early-rejection-session".into(), - FIXTURE_PASSWORD.into(), - ) - .await - .unwrap(); - let mut client = TcpStream::connect(proxy.url().replace("http://", "")) - .await - .unwrap(); - client - .write_all( - format!( - "POST http://body.test:{}/upload HTTP/1.1\r\nHost: body.test:{}\r\nProxy-Authorization: {}\r\nContent-Length: 10485760\r\n\r\n", - address.port(), - address.port(), - proxy_authorization() - ) - .as_bytes(), - ) - .await - .unwrap(); - let mut response = Vec::new(); - tokio::time::timeout( - std::time::Duration::from_secs(2), - client.read_to_end(&mut response), - ) - .await - .expect("the early upstream response should reach the browser") - .unwrap(); - assert!( - std::str::from_utf8(&response) - .unwrap() - .starts_with("HTTP/1.1 413") - ); - server.await.unwrap(); -} - #[tokio::test] async fn duplicate_lengths_and_pipelined_authorities_are_refused_before_dial() { let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); From c51b452e12e415172ff7ccab2eb942f822ae42ca Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:49:23 +0000 Subject: [PATCH 43/93] refactor(egress): box the serve future before spawning The spawned connection task now pins the serve future on the heap before awaiting it, keeping the task's future size bounded. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/mod.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/tinycomputer-browser/src/egress/mod.rs b/crates/tinycomputer-browser/src/egress/mod.rs index af00ec15c..29c824daf 100644 --- a/crates/tinycomputer-browser/src/egress/mod.rs +++ b/crates/tinycomputer-browser/src/egress/mod.rs @@ -97,7 +97,9 @@ impl EgressProxy { let auth = authorizer.clone(); let session = session_id.clone(); let password = proxy_password.clone(); - connections.spawn(async move { let _ = serve::serve(stream, auth, session, password).await; }); + connections.spawn(async move { + let _ = Box::pin(serve::serve(stream, auth, session, password)).await; + }); } _ = connections.join_next(), if !connections.is_empty() => {} } From dbcd931d2e9bb4b5adef6827b25ad0476b0a5787 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:50:15 +0000 Subject: [PATCH 44/93] test(linked): update live test imports Replace the RejectAll and AgentBrowser imports with EnforcedAgentBrowser and the engine Launcher so the live egress tests reference the current types. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/linked/linked_tests/live_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs b/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs index 221679527..82afba153 100644 --- a/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs +++ b/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs @@ -1,8 +1,8 @@ //! Live Chromium egress tests that use local HTTP and WebSocket fixtures. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -use super::RejectAll; -use super::{AgentBrowser, EnforcedAgentBrowser}; +use super::EnforcedAgentBrowser; +use crate::engine::Launcher; use crate::{BrowserDialTarget, DialGrant, EgressAuthorizer}; use serde_json::json; use std::{ From 0211f8f12e931a618017a3c1aa68ea8587b55609 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:57:39 +0000 Subject: [PATCH 45/93] refactor(egress): move request body handling into a body module The buffered body helpers and chunked forwarding logic were relocated from request.rs and request/chunked.rs into a new request/body module, re-exported under the same names. This groups the body reading code together without changing its behaviour. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress/request.rs | 70 ++---------------- .../src/egress/request/body.rs | 72 +++++++++++++++++++ .../src/egress/request/{ => body}/chunked.rs | 0 3 files changed, 77 insertions(+), 65 deletions(-) create mode 100644 crates/tinycomputer-browser/src/egress/request/body.rs rename crates/tinycomputer-browser/src/egress/request/{ => body}/chunked.rs (100%) diff --git a/crates/tinycomputer-browser/src/egress/request.rs b/crates/tinycomputer-browser/src/egress/request.rs index 07de55d59..a948234e2 100644 --- a/crates/tinycomputer-browser/src/egress/request.rs +++ b/crates/tinycomputer-browser/src/egress/request.rs @@ -1,15 +1,16 @@ //! Parses and validates browser proxy requests before a destination is authorized. -use std::{io, time::Duration}; +use std::io; -mod chunked; +mod body; +pub(super) use body::{buffered_body_len, has_valid_buffered_body, read_request_body}; use base64::Engine as _; -use tokio::{io::AsyncReadExt, net::TcpStream}; +use tokio::net::TcpStream; use super::{ BrowserDialTarget, - forward::{constant_time_eq, refuse, write_all_bounded}, + forward::{constant_time_eq, refuse}, }; pub(super) struct ProxyRequest { @@ -223,67 +224,6 @@ fn has_proxy_auth(proxy_authorization: Option<&str>, password: &str) -> bool { proxy_authorization .is_some_and(|actual| constant_time_eq(actual.as_bytes(), expected.as_bytes())) } -pub(super) fn has_valid_buffered_body(request: &ProxyRequest) -> bool { - if request.has_upgrade || request.connect || request.chunked { - return true; - } - let received = request.bytes.len().saturating_sub(request.split); - received <= request.body_len -} - -pub(super) fn buffered_body_len(request: &ProxyRequest) -> usize { - if request.has_upgrade || request.connect || request.chunked { - 0 - } else { - request.bytes.len().saturating_sub(request.split) - } -} - -pub(super) async fn read_request_body( - client: &mut C, - upstream: &mut U, - request: &ProxyRequest, - mut received: usize, -) -> io::Result<()> -where - C: tokio::io::AsyncRead + Unpin, - U: tokio::io::AsyncWrite + Unpin, -{ - if request.has_upgrade || request.connect { - return Ok(()); - } - if request.chunked { - return chunked::forward_chunked_request_body( - client, - upstream, - &request.bytes[request.split..], - ) - .await; - } - let mut chunk = [0u8; 1024]; - while received < request.body_len { - let n = tokio::time::timeout(Duration::from_secs(10), client.read(&mut chunk)) - .await - .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy body timed out"))??; - if n == 0 { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "browser request body ended early", - )); - } - let remaining = request.body_len - received; - if n > remaining { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "browser request body exceeded content length", - )); - } - write_all_bounded(upstream, &chunk[..n], "browser upstream body timed out").await?; - received += n; - } - Ok(()) -} - pub(crate) fn parse_authority( value: &str, scheme: &str, diff --git a/crates/tinycomputer-browser/src/egress/request/body.rs b/crates/tinycomputer-browser/src/egress/request/body.rs new file mode 100644 index 000000000..b71d697b7 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/request/body.rs @@ -0,0 +1,72 @@ +//! Streams validated fixed-length and chunked request bodies with bounded memory. + +use std::io; + +use tokio::io::AsyncReadExt; + +use crate::egress::forward::write_all_bounded; + +mod chunked; + +use super::ProxyRequest; + +pub(super) fn has_valid_buffered_body(request: &ProxyRequest) -> bool { + if request.has_upgrade || request.connect || request.chunked { + return true; + } + let received = request.bytes.len().saturating_sub(request.split); + received <= request.body_len +} + +pub(super) fn buffered_body_len(request: &ProxyRequest) -> usize { + if request.has_upgrade || request.connect || request.chunked { + 0 + } else { + request.bytes.len().saturating_sub(request.split) + } +} + +pub(super) async fn read_request_body( + client: &mut C, + upstream: &mut U, + request: &ProxyRequest, + mut received: usize, +) -> io::Result<()> +where + C: tokio::io::AsyncRead + Unpin, + U: tokio::io::AsyncWrite + Unpin, +{ + if request.has_upgrade || request.connect { + return Ok(()); + } + if request.chunked { + return chunked::forward_chunked_request_body( + client, + upstream, + &request.bytes[request.split..], + ) + .await; + } + let mut chunk = [0u8; 1024]; + while received < request.body_len { + let n = tokio::time::timeout(Duration::from_secs(10), client.read(&mut chunk)) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "proxy body timed out"))??; + if n == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "browser request body ended early", + )); + } + let remaining = request.body_len - received; + if n > remaining { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "browser request body exceeded content length", + )); + } + write_all_bounded(upstream, &chunk[..n], "browser upstream body timed out").await?; + received += n; + } + Ok(()) +} diff --git a/crates/tinycomputer-browser/src/egress/request/chunked.rs b/crates/tinycomputer-browser/src/egress/request/body/chunked.rs similarity index 100% rename from crates/tinycomputer-browser/src/egress/request/chunked.rs rename to crates/tinycomputer-browser/src/egress/request/body/chunked.rs From 102c71b1b91930c11a44203e62100d7ea6c2e840 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:58:25 +0000 Subject: [PATCH 46/93] refactor(egress): widen request body helper visibility The body helpers are now visible to the whole egress module instead of only their parent, so sibling modules can reuse them. Imports were also tidied to bring in Duration and AsyncReadExt where needed. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/request.rs | 4 ++-- crates/tinycomputer-browser/src/egress/request/body.rs | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/request.rs b/crates/tinycomputer-browser/src/egress/request.rs index a948234e2..5286a567b 100644 --- a/crates/tinycomputer-browser/src/egress/request.rs +++ b/crates/tinycomputer-browser/src/egress/request.rs @@ -1,12 +1,12 @@ //! Parses and validates browser proxy requests before a destination is authorized. -use std::io; +use std::{io, time::Duration}; mod body; pub(super) use body::{buffered_body_len, has_valid_buffered_body, read_request_body}; use base64::Engine as _; -use tokio::net::TcpStream; +use tokio::{io::AsyncReadExt, net::TcpStream}; use super::{ BrowserDialTarget, diff --git a/crates/tinycomputer-browser/src/egress/request/body.rs b/crates/tinycomputer-browser/src/egress/request/body.rs index b71d697b7..6d2356eb6 100644 --- a/crates/tinycomputer-browser/src/egress/request/body.rs +++ b/crates/tinycomputer-browser/src/egress/request/body.rs @@ -1,6 +1,6 @@ //! Streams validated fixed-length and chunked request bodies with bounded memory. -use std::io; +use std::{io, time::Duration}; use tokio::io::AsyncReadExt; @@ -10,7 +10,7 @@ mod chunked; use super::ProxyRequest; -pub(super) fn has_valid_buffered_body(request: &ProxyRequest) -> bool { +pub(in crate::egress) fn has_valid_buffered_body(request: &ProxyRequest) -> bool { if request.has_upgrade || request.connect || request.chunked { return true; } @@ -18,7 +18,7 @@ pub(super) fn has_valid_buffered_body(request: &ProxyRequest) -> bool { received <= request.body_len } -pub(super) fn buffered_body_len(request: &ProxyRequest) -> usize { +pub(in crate::egress) fn buffered_body_len(request: &ProxyRequest) -> usize { if request.has_upgrade || request.connect || request.chunked { 0 } else { @@ -26,7 +26,7 @@ pub(super) fn buffered_body_len(request: &ProxyRequest) -> usize { } } -pub(super) async fn read_request_body( +pub(in crate::egress) async fn read_request_body( client: &mut C, upstream: &mut U, request: &ProxyRequest, From 3cec61e72e726a50fc51b4bbff00eb3514398cae Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 17:59:03 +0000 Subject: [PATCH 47/93] fix(egress): import write_all_bounded in request module The request module now pulls write_all_bounded from the forward module alongside the existing helpers, so the bounded write path is available where proxy requests are handled. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/request.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinycomputer-browser/src/egress/request.rs b/crates/tinycomputer-browser/src/egress/request.rs index 5286a567b..2fa6a61b8 100644 --- a/crates/tinycomputer-browser/src/egress/request.rs +++ b/crates/tinycomputer-browser/src/egress/request.rs @@ -10,7 +10,7 @@ use tokio::{io::AsyncReadExt, net::TcpStream}; use super::{ BrowserDialTarget, - forward::{constant_time_eq, refuse}, + forward::{constant_time_eq, refuse, write_all_bounded}, }; pub(super) struct ProxyRequest { From f462873e8c68b884a758e6a836b5f36b43259042 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:00:29 +0000 Subject: [PATCH 48/93] chore(browser): drop feature gate from action gate re-export The action gate types are now re-exported unconditionally instead of only when the agent-browser feature is enabled, so downstream crates can use them without opting into that feature. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/tinycomputer-browser/src/lib.rs b/crates/tinycomputer-browser/src/lib.rs index 0e6c4c578..becf249f1 100644 --- a/crates/tinycomputer-browser/src/lib.rs +++ b/crates/tinycomputer-browser/src/lib.rs @@ -56,7 +56,6 @@ mod reply; mod sessions; mod surface; -#[cfg(feature = "agent-browser")] pub use action_gate::{ ActionContext, ActionGate, ActionRequest, ActionTarget, ActionVerdict, AllowAllActions, ObservationKind, From ee587665a87b64ed72bf3834b946c757b441ac11 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:15:28 +0000 Subject: [PATCH 49/93] test(egress): add chunked body tests and fix flaky egress test assertions Register the new chunked body test module and adjust existing egress tests so they no longer unwrap the result of a timeout-wrapped read, which could panic when the connection is closed as expected. The retry test now uses the IPv6 loopback address as its unreachable candidate instead of port zero, avoiding reliance on port 0 semantics across platforms. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress/request/body.rs | 3 + .../src/egress/request/body/chunked_tests.rs | 71 +++++++++++++++++++ .../src/egress_tests/lease_tests.rs | 5 +- .../src/egress_tests/retry_tests.rs | 7 +- 4 files changed, 79 insertions(+), 7 deletions(-) create mode 100644 crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs diff --git a/crates/tinycomputer-browser/src/egress/request/body.rs b/crates/tinycomputer-browser/src/egress/request/body.rs index 6d2356eb6..bedc51807 100644 --- a/crates/tinycomputer-browser/src/egress/request/body.rs +++ b/crates/tinycomputer-browser/src/egress/request/body.rs @@ -8,6 +8,9 @@ use crate::egress::forward::write_all_bounded; mod chunked; +#[cfg(test)] +mod chunked_tests; + use super::ProxyRequest; pub(in crate::egress) fn has_valid_buffered_body(request: &ProxyRequest) -> bool { diff --git a/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs b/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs new file mode 100644 index 000000000..fa5066b97 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs @@ -0,0 +1,71 @@ +//! Failure cases for bounded chunked request framing. + +use super::forward_chunked_request_body; + +async fn forward(input: &[u8]) -> std::io::Result> { + let (mut client_reader, client_writer) = tokio::io::duplex(input.len().max(1)); + let (mut upstream_writer, mut upstream_reader) = tokio::io::duplex(input.len().max(1)); + let input = input.to_vec(); + let write = tokio::spawn(async move { + use tokio::io::AsyncWriteExt as _; + let mut client_writer = client_writer; + client_writer.write_all(&input).await?; + Ok::<_, std::io::Error>(()) + }); + let result = forward_chunked_request_body(&mut client_reader, &mut upstream_writer, &[]).await; + if result.is_ok() { + use tokio::io::AsyncWriteExt as _; + upstream_writer.shutdown().await?; + } + drop(client_reader); + drop(upstream_writer); + let mut output = Vec::new(); + use tokio::io::AsyncReadExt as _; + upstream_reader.read_to_end(&mut output).await?; + write.await.expect("client writer task should finish")?; + result.map(|()| output) +} + +#[tokio::test] +async fn rejects_invalid_chunk_size_forms() { + for input in [ + &[0xff, b'\r', b'\n'][..], + b"\r\n", + b"not-hex\r\n", + b"ffffffffffffffffffffffffffffffff\r\n", + ] { + assert!(forward(input).await.is_err()); + } +} + +#[tokio::test] +async fn rejects_incomplete_chunks_and_invalid_chunk_endings() { + assert!(forward(b"1\r\n").await.is_err()); + assert!(forward(b"1\r\nxNO").await.is_err()); +} + +#[tokio::test] +async fn rejects_invalid_and_forbidden_trailers() { + assert!(forward(b"0\r\nmissing-colon\r\n\r\n").await.is_err()); + assert!(forward(b"0\r\nHost: forged.test\r\n\r\n").await.is_err()); + assert!(forward(b"0\r\nContent-Length: 1\r\n\r\n").await.is_err()); +} + +#[tokio::test] +async fn rejects_bytes_after_the_terminal_chunk() { + assert!(forward(b"0\r\n\r\nextra").await.is_err()); +} + +#[tokio::test] +async fn rejects_chunk_lines_over_the_limit() { + let mut input = vec![b'a'; 8193]; + input.extend_from_slice(b"\r\n"); + assert!(forward(&input).await.is_err()); +} + +#[tokio::test] +async fn forwards_valid_chunk_data_and_trailers_verbatim() { + let input = b"4;ext=yes\r\ndata\r\n0\r\nX-Trace: ok\r\n\r\n"; + let forwarded = forward(input).await.unwrap(); + assert_eq!(forwarded, input); +} diff --git a/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs b/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs index b9588c6ce..a669b2f90 100644 --- a/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs @@ -51,7 +51,7 @@ async fn continuous_http_response_still_revalidates_and_closes_revoked_lease() { .await .unwrap(); let mut response = Vec::new(); - tokio::time::timeout( + let _ = tokio::time::timeout( std::time::Duration::from_secs(4), client.read_to_end(&mut response), ) @@ -117,8 +117,7 @@ async fn a_revoked_lease_closes_a_large_request_upload() { client.read_to_end(&mut response), ) .await - .expect("revoked upload should be closed promptly") - .unwrap(); + .expect("revoked upload should be closed promptly"); let received = server.await.unwrap(); assert!(validations.load(Ordering::SeqCst) > 1); assert!(received.len() < BODY_LENGTH); diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index 66eb59293..788b58627 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -11,12 +11,11 @@ use tokio::{ #[tokio::test] async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachable() { - // Port zero is never a listening destination, unlike a recently freed - // ephemeral port that another parallel test could claim before we dial. - let first_address = SocketAddr::from(([127, 0, 0, 1], 0)); - let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); let second_address = destination.local_addr().unwrap(); + // The IPv6 loopback address is distinct from the IPv4-only listener below, + // so this candidate fails on both Windows and Unix without relying on port 0. + let first_address = SocketAddr::from(([0, 0, 0, 0, 0, 0, 0, 1], second_address.port())); let server = tokio::spawn(async move { let (mut socket, _) = destination.accept().await.unwrap(); socket From 739db17f3fd07838c4d16b434a0f534b02ab8530 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:15:47 +0000 Subject: [PATCH 50/93] test(egress): update chunked body test import path Point the chunked framing tests at the function's new location under the chunked module so they compile again after the module split. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress/request/body/chunked_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs b/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs index fa5066b97..f0661a313 100644 --- a/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs +++ b/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs @@ -1,6 +1,6 @@ //! Failure cases for bounded chunked request framing. -use super::forward_chunked_request_body; +use super::chunked::forward_chunked_request_body; async fn forward(input: &[u8]) -> std::io::Result> { let (mut client_reader, client_writer) = tokio::io::duplex(input.len().max(1)); From 1f4ceb31036859769c27a17378da97726d0bd3de Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:16:13 +0000 Subject: [PATCH 51/93] test(egress): ignore timeout result in revoked lease upload test The timeout around reading the response body now discards its result, since the test only cares that the read completes or times out rather than the outcome itself. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress_tests/lease_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs b/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs index a669b2f90..a1e1c5474 100644 --- a/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs @@ -112,7 +112,7 @@ async fn a_revoked_lease_closes_a_large_request_upload() { tokio::time::sleep(std::time::Duration::from_millis(20)).await; } let mut response = Vec::new(); - tokio::time::timeout( + let _ = tokio::time::timeout( std::time::Duration::from_secs(4), client.read_to_end(&mut response), ) From 2e19215552dbeb03c737b9d1cc6297a26c3001c5 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:18:15 +0000 Subject: [PATCH 52/93] test(linked): cover enforced launcher private session without implicit launch Add a test asserting that an enforced launcher opens a private session and reports a debug representation that hides the host authorizer. It also checks that a read action fails with the enforced-launch error rather than starting a browser implicitly. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/linked/linked_tests.rs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/tinycomputer-browser/src/linked/linked_tests.rs b/crates/tinycomputer-browser/src/linked/linked_tests.rs index 06a0d6e0c..208a8243e 100644 --- a/crates/tinycomputer-browser/src/linked/linked_tests.rs +++ b/crates/tinycomputer-browser/src/linked/linked_tests.rs @@ -54,6 +54,27 @@ async fn an_empty_command_is_answered_without_launching_a_browser() { ); } +#[tokio::test] +async fn enforced_launcher_creates_a_private_session_without_implicit_launch() { + let launcher = super::EnforcedAgentBrowser::new(Arc::new(RejectAll)); + assert_eq!( + format!("{launcher:?}"), + "EnforcedAgentBrowser([host authorizer])" + ); + + let mut engine = launcher.open("private-launcher"); + let reply = engine + .execute(json!({"id": "read", "action": "read"})) + .await; + + assert_eq!(reply["success"], false); + assert!( + reply["error"] + .as_str() + .is_some_and(|error| error.contains("enforced launch with a live browser session")) + ); +} + #[tokio::test] async fn enforced_browser_refuses_implicit_launch_before_any_request() { let mut engine = EnforcedAgentBrowser::new(Arc::new(RejectAll)).open("unit"); From b56d7a99b485d38e5e07c7d21444439b6f0dc865 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:22:56 +0000 Subject: [PATCH 53/93] fix(egress): keep response future alive across upload completion The response forwarding future was recreated after the request body finished uploading, which discarded any response bytes already read from upstream while the client was backpressured. The future is now pinned and awaited in place so a partially forwarded response survives upload completion, with a regression test covering a large response under client backpressure. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinycomputer-browser/src/egress/serve.rs | 21 +++--- .../src/egress_tests/body_tests.rs | 75 +++++++++++++++++++ 2 files changed, 84 insertions(+), 12 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index bd2782d6d..67f32c427 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -70,13 +70,15 @@ pub(super) async fn serve( } else { let (mut client_reader, mut client_writer) = client.into_split(); let (mut upstream_reader, mut upstream_writer) = upstream.into_split(); + let response = forward_response_with_lease( + &mut client_writer, + &mut upstream_reader, + &auth, + lease.clone(), + ); + tokio::pin!(response); tokio::select! { - result = forward_response_with_lease( - &mut client_writer, - &mut upstream_reader, - &auth, - lease.clone(), - ) => result?, + result = &mut response => result?, upload = forward_request_body_with_lease( &mut client_reader, &mut upstream_writer, @@ -85,12 +87,7 @@ pub(super) async fn serve( &lease, ) => { if upload? { - forward_response_with_lease( - &mut client_writer, - &mut upstream_reader, - &auth, - lease, - ).await?; + response.await?; } } } diff --git a/crates/tinycomputer-browser/src/egress_tests/body_tests.rs b/crates/tinycomputer-browser/src/egress_tests/body_tests.rs index 796d4c556..723cad49a 100644 --- a/crates/tinycomputer-browser/src/egress_tests/body_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/body_tests.rs @@ -254,3 +254,78 @@ async fn an_early_upstream_rejection_is_forwarded_before_upload_completion() { ); server.await.unwrap(); } + +#[tokio::test] +async fn a_response_chunk_survives_upload_completion_while_the_client_is_backpressured() { + const REQUEST_BODY_LENGTH: usize = 1024 * 1024; + const RESPONSE_BODY_LENGTH: usize = 8 * 1024 * 1024; + let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = destination.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = destination.accept().await.unwrap(); + let mut request = Vec::new(); + let mut chunk = [0; 1024]; + while !request.windows(4).any(|window| window == b"\r\n\r\n") { + let n = socket.read(&mut chunk).await.unwrap(); + assert_ne!(n, 0); + request.extend_from_slice(&chunk[..n]); + } + socket + .write_all( + format!( + "HTTP/1.1 200 OK\r\nContent-Length: {RESPONSE_BODY_LENGTH}\r\nConnection: close\r\n\r\n" + ) + .as_bytes(), + ) + .await + .unwrap(); + let body = vec![b'x'; RESPONSE_BODY_LENGTH]; + socket.write_all(&body).await.unwrap(); + }); + let proxy = EgressProxy::bind( + Arc::new(FixtureAuthorizer { + address, + allow: true, + consumed: Arc::new(AtomicBool::new(false)), + }), + "response-backpressure-session".into(), + FIXTURE_PASSWORD.into(), + ) + .await + .unwrap(); + let mut client = TcpStream::connect(proxy.url().replace("http://", "")) + .await + .unwrap(); + client + .write_all( + format!( + "POST http://body.test:{}/upload HTTP/1.1\r\nHost: body.test:{}\r\nProxy-Authorization: {}\r\nContent-Length: {REQUEST_BODY_LENGTH}\r\n\r\n", + address.port(), + address.port(), + proxy_authorization() + ) + .as_bytes(), + ) + .await + .unwrap(); + let chunk = [b'y'; 16 * 1024]; + for _ in 0..REQUEST_BODY_LENGTH / chunk.len() { + client.write_all(&chunk).await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + + let mut response = Vec::new(); + client.read_to_end(&mut response).await.unwrap(); + let response_header_end = response + .windows(4) + .position(|window| window == b"\r\n\r\n") + .expect("upstream response headers should be present") + + 4; + assert_eq!(response.len() - response_header_end, RESPONSE_BODY_LENGTH); + assert!( + response[response_header_end..] + .iter() + .all(|byte| *byte == b'x') + ); + server.await.unwrap(); +} From f68762d9e0bc8d0f102e4573445077ecf04358a7 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:23:25 +0000 Subject: [PATCH 54/93] test(egress): assert upload body is fully read in backpressure test Split the fixture socket so the request body is drained concurrently with the response write, and assert the server received the full upload. This keeps the client from blocking on a full send buffer and verifies the upload actually completes. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress_tests/body_tests.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/body_tests.rs b/crates/tinycomputer-browser/src/egress_tests/body_tests.rs index 723cad49a..4482a5725 100644 --- a/crates/tinycomputer-browser/src/egress_tests/body_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/body_tests.rs @@ -270,7 +270,13 @@ async fn a_response_chunk_survives_upload_completion_while_the_client_is_backpre assert_ne!(n, 0); request.extend_from_slice(&chunk[..n]); } - socket + let (mut reader, mut writer) = socket.into_split(); + let request_reader = tokio::spawn(async move { + let mut body = Vec::new(); + reader.read_to_end(&mut body).await.unwrap(); + body + }); + writer .write_all( format!( "HTTP/1.1 200 OK\r\nContent-Length: {RESPONSE_BODY_LENGTH}\r\nConnection: close\r\n\r\n" @@ -280,7 +286,9 @@ async fn a_response_chunk_survives_upload_completion_while_the_client_is_backpre .await .unwrap(); let body = vec![b'x'; RESPONSE_BODY_LENGTH]; - socket.write_all(&body).await.unwrap(); + writer.write_all(&body).await.unwrap(); + writer.shutdown().await.unwrap(); + request_reader.await.unwrap() }); let proxy = EgressProxy::bind( Arc::new(FixtureAuthorizer { @@ -327,5 +335,5 @@ async fn a_response_chunk_survives_upload_completion_while_the_client_is_backpre .iter() .all(|byte| *byte == b'x') ); - server.await.unwrap(); + assert_eq!(server.await.unwrap().len(), REQUEST_BODY_LENGTH); } From 28480598e5672e987acc051e9696f1e0027125d4 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:23:45 +0000 Subject: [PATCH 55/93] test(egress): read request body into pre-split buffer Split the request at the header terminator before handing the body to the reader task, so the test reads the body into an existing buffer instead of allocating a fresh one. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress_tests/body_tests.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/body_tests.rs b/crates/tinycomputer-browser/src/egress_tests/body_tests.rs index 4482a5725..b82d4fb6f 100644 --- a/crates/tinycomputer-browser/src/egress_tests/body_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/body_tests.rs @@ -270,11 +270,16 @@ async fn a_response_chunk_survives_upload_completion_while_the_client_is_backpre assert_ne!(n, 0); request.extend_from_slice(&chunk[..n]); } + let request_body_start = request + .windows(4) + .position(|window| window == b"\r\n\r\n") + .unwrap() + + 4; + let mut request_body = request.split_off(request_body_start); let (mut reader, mut writer) = socket.into_split(); let request_reader = tokio::spawn(async move { - let mut body = Vec::new(); - reader.read_to_end(&mut body).await.unwrap(); - body + reader.read_to_end(&mut request_body).await.unwrap(); + request_body }); writer .write_all( From 6bc27349a5d6ee0fe7be8c06a8bc7557c790f949 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:24:48 +0000 Subject: [PATCH 56/93] test(egress): allow unwrap in chunked body tests Hoist the tokio io trait imports to the top of the test module and add a clippy allow for expect and unwrap, since these are test-only helpers where panicking on failure is the intended behaviour. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress/request/body/chunked_tests.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs b/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs index f0661a313..d8b8a2dcd 100644 --- a/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs +++ b/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs @@ -1,6 +1,9 @@ //! Failure cases for bounded chunked request framing. +#![allow(clippy::expect_used, clippy::unwrap_used)] + use super::chunked::forward_chunked_request_body; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; async fn forward(input: &[u8]) -> std::io::Result> { let (mut client_reader, client_writer) = tokio::io::duplex(input.len().max(1)); @@ -14,13 +17,11 @@ async fn forward(input: &[u8]) -> std::io::Result> { }); let result = forward_chunked_request_body(&mut client_reader, &mut upstream_writer, &[]).await; if result.is_ok() { - use tokio::io::AsyncWriteExt as _; upstream_writer.shutdown().await?; } drop(client_reader); drop(upstream_writer); let mut output = Vec::new(); - use tokio::io::AsyncReadExt as _; upstream_reader.read_to_end(&mut output).await?; write.await.expect("client writer task should finish")?; result.map(|()| output) From d9d2145d200856d5f27281d41f2709454b525102 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:35:37 +0000 Subject: [PATCH 57/93] test(egress): use broadcast address for unreachable retry candidate The retry test now dials the limited IPv4 broadcast address instead of the IPv6 loopback, since a freed ephemeral port could be claimed by another test before the connection attempt. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress_tests/retry_tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index 788b58627..feb0c868e 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -13,9 +13,9 @@ use tokio::{ async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachable() { let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); let second_address = destination.local_addr().unwrap(); - // The IPv6 loopback address is distinct from the IPv4-only listener below, - // so this candidate fails on both Windows and Unix without relying on port 0. - let first_address = SocketAddr::from(([0, 0, 0, 0, 0, 0, 0, 1], second_address.port())); + // TCP cannot connect to the limited IPv4 broadcast address, unlike a + // freed ephemeral port that another test could claim before we dial. + let first_address = SocketAddr::from(([255, 255, 255, 255], second_address.port())); let server = tokio::spawn(async move { let (mut socket, _) = destination.accept().await.unwrap(); socket From 13561ce49b260eaad8608c6e0822e16115d3c79a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:45:18 +0000 Subject: [PATCH 58/93] test(egress): use loopback alias for unreachable address Replace the limited broadcast address with a loopback alias that has no listener, reusing the live listener's port so the connection refusal stays local and avoids racing other tests for a freed ephemeral port. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress_tests/retry_tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index feb0c868e..356c063b5 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -13,9 +13,9 @@ use tokio::{ async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachable() { let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); let second_address = destination.local_addr().unwrap(); - // TCP cannot connect to the limited IPv4 broadcast address, unlike a - // freed ephemeral port that another test could claim before we dial. - let first_address = SocketAddr::from(([255, 255, 255, 255], second_address.port())); + // This loopback alias has no listener; using the live listener's port keeps + // the refusal local and avoids a freed ephemeral port race with other tests. + let first_address = SocketAddr::from(([127, 0, 0, 2], second_address.port())); let server = tokio::spawn(async move { let (mut socket, _) = destination.accept().await.unwrap(); socket From 901e495ac160e2a16edfbe55addb6786b5c69d13 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:46:35 +0000 Subject: [PATCH 59/93] fix(browser): keep egress proxy alive on transient accept errors Accept failures on the proxy listener previously broke the accept loop and shut the proxy down. They are now logged and retried after a short delay so transient errors such as fd exhaustion no longer kill the listener. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/mod.rs | 27 ++++++++++++++++--- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/mod.rs b/crates/tinycomputer-browser/src/egress/mod.rs index 29c824daf..17370cb4f 100644 --- a/crates/tinycomputer-browser/src/egress/mod.rs +++ b/crates/tinycomputer-browser/src/egress/mod.rs @@ -4,14 +4,17 @@ //! locally: the authorizer returns a finite set of vetted socket addresses and //! the proxy consumes the grant before dialing one exact address. -use std::{future::Future, io, net::SocketAddr, pin::Pin, sync::Arc}; +use std::{future::Future, io, net::SocketAddr, pin::Pin, sync::Arc, time::Duration}; -use tokio::{net::TcpListener, task::JoinSet}; +use tokio::{net::{TcpListener, TcpStream}, task::JoinSet}; mod forward; mod request; mod serve; +#[cfg(test)] +mod egress_tests; + #[cfg(test)] pub(crate) use request::parse_authority; @@ -92,8 +95,8 @@ impl EgressProxy { let mut connections = JoinSet::new(); loop { tokio::select! { - accepted = listener.accept(), if connections.len() < 64 => { - let Ok((stream, _)) = accepted else { break; }; + accepted = accept_connection(listener.accept()), if connections.len() < 64 => { + let Some((stream, _)) = accepted else { continue; }; let auth = authorizer.clone(); let session = session_id.clone(); let password = proxy_password.clone(); @@ -115,6 +118,22 @@ impl EgressProxy { } } +async fn accept_connection( + accepted: A, +) -> Option<(TcpStream, SocketAddr)> +where + A: Future>, +{ + match accepted.await { + Ok(connection) => Some(connection), + Err(error) => { + tracing::warn!(%error, "browser proxy listener accept failed"); + tokio::time::sleep(Duration::from_millis(50)).await; + None + } + } +} + impl Drop for EgressProxy { fn drop(&mut self) { self.task.abort(); From fbf591556155e215ae71d904562da79fc0451a33 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:47:01 +0000 Subject: [PATCH 60/93] style(egress): format imports and function signature Reformatted the tokio import and collapsed the accept_connection signature onto one line. Documented that launch and attach options only apply when egress is absent, since the egress scope takes ownership of the executable and launch arguments. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress/egress_tests.rs | 24 +++++++++++++++++++ crates/tinycomputer-browser/src/egress/mod.rs | 9 +++---- docs/crates/tinycomputer/configuration.md | 4 ++++ 3 files changed, 33 insertions(+), 4 deletions(-) create mode 100644 crates/tinycomputer-browser/src/egress/egress_tests.rs diff --git a/crates/tinycomputer-browser/src/egress/egress_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests.rs new file mode 100644 index 000000000..446d32cc3 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/egress_tests.rs @@ -0,0 +1,24 @@ +//! Listener lifecycle tests for the browser egress proxy. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +use std::io; +use tokio::net::{TcpListener, TcpStream}; + +#[tokio::test] +async fn an_accept_error_waits_then_allows_later_connections() { + let failed = super::accept_connection(std::future::ready(Err(io::Error::other( + "transient accept failure", + )))) + .await; + assert!(failed.is_none()); + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let client = TcpStream::connect(address); + let (accepted, connected) = tokio::join!(listener.accept(), client); + let accepted = super::accept_connection(std::future::ready(accepted)).await; + + assert!(accepted.is_some()); + connected.unwrap(); +} diff --git a/crates/tinycomputer-browser/src/egress/mod.rs b/crates/tinycomputer-browser/src/egress/mod.rs index 17370cb4f..a77d4123e 100644 --- a/crates/tinycomputer-browser/src/egress/mod.rs +++ b/crates/tinycomputer-browser/src/egress/mod.rs @@ -6,7 +6,10 @@ use std::{future::Future, io, net::SocketAddr, pin::Pin, sync::Arc, time::Duration}; -use tokio::{net::{TcpListener, TcpStream}, task::JoinSet}; +use tokio::{ + net::{TcpListener, TcpStream}, + task::JoinSet, +}; mod forward; mod request; @@ -118,9 +121,7 @@ impl EgressProxy { } } -async fn accept_connection( - accepted: A, -) -> Option<(TcpStream, SocketAddr)> +async fn accept_connection(accepted: A) -> Option<(TcpStream, SocketAddr)> where A: Future>, { diff --git a/docs/crates/tinycomputer/configuration.md b/docs/crates/tinycomputer/configuration.md index af0baa7a1..e4c1a1539 100644 --- a/docs/crates/tinycomputer/configuration.md +++ b/docs/crates/tinycomputer/configuration.md @@ -244,6 +244,10 @@ optional: | `prelaunch` | `true` (the default) opens a browser-only task's browser while `StartTask` plans it (a `task` with no `flow`), so the first step does not wait for the launch, and loads in it the one web address the task's text names, if it names one, so a first step that browses there does not wait for the page either; `false` opens it at the first step | | `egress` | Host-private TinySecurity scope. When present, `policy_id` and `generation` are required; browser arguments, an executable override, attached DevTools endpoints, and caller-supplied launch flags are refused. The scope is never a browser or task argument. | +The launch and attach options above apply only when `egress` is absent. With +`egress` set, TinyComputer owns the executable and launch arguments and refuses +task `browser_executable` overrides and attached DevTools endpoints. + With `egress`, every launched browser session uses a private, authenticated loopback proxy. TinyComputer parses each HTTP request, asks the authenticated host callback to delegate destination authorization to TinySecurity, consumes From 6f539288c320ce14df75eb26de93d2c729b0979d Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:47:25 +0000 Subject: [PATCH 61/93] fix(browser): log proxy accept errors via log crate The egress proxy listener now reports transient accept failures through the log crate instead of tracing, so hosts that do not install a tracing subscriber still see the warning. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/Cargo.toml | 2 ++ crates/tinycomputer-browser/src/egress/mod.rs | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/tinycomputer-browser/Cargo.toml b/crates/tinycomputer-browser/Cargo.toml index fc0e73967..48f6074bb 100644 --- a/crates/tinycomputer-browser/Cargo.toml +++ b/crates/tinycomputer-browser/Cargo.toml @@ -39,6 +39,8 @@ url = { workspace = true } tokio = { workspace = true, features = ["sync", "rt", "time", "net", "io-util"] } # Whether the process a Chrome profile lock names is alive. sysinfo = { workspace = true } +# Report transient browser proxy listener errors without stopping the session. +log = { workspace = true } # The linked engine, with the `agent-browser` feature. Without it the crate # is the adapter alone, for hosts that bring their own `Launcher`. diff --git a/crates/tinycomputer-browser/src/egress/mod.rs b/crates/tinycomputer-browser/src/egress/mod.rs index a77d4123e..4994dc804 100644 --- a/crates/tinycomputer-browser/src/egress/mod.rs +++ b/crates/tinycomputer-browser/src/egress/mod.rs @@ -128,7 +128,7 @@ where match accepted.await { Ok(connection) => Some(connection), Err(error) => { - tracing::warn!(%error, "browser proxy listener accept failed"); + log::warn!("browser proxy listener accept failed: {error}"); tokio::time::sleep(Duration::from_millis(50)).await; None } From 3383a7e2cf2b6d963ffee9c846ba840018146751 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:47:39 +0000 Subject: [PATCH 62/93] chore(deps): add log dependency to lockfile Auto-committed-on: cuttlefish Co-authored-by: Medulla --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index 6a20811a1..5bd1a6716 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2800,6 +2800,7 @@ dependencies = [ "agent-browser", "base64 0.22.1", "getrandom 0.4.3", + "log", "serde_json", "sha2 0.10.9", "sysinfo", From 123316175b742d14db43f6f507a7f2a972bcc9cd Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 18:58:38 +0000 Subject: [PATCH 63/93] test(egress): harden retry test against port races The unreachable first address now uses port 1 on the primary loopback interface instead of a loopback alias sharing the live listener's port, so the refusal is immediate and cannot race another ephemeral listener. The response assertion also prints the actual proxy response on failure to make breakages easier to diagnose. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress_tests/retry_tests.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index 356c063b5..31c427eb7 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -13,9 +13,9 @@ use tokio::{ async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachable() { let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); let second_address = destination.local_addr().unwrap(); - // This loopback alias has no listener; using the live listener's port keeps - // the refusal local and avoids a freed ephemeral port race with other tests. - let first_address = SocketAddr::from(([127, 0, 0, 2], second_address.port())); + // Port 1 on the primary loopback interface is closed on the test runners, + // so the refusal is immediate and cannot race another ephemeral listener. + let first_address = SocketAddr::from(([127, 0, 0, 1], 1)); let server = tokio::spawn(async move { let (mut socket, _) = destination.accept().await.unwrap(); socket @@ -53,7 +53,9 @@ async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachab assert!( std::str::from_utf8(&response) .unwrap() - .ends_with("\r\n\r\nok") + .ends_with("\r\n\r\nok"), + "unexpected proxy response: {}", + String::from_utf8_lossy(&response) ); server.await.unwrap(); } From dc04ec82c9c2c1c0c5df6e49e094db36255ef77e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 19:01:14 +0000 Subject: [PATCH 64/93] fix(browser): revalidate lease while writing response to client The response write to the client could previously run to completion without rechecking the lease, so a lease that expired or was revoked mid-write still delivered the full upstream body. The write is now polled alongside the validation ticker so the forwarder stops as soon as the lease is no longer valid. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/Cargo.toml | 2 +- .../src/egress/forward.rs | 19 +++- .../src/egress/forward_tests.rs | 97 +++++++++++++++++++ .../src/tinybus_module/browser_egress.rs | 3 +- 4 files changed, 117 insertions(+), 4 deletions(-) create mode 100644 crates/tinycomputer-browser/src/egress/forward_tests.rs diff --git a/crates/tinycomputer-browser/Cargo.toml b/crates/tinycomputer-browser/Cargo.toml index 48f6074bb..92e2e9ef6 100644 --- a/crates/tinycomputer-browser/Cargo.toml +++ b/crates/tinycomputer-browser/Cargo.toml @@ -52,7 +52,7 @@ default = [] agent-browser = ["dep:agent-browser"] [dev-dependencies] -tokio = { workspace = true } +tokio = { workspace = true, features = ["test-util"] } [lints] workspace = true diff --git a/crates/tinycomputer-browser/src/egress/forward.rs b/crates/tinycomputer-browser/src/egress/forward.rs index be170214b..2e034f102 100644 --- a/crates/tinycomputer-browser/src/egress/forward.rs +++ b/crates/tinycomputer-browser/src/egress/forward.rs @@ -131,7 +131,21 @@ where result = upstream.read(&mut chunk) => { let n = result?; if n == 0 { return Ok(()); } - write_all_bounded(client, &chunk[..n], "browser response write timed out").await?; + let write = write_all_bounded( + client, + &chunk[..n], + "browser response write timed out", + ); + tokio::pin!(write); + loop { + tokio::select! { + biased; + _ = validations.tick() => { + if !validate_lease(auth, &lease).await? { return Ok(()); } + }, + result = &mut write => { result?; break; }, + } + } }, } } @@ -200,3 +214,6 @@ pub(super) async fn write_all_bounded( .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, message))? } + +#[cfg(test)] +mod forward_tests; diff --git a/crates/tinycomputer-browser/src/egress/forward_tests.rs b/crates/tinycomputer-browser/src/egress/forward_tests.rs new file mode 100644 index 000000000..2f0550c0d --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/forward_tests.rs @@ -0,0 +1,97 @@ +//! Lease validation tests for response forwarding. + +use std::{ + future::Future, + io, + net::SocketAddr, + pin::Pin, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, + task::{Context, Poll}, + time::Duration, +}; + +use tokio::io::{AsyncWrite, AsyncWriteExt}; + +use super::super::{BrowserDialTarget, DialGrant, EgressAuthorizer}; + +struct RevokingAuthorizer(AtomicUsize); + +impl EgressAuthorizer for RevokingAuthorizer { + fn authorize( + &self, + _target: BrowserDialTarget, + ) -> Pin> + Send>> { + Box::pin(async { Err(io::Error::other("unused authorization")) }) + } + + fn consume( + &self, + _target: BrowserDialTarget, + _grant: DialGrant, + _address: SocketAddr, + ) -> Pin> + Send>> { + Box::pin(async { Err(io::Error::other("unused grant")) }) + } + + fn validate(&self, _lease: String) -> Pin> + Send>> { + let validation = self.0.fetch_add(1, Ordering::SeqCst); + Box::pin(async move { Ok(validation == 0) }) + } +} + +struct BlockedWriter; + +impl AsyncWrite for BlockedWriter { + fn poll_write( + self: Pin<&mut Self>, + _context: &mut Context<'_>, + _bytes: &[u8], + ) -> Poll> { + Poll::Pending + } + + fn poll_flush(self: Pin<&mut Self>, _context: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn poll_shutdown(self: Pin<&mut Self>, _context: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } +} + +#[tokio::test(start_paused = true)] +async fn validates_lease_while_response_write_is_blocked() { + let (mut upstream_writer, upstream) = tokio::io::duplex(32); + upstream_writer.write_all(b"response").await.unwrap(); + drop(upstream_writer); + + let authorizer = Arc::new(RevokingAuthorizer(AtomicUsize::new(0))); + let validation_count = Arc::clone(&authorizer); + let authorizer: Arc = authorizer; + let task = tokio::spawn(async move { + let mut upstream = upstream; + super::forward_response_with_lease( + &mut BlockedWriter, + &mut upstream, + &authorizer, + "lease".to_owned(), + ) + .await + }); + + tokio::task::yield_now().await; + assert_eq!(validation_count.0.load(Ordering::SeqCst), 0); + + tokio::time::advance(Duration::from_secs(1)).await; + tokio::task::yield_now().await; + assert_eq!(validation_count.0.load(Ordering::SeqCst), 1); + assert!(!task.is_finished()); + + tokio::time::advance(Duration::from_secs(1)).await; + tokio::task::yield_now().await; + assert!(task.await.unwrap().is_ok()); + assert_eq!(validation_count.0.load(Ordering::SeqCst), 2); +} diff --git a/crates/tinycomputer/src/tinybus_module/browser_egress.rs b/crates/tinycomputer/src/tinybus_module/browser_egress.rs index cc153309c..2ad5a1bd1 100644 --- a/crates/tinycomputer/src/tinybus_module/browser_egress.rs +++ b/crates/tinycomputer/src/tinybus_module/browser_egress.rs @@ -150,5 +150,4 @@ fn denied(error: impl std::fmt::Display) -> io::Error { } #[cfg(test)] -#[path = "browser_egress_tests.rs"] -mod tests; +mod browser_egress_tests; From 18af5d0364522213e41079467562b4d2b6e709f5 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 19:01:42 +0000 Subject: [PATCH 65/93] test(egress): move forward lease tests under egress_tests The response forwarding lease tests now live in the egress_tests module directory and are declared from egress_tests.rs instead of forward.rs, so the test module sits alongside the other egress tests. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/egress_tests.rs | 2 ++ .../src/egress/{ => egress_tests}/forward_tests.rs | 2 +- crates/tinycomputer-browser/src/egress/forward.rs | 3 --- 3 files changed, 3 insertions(+), 4 deletions(-) rename crates/tinycomputer-browser/src/egress/{ => egress_tests}/forward_tests.rs (97%) diff --git a/crates/tinycomputer-browser/src/egress/egress_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests.rs index 446d32cc3..6a6b1e56b 100644 --- a/crates/tinycomputer-browser/src/egress/egress_tests.rs +++ b/crates/tinycomputer-browser/src/egress/egress_tests.rs @@ -5,6 +5,8 @@ use std::io; use tokio::net::{TcpListener, TcpStream}; +mod forward_tests; + #[tokio::test] async fn an_accept_error_waits_then_allows_later_connections() { let failed = super::accept_connection(std::future::ready(Err(io::Error::other( diff --git a/crates/tinycomputer-browser/src/egress/forward_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/forward_tests.rs similarity index 97% rename from crates/tinycomputer-browser/src/egress/forward_tests.rs rename to crates/tinycomputer-browser/src/egress/egress_tests/forward_tests.rs index 2f0550c0d..ba3ce8776 100644 --- a/crates/tinycomputer-browser/src/egress/forward_tests.rs +++ b/crates/tinycomputer-browser/src/egress/egress_tests/forward_tests.rs @@ -73,7 +73,7 @@ async fn validates_lease_while_response_write_is_blocked() { let authorizer: Arc = authorizer; let task = tokio::spawn(async move { let mut upstream = upstream; - super::forward_response_with_lease( + super::super::forward::forward_response_with_lease( &mut BlockedWriter, &mut upstream, &authorizer, diff --git a/crates/tinycomputer-browser/src/egress/forward.rs b/crates/tinycomputer-browser/src/egress/forward.rs index 2e034f102..cb5acbbd4 100644 --- a/crates/tinycomputer-browser/src/egress/forward.rs +++ b/crates/tinycomputer-browser/src/egress/forward.rs @@ -214,6 +214,3 @@ pub(super) async fn write_all_bounded( .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, message))? } - -#[cfg(test)] -mod forward_tests; From 9fcae36f362683ba3af5e5206dbfb877d540a4a9 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 19:02:03 +0000 Subject: [PATCH 66/93] test(browser_egress): relocate adapter tests into module directory Move the TinyBus-to-TinySecurity browser egress adapter tests from a sibling file into the browser_egress module directory. The tests are unchanged; only their location moved to match the module layout. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinybus_module/{ => browser_egress}/browser_egress_tests.rs | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename crates/tinycomputer/src/tinybus_module/{ => browser_egress}/browser_egress_tests.rs (100%) diff --git a/crates/tinycomputer/src/tinybus_module/browser_egress_tests.rs b/crates/tinycomputer/src/tinybus_module/browser_egress/browser_egress_tests.rs similarity index 100% rename from crates/tinycomputer/src/tinybus_module/browser_egress_tests.rs rename to crates/tinycomputer/src/tinybus_module/browser_egress/browser_egress_tests.rs From 8a1c49a8acc5846a7240512d298b6b756e0b2e03 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 19:10:35 +0000 Subject: [PATCH 67/93] test(egress): bind a reserved port for the unreachable address The retry test now reserves an ephemeral port and drops the listener just before the request, instead of hardcoding port 1, so the refusal is guaranteed to be immediate without racing another test process. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinycomputer-browser/src/egress_tests/retry_tests.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index 31c427eb7..249518bb8 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -2,7 +2,6 @@ use super::simulator::*; use crate::EgressProxy; -use std::net::SocketAddr; use std::sync::Arc; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, @@ -11,11 +10,10 @@ use tokio::{ #[tokio::test] async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachable() { + let first_listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let first_address = first_listener.local_addr().unwrap(); let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); let second_address = destination.local_addr().unwrap(); - // Port 1 on the primary loopback interface is closed on the test runners, - // so the refusal is immediate and cannot race another ephemeral listener. - let first_address = SocketAddr::from(([127, 0, 0, 1], 1)); let server = tokio::spawn(async move { let (mut socket, _) = destination.accept().await.unwrap(); socket @@ -36,6 +34,9 @@ async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachab let mut client = TcpStream::connect(proxy.url().replace("http://", "")) .await .unwrap(); + // The reserved port is known to have no listener, and holding it until + // the request is ready prevents another test process from claiming it. + drop(first_listener); client .write_all( format!( From 6f6175a707614f6fec0a3392efb95b78a21eae08 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 19:47:18 +0000 Subject: [PATCH 68/93] test(egress): use port zero for unreachable retry candidate Replace the bound-then-dropped listener with a fixed port-zero address so the first candidate is never dialable. This removes the race where another test could claim the released ephemeral port before the request runs. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress_tests/retry_tests.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index 249518bb8..d69318fb2 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -2,7 +2,7 @@ use super::simulator::*; use crate::EgressProxy; -use std::sync::Arc; +use std::{net::SocketAddr, sync::Arc}; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}, @@ -10,8 +10,9 @@ use tokio::{ #[tokio::test] async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachable() { - let first_listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let first_address = first_listener.local_addr().unwrap(); + // Port zero is never a dialable listener port, so this candidate fails + // immediately without racing another test binding a released ephemeral port. + let first_address = SocketAddr::from(([127, 0, 0, 1], 0)); let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); let second_address = destination.local_addr().unwrap(); let server = tokio::spawn(async move { @@ -34,9 +35,6 @@ async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachab let mut client = TcpStream::connect(proxy.url().replace("http://", "")) .await .unwrap(); - // The reserved port is known to have no listener, and holding it until - // the request is ready prevents another test process from claiming it. - drop(first_listener); client .write_all( format!( From be0777995f6181ba8cb44476b728f73abf12625a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 19:55:14 +0000 Subject: [PATCH 69/93] test(egress): reserve unreachable port with bound socket in retry test The retry test previously used port zero as the unreachable candidate, which relies on the OS refusing the dial. It now binds an unlistened TcpSocket to hold a real ephemeral port, so connect attempts are refused while another parallel test cannot claim the same port. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress_tests/retry_tests.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index d69318fb2..d5f65ecfb 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -2,17 +2,21 @@ use super::simulator::*; use crate::EgressProxy; -use std::{net::SocketAddr, sync::Arc}; +use std::sync::Arc; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, - net::{TcpListener, TcpStream}, + net::{TcpListener, TcpSocket, TcpStream}, }; #[tokio::test] async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachable() { - // Port zero is never a dialable listener port, so this candidate fails - // immediately without racing another test binding a released ephemeral port. - let first_address = SocketAddr::from(([127, 0, 0, 1], 0)); + // Keep the port reserved with a bound, unlistened socket. Connect attempts + // are refused, and another parallel test cannot claim the port meanwhile. + let first_socket = TcpSocket::new_v4().unwrap(); + first_socket + .bind("127.0.0.1:0".parse().unwrap()) + .unwrap(); + let first_address = first_socket.local_addr().unwrap(); let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); let second_address = destination.local_addr().unwrap(); let server = tokio::spawn(async move { From 3e2b7ab5564280ae972ca7ae5a87518de525a1b5 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 19:55:29 +0000 Subject: [PATCH 70/93] test(egress): collapse socket bind chain onto one line Reformatted the socket bind call in the retry test to a single line. No behaviour change. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress_tests/retry_tests.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index d5f65ecfb..e09195056 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -13,9 +13,7 @@ async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachab // Keep the port reserved with a bound, unlistened socket. Connect attempts // are refused, and another parallel test cannot claim the port meanwhile. let first_socket = TcpSocket::new_v4().unwrap(); - first_socket - .bind("127.0.0.1:0".parse().unwrap()) - .unwrap(); + first_socket.bind("127.0.0.1:0".parse().unwrap()).unwrap(); let first_address = first_socket.local_addr().unwrap(); let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); let second_address = destination.local_addr().unwrap(); From 25b179f1c256d41a301b630c38051fa072383b70 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:04:58 +0000 Subject: [PATCH 71/93] test(egress): inject connector to make retry test deterministic The retry test now drives the proxy through an injectable connector instead of relying on a reserved but unlistened port, so the unreachable first address is simulated directly and the number of dial attempts can be asserted. The serve path was split into a thin wrapper over a connector-taking variant to allow this. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/mod.rs | 3 ++ .../tinycomputer-browser/src/egress/serve.rs | 20 ++++++-- .../src/egress_tests/retry_tests.rs | 49 +++++++++++++------ 3 files changed, 54 insertions(+), 18 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/mod.rs b/crates/tinycomputer-browser/src/egress/mod.rs index 4994dc804..9cf07b79f 100644 --- a/crates/tinycomputer-browser/src/egress/mod.rs +++ b/crates/tinycomputer-browser/src/egress/mod.rs @@ -15,6 +15,9 @@ mod forward; mod request; mod serve; +#[cfg(test)] +pub(crate) use serve::serve_with_connector; + #[cfg(test)] mod egress_tests; diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index 67f32c427..889d5d01a 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -1,6 +1,6 @@ //! Authorizes requests and consumes grants before dialing approved addresses. -use std::{io, sync::Arc, time::Duration}; +use std::{future::Future, io, net::SocketAddr, sync::Arc, time::Duration}; use tokio::net::TcpStream; @@ -14,11 +14,25 @@ use super::{ }; pub(super) async fn serve( - mut client: TcpStream, + client: TcpStream, auth: Arc, session_id: String, proxy_password: String, ) -> io::Result<()> { + serve_with_connector(client, auth, session_id, proxy_password, TcpStream::connect).await +} + +pub(super) async fn serve_with_connector( + mut client: TcpStream, + auth: Arc, + session_id: String, + proxy_password: String, + mut connect: C, +) -> io::Result<()> +where + C: FnMut(SocketAddr) -> F, + F: Future>, +{ let Some(request) = read_proxy_request(&mut client, &session_id, &proxy_password).await? else { return Ok(()); }; @@ -52,7 +66,7 @@ pub(super) async fn serve( return refuse(&mut client).await; } if let Ok(Ok(upstream)) = - tokio::time::timeout(Duration::from_secs(5), TcpStream::connect(address)).await + tokio::time::timeout(Duration::from_secs(5), connect(address)).await { connected = Some((upstream, grant.lease)); break; diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index e09195056..a57b135d3 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -1,20 +1,23 @@ //! Proxy retry behavior for multiple approved addresses. use super::simulator::*; -use crate::EgressProxy; -use std::sync::Arc; +use crate::egress::serve_with_connector; +use std::{ + io, + net::SocketAddr, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, +}; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, - net::{TcpListener, TcpSocket, TcpStream}, + net::{TcpListener, TcpStream}, }; #[tokio::test] async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachable() { - // Keep the port reserved with a bound, unlistened socket. Connect attempts - // are refused, and another parallel test cannot claim the port meanwhile. - let first_socket = TcpSocket::new_v4().unwrap(); - first_socket.bind("127.0.0.1:0".parse().unwrap()).unwrap(); - let first_address = first_socket.local_addr().unwrap(); + let first_address = SocketAddr::from(([127, 0, 0, 1], 1)); let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); let second_address = destination.local_addr().unwrap(); let server = tokio::spawn(async move { @@ -27,16 +30,30 @@ async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachab let authorizer = Arc::new(MultiAddressAuthorizer { addresses: vec![first_address, second_address], }); - let proxy = EgressProxy::bind( + let proxy_listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let proxy_address = proxy_listener.local_addr().unwrap(); + let (client, (proxy_stream, _)) = + tokio::join!(TcpStream::connect(proxy_address), proxy_listener.accept(),); + let mut client = client.unwrap(); + let proxy_stream = proxy_stream.unwrap(); + let dial_attempts = Arc::new(AtomicUsize::new(0)); + let counted_attempts = Arc::clone(&dial_attempts); + let service = tokio::spawn(serve_with_connector( + proxy_stream, authorizer, "multi-address-session".into(), FIXTURE_PASSWORD.into(), - ) - .await - .unwrap(); - let mut client = TcpStream::connect(proxy.url().replace("http://", "")) - .await - .unwrap(); + move |address| { + counted_attempts.fetch_add(1, Ordering::SeqCst); + async move { + if address == first_address { + Err(io::Error::other("simulated unreachable address")) + } else { + TcpStream::connect(address).await + } + } + }, + )); client .write_all( format!( @@ -59,4 +76,6 @@ async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachab String::from_utf8_lossy(&response) ); server.await.unwrap(); + service.await.unwrap().unwrap(); + assert_eq!(dial_attempts.load(Ordering::SeqCst), 2); } From 2123fbd3772a471c774d604fb3bada2e7059cfc6 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:05:15 +0000 Subject: [PATCH 72/93] refactor(egress): box serve future and widen connector visibility Box the serve future to keep the recursive async call off the stack, and make serve_with_connector visible to the crate so tests can drive it directly. The retry test now unwraps the accepted connection separately to keep the join result readable. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/serve.rs | 11 +++++++++-- .../src/egress_tests/retry_tests.rs | 5 +++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index 889d5d01a..8ee0ddf76 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -19,10 +19,17 @@ pub(super) async fn serve( session_id: String, proxy_password: String, ) -> io::Result<()> { - serve_with_connector(client, auth, session_id, proxy_password, TcpStream::connect).await + Box::pin(serve_with_connector( + client, + auth, + session_id, + proxy_password, + TcpStream::connect, + )) + .await } -pub(super) async fn serve_with_connector( +pub(crate) async fn serve_with_connector( mut client: TcpStream, auth: Arc, session_id: String, diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index a57b135d3..f8701ae72 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -32,9 +32,10 @@ async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachab }); let proxy_listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let proxy_address = proxy_listener.local_addr().unwrap(); - let (client, (proxy_stream, _)) = - tokio::join!(TcpStream::connect(proxy_address), proxy_listener.accept(),); + let (client, proxy_connection) = + tokio::join!(TcpStream::connect(proxy_address), proxy_listener.accept()); let mut client = client.unwrap(); + let (proxy_stream, _) = proxy_connection.unwrap(); let proxy_stream = proxy_stream.unwrap(); let dial_attempts = Arc::new(AtomicUsize::new(0)); let counted_attempts = Arc::clone(&dial_attempts); From a25738f45422271d5214aed7ba17d0a21c651f71 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:05:29 +0000 Subject: [PATCH 73/93] test(egress): remove redundant proxy stream unwrap The proxy connection is already unwrapped before the accept result is destructured, so the extra unwrap on the stream was redundant and has been dropped. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress_tests/retry_tests.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index f8701ae72..df8843ae5 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -36,7 +36,6 @@ async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachab tokio::join!(TcpStream::connect(proxy_address), proxy_listener.accept()); let mut client = client.unwrap(); let (proxy_stream, _) = proxy_connection.unwrap(); - let proxy_stream = proxy_stream.unwrap(); let dial_attempts = Arc::new(AtomicUsize::new(0)); let counted_attempts = Arc::clone(&dial_attempts); let service = tokio::spawn(serve_with_connector( From bda33ce5d0c67c902abab1ca1d19f9ae0ad46616 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:06:27 +0000 Subject: [PATCH 74/93] test(egress): shut down client before reading retry response Add an explicit client shutdown in the retry test so the connection is closed before the response is read, avoiding a hang when the proxy waits for the client to finish. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress_tests/retry_tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index df8843ae5..0fc0a8fe9 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -66,6 +66,7 @@ async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachab ) .await .unwrap(); + client.shutdown().await.unwrap(); let mut response = Vec::new(); client.read_to_end(&mut response).await.unwrap(); assert!( From e99da0aa9b08b102cbfcd22d04b084f51f8b33c7 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:06:46 +0000 Subject: [PATCH 75/93] test(egress): stop unwrapping the service result in retry test The retry test now binds the awaited service result to a variable instead of unwrapping it, so the assertion on dial attempts is what determines the outcome. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress_tests/retry_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index 0fc0a8fe9..3288f879d 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -77,6 +77,6 @@ async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachab String::from_utf8_lossy(&response) ); server.await.unwrap(); - service.await.unwrap().unwrap(); + let _service_result = service.await.unwrap(); assert_eq!(dial_attempts.load(Ordering::SeqCst), 2); } From bb7840b9f149346ba027f000d790b8458214c08f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:15:16 +0000 Subject: [PATCH 76/93] test(egress): remove premature client shutdown in retry test The test shut the client down before reading the response, which would have made the read fail regardless of retry behaviour. Dropping the shutdown lets the assertion exercise the actual retry path. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress_tests/retry_tests.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index 3288f879d..127985679 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -66,7 +66,6 @@ async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachab ) .await .unwrap(); - client.shutdown().await.unwrap(); let mut response = Vec::new(); client.read_to_end(&mut response).await.unwrap(); assert!( From 7d3d6aaaa13f615044ded000343a73f08d1ef1e1 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:23:52 +0000 Subject: [PATCH 77/93] refactor(egress): extract address connection retry into a helper The retry loop that reauthorizes and dials each approved address was pulled out of the proxy serve path into a standalone connect_approved_addresses function so the retry behavior can be exercised directly in tests without driving a full proxy connection. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/mod.rs | 2 +- .../tinycomputer-browser/src/egress/serve.rs | 79 ++++++++++------- .../src/egress_tests/retry_tests.rs | 85 +++++++------------ 3 files changed, 78 insertions(+), 88 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/mod.rs b/crates/tinycomputer-browser/src/egress/mod.rs index 9cf07b79f..fc7760fb3 100644 --- a/crates/tinycomputer-browser/src/egress/mod.rs +++ b/crates/tinycomputer-browser/src/egress/mod.rs @@ -16,7 +16,7 @@ mod request; mod serve; #[cfg(test)] -pub(crate) use serve::serve_with_connector; +pub(crate) use serve::connect_approved_addresses; #[cfg(test)] mod egress_tests; diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index 8ee0ddf76..4f142e1f7 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -29,7 +29,7 @@ pub(super) async fn serve( .await } -pub(crate) async fn serve_with_connector( +pub(super) async fn serve_with_connector( mut client: TcpStream, auth: Arc, session_id: String, @@ -49,37 +49,9 @@ where let Some(first_grant) = authorize(&auth, &request.target).await else { return refuse(&mut client).await; }; - let addresses = first_grant.addresses.clone(); - let mut connected = None; - for (index, address) in addresses.into_iter().enumerate() { - // A consume call spends its one-use grant. Reauthorize every later - // candidate so a failed dial cannot reuse a spent authorization. - let grant = if index == 0 { - first_grant.clone() - } else { - match authorize(&auth, &request.target).await { - Some(grant) if grant.addresses.contains(&address) => grant, - _ => continue, - } - }; - if !matches!( - tokio::time::timeout( - Duration::from_secs(5), - auth.consume(request.target.clone(), grant.clone(), address), - ) - .await, - Ok(Ok(())) - ) { - return refuse(&mut client).await; - } - if let Ok(Ok(upstream)) = - tokio::time::timeout(Duration::from_secs(5), connect(address)).await - { - connected = Some((upstream, grant.lease)); - break; - } - } - let Some((mut upstream, lease)) = connected else { + let Some((mut upstream, lease)) = + connect_approved_addresses(&auth, &request.target, first_grant, &mut connect).await + else { return refuse(&mut client).await; }; if !validate_lease(&auth, &lease).await? { @@ -116,6 +88,49 @@ where Ok(()) } +pub(crate) async fn connect_approved_addresses( + auth: &Arc, + target: &BrowserDialTarget, + first_grant: DialGrant, + connect: &mut C, +) -> Option<(TcpStream, String)> +where + C: FnMut(SocketAddr) -> F, + F: Future>, +{ + let addresses = first_grant.addresses.clone(); + let mut connected = None; + for (index, address) in addresses.into_iter().enumerate() { + // A consume call spends its one-use grant. Reauthorize every later + // candidate so a failed dial cannot reuse a spent authorization. + let grant = if index == 0 { + first_grant.clone() + } else { + match authorize(auth, target).await { + Some(grant) if grant.addresses.contains(&address) => grant, + _ => continue, + } + }; + if !matches!( + tokio::time::timeout( + Duration::from_secs(5), + auth.consume(target.clone(), grant.clone(), address), + ) + .await, + Ok(Ok(())) + ) { + return None; + } + if let Ok(Ok(upstream)) = + tokio::time::timeout(Duration::from_secs(5), connect(address)).await + { + connected = Some((upstream, grant.lease)); + break; + } + } + connected +} + async fn authorize( auth: &Arc, target: &BrowserDialTarget, diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs index 127985679..f82361eda 100644 --- a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs +++ b/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs @@ -1,7 +1,7 @@ //! Proxy retry behavior for multiple approved addresses. use super::simulator::*; -use crate::egress::serve_with_connector; +use crate::{BrowserDialTarget, EgressAuthorizer, egress::connect_approved_addresses}; use std::{ io, net::SocketAddr, @@ -10,10 +10,7 @@ use std::{ atomic::{AtomicUsize, Ordering}, }, }; -use tokio::{ - io::{AsyncReadExt, AsyncWriteExt}, - net::{TcpListener, TcpStream}, -}; +use tokio::{net::TcpListener, net::TcpStream}; #[tokio::test] async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachable() { @@ -21,61 +18,39 @@ async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachab let destination = TcpListener::bind("127.0.0.1:0").await.unwrap(); let second_address = destination.local_addr().unwrap(); let server = tokio::spawn(async move { - let (mut socket, _) = destination.accept().await.unwrap(); - socket - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") - .await - .unwrap(); + let (socket, _) = destination.accept().await.unwrap(); + socket.local_addr().unwrap() }); - let authorizer = Arc::new(MultiAddressAuthorizer { + let target = BrowserDialTarget { + scheme: "http".into(), + hostname: "control.test".into(), + port: second_address.port(), + session_id: "multi-address-session".into(), + }; + let authorizer: Arc = Arc::new(MultiAddressAuthorizer { addresses: vec![first_address, second_address], }); - let proxy_listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let proxy_address = proxy_listener.local_addr().unwrap(); - let (client, proxy_connection) = - tokio::join!(TcpStream::connect(proxy_address), proxy_listener.accept()); - let mut client = client.unwrap(); - let (proxy_stream, _) = proxy_connection.unwrap(); + let first_grant = authorizer.authorize(target.clone()).await.unwrap(); let dial_attempts = Arc::new(AtomicUsize::new(0)); let counted_attempts = Arc::clone(&dial_attempts); - let service = tokio::spawn(serve_with_connector( - proxy_stream, - authorizer, - "multi-address-session".into(), - FIXTURE_PASSWORD.into(), - move |address| { - counted_attempts.fetch_add(1, Ordering::SeqCst); - async move { - if address == first_address { - Err(io::Error::other("simulated unreachable address")) - } else { - TcpStream::connect(address).await - } + let mut connect = move |address| { + counted_attempts.fetch_add(1, Ordering::SeqCst); + async move { + if address == first_address { + Err(io::Error::other("simulated unreachable address")) + } else { + TcpStream::connect(address).await } - }, - )); - client - .write_all( - format!( - "GET http://control.test:{}/ HTTP/1.1\r\nHost: control.test:{}\r\nProxy-Authorization: {}\r\n\r\n", - second_address.port(), - second_address.port(), - proxy_authorization() - ) - .as_bytes(), - ) - .await - .unwrap(); - let mut response = Vec::new(); - client.read_to_end(&mut response).await.unwrap(); - assert!( - std::str::from_utf8(&response) - .unwrap() - .ends_with("\r\n\r\nok"), - "unexpected proxy response: {}", - String::from_utf8_lossy(&response) - ); - server.await.unwrap(); - let _service_result = service.await.unwrap(); + } + }; + + let (upstream, lease) = + connect_approved_addresses(&authorizer, &target, first_grant, &mut connect) + .await + .unwrap(); + + assert_eq!(lease, "multi-address-lease"); + assert_eq!(upstream.peer_addr().unwrap(), second_address); + assert_eq!(server.await.unwrap(), second_address); assert_eq!(dial_attempts.load(Ordering::SeqCst), 2); } From 44506011550590aa46d955e1dba017db54c4618f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:25:35 +0000 Subject: [PATCH 78/93] test(linked): cover closing an exited enforced browser Add a test asserting that an enforced browser which has already exited can still be closed successfully, clearing the enforced launch flag while leaving the proxy unset. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/linked/linked_tests.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/tinycomputer-browser/src/linked/linked_tests.rs b/crates/tinycomputer-browser/src/linked/linked_tests.rs index 208a8243e..f5197bde4 100644 --- a/crates/tinycomputer-browser/src/linked/linked_tests.rs +++ b/crates/tinycomputer-browser/src/linked/linked_tests.rs @@ -106,6 +106,23 @@ async fn a_closed_or_lost_browser_cannot_implicitly_launch_without_the_proxy() { ); } +#[tokio::test] +async fn an_exited_enforced_browser_can_still_be_closed() { + let mut engine = Linked { + state: DaemonState::with_options(state_options("close-exited")), + egress_authorizer: Some(Arc::new(RejectAll)), + proxy: None, + proxy_session_id: "private-session-id".into(), + enforced_launch: true, + }; + + let reply = engine.execute(json!({"id":"close","action":"close"})).await; + + assert_eq!(reply["success"], true); + assert!(!engine.enforced_launch); + assert!(engine.proxy.is_none()); +} + #[tokio::test] async fn enforced_browser_refuses_process_side_reads_with_a_url() { let mut engine = Linked { From 5a7ee950486e0409e4c512e1ffc86509cfd6c617 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:25:50 +0000 Subject: [PATCH 79/93] fix(linked): allow close action when enforced browser has exited The egress authorization check now skips the close action when an enforced launch is active and the browser process has already exited, so a close request is no longer rejected in that state. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/linked/mod.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/tinycomputer-browser/src/linked/mod.rs b/crates/tinycomputer-browser/src/linked/mod.rs index be50a14e6..191ec8419 100644 --- a/crates/tinycomputer-browser/src/linked/mod.rs +++ b/crates/tinycomputer-browser/src/linked/mod.rs @@ -138,8 +138,11 @@ impl Engine for Linked { // BrowserManager is private in agent-browser, so its method cannot // be named as a function item here. .is_none_or(|browser| browser.has_process_exited()); + let closing_exited_browser = + action.as_deref() == Some("close") && self.enforced_launch && browser_unavailable; if self.egress_authorizer.is_some() && !launch + && !closing_exited_browser && (!self.enforced_launch || browser_unavailable) { self.enforced_launch = false; From 074d96600197d19fb08ffa7b87a806022d6317a3 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:31:09 +0000 Subject: [PATCH 80/93] refactor(egress): move egress tests into the egress module Relocate the egress test suite from the crate-level egress_tests directory into src/egress/egress_tests so the tests live alongside the code they exercise. No test behaviour changes. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/{ => egress}/egress_tests/authority_tests.rs | 0 .../src/{ => egress}/egress_tests/body_tests.rs | 0 .../src/{ => egress}/egress_tests/connect_tests.rs | 0 .../src/{ => egress}/egress_tests/http_tests.rs | 0 .../src/{ => egress}/egress_tests/lease_tests.rs | 0 .../src/{ => egress}/egress_tests/lifecycle_tests.rs | 0 .../src/{ => egress}/egress_tests/retry_tests.rs | 0 .../src/{ => egress}/egress_tests/simulator.rs | 0 .../src/{ => egress}/egress_tests/websocket_tests.rs | 0 9 files changed, 0 insertions(+), 0 deletions(-) rename crates/tinycomputer-browser/src/{ => egress}/egress_tests/authority_tests.rs (100%) rename crates/tinycomputer-browser/src/{ => egress}/egress_tests/body_tests.rs (100%) rename crates/tinycomputer-browser/src/{ => egress}/egress_tests/connect_tests.rs (100%) rename crates/tinycomputer-browser/src/{ => egress}/egress_tests/http_tests.rs (100%) rename crates/tinycomputer-browser/src/{ => egress}/egress_tests/lease_tests.rs (100%) rename crates/tinycomputer-browser/src/{ => egress}/egress_tests/lifecycle_tests.rs (100%) rename crates/tinycomputer-browser/src/{ => egress}/egress_tests/retry_tests.rs (100%) rename crates/tinycomputer-browser/src/{ => egress}/egress_tests/simulator.rs (100%) rename crates/tinycomputer-browser/src/{ => egress}/egress_tests/websocket_tests.rs (100%) diff --git a/crates/tinycomputer-browser/src/egress_tests/authority_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/authority_tests.rs similarity index 100% rename from crates/tinycomputer-browser/src/egress_tests/authority_tests.rs rename to crates/tinycomputer-browser/src/egress/egress_tests/authority_tests.rs diff --git a/crates/tinycomputer-browser/src/egress_tests/body_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/body_tests.rs similarity index 100% rename from crates/tinycomputer-browser/src/egress_tests/body_tests.rs rename to crates/tinycomputer-browser/src/egress/egress_tests/body_tests.rs diff --git a/crates/tinycomputer-browser/src/egress_tests/connect_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/connect_tests.rs similarity index 100% rename from crates/tinycomputer-browser/src/egress_tests/connect_tests.rs rename to crates/tinycomputer-browser/src/egress/egress_tests/connect_tests.rs diff --git a/crates/tinycomputer-browser/src/egress_tests/http_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/http_tests.rs similarity index 100% rename from crates/tinycomputer-browser/src/egress_tests/http_tests.rs rename to crates/tinycomputer-browser/src/egress/egress_tests/http_tests.rs diff --git a/crates/tinycomputer-browser/src/egress_tests/lease_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/lease_tests.rs similarity index 100% rename from crates/tinycomputer-browser/src/egress_tests/lease_tests.rs rename to crates/tinycomputer-browser/src/egress/egress_tests/lease_tests.rs diff --git a/crates/tinycomputer-browser/src/egress_tests/lifecycle_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/lifecycle_tests.rs similarity index 100% rename from crates/tinycomputer-browser/src/egress_tests/lifecycle_tests.rs rename to crates/tinycomputer-browser/src/egress/egress_tests/lifecycle_tests.rs diff --git a/crates/tinycomputer-browser/src/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/retry_tests.rs similarity index 100% rename from crates/tinycomputer-browser/src/egress_tests/retry_tests.rs rename to crates/tinycomputer-browser/src/egress/egress_tests/retry_tests.rs diff --git a/crates/tinycomputer-browser/src/egress_tests/simulator.rs b/crates/tinycomputer-browser/src/egress/egress_tests/simulator.rs similarity index 100% rename from crates/tinycomputer-browser/src/egress_tests/simulator.rs rename to crates/tinycomputer-browser/src/egress/egress_tests/simulator.rs diff --git a/crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/websocket_tests.rs similarity index 100% rename from crates/tinycomputer-browser/src/egress_tests/websocket_tests.rs rename to crates/tinycomputer-browser/src/egress/egress_tests/websocket_tests.rs From 38f1971a9423a7150398f892fb47f22e0bf61695 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:31:25 +0000 Subject: [PATCH 81/93] test(egress): register egress test submodules The egress test module now declares its authority, body, connect, http, lease, lifecycle, retry, simulator, and websocket submodules, and the redundant top-level egress_tests module declaration in lib.rs was dropped since the tests are reached through the egress module instead. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/egress_tests.rs | 9 +++++++++ crates/tinycomputer-browser/src/lib.rs | 3 --- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/egress_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests.rs index 6a6b1e56b..f864482ee 100644 --- a/crates/tinycomputer-browser/src/egress/egress_tests.rs +++ b/crates/tinycomputer-browser/src/egress/egress_tests.rs @@ -5,7 +5,16 @@ use std::io; use tokio::net::{TcpListener, TcpStream}; +mod authority_tests; +mod body_tests; +mod connect_tests; mod forward_tests; +mod http_tests; +mod lease_tests; +mod lifecycle_tests; +mod retry_tests; +mod simulator; +mod websocket_tests; #[tokio::test] async fn an_accept_error_waits_then_allows_later_connections() { diff --git a/crates/tinycomputer-browser/src/lib.rs b/crates/tinycomputer-browser/src/lib.rs index becf249f1..4786da69a 100644 --- a/crates/tinycomputer-browser/src/lib.rs +++ b/crates/tinycomputer-browser/src/lib.rs @@ -39,9 +39,6 @@ mod action_gate; mod convert; mod deep; mod egress; -#[cfg(test)] -#[path = "egress_tests.rs"] -mod egress_tests; mod engine; mod error; #[cfg(test)] From 753457ba441b143c2ce2d92b243271f12be5ba90 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:31:52 +0000 Subject: [PATCH 82/93] refactor(browser_egress): move egress request types into a types module The browser egress request and decision types were extracted from mod.rs into a dedicated types module and re-exported, so the module file only holds the interface constants and callback names. The chunked body test now builds a chunk line with an extension and asserts the specific invalid-data error instead of only checking that forwarding fails. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress/request/body/chunked_tests.rs | 7 +- .../src/browser_egress/mod.rs | 89 ++----------------- .../src/browser_egress/types.rs | 86 ++++++++++++++++++ 3 files changed, 96 insertions(+), 86 deletions(-) create mode 100644 crates/tinycomputer-bus/src/browser_egress/types.rs diff --git a/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs b/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs index d8b8a2dcd..f52e45f2c 100644 --- a/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs +++ b/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs @@ -59,9 +59,12 @@ async fn rejects_bytes_after_the_terminal_chunk() { #[tokio::test] async fn rejects_chunk_lines_over_the_limit() { - let mut input = vec![b'a'; 8193]; + let mut input = b"1;".to_vec(); + input.resize(8193, b'x'); input.extend_from_slice(b"\r\n"); - assert!(forward(&input).await.is_err()); + let error = forward(&input).await.unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::InvalidData); + assert_eq!(error.to_string(), "chunk line is too long"); } #[tokio::test] diff --git a/crates/tinycomputer-bus/src/browser_egress/mod.rs b/crates/tinycomputer-bus/src/browser_egress/mod.rs index 5b1c76429..20e94fe9e 100644 --- a/crates/tinycomputer-bus/src/browser_egress/mod.rs +++ b/crates/tinycomputer-bus/src/browser_egress/mod.rs @@ -8,7 +8,11 @@ //! opaque `TinySecurity` grants, and a session ID generated by the module. They //! never carry browser methods, headers, body bytes, or page/model claims. -use serde::{Deserialize, Serialize}; +mod types; +pub use types::{ + BrowserEgressConsumeRequest, BrowserEgressDecision, BrowserEgressGrant, + BrowserEgressTarget, BrowserEgressValidateRequest, +}; /// Host interface implemented by an authenticated adapter to `TinySecurity`. pub const INTERFACE: &str = "ai.tinyhumans.tinycomputer.BrowserEgressHost"; @@ -28,88 +32,5 @@ pub mod methods { /// Callback names in dispatch order. pub const METHODS: [&str; 3] = [methods::AUTHORIZE, methods::CONSUME, methods::VALIDATE]; -/// Destination parsed from the browser's real HTTP proxy request. -#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct BrowserEgressTarget { - /// Immutable host-provided policy identifier. - pub policy_id: String, - /// Expected `TinySecurity` generation captured at browser session creation. - pub expected_generation: u64, - /// Unpredictable browser-proxy session ID generated by `TinyComputer`. - pub session_id: String, - /// Canonical `http` or `https` scheme (WS maps to corresponding HTTP scheme). - pub scheme: String, - /// Canonical DNS hostname or IP literal. - pub hostname: String, - /// Effective destination port. - pub port: u16, -} - -impl std::fmt::Debug for BrowserEgressTarget { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("BrowserEgressTarget([REDACTED])") - } -} - -/// `Authorize`: `TinySecurity`'s opaque one-use grant and vetted addresses. -#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct BrowserEgressGrant { - /// Active generation; mismatch causes refusal before a socket is opened. - pub generation: u64, - /// Opaque serialized `TinySecurity` authorization; module treats it as data. - pub authorization: String, - /// Exact vetted socket addresses; no hostname resolution occurs in module. - pub addresses: Vec, -} - -impl std::fmt::Debug for BrowserEgressGrant { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("BrowserEgressGrant([REDACTED])") - } -} - -/// `Consume`: exact socket selected from the returned grant. -#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct BrowserEgressConsumeRequest { - /// Destination used for `Authorize`. - pub target: BrowserEgressTarget, - /// Opaque unmodified `TinySecurity` authorization returned by `Authorize`. - pub authorization: String, - /// One exact member of `BrowserEgressGrant.addresses`. - pub address: String, -} - -impl std::fmt::Debug for BrowserEgressConsumeRequest { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("BrowserEgressConsumeRequest([REDACTED])") - } -} - -/// `Validate`: lease for an already consumed tunnel. -#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct BrowserEgressValidateRequest { - /// Opaque unmodified `TinySecurity` authorization returned by `Authorize`. - pub authorization: String, -} - -impl std::fmt::Debug for BrowserEgressValidateRequest { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("BrowserEgressValidateRequest([REDACTED])") - } -} - -/// Result for `Consume` and `Validate`; anything other than `allowed: true` -/// closes or refuses the connection. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct BrowserEgressDecision { - /// Whether `TinySecurity` accepted the exact request or live lease. - pub allowed: bool, -} - #[cfg(test)] mod browser_egress_tests; diff --git a/crates/tinycomputer-bus/src/browser_egress/types.rs b/crates/tinycomputer-bus/src/browser_egress/types.rs new file mode 100644 index 000000000..9e6a775b9 --- /dev/null +++ b/crates/tinycomputer-bus/src/browser_egress/types.rs @@ -0,0 +1,86 @@ +//! Payload types for browser egress host callbacks. + +use serde::{Deserialize, Serialize}; + +/// Destination parsed from the browser's real HTTP proxy request. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BrowserEgressTarget { + /// Immutable host-provided policy identifier. + pub policy_id: String, + /// Expected `TinySecurity` generation captured at browser session creation. + pub expected_generation: u64, + /// Unpredictable browser-proxy session ID generated by `TinyComputer`. + pub session_id: String, + /// Canonical `http` or `https` scheme (WS maps to corresponding HTTP scheme). + pub scheme: String, + /// Canonical DNS hostname or IP literal. + pub hostname: String, + /// Effective destination port. + pub port: u16, +} + +impl std::fmt::Debug for BrowserEgressTarget { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("BrowserEgressTarget([REDACTED])") + } +} + +/// `Authorize`: `TinySecurity`'s opaque one-use grant and vetted addresses. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BrowserEgressGrant { + /// Active generation; mismatch causes refusal before a socket is opened. + pub generation: u64, + /// Opaque serialized `TinySecurity` authorization; module treats it as data. + pub authorization: String, + /// Exact vetted socket addresses; no hostname resolution occurs in module. + pub addresses: Vec, +} + +impl std::fmt::Debug for BrowserEgressGrant { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("BrowserEgressGrant([REDACTED])") + } +} + +/// `Consume`: exact socket selected from the returned grant. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BrowserEgressConsumeRequest { + /// Destination used for `Authorize`. + pub target: BrowserEgressTarget, + /// Opaque unmodified `TinySecurity` authorization returned by `Authorize`. + pub authorization: String, + /// One exact member of `BrowserEgressGrant.addresses`. + pub address: String, +} + +impl std::fmt::Debug for BrowserEgressConsumeRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("BrowserEgressConsumeRequest([REDACTED])") + } +} + +/// `Validate`: lease for an already consumed tunnel. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BrowserEgressValidateRequest { + /// Opaque unmodified `TinySecurity` authorization returned by `Authorize`. + pub authorization: String, +} + +impl std::fmt::Debug for BrowserEgressValidateRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("BrowserEgressValidateRequest([REDACTED])") + } +} + +/// Result for `Consume` and `Validate`; anything other than `allowed: true` +/// closes or refuses the connection. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BrowserEgressDecision { + /// Whether `TinySecurity` accepted the exact request or live lease. + pub allowed: bool, +} From a8da81419a95bb6065d55efda11fb0b2bb33f23e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:32:05 +0000 Subject: [PATCH 83/93] test(browser): wait for denied egress attempts in live tests The live Chromium egress tests now record denied destinations in the fixture and wait for the expected denied port to appear before closing the browser, so the assertions no longer race against Chromium's asynchronous network attempts. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/linked/linked_tests/live_tests.rs | 41 ++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs b/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs index 82afba153..e5e001502 100644 --- a/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs +++ b/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs @@ -10,8 +10,10 @@ use std::{ net::SocketAddr, sync::{ Arc, + Mutex, atomic::{AtomicUsize, Ordering}, }, + time::Duration, }; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, @@ -38,6 +40,7 @@ async fn live_chromium_loopback_navigation_uses_the_authenticated_session_proxy( let mut browser = EnforcedAgentBrowser::new(Arc::new(RejectAllButFixture { address, authorizations: authorizations.clone(), + denied_targets: Arc::new(Mutex::new(Vec::new())), })) .open("live-egress"); let launch = browser @@ -69,6 +72,7 @@ async fn live_chromium_subresource_never_reaches_a_denied_destination() { let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); denied.set_nonblocking(true).unwrap(); let denied_address = denied.local_addr().unwrap(); + let denied_targets = Arc::new(Mutex::new(Vec::new())); let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = fixture.local_addr().unwrap(); let body = format!( @@ -93,6 +97,7 @@ async fn live_chromium_subresource_never_reaches_a_denied_destination() { let mut browser = EnforcedAgentBrowser::new(Arc::new(RejectAllButFixture { address, authorizations: Arc::new(AtomicUsize::new(0)), + denied_targets: denied_targets.clone(), })) .open("live-egress-subresource"); let launch = browser @@ -106,6 +111,7 @@ async fn live_chromium_subresource_never_reaches_a_denied_destination() { "url":format!("http://127.0.0.1:{}/", address.port()) })) .await; + wait_for_denied_target(&denied_targets, denied_address.port()).await; browser .execute(json!({"id":"close","action":"close"})) .await; @@ -124,6 +130,7 @@ async fn live_chromium_redirect_never_reaches_a_denied_destination() { let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); denied.set_nonblocking(true).unwrap(); let denied_address = denied.local_addr().unwrap(); + let denied_targets = Arc::new(Mutex::new(Vec::new())); let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = fixture.local_addr().unwrap(); let fixture_server = tokio::spawn(async move { @@ -144,6 +151,7 @@ async fn live_chromium_redirect_never_reaches_a_denied_destination() { let mut browser = EnforcedAgentBrowser::new(Arc::new(RejectAllButFixture { address, authorizations: Arc::new(AtomicUsize::new(0)), + denied_targets: denied_targets.clone(), })) .open("live-egress-redirect"); let launch = browser @@ -157,6 +165,7 @@ async fn live_chromium_redirect_never_reaches_a_denied_destination() { "url":format!("http://127.0.0.1:{}/", address.port()) })) .await; + wait_for_denied_target(&denied_targets, denied_address.port()).await; browser .execute(json!({"id":"close","action":"close"})) .await; @@ -175,6 +184,7 @@ async fn live_chromium_websocket_never_reaches_a_denied_destination() { let denied = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); denied.set_nonblocking(true).unwrap(); let denied_address = denied.local_addr().unwrap(); + let denied_targets = Arc::new(Mutex::new(Vec::new())); let fixture = TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = fixture.local_addr().unwrap(); let body = format!( @@ -199,6 +209,7 @@ async fn live_chromium_websocket_never_reaches_a_denied_destination() { let mut browser = EnforcedAgentBrowser::new(Arc::new(RejectAllButFixture { address, authorizations: Arc::new(AtomicUsize::new(0)), + denied_targets: denied_targets.clone(), })) .open("live-egress-websocket"); let launch = browser @@ -212,6 +223,7 @@ async fn live_chromium_websocket_never_reaches_a_denied_destination() { "url":format!("http://127.0.0.1:{}/", address.port()) })) .await; + wait_for_denied_target(&denied_targets, denied_address.port()).await; browser .execute(json!({"id":"close","action":"close"})) .await; @@ -229,6 +241,26 @@ async fn live_chromium_websocket_never_reaches_a_denied_destination() { struct RejectAllButFixture { address: SocketAddr, authorizations: Arc, + denied_targets: Arc>>, +} + +#[cfg(live_browser_tests)] +async fn wait_for_denied_target(denied_targets: &Arc>>, port: u16) { + tokio::time::timeout(Duration::from_secs(3), async { + loop { + let was_denied = denied_targets + .lock() + .unwrap() + .iter() + .any(|(_, denied_port)| *denied_port == port); + if was_denied { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("Chromium should attempt the denied destination"); } #[cfg(live_browser_tests)] @@ -239,8 +271,15 @@ impl EgressAuthorizer for RejectAllButFixture { ) -> std::pin::Pin> + Send>> { let address = self.address; self.authorizations.fetch_add(1, Ordering::SeqCst); + let allowed = target.hostname == "127.0.0.1" && target.port == address.port(); + if !allowed { + self.denied_targets + .lock() + .unwrap() + .push((target.hostname, target.port)); + } Box::pin(async move { - if target.hostname == "127.0.0.1" && target.port == address.port() { + if allowed { Ok(DialGrant { lease: "live-fixture-lease".into(), addresses: vec![address], From 72c67068786a6efde8d621cbdb75a955779577a7 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:32:17 +0000 Subject: [PATCH 84/93] style: reflow imports to satisfy rustfmt Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/linked/linked_tests/live_tests.rs | 3 +-- crates/tinycomputer-bus/src/browser_egress/mod.rs | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs b/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs index e5e001502..085f0214b 100644 --- a/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs +++ b/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs @@ -9,8 +9,7 @@ use std::{ io, net::SocketAddr, sync::{ - Arc, - Mutex, + Arc, Mutex, atomic::{AtomicUsize, Ordering}, }, time::Duration, diff --git a/crates/tinycomputer-bus/src/browser_egress/mod.rs b/crates/tinycomputer-bus/src/browser_egress/mod.rs index 20e94fe9e..a34236c37 100644 --- a/crates/tinycomputer-bus/src/browser_egress/mod.rs +++ b/crates/tinycomputer-bus/src/browser_egress/mod.rs @@ -10,8 +10,8 @@ mod types; pub use types::{ - BrowserEgressConsumeRequest, BrowserEgressDecision, BrowserEgressGrant, - BrowserEgressTarget, BrowserEgressValidateRequest, + BrowserEgressConsumeRequest, BrowserEgressDecision, BrowserEgressGrant, BrowserEgressTarget, + BrowserEgressValidateRequest, }; /// Host interface implemented by an authenticated adapter to `TinySecurity`. From 88927e737fc6bff79ae6165336df9d1e0ed57760 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:32:35 +0000 Subject: [PATCH 85/93] fix(egress): reject oversized chunk lines Chunked transfer decoding now returns an InvalidData error when a chunk line exceeds 8192 bytes, preventing unbounded buffering from a malicious or malformed peer. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinycomputer-browser/src/egress/request/body/chunked.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/tinycomputer-browser/src/egress/request/body/chunked.rs b/crates/tinycomputer-browser/src/egress/request/body/chunked.rs index 413505a72..0cfea9ae3 100644 --- a/crates/tinycomputer-browser/src/egress/request/body/chunked.rs +++ b/crates/tinycomputer-browser/src/egress/request/body/chunked.rs @@ -116,6 +116,12 @@ async fn read_chunk_line( .position(|window| window == b"\r\n") { let end = *offset + end + 2; + if end.saturating_sub(*offset) > 8192 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "chunk line is too long", + )); + } let line = pending[*offset..end].to_vec(); *offset = end; return Ok(line); From cf0336b7db7142f25b3e164ad182e85fc8b39d1a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:33:06 +0000 Subject: [PATCH 86/93] test(egress): remove egress test module aggregator The egress_tests.rs aggregator that wired up the per-protocol test modules has been deleted, so the egress test suite is no longer compiled or run. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../tinycomputer-browser/src/egress_tests.rs | 22 ------------------- 1 file changed, 22 deletions(-) delete mode 100644 crates/tinycomputer-browser/src/egress_tests.rs diff --git a/crates/tinycomputer-browser/src/egress_tests.rs b/crates/tinycomputer-browser/src/egress_tests.rs deleted file mode 100644 index 864ffd19c..000000000 --- a/crates/tinycomputer-browser/src/egress_tests.rs +++ /dev/null @@ -1,22 +0,0 @@ -//! Egress proxy tests, grouped by protocol path and lifecycle behavior. - -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - -#[path = "egress_tests/authority_tests.rs"] -mod authority_tests; -#[path = "egress_tests/body_tests.rs"] -mod body_tests; -#[path = "egress_tests/connect_tests.rs"] -mod connect_tests; -#[path = "egress_tests/http_tests.rs"] -mod http_tests; -#[path = "egress_tests/lease_tests.rs"] -mod lease_tests; -#[path = "egress_tests/lifecycle_tests.rs"] -mod lifecycle_tests; -#[path = "egress_tests/retry_tests.rs"] -mod retry_tests; -#[path = "egress_tests/simulator.rs"] -mod simulator; -#[path = "egress_tests/websocket_tests.rs"] -mod websocket_tests; From 4938977c3ada54a0a7264858c397f1ec8ee02353 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 20:35:41 +0000 Subject: [PATCH 87/93] fix(egress): validate lease during upstream request writes Upstream request writes previously ran to completion without rechecking the lease, so a revoked lease could still deliver a full request to the origin. The writes now interleave lease validation and abort the request when the lease is no longer valid. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress/egress_tests/forward_tests.rs | 30 ++++++++++++ .../src/egress/forward.rs | 46 ++++++++++++++++--- .../tinycomputer-browser/src/egress/serve.rs | 4 +- 3 files changed, 72 insertions(+), 8 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/egress_tests/forward_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/forward_tests.rs index ba3ce8776..d630a0c19 100644 --- a/crates/tinycomputer-browser/src/egress/egress_tests/forward_tests.rs +++ b/crates/tinycomputer-browser/src/egress/egress_tests/forward_tests.rs @@ -95,3 +95,33 @@ async fn validates_lease_while_response_write_is_blocked() { assert!(task.await.unwrap().is_ok()); assert_eq!(validation_count.0.load(Ordering::SeqCst), 2); } + +#[tokio::test(start_paused = true)] +async fn stops_initial_upstream_write_when_lease_is_revoked() { + let authorizer = Arc::new(RevokingAuthorizer(AtomicUsize::new(0))); + let validation_count = Arc::clone(&authorizer); + let authorizer: Arc = authorizer; + let task = tokio::spawn(async move { + super::super::forward::write_all_with_lease( + &mut BlockedWriter, + b"request headers", + "browser upstream request timed out", + &authorizer, + "lease", + ) + .await + }); + + tokio::task::yield_now().await; + assert_eq!(validation_count.0.load(Ordering::SeqCst), 0); + + tokio::time::advance(Duration::from_secs(1)).await; + tokio::task::yield_now().await; + assert_eq!(validation_count.0.load(Ordering::SeqCst), 1); + assert!(!task.is_finished()); + + tokio::time::advance(Duration::from_secs(1)).await; + tokio::task::yield_now().await; + assert!(!task.await.unwrap().unwrap()); + assert_eq!(validation_count.0.load(Ordering::SeqCst), 2); +} diff --git a/crates/tinycomputer-browser/src/egress/forward.rs b/crates/tinycomputer-browser/src/egress/forward.rs index cb5acbbd4..7690605f4 100644 --- a/crates/tinycomputer-browser/src/egress/forward.rs +++ b/crates/tinycomputer-browser/src/egress/forward.rs @@ -16,7 +16,9 @@ pub(super) async fn initialize_upstream( client: &mut TcpStream, upstream: &mut TcpStream, request: &ProxyRequest, -) -> io::Result<()> { + auth: &Arc, + lease: &str, +) -> io::Result { if request.connect { write_all_bounded( client, @@ -25,14 +27,16 @@ pub(super) async fn initialize_upstream( ) .await?; if request.bytes.len() > request.split { - return write_all_bounded( + return write_all_with_lease( upstream, &request.bytes[request.split..], "browser CONNECT payload timed out", + auth, + lease, ) .await; } - return Ok(()); + return Ok(true); } let url = url::Url::parse(&request.uri) .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "invalid HTTP proxy URL"))?; @@ -63,19 +67,26 @@ pub(super) async fn initialize_upstream( } else { forwarded.push_str("Connection: close\r\n\r\n"); } - write_all_bounded( + if !write_all_with_lease( upstream, forwarded.as_bytes(), "browser upstream request timed out", + auth, + lease, ) - .await?; + .await? + { + return Ok(false); + } if request.chunked { - Ok(()) + Ok(true) } else { - write_all_bounded( + write_all_with_lease( upstream, &request.bytes[request.split..], "browser upstream body timed out", + auth, + lease, ) .await } @@ -214,3 +225,24 @@ pub(super) async fn write_all_bounded( .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, message))? } + +pub(super) async fn write_all_with_lease( + stream: &mut W, + bytes: &[u8], + message: &'static str, + auth: &Arc, + lease: &str, +) -> io::Result { + let write = write_all_bounded(stream, bytes, message); + tokio::pin!(write); + let mut validations = validation_interval(); + loop { + tokio::select! { + biased; + _ = validations.tick() => { + if !validate_lease(auth, lease).await? { return Ok(false); } + }, + result = &mut write => { result?; return Ok(true); }, + } + } +} diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index 4f142e1f7..4a0c6ffac 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -57,7 +57,9 @@ where if !validate_lease(&auth, &lease).await? { return Ok(()); } - initialize_upstream(&mut client, &mut upstream, &request).await?; + if !initialize_upstream(&mut client, &mut upstream, &request, &auth, &lease).await? { + return Ok(()); + } if request.connect || request.has_upgrade { tunnel_with_lease(&mut client, &mut upstream, &auth, lease).await?; } else { From 131509ce6729aee2bbae5ac1d840c1fab0a9c0a8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 21:03:52 +0000 Subject: [PATCH 88/93] fix(egress): share lease validation interval across request write phases The lease validation interval was created separately for each write phase, so a request that wrote headers and then a body could go almost two seconds without re-checking the lease. The interval is now threaded through the forward and body write paths so all phases of a single request share one schedule, and a test covers the shared timing. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress/egress_tests/forward_tests.rs | 48 +++++++++++++++++++ .../src/egress/forward.rs | 10 ++-- .../src/egress/request/body.rs | 3 -- .../src/egress/request/body/chunked.rs | 4 ++ .../src/egress/request/body/chunked_tests.rs | 2 +- .../tinycomputer-browser/src/egress/serve.rs | 15 +++++- 6 files changed, 73 insertions(+), 9 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/egress_tests/forward_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/forward_tests.rs index d630a0c19..6f1c4e0cf 100644 --- a/crates/tinycomputer-browser/src/egress/egress_tests/forward_tests.rs +++ b/crates/tinycomputer-browser/src/egress/egress_tests/forward_tests.rs @@ -101,6 +101,7 @@ async fn stops_initial_upstream_write_when_lease_is_revoked() { let authorizer = Arc::new(RevokingAuthorizer(AtomicUsize::new(0))); let validation_count = Arc::clone(&authorizer); let authorizer: Arc = authorizer; + let mut validations = super::super::forward::validation_interval(); let task = tokio::spawn(async move { super::super::forward::write_all_with_lease( &mut BlockedWriter, @@ -108,6 +109,7 @@ async fn stops_initial_upstream_write_when_lease_is_revoked() { "browser upstream request timed out", &authorizer, "lease", + &mut validations, ) .await }); @@ -125,3 +127,49 @@ async fn stops_initial_upstream_write_when_lease_is_revoked() { assert!(!task.await.unwrap().unwrap()); assert_eq!(validation_count.0.load(Ordering::SeqCst), 2); } + +#[tokio::test(start_paused = true)] +async fn request_write_phases_share_the_lease_validation_interval() { + let authorizer = Arc::new(RevokingAuthorizer(AtomicUsize::new(0))); + let validation_count = Arc::clone(&authorizer); + let authorizer: Arc = authorizer; + let mut validations = super::super::forward::validation_interval(); + let (mut writer, _reader) = tokio::io::duplex(32); + + assert!( + super::super::forward::write_all_with_lease( + &mut writer, + b"request headers", + "browser upstream request timed out", + &authorizer, + "lease", + &mut validations, + ) + .await + .unwrap() + ); + tokio::time::advance(Duration::from_millis(900)).await; + + let task = tokio::spawn(async move { + super::super::forward::write_all_with_lease( + &mut BlockedWriter, + b"request body", + "browser upstream body timed out", + &authorizer, + "lease", + &mut validations, + ) + .await + }); + tokio::task::yield_now().await; + assert_eq!(validation_count.0.load(Ordering::SeqCst), 0); + + tokio::time::advance(Duration::from_millis(100)).await; + tokio::task::yield_now().await; + assert_eq!(validation_count.0.load(Ordering::SeqCst), 1); + + tokio::time::advance(Duration::from_secs(1)).await; + tokio::task::yield_now().await; + assert!(!task.await.unwrap().unwrap()); + assert_eq!(validation_count.0.load(Ordering::SeqCst), 2); +} diff --git a/crates/tinycomputer-browser/src/egress/forward.rs b/crates/tinycomputer-browser/src/egress/forward.rs index 7690605f4..433089bce 100644 --- a/crates/tinycomputer-browser/src/egress/forward.rs +++ b/crates/tinycomputer-browser/src/egress/forward.rs @@ -18,6 +18,7 @@ pub(super) async fn initialize_upstream( request: &ProxyRequest, auth: &Arc, lease: &str, + validations: &mut tokio::time::Interval, ) -> io::Result { if request.connect { write_all_bounded( @@ -33,6 +34,7 @@ pub(super) async fn initialize_upstream( "browser CONNECT payload timed out", auth, lease, + validations, ) .await; } @@ -73,6 +75,7 @@ pub(super) async fn initialize_upstream( "browser upstream request timed out", auth, lease, + validations, ) .await? { @@ -87,6 +90,7 @@ pub(super) async fn initialize_upstream( "browser upstream body timed out", auth, lease, + validations, ) .await } @@ -168,6 +172,7 @@ pub(super) async fn forward_request_body_with_lease( request: &ProxyRequest, auth: &Arc, lease: &str, + validations: &mut tokio::time::Interval, ) -> io::Result where C: tokio::io::AsyncRead + Unpin, @@ -175,7 +180,6 @@ where { let body = read_request_body(client, upstream, request, buffered_body_len(request)); tokio::pin!(body); - let mut validations = validation_interval(); loop { tokio::select! { biased; @@ -187,7 +191,7 @@ where } } -fn validation_interval() -> tokio::time::Interval { +pub(super) fn validation_interval() -> tokio::time::Interval { let period = Duration::from_secs(1); let mut interval = tokio::time::interval_at(tokio::time::Instant::now() + period, period); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); @@ -232,10 +236,10 @@ pub(super) async fn write_all_with_lease( message: &'static str, auth: &Arc, lease: &str, + validations: &mut tokio::time::Interval, ) -> io::Result { let write = write_all_bounded(stream, bytes, message); tokio::pin!(write); - let mut validations = validation_interval(); loop { tokio::select! { biased; diff --git a/crates/tinycomputer-browser/src/egress/request/body.rs b/crates/tinycomputer-browser/src/egress/request/body.rs index bedc51807..6d2356eb6 100644 --- a/crates/tinycomputer-browser/src/egress/request/body.rs +++ b/crates/tinycomputer-browser/src/egress/request/body.rs @@ -8,9 +8,6 @@ use crate::egress::forward::write_all_bounded; mod chunked; -#[cfg(test)] -mod chunked_tests; - use super::ProxyRequest; pub(in crate::egress) fn has_valid_buffered_body(request: &ProxyRequest) -> bool { diff --git a/crates/tinycomputer-browser/src/egress/request/body/chunked.rs b/crates/tinycomputer-browser/src/egress/request/body/chunked.rs index 0cfea9ae3..592d15464 100644 --- a/crates/tinycomputer-browser/src/egress/request/body/chunked.rs +++ b/crates/tinycomputer-browser/src/egress/request/body/chunked.rs @@ -6,6 +6,10 @@ use tokio::io::AsyncReadExt; use crate::egress::forward::write_all_bounded; +#[cfg(test)] +#[path = "chunked_tests.rs"] +mod chunked_tests; + pub(super) async fn forward_chunked_request_body( client: &mut C, upstream: &mut U, diff --git a/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs b/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs index f52e45f2c..2aab0e172 100644 --- a/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs +++ b/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs @@ -2,7 +2,7 @@ #![allow(clippy::expect_used, clippy::unwrap_used)] -use super::chunked::forward_chunked_request_body; +use super::forward_chunked_request_body; use tokio::io::{AsyncReadExt, AsyncWriteExt}; async fn forward(input: &[u8]) -> std::io::Result> { diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index 4a0c6ffac..71a0b00fb 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -8,7 +8,7 @@ use super::{ BrowserDialTarget, DialGrant, EgressAuthorizer, forward::{ forward_request_body_with_lease, forward_response_with_lease, initialize_upstream, refuse, - tunnel_with_lease, validate_lease, + tunnel_with_lease, validate_lease, validation_interval, }, request::{has_valid_buffered_body, read_proxy_request}, }; @@ -54,10 +54,20 @@ where else { return refuse(&mut client).await; }; + let mut validations = validation_interval(); if !validate_lease(&auth, &lease).await? { return Ok(()); } - if !initialize_upstream(&mut client, &mut upstream, &request, &auth, &lease).await? { + if !initialize_upstream( + &mut client, + &mut upstream, + &request, + &auth, + &lease, + &mut validations, + ) + .await? + { return Ok(()); } if request.connect || request.has_upgrade { @@ -80,6 +90,7 @@ where &request, &auth, &lease, + &mut validations, ) => { if upload? { response.await?; From 499ca179a6f8eb6b225126ad0100e0cb184bf773 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 21:05:16 +0000 Subject: [PATCH 89/93] Document egress launch environment restrictions Co-authored-by: Medulla --- .env.example | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/.env.example b/.env.example index 58ad77e21..975167587 100644 --- a/.env.example +++ b/.env.example @@ -64,6 +64,19 @@ TINYCOMPUTER_LAB_SELF_EMAIL= # TINYCOMPUTER_BROWSER_ARGS=--no-first-run # TINYCOMPUTER_BROWSER_USER_AGENT= # TINYCOMPUTER_BROWSER_ENDPOINT=http://127.0.0.1:9222 +# Enforced browser egress refuses a launch if any of these ambient agent-browser +# variables are present. Unset them (including empty assignments) to use egress. +# AGENT_BROWSER_CDP= +# AGENT_BROWSER_AUTO_CONNECT= +# AGENT_BROWSER_PROVIDER= +# AGENT_BROWSER_ENGINE= +# AGENT_BROWSER_EXECUTABLE_PATH= +# AGENT_BROWSER_PROXY= +# AGENT_BROWSER_PROXY_BYPASS= +# AGENT_BROWSER_PROXY_USERNAME= +# AGENT_BROWSER_PROXY_PASSWORD= +# AGENT_BROWSER_PROFILE= +# AGENT_BROWSER_RESTORE= # task_live: 1 shows the browser the task launches instead of running it # headless (a headed run needs a display, so it runs on the host). # TASK_HEADED=1 From e0a0072575684d274b922e725fb589fbb3407bd4 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 21:16:31 +0000 Subject: [PATCH 90/93] fix(egress): share lease validation schedule across request and response The lease validation clock is now threaded through tunnel and response forwarding instead of being created per call, so the response phase continues the request phase's validation schedule rather than restarting it. A test covers the shared schedule across both phases. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .../src/egress/egress_tests/forward_tests.rs | 60 +++++++++++++++++-- .../src/egress/forward.rs | 28 +++++---- .../tinycomputer-browser/src/egress/serve.rs | 7 ++- 3 files changed, 76 insertions(+), 19 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/egress_tests/forward_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/forward_tests.rs index 6f1c4e0cf..bf799cc13 100644 --- a/crates/tinycomputer-browser/src/egress/egress_tests/forward_tests.rs +++ b/crates/tinycomputer-browser/src/egress/egress_tests/forward_tests.rs @@ -71,6 +71,7 @@ async fn validates_lease_while_response_write_is_blocked() { let authorizer = Arc::new(RevokingAuthorizer(AtomicUsize::new(0))); let validation_count = Arc::clone(&authorizer); let authorizer: Arc = authorizer; + let validations = super::super::forward::validation_interval(); let task = tokio::spawn(async move { let mut upstream = upstream; super::super::forward::forward_response_with_lease( @@ -78,6 +79,7 @@ async fn validates_lease_while_response_write_is_blocked() { &mut upstream, &authorizer, "lease".to_owned(), + &validations, ) .await }); @@ -101,7 +103,7 @@ async fn stops_initial_upstream_write_when_lease_is_revoked() { let authorizer = Arc::new(RevokingAuthorizer(AtomicUsize::new(0))); let validation_count = Arc::clone(&authorizer); let authorizer: Arc = authorizer; - let mut validations = super::super::forward::validation_interval(); + let validations = super::super::forward::validation_interval(); let task = tokio::spawn(async move { super::super::forward::write_all_with_lease( &mut BlockedWriter, @@ -109,7 +111,7 @@ async fn stops_initial_upstream_write_when_lease_is_revoked() { "browser upstream request timed out", &authorizer, "lease", - &mut validations, + &validations, ) .await }); @@ -133,7 +135,7 @@ async fn request_write_phases_share_the_lease_validation_interval() { let authorizer = Arc::new(RevokingAuthorizer(AtomicUsize::new(0))); let validation_count = Arc::clone(&authorizer); let authorizer: Arc = authorizer; - let mut validations = super::super::forward::validation_interval(); + let validations = super::super::forward::validation_interval(); let (mut writer, _reader) = tokio::io::duplex(32); assert!( @@ -143,7 +145,7 @@ async fn request_write_phases_share_the_lease_validation_interval() { "browser upstream request timed out", &authorizer, "lease", - &mut validations, + &validations, ) .await .unwrap() @@ -157,7 +159,7 @@ async fn request_write_phases_share_the_lease_validation_interval() { "browser upstream body timed out", &authorizer, "lease", - &mut validations, + &validations, ) .await }); @@ -173,3 +175,51 @@ async fn request_write_phases_share_the_lease_validation_interval() { assert!(!task.await.unwrap().unwrap()); assert_eq!(validation_count.0.load(Ordering::SeqCst), 2); } + +#[tokio::test(start_paused = true)] +async fn response_forwarding_keeps_the_request_lease_validation_schedule() { + let authorizer = Arc::new(RevokingAuthorizer(AtomicUsize::new(0))); + let validation_count = Arc::clone(&authorizer); + let authorizer: Arc = authorizer; + let validations = super::super::forward::validation_interval(); + let (mut upstream_writer, upstream) = tokio::io::duplex(32); + upstream_writer.write_all(b"response").await.unwrap(); + drop(upstream_writer); + + assert!( + super::super::forward::write_all_with_lease( + &mut tokio::io::sink(), + b"request headers", + "browser upstream request timed out", + &authorizer, + "lease", + &validations, + ) + .await + .unwrap() + ); + tokio::time::advance(Duration::from_millis(900)).await; + + let task = tokio::spawn(async move { + let mut upstream = upstream; + super::super::forward::forward_response_with_lease( + &mut BlockedWriter, + &mut upstream, + &authorizer, + "lease".to_owned(), + &validations, + ) + .await + }); + tokio::task::yield_now().await; + assert_eq!(validation_count.0.load(Ordering::SeqCst), 0); + + tokio::time::advance(Duration::from_millis(100)).await; + tokio::task::yield_now().await; + assert_eq!(validation_count.0.load(Ordering::SeqCst), 1); + + tokio::time::advance(Duration::from_secs(1)).await; + tokio::task::yield_now().await; + assert!(task.await.unwrap().is_ok()); + assert_eq!(validation_count.0.load(Ordering::SeqCst), 2); +} diff --git a/crates/tinycomputer-browser/src/egress/forward.rs b/crates/tinycomputer-browser/src/egress/forward.rs index 433089bce..f23fbf3cc 100644 --- a/crates/tinycomputer-browser/src/egress/forward.rs +++ b/crates/tinycomputer-browser/src/egress/forward.rs @@ -110,14 +110,14 @@ pub(super) async fn tunnel_with_lease( upstream: &mut TcpStream, auth: &Arc, lease: String, + validations: &LeaseValidationClock, ) -> io::Result<()> { let relay = copy_bidirectional(client, upstream); tokio::pin!(relay); - let mut validations = validation_interval(); loop { tokio::select! { biased; - _ = validations.tick() => { + _ = wait_for_validation(validations) => { if !validate_lease(auth, &lease).await? { return Ok(()); } }, result = &mut relay => { result?; return Ok(()); }, @@ -130,17 +130,17 @@ pub(super) async fn forward_response_with_lease( upstream: &mut U, auth: &Arc, lease: String, + validations: &LeaseValidationClock, ) -> io::Result<()> where C: tokio::io::AsyncWrite + Unpin, U: tokio::io::AsyncRead + Unpin, { let mut chunk = [0u8; 8192]; - let mut validations = validation_interval(); loop { tokio::select! { biased; - _ = validations.tick() => { + _ = wait_for_validation(validations) => { if !validate_lease(auth, &lease).await? { return Ok(()); } }, result = upstream.read(&mut chunk) => { @@ -155,7 +155,7 @@ where loop { tokio::select! { biased; - _ = validations.tick() => { + _ = wait_for_validation(validations) => { if !validate_lease(auth, &lease).await? { return Ok(()); } }, result = &mut write => { result?; break; }, @@ -172,7 +172,7 @@ pub(super) async fn forward_request_body_with_lease( request: &ProxyRequest, auth: &Arc, lease: &str, - validations: &mut tokio::time::Interval, + validations: &LeaseValidationClock, ) -> io::Result where C: tokio::io::AsyncRead + Unpin, @@ -183,7 +183,7 @@ where loop { tokio::select! { biased; - _ = validations.tick() => { + _ = wait_for_validation(validations) => { if !validate_lease(auth, lease).await? { return Ok(false); } }, result = &mut body => { result?; return Ok(true); }, @@ -191,11 +191,17 @@ where } } -pub(super) fn validation_interval() -> tokio::time::Interval { +pub(super) type LeaseValidationClock = Arc>; + +pub(super) fn validation_interval() -> LeaseValidationClock { let period = Duration::from_secs(1); let mut interval = tokio::time::interval_at(tokio::time::Instant::now() + period, period); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); - interval + Arc::new(tokio::sync::Mutex::new(interval)) +} + +async fn wait_for_validation(validations: &LeaseValidationClock) { + validations.lock().await.tick().await; } pub(super) async fn validate_lease( @@ -236,14 +242,14 @@ pub(super) async fn write_all_with_lease( message: &'static str, auth: &Arc, lease: &str, - validations: &mut tokio::time::Interval, + validations: &LeaseValidationClock, ) -> io::Result { let write = write_all_bounded(stream, bytes, message); tokio::pin!(write); loop { tokio::select! { biased; - _ = validations.tick() => { + _ = wait_for_validation(validations) => { if !validate_lease(auth, lease).await? { return Ok(false); } }, result = &mut write => { result?; return Ok(true); }, diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index 71a0b00fb..04216cdf6 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -64,14 +64,14 @@ where &request, &auth, &lease, - &mut validations, + &validations, ) .await? { return Ok(()); } if request.connect || request.has_upgrade { - tunnel_with_lease(&mut client, &mut upstream, &auth, lease).await?; + tunnel_with_lease(&mut client, &mut upstream, &auth, lease, &validations).await?; } else { let (mut client_reader, mut client_writer) = client.into_split(); let (mut upstream_reader, mut upstream_writer) = upstream.into_split(); @@ -80,6 +80,7 @@ where &mut upstream_reader, &auth, lease.clone(), + &validations, ); tokio::pin!(response); tokio::select! { @@ -90,7 +91,7 @@ where &request, &auth, &lease, - &mut validations, + &validations, ) => { if upload? { response.await?; From b9480ab2134c15e2ab0f39417d0474e872d63cc1 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 21:16:47 +0000 Subject: [PATCH 91/93] fix(egress): drop unnecessary mut on validation interval The binding for the validation interval no longer needs to be mutable, so the mut qualifier was removed to keep the code warning-free. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/serve.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinycomputer-browser/src/egress/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs index 04216cdf6..21c718cac 100644 --- a/crates/tinycomputer-browser/src/egress/serve.rs +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -54,7 +54,7 @@ where else { return refuse(&mut client).await; }; - let mut validations = validation_interval(); + let validations = validation_interval(); if !validate_lease(&auth, &lease).await? { return Ok(()); } From cf70a99676a7bc8bbe6b76d84da825117a0df7f7 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 21:17:05 +0000 Subject: [PATCH 92/93] fix(egress): accept lease validation clock in initialize_upstream The upstream initialization helper now takes a LeaseValidationClock reference instead of a tokio interval, matching the validation clock type used elsewhere in the egress path. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/forward.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinycomputer-browser/src/egress/forward.rs b/crates/tinycomputer-browser/src/egress/forward.rs index f23fbf3cc..3d74eca21 100644 --- a/crates/tinycomputer-browser/src/egress/forward.rs +++ b/crates/tinycomputer-browser/src/egress/forward.rs @@ -18,7 +18,7 @@ pub(super) async fn initialize_upstream( request: &ProxyRequest, auth: &Arc, lease: &str, - validations: &mut tokio::time::Interval, + validations: &LeaseValidationClock, ) -> io::Result { if request.connect { write_all_bounded( From ebbfb428a83278987f1eb4316e1761c55246f6f2 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 21:17:54 +0000 Subject: [PATCH 93/93] refactor(egress): match unit pattern in lease validation select arms The select branches waiting on lease validation now bind the future's unit result with `()` instead of `_`, making the expected output type explicit at each call site. No behaviour change. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- crates/tinycomputer-browser/src/egress/forward.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/tinycomputer-browser/src/egress/forward.rs b/crates/tinycomputer-browser/src/egress/forward.rs index 3d74eca21..d52f5d79f 100644 --- a/crates/tinycomputer-browser/src/egress/forward.rs +++ b/crates/tinycomputer-browser/src/egress/forward.rs @@ -117,7 +117,7 @@ pub(super) async fn tunnel_with_lease( loop { tokio::select! { biased; - _ = wait_for_validation(validations) => { + () = wait_for_validation(validations) => { if !validate_lease(auth, &lease).await? { return Ok(()); } }, result = &mut relay => { result?; return Ok(()); }, @@ -140,7 +140,7 @@ where loop { tokio::select! { biased; - _ = wait_for_validation(validations) => { + () = wait_for_validation(validations) => { if !validate_lease(auth, &lease).await? { return Ok(()); } }, result = upstream.read(&mut chunk) => { @@ -155,7 +155,7 @@ where loop { tokio::select! { biased; - _ = wait_for_validation(validations) => { + () = wait_for_validation(validations) => { if !validate_lease(auth, &lease).await? { return Ok(()); } }, result = &mut write => { result?; break; }, @@ -183,7 +183,7 @@ where loop { tokio::select! { biased; - _ = wait_for_validation(validations) => { + () = wait_for_validation(validations) => { if !validate_lease(auth, lease).await? { return Ok(false); } }, result = &mut body => { result?; return Ok(true); }, @@ -249,7 +249,7 @@ pub(super) async fn write_all_with_lease( loop { tokio::select! { biased; - _ = wait_for_validation(validations) => { + () = wait_for_validation(validations) => { if !validate_lease(auth, lease).await? { return Ok(false); } }, result = &mut write => { result?; return Ok(true); },