The headless browser for AI agents and web scraping
fix(net): gate file:// reads inside the loader
Anzal Husain Abidie217e9939513
diff --git a/crates/obscura-browser/src/context.rs b/crates/obscura-browser/src/context.rsindex fb68a9cc..fbfefd89 100644--- a/crates/obscura-browser/src/context.rs+++ b/crates/obscura-browser/src/context.rs@@ -217,6 +217,14 @@ impl BrowserContext {}}+ /// Sets the file:// opt-in on the context and on its http client, whose+ /// loader enforces it for every fetch, not only for navigation. Assigning+ /// the field directly leaves the client refusing file://.+ pub fn set_allow_file_access(&mut self, allow: bool) {+ self.allow_file_access = allow;+ self.http_client.set_allow_file_access(allow);+ }+pub fn with_options(id: String, proxy_url: Option<String>, stealth: bool) -> Self {Self::with_full_options(id, proxy_url, stealth, None)}@@ -252,6 +260,7 @@ impl BrowserContext {if self.stealth {client.block_trackers = true;}+ client.set_allow_file_access(self.allow_file_access);if let Ok(mut guard) = client.user_agent.try_write() {*guard = self.user_agent.clone();}diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex f24e63fe..fa6c02d3 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -1093,11 +1093,13 @@ impl Page {// http://, which only works when the upstream happens to be a// Clash-style mixed-mode proxy and breaks plain SOCKS5 servers// like `ssh -ND` (#160).- Some(Arc::new(StealthHttpClient::with_proxy(+ let mut client = StealthHttpClient::with_proxy(context.cookie_jar.clone(),context.proxy_url.as_deref(),context.allow_private_network,- )))+ );+ client.allow_file_access = context.allow_file_access;+ Some(Arc::new(client))} else {None};@@ -5346,7 +5348,7 @@ mod tests {None,true,);- context.allow_file_access = allow_file_access;+ context.set_allow_file_access(allow_file_access);std::sync::Arc::new(context)}@@ -5374,6 +5376,27 @@ mod tests {let _ = std::fs::remove_file(&path);}+ // Server connections navigate through an isolated copy of the startup+ // context, so the copy's own http client must carry the opt-in too.+ #[tokio::test(flavor = "current_thread")]+ async fn isolated_context_copy_keeps_the_file_access_setting() {+ let (path, file_url) = local_html_fixture("copy");++ let open_copy = std::sync::Arc::new(+ file_gate_context("file-gate-copy", true).isolated_copy("copy-open".to_string(), false),+ );+ let mut open = super::Page::new("file-gate-copy-open".to_string(), open_copy);+ open.navigate(&file_url).await.expect("the copy keeps the opt-in");++ let locked_copy = std::sync::Arc::new(+ file_gate_context("file-gate-copy-locked", false)+ .isolated_copy("copy-locked".to_string(), false),+ );+ assert!(locked_copy.http_client.fetch(&url::Url::parse(&file_url).unwrap()).await.is_err());++ let _ = std::fs::remove_file(&path);+ }+// A page must never drive itself from a web origin into file://, even in a// context that lets clients open local files. Timers, link clicks and form// submits are consumed by process_pending_navigation as a fresh first URL,diff --git a/crates/obscura-cdp/src/dispatch.rs b/crates/obscura-cdp/src/dispatch.rsindex ba2bc7f4..4b87f945 100644--- a/crates/obscura-cdp/src/dispatch.rs+++ b/crates/obscura-cdp/src/dispatch.rs@@ -224,7 +224,7 @@ impl CdpContext {storage_dir,allow_private_network,);- ctx.allow_file_access = allow_file_access;+ ctx.set_allow_file_access(allow_file_access);Self::new_with_shared_context(Arc::new(ctx))}diff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rsindex 93fd8f84..e2a6b976 100644--- a/crates/obscura-cdp/src/server.rs+++ b/crates/obscura-cdp/src/server.rs@@ -523,7 +523,7 @@ pub async fn start_with_serve_options_limit_and_ready_file(storage_dir,allow_private_network,);- bctx.allow_file_access = allow_file_access;+ bctx.set_allow_file_access(allow_file_access);let shared_ctx = Arc::new(bctx);// Persistence is deliberately separate from the connection template.// Cookie deltas are merged here, but new connections always clone thediff --git a/crates/obscura-cli/src/main.rs b/crates/obscura-cli/src/main.rsindex 2c9f8a6b..7e5f1873 100644--- a/crates/obscura-cli/src/main.rs+++ b/crates/obscura-cli/src/main.rs@@ -1200,7 +1200,7 @@ async fn run_fetch(// The browser layer refuses file:// unless the context opts in. A local// user running `obscura fetch file://...` on their own files is the// intended case; only network-facing servers (serve, mcp) keep it off.- context.allow_file_access = true;+ context.set_allow_file_access(true);let context = Arc::new(context);let mut page = Page::new("fetch-page".to_string(), context.clone());// Keep the browser's end-to-end navigation ceiling aligned with the CLI@@ -1605,6 +1605,9 @@ async fn fetch_original_response(Arc::new(obscura_net::CookieJar::new()),proxy.as_deref(),);+ // Same local-user opt-in as `fetch`: `--dump original file://...` reads+ // the user's own file. The client refuses file:// unless told otherwise.+ client.set_allow_file_access(true);if let Some(ua) = user_agent {client.set_user_agent(&ua).await;}diff --git a/crates/obscura-net/src/client.rs b/crates/obscura-net/src/client.rsindex b4db2848..f887c633 100644--- a/crates/obscura-net/src/client.rs+++ b/crates/obscura-net/src/client.rs@@ -1,6 +1,6 @@use std::collections::{HashMap, VecDeque};use std::sync::{Arc, OnceLock};-use std::sync::atomic::{AtomicU32, Ordering};+use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};use std::time::{Duration, Instant};use std::net::{IpAddr, SocketAddr};@@ -696,10 +696,18 @@ pub(crate) fn validate_url(url: &Url, allow_private_network: bool) -> Result<(),Ok(())}+/// The only reader of local files in the net layer. It checks the opt-in+/// itself so a new caller cannot read `file://` by forgetting the gate.pub(crate) async fn fetch_file_url(url: &Url,max_response_bytes: usize,+ allow_file_access: bool,) -> Result<Response, ObscuraNetError> {+ if !allow_file_access {+ return Err(ObscuraNetError::Network(format!(+ "file:// access is disabled (requires --allow-file-access): {url}"+ )));+ }let path = url.to_file_path().map_err(|_| ObscuraNetError::Network("Invalid file URL".to_string()))?;@@ -850,6 +858,9 @@ pub struct ObscuraHttpClient {/// through in addition to the `OBSCURA_ALLOW_PRIVATE_NETWORK` env var./// Set via `--allow-private-network` on the CLI (issue #33).pub allow_private_network: bool,+ /// Lets `fetch_file_url` read local files. Off by default. Atomic because+ /// `BrowserContext` flips it after the client is already shared.+ allow_file_access: AtomicBool,}const RESOURCE_CACHE_MAX_ENTRIES: usize = 256;@@ -1062,9 +1073,18 @@ impl ObscuraHttpClient {block_trackers: false,resource_loader: std::sync::Mutex::new(ResourceLoaderState::default()),allow_private_network,+ allow_file_access: AtomicBool::new(false),}}+ pub fn allow_file_access(&self) -> bool {+ self.allow_file_access.load(Ordering::Relaxed)+ }++ pub fn set_allow_file_access(&self, allow: bool) {+ self.allow_file_access.store(allow, Ordering::Relaxed);+ }+async fn get_client(&self) -> &Client {self.client.get_or_init(|| async {let mut builder = Client::builder()@@ -1383,7 +1403,7 @@ impl ObscuraHttpClient {validate_request_mode(&request, url)?;if url.scheme() == "file" {- return fetch_file_url(url, request.max_response_bytes).await;+ return fetch_file_url(url, request.max_response_bytes, self.allow_file_access()).await;}let mut method = initial_method;@@ -2982,3 +3002,50 @@ mod cert_env_tests {));}}++#[cfg(test)]+mod file_access_tests {+ use super::{fetch_file_url, ObscuraHttpClient};+ use crate::cookies::CookieJar;+ use std::sync::Arc;+ use url::Url;++ fn fixture() -> (tempfile::TempDir, Url) {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("secret.html");+ std::fs::write(&path, "local-secret").unwrap();+ let url = Url::from_file_path(&path).unwrap();+ (dir, url)+ }++ // The gate lives in the loader, so a caller that never checks the flag+ // still cannot read a local file.+ #[tokio::test]+ async fn loader_refuses_file_urls_without_the_opt_in() {+ let (_dir, url) = fixture();+ let error = fetch_file_url(&url, 1024, false)+ .await+ .expect_err("file:// must be refused without allow_file_access")+ .to_string();+ assert!(error.contains("allow-file-access"), "{error}");+ }++ #[tokio::test]+ async fn loader_reads_file_urls_with_the_opt_in() {+ let (_dir, url) = fixture();+ let response = fetch_file_url(&url, 1024, true).await.expect("opted in");+ assert_eq!(response.body, b"local-secret");+ assert_eq!(response.headers.get("content-type").unwrap(), "text/html");+ }++ #[tokio::test]+ async fn client_fetch_follows_its_file_access_setting() {+ let (_dir, url) = fixture();+ let client = ObscuraHttpClient::with_full_options(Arc::new(CookieJar::new()), None, false);+ assert!(client.fetch(&url).await.is_err());+ client.set_allow_file_access(true);+ assert_eq!(client.fetch(&url).await.unwrap().body, b"local-secret");+ client.set_allow_file_access(false);+ assert!(client.fetch(&url).await.is_err());+ }+}diff --git a/crates/obscura-net/src/wreq_client.rs b/crates/obscura-net/src/wreq_client.rsindex 9547d857..2f67d18d 100644--- a/crates/obscura-net/src/wreq_client.rs+++ b/crates/obscura-net/src/wreq_client.rs@@ -187,6 +187,8 @@ async fn send_get_with_connection_reset_retry(pub struct StealthHttpClient {client: wreq::Client,allow_private_network: bool,+ /// Lets `fetch_file_url` read local files. Off by default.+ pub allow_file_access: bool,pub block_trackers: bool,pub cookie_jar: Arc<CookieJar>,pub extra_headers: RwLock<HashMap<String, String>>,@@ -280,6 +282,7 @@ impl StealthHttpClient {StealthHttpClient {client,allow_private_network,+ allow_file_access: false,block_trackers: tracker_blocking_enabled(std::env::var("OBSCURA_BLOCK_TRACKERS").ok().as_deref(),),@@ -320,7 +323,7 @@ impl StealthHttpClient {validate_url(url, self.allow_private_network)?;validate_request_mode(&request, url)?;if url.scheme() == "file" {- return fetch_file_url(url, request.max_response_bytes).await;+ return fetch_file_url(url, request.max_response_bytes, self.allow_file_access).await;}let mut current_url = url.clone();@@ -664,6 +667,21 @@ mod tests {}}+ // The stealth transport delegates file:// to the shared loader, so it+ // inherits the same opt-in instead of reading local files unconditionally.+ #[tokio::test]+ async fn stealth_client_reads_file_urls_only_when_allowed() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("page.html");+ std::fs::write(&path, "local-secret").unwrap();+ let url = Url::from_file_path(&path).unwrap();++ let mut client = StealthHttpClient::new(Arc::new(CookieJar::new()));+ assert!(client.fetch(&url).await.is_err());+ client.allow_file_access = true;+ assert_eq!(client.fetch(&url).await.unwrap().body, b"local-secret");+ }+#[test]fn tracker_blocking_respects_host_and_setting() {let url = Url::parse("https://www.google-analytics.com/collect").unwrap();@@ -819,6 +837,7 @@ mod tests {let client = StealthHttpClient {client: wreq::Client::builder().no_proxy().build().unwrap(),allow_private_network: true,+ allow_file_access: false,block_trackers: true,cookie_jar: Arc::new(CookieJar::new()),extra_headers: tokio::sync::RwLock::new(std::collections::HashMap::new()),