Skip to content

The headless browser for AI agents and web scraping

fix(cdp): accept loopback origins on the CDP WebSocket endpoint

coolswood8a2f957019d7
diff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rs
index 26195790..88ccd403 100644
--- a/crates/obscura-cdp/src/server.rs
+++ b/crates/obscura-cdp/src/server.rs
@@ -142,23 +142,95 @@ fn host_matches_bind(
})
}
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
enum ControlRefusal {
- BrowserOrigin,
+ BrowserOrigin(String),
ForeignHost,
Unauthorized,
OversizedHead,
}
+/// 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.
+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.
+fn origin_accepted(
+ origin: &str,
+ bind_ip: std::net::IpAddr,
+ bind_port: u16,
+ 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))
+ {
+ return true;
+ }
+ }
+ let Ok(parsed) = url::Url::parse(origin) else {
+ return false;
+ };
+ let scheme = parsed.scheme();
+ if scheme != "http" && scheme != "https" {
+ 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,
+ };
+ 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 {
+ return false;
+ };
+ parsed.origin() == server.origin()
+}
+
fn control_refusal(
head: &str,
bind_ip: std::net::IpAddr,
port: u16,
forwarded: Option<(std::net::IpAddr, u16)>,
auth_token: Option<&str>,
+ allowed_origins: Option<&str>,
) -> Option<ControlRefusal> {
- if header_value(head, "origin").is_some() {
- return Some(ControlRefusal::BrowserOrigin);
+ if let Some(origin) = header_value(head, "origin") {
+ if !origin_accepted(origin, bind_ip, port, allowed_origins) {
+ return Some(ControlRefusal::BrowserOrigin(origin.to_owned()));
+ }
}
if !header_value(head, "host")
.is_some_and(|host| host_matches_bind(host, bind_ip, port, forwarded))
@@ -173,17 +245,30 @@ fn control_refusal(
fn refuse_control_connection(mut stream: std::net::TcpStream, refusal: ControlRefusal) {
use std::io::Write;
- let (status, reason) = match refusal {
+ let (status, reason) = match &refusal {
ControlRefusal::Unauthorized => ("401 Unauthorized", "authentication required"),
ControlRefusal::OversizedHead => (
"431 Request Header Fields Too Large",
"request head too large",
),
- ControlRefusal::BrowserOrigin | ControlRefusal::ForeignHost => {
+ ControlRefusal::BrowserOrigin(_) | ControlRefusal::ForeignHost => {
("403 Forbidden", "request refused")
}
};
- let body = format!("{{\"error\":\"{reason}\"}}");
+ 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. \
+ Set OBSCURA_CDP_ALLOWED_ORIGINS={origin} to allow connections from this \
+ origin or OBSCURA_CDP_ALLOWED_ORIGINS=* to allow all origins."
+ ),
+ })
+ .to_string(),
+ _ => format!("{{\"error\":\"{reason}\"}}"),
+ };
let response = format!(
"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
@@ -439,6 +524,7 @@ pub async fn start_with_serve_options_limit_and_ready_file(
// under a connection burst.
let accept_flag = shutdown_flag.clone();
let accept_auth_token = auth_token.clone();
+ let accept_allowed_origins = allowed_origins_env();
std::thread::Builder::new()
.name("obscura-cdp-accept".into())
.spawn(move || {
@@ -504,6 +590,7 @@ pub async fn start_with_serve_options_limit_and_ready_file(
port,
forwarded,
accept_auth_token.as_deref(),
+ accept_allowed_origins.as_deref(),
&ws_tx,
&head,
) {
@@ -1115,10 +1202,11 @@ fn accept_dispatch(
port: u16,
forwarded: Option<(std::net::IpAddr, u16)>,
auth_token: Option<&str>,
+ allowed_origins: Option<&str>,
ws_tx: &mpsc::Sender<std::net::TcpStream>,
head: &str,
) -> anyhow::Result<()> {
- if let Some(refusal) = control_refusal(head, bind_ip, port, forwarded, auth_token) {
+ if let Some(refusal) = control_refusal(head, bind_ip, port, forwarded, auth_token, allowed_origins) {
refuse_control_connection(stream, refusal);
return Ok(());
}
@@ -2605,7 +2693,7 @@ mod tests {
fn native_loopback_cdp_request_is_allowed() {
let head = native_head("127.0.0.1:9222");
assert_eq!(
- control_refusal(&head, "127.0.0.1".parse().unwrap(), 9222, None, None),
+ control_refusal(&head, "127.0.0.1".parse().unwrap(), 9222, None, None, None),
None
);
}
@@ -2623,8 +2711,9 @@ mod tests {
9222,
None,
None,
+ None,
),
- Some(ControlRefusal::BrowserOrigin)
+ Some(ControlRefusal::BrowserOrigin("https://evil.example".to_owned()))
);
assert_eq!(
control_refusal(
@@ -2633,6 +2722,7 @@ mod tests {
9222,
None,
None,
+ None,
),
Some(ControlRefusal::ForeignHost)
);
@@ -2643,7 +2733,7 @@ mod tests {
let bind = "127.0.0.1".parse().unwrap();
let forwarded = Some((bind, 9222));
assert_eq!(
- control_refusal(&native_head("127.0.0.1:9222"), bind, 9223, forwarded, None),
+ control_refusal(&native_head("127.0.0.1:9222"), bind, 9223, forwarded, None, None),
None
);
assert_eq!(
@@ -2653,11 +2743,12 @@ mod tests {
9223,
forwarded,
None,
+ None,
),
Some(ControlRefusal::ForeignHost)
);
assert_eq!(
- control_refusal(&native_head("127.0.0.1:9444"), bind, 9223, forwarded, None),
+ control_refusal(&native_head("127.0.0.1:9444"), bind, 9223, forwarded, None, None),
Some(ControlRefusal::ForeignHost)
);
}
@@ -2668,11 +2759,61 @@ mod tests {
let public = Some(("0.0.0.0".parse().unwrap(), 9222));
let head = native_head("cdp.example.test:9222");
assert_eq!(
- control_refusal(&head, bind, 9223, public, Some("secret")),
+ control_refusal(&head, bind, 9223, public, Some("secret"), None),
Some(ControlRefusal::Unauthorized)
);
}
+ #[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",
+ ] {
+ assert!(super::origin_accepted(origin, bind, 9222, 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();
+ for origin in [
+ "https://evil.example",
+ "http://evil.example:8080",
+ "http://rebind.example:9222",
+ "null",
+ "",
+ ] {
+ assert!(!super::origin_accepted(origin, bind, 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));
+ }
+
+ #[test]
+ fn allowed_origins_list_overrides_the_default_policy() {
+ let bind = "127.0.0.1".parse().unwrap();
+ 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));
+ }
+
#[test]
fn configured_cdp_token_is_mandatory() {
let token = "01234567890123456789012345678901";
diff --git a/crates/obscura-cdp/tests/cdp_ws_origin_policy.rs b/crates/obscura-cdp/tests/cdp_ws_origin_policy.rs
new file mode 100644
index 00000000..0d0412d1
--- /dev/null
+++ b/crates/obscura-cdp/tests/cdp_ws_origin_policy.rs
@@ -0,0 +1,238 @@
+//! 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)'`.
+
+use std::time::Duration;
+
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::{TcpListener, TcpStream};
+
+async fn pick_port() -> u16 {
+ let l = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = l.local_addr().unwrap().port();
+ drop(l);
+ port
+}
+
+/// 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.
+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 request = format!(
+ "GET {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n\
+ Upgrade: websocket\r\nConnection: Upgrade\r\n\
+ Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
+ Sec-WebSocket-Version: 13\r\n"
+ );
+ if let Some(origin) = origin {
+ request.push_str(&format!("Origin: {origin}\r\n"));
+ }
+ 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.
+ let mut buf = Vec::new();
+ tokio::time::timeout(Duration::from_secs(5), async {
+ let mut chunk = [0u8; 1024];
+ loop {
+ 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;
+ }
+ }
+ })
+ .await
+ .expect("handshake response timed out");
+ String::from_utf8_lossy(&buf).to_string()
+}
+
+fn start_server(port: u16) {
+ tokio::task::spawn_local(async move {
+ let _ = obscura_cdp::start_with_serve_options_and_limit(
+ port,
+ "127.0.0.1",
+ None,
+ false,
+ None,
+ false,
+ None,
+ true,
+ 128,
+ )
+ .await;
+ });
+}
+
+#[test]
+fn standard_client_origins_complete_the_websocket_handshake() {
+ 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;
+
+ // 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()
+ );
+ }
+
+ // Native clients never send Origin and were never affected.
+ let response = tokio::time::timeout(
+ Duration::from_secs(5),
+ raw_handshake(port, None, "/devtools/browser"),
+ )
+ .await
+ .expect("handshake timed out");
+ assert!(response.starts_with("HTTP/1.1 101"), "no-Origin connect: {response}");
+
+ // The /json discovery endpoints share the accept thread and the same
+ // 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"),
+ )
+ .await
+ .expect("/json/version timed out");
+ assert!(
+ response.starts_with("HTTP/1.1 200"),
+ "/json/version with loopback Origin must answer, got: {:?}",
+ response.lines().next()
+ );
+ });
+}
+
+#[test]
+fn cross_origin_handshake_is_refused_with_an_actionable_message() {
+ 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),
+ 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}"
+ );
+ });
+}
+
+#[test]
+fn allowed_origins_env_var_admits_listed_and_wildcard_origins() {
+ // SAFETY: nextest runs every test in its own process, and each server
+ // reads the variable once, when its accept thread starts.
+ unsafe {
+ std::env::set_var("OBSCURA_CDP_ALLOWED_ORIGINS", "*");
+ }
+ let rt = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ let local = tokio::task::LocalSet::new();
+ local.block_on(&rt, async move {
+ // 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"),
+ )
+ .await
+ .expect("handshake timed out");
+ assert!(
+ response.starts_with("HTTP/1.1 101"),
+ "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");
+ }
+ 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://tunnel.example:4242"), "/devtools/browser"),
+ )
+ .await
+ .expect("handshake timed out");
+ assert!(
+ response.starts_with("HTTP/1.1 101"),
+ "allowlisted origin must complete the upgrade, got: {:?}",
+ response.lines().next()
+ );
+
+ let response = tokio::time::timeout(
+ Duration::from_secs(5),
+ raw_handshake(port, Some("http://unlisted.example:1"), "/devtools/browser"),
+ )
+ .await
+ .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/crates/obscura-cdp/tests/integration.rs b/crates/obscura-cdp/tests/integration.rs
index e82a26f9..32fe8b7d 100644
--- a/crates/obscura-cdp/tests/integration.rs
+++ b/crates/obscura-cdp/tests/integration.rs
@@ -27,6 +27,7 @@ integration_tests!(
binding_called_session,
call_function_on_object_id_arg,
cdp_click_submit_parity,
+ cdp_ws_origin_policy,
child_frame_tree,
concurrent_connections_heavy_page,
concurrent_navigations,
diff --git a/docs/Environment-variables.md b/docs/Environment-variables.md
index fb0214d7..f9f608a9 100644
--- a/docs/Environment-variables.md
+++ b/docs/Environment-variables.md
@@ -73,6 +73,20 @@ bytes. Pass it as `Authorization: Bearer <token>` in the CDP client's headers.
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.
+
+```bash
+OBSCURA_CDP_ALLOWED_ORIGINS="https://tunnel.example" obscura serve
+```
+
### `OBSCURA_FETCH_TIMEOUT_MS`
Request timeout for scripted `fetch()`, `XMLHttpRequest`, and ES-module loads. Without it a request to a server that accepts the connection but never responds (including a CORS preflight) hangs forever and the XHR is stuck with no completion event. Default 30000 (30 seconds).