The headless browser for AI agents and web scraping
Limit default CDP origins to the endpoint authority
SGavrl1faf17f8b6bd
diff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rsindex 88ccd403..e01f928c 100644--- a/crates/obscura-cdp/src/server.rs+++ b/crates/obscura-cdp/src/server.rs@@ -151,45 +151,27 @@ enum ControlRefusal {}/// Origin allowlist for CDP callers, read from `OBSCURA_CDP_ALLOWED_ORIGINS`-/// (comma-separated, `*` allows every origin). Unset means only the-/// Chrome-default policy in `origin_accepted` applies.+/// (comma-separated, `*` allows every origin). Unset accepts only the+/// endpoint's own HTTP origin.fn allowed_origins_env() -> Option<String> {std::env::var("OBSCURA_CDP_ALLOWED_ORIGINS").ok().filter(|s| !s.trim().is_empty())}-/// Whether a control connection's `Origin` header is accepted (issue #1495).-///-/// Chrome's DevTools handler rejects a WebSocket handshake whose `Origin` is-/// neither the server's own address nor allowlisted, but Puppeteer, Playwright,-/// and chrome-remote-interface all send a normal loopback `Origin` on every-/// connect, so refusing every request with an `Origin` header locked those-/// clients out entirely. The Chrome-compatible policy here:-///-/// - an entry in `OBSCURA_CDP_ALLOWED_ORIGINS` (exact, case-insensitive, `*`-/// wildcard — the `--remote-allow-origins` semantics) overrides everything,-/// including the `null` origin that sandboxed pages send,-/// - a loopback origin (any `localhost` / loopback host, any port) is-/// accepted: such a page is served by a local process, the same trust-/// domain as the automation client itself,-/// - an origin equal to the server's own `http://<bind-ip>:<bind-port>`-/// address is accepted (Chrome's same-origin rule).-///-/// Requests without an `Origin` header (native clients) never reach this.+// The request authority can name the public listener instead of its worker.+// Host validation and authentication still apply after the origin check.fn origin_accepted(origin: &str,- bind_ip: std::net::IpAddr,- bind_port: u16,+ request_host: Option<&str>,allowed_origins: Option<&str>,) -> bool {let origin = origin.trim();if let Some(list) = allowed_origins {- let wanted = origin.to_ascii_lowercase();if list.split(',').map(str::trim)- .any(|entry| entry == "*" || entry.eq_ignore_ascii_case(&wanted))+ .any(|entry| entry == "*" || entry.eq_ignore_ascii_case(origin)){return true;}@@ -197,23 +179,20 @@ fn origin_accepted(let Ok(parsed) = url::Url::parse(origin) else {return false;};- let scheme = parsed.scheme();- if scheme != "http" && scheme != "https" {+ if parsed.scheme() != "http"+ || !origin.contains("://")+ || !parsed.username().is_empty()+ || parsed.password().is_some()+ || parsed.path() != "/"+ || parsed.query().is_some()+ || parsed.fragment().is_some()+ {return false;}- let loopback_host = match parsed.host() {- Some(url::Host::Ipv4(address)) => address.is_loopback(),- Some(url::Host::Ipv6(address)) => address.is_loopback(),- Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"),- None => false,+ let Some(request_host) = request_host else {+ return false;};- if loopback_host {- return true;- }- // Chrome's same-origin rule: the handshake is trusted when the origin is- // exactly the server's own http address.- let Ok(server) = url::Url::parse(&format!("http://{}", SocketAddr::new(bind_ip, bind_port)))- else {+ let Ok(server) = url::Url::parse(&format!("http://{request_host}/")) else {return false;};parsed.origin() == server.origin()@@ -228,7 +207,7 @@ fn control_refusal(allowed_origins: Option<&str>,) -> Option<ControlRefusal> {if let Some(origin) = header_value(head, "origin") {- if !origin_accepted(origin, bind_ip, port, allowed_origins) {+ if !origin_accepted(origin, header_value(head, "host"), allowed_origins) {return Some(ControlRefusal::BrowserOrigin(origin.to_owned()));}}@@ -256,12 +235,10 @@ fn refuse_control_connection(mut stream: std::net::TcpStream, refusal: ControlRe}};let body = match &refusal {- // Mirror Chrome's actionable rejection so a failing client can be- // fixed by configuration, not by suppressing the header.ControlRefusal::BrowserOrigin(origin) => json!({"error": reason,"detail": format!(- "Rejected an incoming WebSocket connection from the '{origin}' origin. \+ "Rejected a CDP control request from the '{origin}' origin. \Set OBSCURA_CDP_ALLOWED_ORIGINS={origin} to allow connections from this \origin or OBSCURA_CDP_ALLOWED_ORIGINS=* to allow all origins."),@@ -2765,53 +2742,81 @@ mod tests {}#[test]- fn loopback_origins_are_accepted_without_configuration() {- let bind = "127.0.0.1".parse().unwrap();- // What Puppeteer, Playwright, and chrome-remote-interface send on a- // standard connect (issue #1495): origin derived from the ws URL.- for origin in [- "http://127.0.0.1:9222",- "http://localhost:9222",- "http://localhost:8080",- "http://[::1]:9222",- "https://localhost:5173",+ fn endpoint_origins_are_accepted_without_configuration() {+ for (origin, host) in [+ ("http://127.0.0.1:9222", "127.0.0.1:9222"),+ ("HTTP://LOCALHOST:9222", "localhost:9222"),+ ("http://[::1]:9222", "[::1]:9222"),+ ("http://192.168.1.10:9333", "192.168.1.10:9333"),+ ("http://localhost", "localhost:80"),+ ("http://cdp.example.test:9222", "cdp.example.test:9222"),] {- assert!(super::origin_accepted(origin, bind, 9222, None), "{origin}");+ assert!(super::origin_accepted(origin, Some(host), None), "{origin}");}- // A different port than the bind is still loopback.- assert!(super::origin_accepted("http://127.0.0.1:7777", bind, 9222, None));}#[test]- fn non_loopback_origins_stay_refused_without_configuration() {- let bind = "127.0.0.1".parse().unwrap();+ fn foreign_and_malformed_origins_stay_refused_without_configuration() {for origin in ["https://evil.example","http://evil.example:8080","http://rebind.example:9222",+ "http://127.0.0.1:7777",+ "http://localhost:9222",+ "https://127.0.0.1:9222",+ "http://[email protected]:9222",+ "http://user:[email protected]:9222",+ "http://127.0.0.1:9222/path",+ "http://127.0.0.1:9222/?query",+ "http://127.0.0.1:9222/#fragment",+ "http:127.0.0.1:9222","null","",] {- assert!(!super::origin_accepted(origin, bind, 9222, None), "{origin}");+ assert!(!super::origin_accepted(origin, Some("127.0.0.1:9222"), None), "{origin}");}- // Chrome's same-origin rule: the exact server address is accepted.- assert!(super::origin_accepted("http://192.168.1.10:9333", "192.168.1.10".parse().unwrap(), 9333, None));- assert!(!super::origin_accepted("http://192.168.1.10:9333", "192.168.1.10".parse().unwrap(), 9444, None));+ assert!(!super::origin_accepted("http://127.0.0.1:9222", None, None));}#[test]fn allowed_origins_list_overrides_the_default_policy() {- let bind = "127.0.0.1".parse().unwrap();+ let host = Some("127.0.0.1:9222");let list = Some("http://dev.example:4173, https://tunnel.example");- assert!(super::origin_accepted("http://dev.example:4173", bind, 9222, list));- assert!(super::origin_accepted("https://tunnel.example", bind, 9222, list));- assert!(super::origin_accepted(" https://tunnel.example ", bind, 9222, list));- assert!(!super::origin_accepted("http://other.example", bind, 9222, list));- // `*` allows everything, matching --remote-allow-origins=*- assert!(super::origin_accepted("http://anything.example", bind, 9222, Some("*")));- assert!(super::origin_accepted("null", bind, 9222, Some("null")));- // Matching is case-insensitive like Chrome's lowercased set.- assert!(super::origin_accepted("HTTP://DEV.EXAMPLE:4173", bind, 9222, list));+ assert!(super::origin_accepted("http://dev.example:4173", host, list));+ assert!(super::origin_accepted("https://tunnel.example", host, list));+ assert!(super::origin_accepted(" https://tunnel.example ", host, list));+ assert!(!super::origin_accepted("http://other.example", host, list));+ assert!(super::origin_accepted("http://anything.example", host, Some("*")));+ assert!(super::origin_accepted("null", host, Some("null")));+ assert!(super::origin_accepted("HTTP://DEV.EXAMPLE:4173", host, list));+ }++ #[test]+ fn allowed_origins_preserve_forwarded_host_and_authentication_checks() {+ let bind = "127.0.0.1".parse().unwrap();+ let forwarded = Some((bind, 9222));+ let token = "01234567890123456789012345678901";+ let with_origin = |host, origin| native_head(host).replace(+ "Upgrade: websocket", &format!("Origin: {origin}\r\nUpgrade: websocket"),+ );+ assert_eq!(control_refusal(+ &with_origin("127.0.0.1:9222", "http://127.0.0.1:9222"),+ bind, 9223, forwarded, None, None,+ ), None);+ assert_eq!(control_refusal(+ &with_origin("rebind.example:9222", "http://rebind.example:9222"),+ bind, 9223, forwarded, None, Some("*"),+ ), Some(ControlRefusal::ForeignHost));+ assert_eq!(control_refusal(+ &with_origin("127.0.0.1:9222", "https://allowed.example"),+ bind, 9223, forwarded, Some(token), Some("https://allowed.example"),+ ), Some(ControlRefusal::Unauthorized));+ let authenticated = with_origin("cdp.example.test:9222", "http://cdp.example.test:9222")+ .replace("Upgrade: websocket", &format!("Authorization: Bearer {token}\r\nUpgrade: websocket"));+ assert_eq!(control_refusal(+ &authenticated, bind, 9223, Some(("0.0.0.0".parse().unwrap(), 9222)),+ Some(token), None,+ ), None);}#[test]diff --git a/crates/obscura-cdp/tests/cdp_ws_origin_policy.rs b/crates/obscura-cdp/tests/cdp_ws_origin_policy.rsindex 0d0412d1..12796603 100644--- a/crates/obscura-cdp/tests/cdp_ws_origin_policy.rs+++ b/crates/obscura-cdp/tests/cdp_ws_origin_policy.rs@@ -1,20 +1,5 @@-//! The CDP endpoint must accept the handshakes that standard WebSocket-//! clients actually send (issue #1495).-//!-//! RFC 6455 browsers attach an `Origin` header to every cross-site-//! WebSocket connect, and the mainstream CDP clients (Puppeteer, Playwright's-//! `connect_over_cdp`, `chrome-remote-interface`, Python `websocket-client`)-//! send a normal loopback `Origin` on every connect. Before the fix any-//! request with an `Origin` header was refused with-//! `403 {"error":"request refused"}`, so every one of those clients failed-//! while only clients that suppress the header could connect.-//!-//! The policy now matches Chrome's DevTools handler: loopback origins and the-//! server's own address are accepted, native clients without `Origin` are-//! accepted, and a non-loopback origin is refused with an actionable-//! `OBSCURA_CDP_ALLOWED_ORIGINS` hint unless the allowlist admits it.-//!-//! Run with `cargo nextest run -p obscura-cdp -E 'test(cdp_ws_origin_policy)'`.+//! Endpoint-derived client origins are accepted without trusting other local+//! applications. Additional origins require an explicit allowlist.use std::time::Duration;@@ -29,12 +14,19 @@ async fn pick_port() -> u16 {}/// Send one handshake request with a caller-chosen `Origin` and return the-/// raw response head. The status line and any JSON body come back together-/// for refusals; a 101 answer has no body.+/// response head and any Content-Length body; a 101 answer has no body.async fn raw_handshake(port: u16, origin: Option<&str>, path: &str) -> String {- let mut stream = TcpStream::connect(("127.0.0.1", port))- .await- .expect("control connection must open");+ let mut stream = tokio::time::timeout(Duration::from_secs(5), async {+ loop {+ match TcpStream::connect(("127.0.0.1", port)).await {+ Ok(stream) => break stream,+ Err(error) if error.kind() == std::io::ErrorKind::ConnectionRefused => {+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ Err(error) => panic!("control connection failed: {error}"),+ }+ }+ }).await.expect("CDP listener must become ready");let mut request = format!("GET {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n\Upgrade: websocket\r\nConnection: Upgrade\r\n\@@ -47,8 +39,7 @@ async fn raw_handshake(port: u16, origin: Option<&str>, path: &str) -> String {request.push_str("\r\n");stream.write_all(request.as_bytes()).await.expect("handshake write");- // The refusal carries `Connection: close`, the 101 keeps the socket open,- // so read until the end of the response head rather than until EOF.+ // An upgrade keeps the connection open, so do not wait for EOF.let mut buf = Vec::new();tokio::time::timeout(Duration::from_secs(5), async {let mut chunk = [0u8; 1024];@@ -56,8 +47,15 @@ async fn raw_handshake(port: u16, origin: Option<&str>, path: &str) -> String {let n = stream.read(&mut chunk).await.expect("handshake read");assert!(n > 0, "connection closed before a response head arrived");buf.extend_from_slice(&chunk[..n]);- if buf.windows(4).any(|w| w == b"\r\n\r\n") {- break;+ if let Some(end) = buf.windows(4).position(|w| w == b"\r\n\r\n") {+ let head = std::str::from_utf8(&buf[..end]).expect("UTF-8 response head");+ let length = head.lines().filter_map(|line| line.split_once(':'))+ .find(|(name, _)| name.eq_ignore_ascii_case("content-length"))+ .map(|(_, value)| value.trim().parse::<usize>().expect("valid content length"))+ .unwrap_or(0);+ if buf.len() >= end + 4 + length {+ break;+ }}}})@@ -68,7 +66,7 @@ async fn raw_handshake(port: u16, origin: Option<&str>, path: &str) -> String {fn start_server(port: u16) {tokio::task::spawn_local(async move {- let _ = obscura_cdp::start_with_serve_options_and_limit(+ obscura_cdp::start_with_serve_options_and_limit(port,"127.0.0.1",None,@@ -79,7 +77,7 @@ fn start_server(port: u16) {true,128,)- .await;+ .await.expect("CDP server must start");});}@@ -93,30 +91,12 @@ fn standard_client_origins_complete_the_websocket_handshake() {local.block_on(&rt, async move {let port = pick_port().await;start_server(port);- tokio::time::sleep(Duration::from_millis(300)).await;- // What the mainstream CDP clients send: an Origin derived from the- // ws://127.0.0.1:<port> endpoint, or from a localhost variant of it.- // Before the fix each of these was a 403.- for origin in [- format!("http://127.0.0.1:{port}"),- format!("http://localhost:{port}"),- "http://127.0.0.1:5173".to_string(),- ] {- let response = tokio::time::timeout(- Duration::from_secs(5),- raw_handshake(port, Some(&origin), "/devtools/browser"),- )- .await- .expect("handshake timed out");- assert!(- response.starts_with("HTTP/1.1 101"),- "origin {origin} must complete the upgrade, got: {:?}",- response.lines().next()- );- }+ let origin = format!("http://127.0.0.1:{port}");+ let response = raw_handshake(port, Some(&origin), "/devtools/browser").await;+ assert!(response.starts_with("HTTP/1.1 101"), "endpoint Origin: {response}");- // Native clients never send Origin and were never affected.+ // Clients that omit Origin remain accepted.let response = tokio::time::timeout(Duration::from_secs(5),raw_handshake(port, None, "/devtools/browser"),@@ -129,13 +109,13 @@ fn standard_client_origins_complete_the_websocket_handshake() {// origin policy; a browser tab probing them sends an Origin too.let response = tokio::time::timeout(Duration::from_secs(5),- raw_handshake(port, Some("http://localhost:5173"), "/json/version"),+ raw_handshake(port, Some(&origin), "/json/version"),).await.expect("/json/version timed out");assert!(response.starts_with("HTTP/1.1 200"),- "/json/version with loopback Origin must answer, got: {:?}",+ "/json/version with endpoint Origin must answer, got: {:?}",response.lines().next());});@@ -151,31 +131,25 @@ fn cross_origin_handshake_is_refused_with_an_actionable_message() {local.block_on(&rt, async move {let port = pick_port().await;start_server(port);- tokio::time::sleep(Duration::from_millis(300)).await;- let response = tokio::time::timeout(- Duration::from_secs(5),- raw_handshake(port, Some("http://evil.example:8080"), "/devtools/browser"),- )- .await- .expect("handshake timed out");- assert!(- response.starts_with("HTTP/1.1 403"),- "cross-origin connect must be refused, got: {:?}",- response.lines().next()- );- assert!(response.contains("\"error\":\"request refused\""), "body: {response}");- // The refusal names the knob, like Chrome names- // --remote-allow-origins in its 403 body.- assert!(- response.contains("OBSCURA_CDP_ALLOWED_ORIGINS=http://evil.example:8080"),- "refusal must be actionable, body: {response}"- );+ for origin in [+ "http://evil.example:8080".to_string(),+ format!("http://127.0.0.1:{}", port.wrapping_add(1)),+ format!("http://localhost:{port}"),+ format!("https://127.0.0.1:{port}"),+ "null".to_string(),+ ] {+ let response = raw_handshake(port, Some(&origin), "/devtools/browser").await;+ assert!(response.starts_with("HTTP/1.1 403"), "origin {origin}: {response}");+ assert!(response.contains("\"error\":\"request refused\""), "body: {response}");+ assert!(response.contains(&format!("OBSCURA_CDP_ALLOWED_ORIGINS={origin}")),+ "refusal must be actionable, body: {response}");+ }});}#[test]-fn allowed_origins_env_var_admits_listed_and_wildcard_origins() {+fn allowed_origins_env_var_admits_wildcard_origins() {// SAFETY: nextest runs every test in its own process, and each server// reads the variable once, when its accept thread starts.unsafe {@@ -190,7 +164,6 @@ fn allowed_origins_env_var_admits_listed_and_wildcard_origins() {// Wildcard server: even a non-loopback origin now upgrades.let wildcard_port = pick_port().await;start_server(wildcard_port);- tokio::time::sleep(Duration::from_millis(300)).await;let response = tokio::time::timeout(Duration::from_secs(5),raw_handshake(wildcard_port, Some("http://evil.example:8080"), "/devtools/browser"),@@ -202,14 +175,23 @@ fn allowed_origins_env_var_admits_listed_and_wildcard_origins() {"wildcard must admit any origin, got: {:?}",response.lines().next());+ });+}- // Explicit-list server on a second port: only listed origins pass.- unsafe {- std::env::set_var("OBSCURA_CDP_ALLOWED_ORIGINS", "http://tunnel.example:4242");- }+#[test]+fn allowed_origins_env_var_admits_only_listed_origins() {+ // SAFETY: set before starting runtime or server threads; nextest isolates tests.+ unsafe {+ std::env::set_var("OBSCURA_CDP_ALLOWED_ORIGINS", "http://tunnel.example:4242");+ }+ let rt = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap();+ let local = tokio::task::LocalSet::new();+ local.block_on(&rt, async move {let port = pick_port().await;start_server(port);- tokio::time::sleep(Duration::from_millis(300)).await;let response = tokio::time::timeout(Duration::from_secs(5),@@ -231,8 +213,4 @@ fn allowed_origins_env_var_admits_listed_and_wildcard_origins() {.expect("handshake timed out");assert!(response.starts_with("HTTP/1.1 403"), "unlisted origin: {response}");});- // SAFETY: as above; restored so a same-process cargo test run is clean.- unsafe {- std::env::remove_var("OBSCURA_CDP_ALLOWED_ORIGINS");- }}diff --git a/docs/Environment-variables.md b/docs/Environment-variables.mdindex f9f608a9..0e243477 100644--- a/docs/Environment-variables.md+++ b/docs/Environment-variables.md@@ -75,13 +75,16 @@ OBSCURA_CDP_TOKEN="$(openssl rand -hex 32)" obscura serve --host 0.0.0.0### `OBSCURA_CDP_ALLOWED_ORIGINS`-Comma-separated `Origin` allowlist for CDP clients that send an `Origin`-header (browser-style WebSocket clients such as Puppeteer, Playwright, and-chrome-remote-interface all do). Loopback origins and the server's own address-are always accepted without it, so standard clients work out of the box; a-non-loopback origin is refused with an actionable 403 unless it is listed-here. `*` allows every origin, including the `null` origin that sandboxed-pages send.+Comma-separated `Origin` allowlist for CDP discovery and WebSocket requests.+Without it, clients that omit `Origin` or send the endpoint's own HTTP origin+are accepted. Origins with a different scheme, hostname, or port are refused+with an actionable 403, including other loopback applications. Forwarded+workers compare against the client-facing request authority.++List another application's exact origin to grant it access. Matching is+case-insensitive. `*` allows every origin, including `null`, and removes the+browser-origin boundary; avoid it for untrusted pages. Host validation and+`OBSCURA_CDP_TOKEN` authentication still apply to allowlisted origins.```bashOBSCURA_CDP_ALLOWED_ORIGINS="https://tunnel.example" obscura serve