diff --git a/.env.example b/.env.example index c3ccee456..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 @@ -103,3 +116,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 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", diff --git a/crates/tinycomputer-browser/Cargo.toml b/crates/tinycomputer-browser/Cargo.toml index c699924eb..92e2e9ef6 100644 --- a/crates/tinycomputer-browser/Cargo.toml +++ b/crates/tinycomputer-browser/Cargo.toml @@ -36,9 +36,11 @@ 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 } +# 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`. @@ -50,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/README.md b/crates/tinycomputer-browser/README.md index a31fe4fa0..4ee4cbb59 100644 --- a/crates/tinycomputer-browser/README.md +++ b/crates/tinycomputer-browser/README.md @@ -30,5 +30,23 @@ 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 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_`. +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/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. 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..f864482ee --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/egress_tests.rs @@ -0,0 +1,35 @@ +//! Listener lifecycle tests for the browser egress proxy. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +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() { + 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/egress_tests/authority_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/authority_tests.rs new file mode 100644 index 000000000..546651d50 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/egress_tests/authority_tests.rs @@ -0,0 +1,48 @@ +//! Authority parsing and redaction tests. + +use crate::{BrowserDialTarget, DialGrant, egress::parse_authority}; + +#[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()); +} diff --git a/crates/tinycomputer-browser/src/egress/egress_tests/body_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/body_tests.rs new file mode 100644 index 000000000..b82d4fb6f --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/egress_tests/body_tests.rs @@ -0,0 +1,344 @@ +//! 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(); +} + +#[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]); + } + 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 { + reader.read_to_end(&mut request_body).await.unwrap(); + request_body + }); + writer + .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]; + writer.write_all(&body).await.unwrap(); + writer.shutdown().await.unwrap(); + request_reader.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') + ); + assert_eq!(server.await.unwrap().len(), REQUEST_BODY_LENGTH); +} diff --git a/crates/tinycomputer-browser/src/egress/egress_tests/connect_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/connect_tests.rs new file mode 100644 index 000000000..9d2ccd4ce --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/egress_tests/connect_tests.rs @@ -0,0 +1,63 @@ +//! CONNECT proxy tests. + +use super::simulator::*; +use crate::EgressProxy; +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() { + 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/egress_tests/forward_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/forward_tests.rs new file mode 100644 index 000000000..bf799cc13 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/egress_tests/forward_tests.rs @@ -0,0 +1,225 @@ +//! 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 validations = super::super::forward::validation_interval(); + 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_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); +} + +#[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 validations = super::super::forward::validation_interval(); + 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", + &validations, + ) + .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); +} + +#[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 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", + &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", + &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); +} + +#[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/egress_tests/http_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/http_tests.rs new file mode 100644 index 000000000..575451b22 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/egress_tests/http_tests.rs @@ -0,0 +1,210 @@ +//! HTTP request, body, authentication, and refusal tests. + +use super::simulator::*; +use crate::EgressProxy; +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() { + 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 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/egress_tests/lease_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/lease_tests.rs new file mode 100644 index 000000000..a1e1c5474 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/egress_tests/lease_tests.rs @@ -0,0 +1,124 @@ +//! Lease validation and revocation tests for active streams. + +use super::simulator::*; +use crate::EgressProxy; +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() { + 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(); + let _ = 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 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(); + let _ = tokio::time::timeout( + std::time::Duration::from_secs(4), + client.read_to_end(&mut response), + ) + .await + .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/egress_tests/lifecycle_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/lifecycle_tests.rs new file mode 100644 index 000000000..74acaf4c9 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/egress_tests/lifecycle_tests.rs @@ -0,0 +1,26 @@ +//! Session proxy listener lifecycle tests. + +use super::simulator::*; +use crate::EgressProxy; +use std::sync::{Arc, atomic::AtomicBool}; +use tokio::net::{TcpListener, TcpStream}; + +#[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/egress_tests/retry_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/retry_tests.rs new file mode 100644 index 000000000..f82361eda --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/egress_tests/retry_tests.rs @@ -0,0 +1,56 @@ +//! Proxy retry behavior for multiple approved addresses. + +use super::simulator::*; +use crate::{BrowserDialTarget, EgressAuthorizer, egress::connect_approved_addresses}; +use std::{ + io, + net::SocketAddr, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, +}; +use tokio::{net::TcpListener, net::TcpStream}; + +#[tokio::test] +async fn proxy_tries_later_addresses_when_the_first_granted_address_is_unreachable() { + 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 { + let (socket, _) = destination.accept().await.unwrap(); + socket.local_addr().unwrap() + }); + 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 first_grant = authorizer.authorize(target.clone()).await.unwrap(); + let dial_attempts = Arc::new(AtomicUsize::new(0)); + let counted_attempts = Arc::clone(&dial_attempts); + 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 + } + } + }; + + 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); +} diff --git a/crates/tinycomputer-browser/src/egress/egress_tests/simulator.rs b/crates/tinycomputer-browser/src/egress/egress_tests/simulator.rs new file mode 100644 index 000000000..0dbf8d2c1 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/egress_tests/simulator.rs @@ -0,0 +1,169 @@ +//! Local authorizers and fixture helpers shared by egress tests. + +use crate::{BrowserDialTarget, DialGrant, EgressAuthorizer}; +use base64::Engine as _; +use std::{ + io, + net::SocketAddr, + sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, +}; + +pub(super) const FIXTURE_PASSWORD: &str = "fixture-proxy-secret"; + +pub(super) fn proxy_authorization() -> String { + format!( + "Basic {}", + base64::engine::general_purpose::STANDARD + .encode(format!("tinycomputer:{FIXTURE_PASSWORD}")) + ) +} + +#[derive(Clone)] +pub(super) struct FixtureAuthorizer { + pub(super) address: SocketAddr, + pub(super) allow: bool, + pub(super) 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) }) + } +} + +pub(super) struct MultiAddressAuthorizer { + pub(super) 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) }) + } +} + +pub(super) struct RevokingAuthorizer { + pub(super) address: SocketAddr, + pub(super) 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/egress_tests/websocket_tests.rs b/crates/tinycomputer-browser/src/egress/egress_tests/websocket_tests.rs new file mode 100644 index 000000000..a1542d3d0 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/egress_tests/websocket_tests.rs @@ -0,0 +1,77 @@ +//! WebSocket upgrade 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_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(); +} diff --git a/crates/tinycomputer-browser/src/egress/forward.rs b/crates/tinycomputer-browser/src/egress/forward.rs new file mode 100644 index 000000000..d52f5d79f --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/forward.rs @@ -0,0 +1,258 @@ +//! Forwards authorized proxy traffic and keeps active streams tied to their lease. + +use std::{io, sync::Arc, time::Duration}; + +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt, copy_bidirectional}, + net::TcpStream, +}; + +use super::{ + EgressAuthorizer, + request::{ProxyRequest, buffered_body_len, read_request_body}, +}; + +pub(super) async fn initialize_upstream( + client: &mut TcpStream, + upstream: &mut TcpStream, + request: &ProxyRequest, + auth: &Arc, + lease: &str, + validations: &LeaseValidationClock, +) -> 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_with_lease( + upstream, + &request.bytes[request.split..], + "browser CONNECT payload timed out", + auth, + lease, + validations, + ) + .await; + } + return Ok(true); + } + 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"); + } + if !write_all_with_lease( + upstream, + forwarded.as_bytes(), + "browser upstream request timed out", + auth, + lease, + validations, + ) + .await? + { + return Ok(false); + } + if request.chunked { + Ok(true) + } else { + write_all_with_lease( + upstream, + &request.bytes[request.split..], + "browser upstream body timed out", + auth, + lease, + validations, + ) + .await + } +} +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( + 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, + validations: &LeaseValidationClock, +) -> io::Result<()> { + let relay = copy_bidirectional(client, upstream); + tokio::pin!(relay); + loop { + tokio::select! { + biased; + () = wait_for_validation(validations) => { + if !validate_lease(auth, &lease).await? { return Ok(()); } + }, + result = &mut relay => { result?; return Ok(()); }, + } + } +} + +pub(super) async fn forward_response_with_lease( + client: &mut C, + 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]; + loop { + tokio::select! { + biased; + () = wait_for_validation(validations) => { + if !validate_lease(auth, &lease).await? { return Ok(()); } + }, + result = upstream.read(&mut chunk) => { + let n = result?; + if n == 0 { return Ok(()); } + let write = write_all_bounded( + client, + &chunk[..n], + "browser response write timed out", + ); + tokio::pin!(write); + loop { + tokio::select! { + biased; + () = wait_for_validation(validations) => { + if !validate_lease(auth, &lease).await? { return Ok(()); } + }, + result = &mut write => { result?; break; }, + } + } + }, + } + } +} + +pub(super) async fn forward_request_body_with_lease( + client: &mut C, + upstream: &mut U, + request: &ProxyRequest, + auth: &Arc, + lease: &str, + validations: &LeaseValidationClock, +) -> 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); + loop { + tokio::select! { + biased; + () = wait_for_validation(validations) => { + if !validate_lease(auth, lease).await? { return Ok(false); } + }, + result = &mut body => { result?; return Ok(true); }, + } + } +} + +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); + 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( + 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 W, + 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))? +} + +pub(super) async fn write_all_with_lease( + stream: &mut W, + bytes: &[u8], + message: &'static str, + auth: &Arc, + lease: &str, + validations: &LeaseValidationClock, +) -> io::Result { + let write = write_all_bounded(stream, bytes, message); + tokio::pin!(write); + loop { + tokio::select! { + biased; + () = 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/mod.rs b/crates/tinycomputer-browser/src/egress/mod.rs new file mode 100644 index 000000000..fc7760fb3 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/mod.rs @@ -0,0 +1,145 @@ +//! 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 tokio::{ + net::{TcpListener, TcpStream}, + task::JoinSet, +}; + +mod forward; +mod request; +mod serve; + +#[cfg(test)] +pub(crate) use serve::connect_approved_addresses; + +#[cfg(test)] +mod egress_tests; + +#[cfg(test)] +pub(crate) 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 = 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(); + connections.spawn(async move { + let _ = Box::pin(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()) + } +} + +async fn accept_connection(accepted: A) -> Option<(TcpStream, SocketAddr)> +where + A: Future>, +{ + match accepted.await { + Ok(connection) => Some(connection), + Err(error) => { + log::warn!("browser proxy listener accept failed: {error}"); + tokio::time::sleep(Duration::from_millis(50)).await; + None + } + } +} + +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..2fa6a61b8 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/request.rs @@ -0,0 +1,263 @@ +//! Parses and validates browser proxy requests before a destination is authorized. + +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::{io::AsyncReadExt, net::TcpStream}; + +use super::{ + BrowserDialTarget, + forward::{constant_time_eq, refuse, write_all_bounded}, +}; + +pub(super) 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) chunked: bool, + 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, + chunked: headers.chunked, + 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, + chunked: bool, + 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; + let mut chunked = false; + let mut saw_transfer_encoding = 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().ok()?; + } 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 + .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 + || (saw_content_length && chunked) + || ((connect || has_upgrade) && (body_len != 0 || chunked)) + { + return None; + } + Some(ParsedHeaders { + body_len, + chunked, + 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(crate) 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/request/body.rs b/crates/tinycomputer-browser/src/egress/request/body.rs new file mode 100644 index 000000000..6d2356eb6 --- /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, time::Duration}; + +use tokio::io::AsyncReadExt; + +use crate::egress::forward::write_all_bounded; + +mod chunked; + +use super::ProxyRequest; + +pub(in crate::egress) 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(in crate::egress) 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(in crate::egress) 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/body/chunked.rs b/crates/tinycomputer-browser/src/egress/request/body/chunked.rs new file mode 100644 index 000000000..592d15464 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/request/body/chunked.rs @@ -0,0 +1,184 @@ +//! Bounded HTTP/1.1 chunk framing validation and forwarding. + +use std::{io, time::Duration}; + +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, + initial: &[u8], +) -> 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; + 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 C, + 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; + 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); + } + 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 C, + 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) +} 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..2aab0e172 --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/request/body/chunked_tests.rs @@ -0,0 +1,75 @@ +//! Failure cases for bounded chunked request framing. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +use super::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)); + 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() { + upstream_writer.shutdown().await?; + } + drop(client_reader); + drop(upstream_writer); + let mut output = Vec::new(); + 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 = b"1;".to_vec(); + input.resize(8193, b'x'); + input.extend_from_slice(b"\r\n"); + 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] +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/serve.rs b/crates/tinycomputer-browser/src/egress/serve.rs new file mode 100644 index 000000000..21c718cac --- /dev/null +++ b/crates/tinycomputer-browser/src/egress/serve.rs @@ -0,0 +1,156 @@ +//! Authorizes requests and consumes grants before dialing approved addresses. + +use std::{future::Future, io, net::SocketAddr, sync::Arc, time::Duration}; + +use tokio::net::TcpStream; + +use super::{ + BrowserDialTarget, DialGrant, EgressAuthorizer, + forward::{ + forward_request_body_with_lease, forward_response_with_lease, initialize_upstream, refuse, + tunnel_with_lease, validate_lease, validation_interval, + }, + request::{has_valid_buffered_body, read_proxy_request}, +}; + +pub(super) async fn serve( + client: TcpStream, + auth: Arc, + session_id: String, + proxy_password: String, +) -> io::Result<()> { + Box::pin(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(()); + }; + if !has_valid_buffered_body(&request) { + return refuse(&mut client).await; + } + let Some(first_grant) = authorize(&auth, &request.target).await else { + return refuse(&mut client).await; + }; + let Some((mut upstream, lease)) = + connect_approved_addresses(&auth, &request.target, first_grant, &mut connect).await + else { + return refuse(&mut client).await; + }; + let validations = validation_interval(); + if !validate_lease(&auth, &lease).await? { + return Ok(()); + } + if !initialize_upstream( + &mut client, + &mut upstream, + &request, + &auth, + &lease, + &validations, + ) + .await? + { + return Ok(()); + } + if request.connect || request.has_upgrade { + 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(); + let response = forward_response_with_lease( + &mut client_writer, + &mut upstream_reader, + &auth, + lease.clone(), + &validations, + ); + tokio::pin!(response); + tokio::select! { + result = &mut response => result?, + upload = forward_request_body_with_lease( + &mut client_reader, + &mut upstream_writer, + &request, + &auth, + &lease, + &validations, + ) => { + if upload? { + response.await?; + } + } + } + } + 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, +) -> 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, + } +} diff --git a/crates/tinycomputer-browser/src/lib.rs b/crates/tinycomputer-browser/src/lib.rs index 17b07a80c..4786da69a 100644 --- a/crates/tinycomputer-browser/src/lib.rs +++ b/crates/tinycomputer-browser/src/lib.rs @@ -38,6 +38,7 @@ mod action_gate; mod convert; mod deep; +mod egress; mod engine; mod error; #[cfg(test)] @@ -56,10 +57,11 @@ pub use action_gate::{ ActionContext, ActionGate, ActionRequest, ActionTarget, ActionVerdict, AllowAllActions, ObservationKind, }; +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 observer::{ActionObservation, ActionObserver, ObservedAction, ObservedTarget}; pub use outputs::SWEEP_INTERVAL; pub use profile_lock::{claim_profile, in_use as profile_in_use, release as release_profile}; diff --git a/crates/tinycomputer-browser/src/linked/linked_tests.rs b/crates/tinycomputer-browser/src/linked/linked_tests.rs index e19488e15..f5197bde4 100644 --- a/crates/tinycomputer-browser/src/linked/linked_tests.rs +++ b/crates/tinycomputer-browser/src/linked/linked_tests.rs @@ -7,9 +7,40 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::json; +use std::{io, net::SocketAddr, sync::Arc}; -use super::AgentBrowser; -use crate::engine::Launcher; +use super::{AgentBrowser, ENGINE, EnforcedAgentBrowser, Linked, 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 +53,135 @@ async fn an_empty_command_is_answered_without_launching_a_browser() { .is_some_and(|error| !error.is_empty()) ); } + +#[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"); + 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] +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 { + 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 { + 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") + ); +} + +mod launch_tests; +#[cfg(live_browser_tests)] +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..085f0214b --- /dev/null +++ b/crates/tinycomputer-browser/src/linked/linked_tests/live_tests.rs @@ -0,0 +1,313 @@ +//! Live Chromium egress tests that use local HTTP and WebSocket fixtures. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::EnforcedAgentBrowser; +use crate::engine::Launcher; +use crate::{BrowserDialTarget, DialGrant, EgressAuthorizer}; +use serde_json::json; +use std::{ + io, + net::SocketAddr, + sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, + }, + time::Duration, +}; +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(), + denied_targets: Arc::new(Mutex::new(Vec::new())), + })) + .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 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!( + "", + 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)), + denied_targets: denied_targets.clone(), + })) + .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; + wait_for_denied_target(&denied_targets, denied_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 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 { + 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)), + denied_targets: denied_targets.clone(), + })) + .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; + wait_for_denied_target(&denied_targets, denied_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 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!( + "", + 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)), + denied_targets: denied_targets.clone(), + })) + .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; + wait_for_denied_target(&denied_targets, denied_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, + 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)] +impl EgressAuthorizer for RejectAllButFixture { + fn authorize( + &self, + target: BrowserDialTarget, + ) -> 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 allowed { + 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) }) + } +} diff --git a/crates/tinycomputer-browser/src/linked/mod.rs b/crates/tinycomputer-browser/src/linked/mod.rs index f570def6c..191ec8419 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,253 @@ 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); + 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 + 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 + .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()); + 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; + 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; + } + 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( + 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); + } + 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 has_ambient_browser_config { + 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) +} + +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; 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..bef43c76c --- /dev/null +++ b/crates/tinycomputer-bus/src/browser_egress/browser_egress_tests.rs @@ -0,0 +1,154 @@ +//! 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, + }; + 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!( + 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"]); +} + +#[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..a34236c37 --- /dev/null +++ b/crates/tinycomputer-bus/src/browser_egress/mod.rs @@ -0,0 +1,36 @@ +//! 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. + +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"; +/// 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]; + +#[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, +} 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 c238b7aef..d2c7e2cfe 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, 24); +pub const CONTRACT_VERSION: (u32, u32) = (2, 25); /// 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, 24); /// ``` /// # use tinycomputer_bus::{is_compatible, CONTRACT_VERSION}; /// assert!(is_compatible(CONTRACT_VERSION)); -/// assert!(is_compatible((2, 24))); +/// assert!(is_compatible((2, 25))); /// 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 807b21afc..37d58e5bb 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, 24)); + assert_eq!(CONTRACT_VERSION, (2, 25)); } #[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, 24))); + assert!(is_compatible((2, 25))); assert!(is_compatible((2, 97))); // 2.24 adds same-task flow-to-planner handoff to StartTask. // 2.22 adds optional host-held secret handles to StartTask and RunFlow. @@ -41,6 +41,12 @@ fn a_newer_minor_on_the_module_side_binds() { // would never reach the host's policy. assert!(!is_compatible((2, 23))); assert!(!is_compatible((2, 22))); + // 2.25 adds BrowserEgressHost (Authorize/Consume/Validate): a 2.25 host + // serves it, while a 2.24 module cannot enforce per-destination browser dials. + // 2.20 adds SessionOptions' optional browser identity and fingerprint fields. + assert!(!is_compatible((2, 24))); + assert!(!is_compatible((2, 20))); + 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..2ad5a1bd1 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/browser_egress.rs @@ -0,0 +1,153 @@ +//! 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)] +mod browser_egress_tests; diff --git a/crates/tinycomputer/src/tinybus_module/browser_egress/browser_egress_tests.rs b/crates/tinycomputer/src/tinybus_module/browser_egress/browser_egress_tests.rs new file mode 100644 index 000000000..5e385e679 --- /dev/null +++ b/crates/tinycomputer/src/tinybus_module/browser_egress/browser_egress_tests.rs @@ -0,0 +1,186 @@ +//! Tests for the mechanical TinyBus-to-TinySecurity browser egress adapter. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +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 { + tokio::task::yield_now().await; + 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 { + tokio::task::yield_now().await; + 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 { + tokio::task::yield_now().await; + 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 c32b4d8b3..2a5ad2ad4 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, 24)); + assert_eq!(CONTRACT_VERSION, (2, 25)); } #[test] diff --git a/docs/crates/tinycomputer-bus/versioning.md b/docs/crates/tinycomputer-bus/versioning.md index b8229e67b..abeaff0dd 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, 25); ``` This describes the *vocabulary*: the member set and the payload shapes, @@ -45,15 +45,16 @@ 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 - host expects, plus something newer the host simply does not use yet, so - it is accepted. + built against `(2, 24)` expects at least the members and fields that + existed at `(2, 24)`. A module reporting `(2, 23)` might be missing one of + them, so it is rejected. A module reporting `(2, 24)` is an exact match + and is accepted. A module reporting `(2, 25)` 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, 25), the exact version this crate ships +assert!(is_compatible((2, 26))); // 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..e4c1a1539 100644 --- a/docs/crates/tinycomputer/configuration.md +++ b/docs/crates/tinycomputer/configuration.md @@ -217,12 +217,14 @@ 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 + "prelaunch": true, + "egress": { + "policy_id": "host-selected-policy", + "generation": 4 + } } } ``` @@ -240,6 +242,29 @@ 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. | + +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 +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 diff --git a/docs/technical/specs/desktop-module-contract.md b/docs/technical/specs/desktop-module-contract.md index 8668aa597..d2503c36d 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.25): 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 uploads, tunnels, or responses remain active. A 2.24 +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 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`.