Skip to content

The headless browser for AI agents and web scraping

fix(browser): enforce the file:// navigation gate in Page itself

Andrey Mnatsakanov36c0aef93107
diff --git a/crates/obscura-browser/src/context.rs b/crates/obscura-browser/src/context.rs
index ccbede2f..7b5139aa 100644
--- a/crates/obscura-browser/src/context.rs
+++ b/crates/obscura-browser/src/context.rs
@@ -19,9 +19,10 @@ pub struct BrowserContext {
/// Default is false: a remote CDP client cannot point the browser
/// at /etc/shadow even if Obscura is running as a privileged user.
/// Flip on via `obscura serve --allow-file-access` for legitimate
- /// local-HTML testing workflows. The CLI's own `obscura fetch
- /// file://...` path is unaffected because it does not go through
- /// the CDP server.
+ /// local-HTML testing workflows. Enforced by `Page` navigation itself,
+ /// so every CDP and MCP route is covered; the CLI's own `obscura fetch
+ /// file://...` opts its local context in. A page can never drive
+ /// itself from a web origin into file:// regardless of this flag.
pub allow_file_access: bool,
pub storage_dir: Option<PathBuf>,
/// When true, the http client allows fetching localhost / RFC1918 /
diff --git a/crates/obscura-browser/src/fork_virtual_url.rs b/crates/obscura-browser/src/fork_virtual_url.rs
index d960042c..b9ce3335 100644
--- a/crates/obscura-browser/src/fork_virtual_url.rs
+++ b/crates/obscura-browser/src/fork_virtual_url.rs
@@ -36,6 +36,11 @@ impl Page {
if self.url.as_ref() == Some(&parsed) {
return false;
}
+ // A web document must not become a file:// page without loading one:
+ // page.url keys the file:// sub-resource gate (#1069).
+ if crate::page::cross_scheme_to_file(&self.url_string(), virtual_url) {
+ return false;
+ }
self.url = Some(parsed);
self.push_history(self.url_string());
true
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index 5c9b6488..9bd12aae 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -107,7 +107,7 @@ use obscura_net::StealthHttpClient;
/// non-file scheme into a file: URL. We treat that move as an SOP
/// violation because the existing realm survives the navigation and
/// can read the new document's body.
-fn cross_scheme_to_file(from: &str, to: &str) -> bool {
+pub(crate) fn cross_scheme_to_file(from: &str, to: &str) -> bool {
let to_is_file = Url::parse(to)
.map(|u| u.scheme().eq_ignore_ascii_case("file"))
.unwrap_or(false);
@@ -119,6 +119,14 @@ fn cross_scheme_to_file(from: &str, to: &str) -> bool {
.unwrap_or(true)
}
+/// Whether a navigation target is a local file, including spellings the URL
+/// parser rejects (a bare `file:` prefix) so they cannot slip past the gate.
+fn url_is_file_scheme(raw: &str) -> bool {
+ Url::parse(raw)
+ .map(|u| u.scheme().eq_ignore_ascii_case("file"))
+ .unwrap_or_else(|_| raw.trim_start().to_ascii_lowercase().starts_with("file:"))
+}
+
/// Sub-resource fetch policy. http(s) is always fine; data: is allowed
/// because the bytes are inline in the URI (no network fetch, no SSRF);
/// file: is only allowed when the page itself was loaded from file:;
@@ -3193,6 +3201,16 @@ impl Page {
body: &str,
initial_referrer: &str,
) -> Result<(), PageError> {
+ // file:// is a local file read. Every client route (CLI, CDP's
+ // Page.navigate/reload/history and Target.createTarget, the MCP
+ // tools) ends up here, so the context's opt-in is enforced once
+ // instead of being copied into each handler, where a route that
+ // missed its copy read local files (#1069).
+ if url_is_file_scheme(url_str) && !self.context.allow_file_access {
+ return Err(PageError::NetworkError(format!(
+ "file:// navigation is disabled for this browser context: {url_str}"
+ )));
+ }
let mut current_url = url_str.to_string();
let mut current_method = method.to_string();
let mut current_body = body.to_string();
@@ -4688,6 +4706,33 @@ impl Page {
pub async fn process_pending_navigation(&mut self) -> Result<bool, PageError> {
if let Some((url, method, body)) = self.take_pending_navigation() {
+ // SOP gate for navigations the page queued itself (a timer or
+ // handler assigning location, a link click, a form submit). They
+ // arrive here as a fresh first URL, so the chain gate in
+ // navigate_with_wait_post_inner never sees them. A web document
+ // must not drive itself into file:// even in a context that lets
+ // clients open local files (#1069).
+ let current_url = self.url_string();
+ if cross_scheme_to_file(&current_url, &url) {
+ tracing::warn!(
+ "blocking page-initiated cross-scheme navigation to file: {} -> {}",
+ current_url,
+ url,
+ );
+ // The location setter already published the target as the
+ // virtual URL; put location back on the document that is
+ // still loaded so nothing later adopts the blocked target.
+ if let Some(js) = self.js.as_mut() {
+ let _ = js.execute_script(
+ "<blocked-navigation>",
+ &format!(
+ "globalThis.__virtualUrl = {};",
+ serde_json::to_string(&current_url).unwrap_or_else(|_| "null".into())
+ ),
+ );
+ }
+ return Ok(false);
+ }
let source_url = self
.url
.as_ref()
@@ -4874,6 +4919,89 @@ mod tests {
assert_eq!(a_loaded.as_str(), None, "load did not fire on the other link");
}
+ fn local_html_fixture(tag: &str) -> (std::path::PathBuf, String) {
+ let path = std::env::temp_dir().join(format!(
+ "obscura-file-gate-{tag}-{}.html",
+ std::process::id()
+ ));
+ std::fs::write(&path, "<p id=secret>local-secret</p>").expect("write fixture");
+ let file_url = url::Url::from_file_path(&path).expect("file url").to_string();
+ (path, file_url)
+ }
+
+ fn file_gate_context(name: &str, allow_file_access: bool) -> std::sync::Arc<crate::BrowserContext> {
+ let mut context = crate::BrowserContext::with_storage_and_network(
+ name.to_string(),
+ None,
+ false,
+ None,
+ None,
+ true,
+ );
+ context.allow_file_access = allow_file_access;
+ std::sync::Arc::new(context)
+ }
+
+ // file:// is a local file read, so a browser context must opt in before any
+ // client-driven navigation reaches it. Every CLI, CDP and MCP route funnels
+ // through the one navigation entry point, so the opt-in is enforced there
+ // rather than copied into each handler.
+ #[tokio::test(flavor = "current_thread")]
+ async fn file_navigation_requires_the_context_to_allow_file_access() {
+ let (path, file_url) = local_html_fixture("client");
+
+ let mut locked = super::Page::new("file-gate".to_string(), file_gate_context("file-gate", false));
+ let error = locked
+ .navigate(&file_url)
+ .await
+ .expect_err("file:// must be refused unless the context allows it")
+ .to_string();
+ assert!(error.contains("file://"), "{error}");
+ assert_ne!(locked.url_string(), file_url);
+
+ let mut open = super::Page::new("file-gate-open".to_string(), file_gate_context("file-gate-open", true));
+ open.navigate(&file_url).await.expect("an opted-in context reads local files");
+ assert_eq!(open.url_string(), file_url);
+
+ 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,
+ // so the in-navigation chain's cross-scheme gate never sees them.
+ #[tokio::test(flavor = "current_thread")]
+ async fn page_driven_navigation_cannot_cross_into_file_scheme() {
+ let (path, file_url) = local_html_fixture("page");
+ let mut page = super::Page::new("file-gate-page".to_string(), file_gate_context("file-gate-page", true));
+ page.navigate("data:text/html,<p id=web>web</p>")
+ .await
+ .expect("web page");
+ let web_url = page.url_string();
+
+ page.evaluate(&format!(
+ "location.href = {}",
+ serde_json::to_string(&file_url).expect("json string")
+ ));
+ assert!(page.has_pending_navigation(), "the page queued a navigation");
+
+ let navigated = page
+ .process_pending_navigation()
+ .await
+ .expect("a blocked page navigation is not an error");
+ assert!(!navigated);
+ assert_eq!(page.url_string(), web_url);
+ assert!(!page.has_pending_navigation(), "the blocked navigation is dropped");
+ // The location setter published the target before the block; the
+ // page must not keep reporting (or later adopt) a document it never
+ // loaded.
+ assert_eq!(page.evaluate("location.href"), serde_json::json!(web_url));
+ assert!(!page.sync_virtual_url());
+ assert_eq!(page.url_string(), web_url);
+
+ let _ = std::fs::remove_file(&path);
+ }
+
#[test]
fn navigation_timeout_environment_default_remains_thirty_seconds() {
assert_eq!(
diff --git a/crates/obscura-cdp/tests/file_navigation_gate.rs b/crates/obscura-cdp/tests/file_navigation_gate.rs
new file mode 100644
index 00000000..bc730f23
--- /dev/null
+++ b/crates/obscura-cdp/tests/file_navigation_gate.rs
@@ -0,0 +1,105 @@
+// A CDP client must not read local files unless the server was started with
+// --allow-file-access, whichever route the navigation takes. The real
+// Page.navigate path is the server's spawn-and-defer path, not the domain
+// handler, and a page's own `location.href` assignment is consumed after
+// Runtime.evaluate; both must be gated.
+
+use std::time::Duration;
+
+use futures_util::{SinkExt, StreamExt};
+use serde_json::{json, Value};
+use tokio::net::TcpListener;
+use tokio_tungstenite::{connect_async, tungstenite::Message};
+
+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
+}
+
+type Ws = tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
+
+/// Send one command and return its response, collecting any `sessionId`
+/// announced by an event on the way (Target.attachedToTarget).
+async fn call(ws: &mut Ws, id: u64, method: &str, params: Value, session: Option<&str>) -> (Value, Option<String>) {
+ let mut msg = json!({"id": id, "method": method, "params": params});
+ if let Some(session) = session {
+ msg["sessionId"] = json!(session);
+ }
+ ws.send(Message::Text(msg.to_string().into())).await.unwrap();
+ let mut announced = None;
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(15);
+ loop {
+ let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
+ let frame = tokio::time::timeout(remaining, ws.next())
+ .await
+ .unwrap_or_else(|_| panic!("timeout waiting for {method}"))
+ .expect("ws closed")
+ .unwrap();
+ let Message::Text(text) = frame else { continue };
+ let v: Value = serde_json::from_str(&text).unwrap();
+ if let Some(s) = v.get("params").and_then(|p| p.get("sessionId")).and_then(Value::as_str) {
+ announced = Some(s.to_string());
+ }
+ if v.get("id").and_then(Value::as_u64) == Some(id) {
+ return (v, announced);
+ }
+ }
+}
+
+fn evaluate_value(response: &Value) -> String {
+ response["result"]["result"]["value"]
+ .as_str()
+ .unwrap_or_default()
+ .to_string()
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn cdp_cannot_reach_local_files_without_allow_file_access() {
+ let path = std::env::temp_dir().join(format!("obscura-cdp-file-gate-{}.html", std::process::id()));
+ std::fs::write(&path, "<p>local-secret</p>").unwrap();
+ let file_url = url::Url::from_file_path(&path).unwrap().to_string();
+
+ let port = pick_port().await;
+ let local = tokio::task::LocalSet::new();
+ local
+ .run_until(async {
+ tokio::task::spawn_local(async move {
+ let _ = obscura_cdp::server::start(port).await;
+ });
+ tokio::time::sleep(Duration::from_millis(200)).await;
+
+ let (mut ws, _) = connect_async(format!("ws://127.0.0.1:{port}/devtools/browser"))
+ .await
+ .expect("connect");
+ let (_, session) = call(&mut ws, 1, "Target.createTarget", json!({"url": "about:blank"}), None).await;
+ let session = session.expect("attached session");
+ let sid = session.as_str();
+
+ // The spawn-and-defer Page.navigate path.
+ let (reply, _) = call(&mut ws, 2, "Page.navigate", json!({"url": file_url}), Some(sid)).await;
+ let message = reply["error"]["message"].as_str().unwrap_or_default().to_string();
+ assert!(message.contains("file://"), "Page.navigate must refuse file://: {reply}");
+ let (reply, _) = call(&mut ws, 3, "Runtime.evaluate", json!({"expression": "location.href", "returnByValue": true}), Some(sid)).await;
+ assert!(!evaluate_value(&reply).starts_with("file:"), "{reply}");
+
+ // A page-driven navigation consumed after Runtime.evaluate.
+ call(&mut ws, 4, "Page.navigate", json!({"url": "data:text/html,<p>web</p>"}), Some(sid)).await;
+ let assign = format!("location.href = {}", serde_json::to_string(&file_url).unwrap());
+ call(&mut ws, 5, "Runtime.evaluate", json!({"expression": assign}), Some(sid)).await;
+ let (reply, _) = call(
+ &mut ws,
+ 6,
+ "Runtime.evaluate",
+ json!({"expression": "location.href + ' | ' + document.body.textContent", "returnByValue": true}),
+ Some(sid),
+ )
+ .await;
+ let state = evaluate_value(&reply);
+ assert!(state.starts_with("data:"), "page must stay on its web document: {state}");
+ assert!(!state.contains("local-secret"), "{state}");
+ })
+ .await;
+ let _ = std::fs::remove_file(&path);
+}
diff --git a/crates/obscura-cli/src/main.rs b/crates/obscura-cli/src/main.rs
index 7eaafc43..65c180c8 100644
--- a/crates/obscura-cli/src/main.rs
+++ b/crates/obscura-cli/src/main.rs
@@ -856,6 +856,10 @@ async fn run_fetch(
allow_private_network,
);
context.obey_robots = obey_robots;
+ // 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;
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
diff --git a/crates/obscura-mcp/src/lib.rs b/crates/obscura-mcp/src/lib.rs
index 271fe835..fcdae5bf 100644
--- a/crates/obscura-mcp/src/lib.rs
+++ b/crates/obscura-mcp/src/lib.rs
@@ -2200,6 +2200,58 @@ mod tests {
assert!(error.contains("file:// navigation is disabled"));
}
+ // Every MCP route that navigates must refuse local files, not only
+ // browser_navigate: the browser layer enforces it for all of them.
+ #[tokio::test(flavor = "current_thread")]
+ async fn mcp_tab_new_rejects_local_files() {
+ let mut state = BrowserState::new(None, None, false);
+ let error = tool_tab_new(&json!({"url": "file:///etc/passwd"}), &mut state)
+ .await
+ .expect_err("browser_tab_new must not expose local files");
+ assert!(error.contains("file://"), "{error}");
+ assert!(!state.page_mut().url_string().starts_with("file:"));
+ }
+
+ // An untrusted page must not be able to pull a local file into the agent's
+ // context by planting a file:// link for the agent to click.
+ #[tokio::test(flavor = "current_thread")]
+ async fn mcp_click_cannot_follow_a_link_into_file_scheme() {
+ let path = std::env::temp_dir().join(format!("obscura-mcp-file-link-{}.html", std::process::id()));
+ std::fs::write(&path, "<p>local-secret</p>").expect("write fixture");
+ let file_url = url::Url::from_file_path(&path).expect("file url").to_string();
+
+ let mut state = BrowserState::new(None, None, false);
+ state
+ .page_mut()
+ .navigate(&format!("data:text/html,<a id=l href='{file_url}'>go</a>"))
+ .await
+ .expect("web page");
+ let web_url = state.page_mut().url_string();
+
+ let click = handle_tool_call(
+ json!(1),
+ &json!({"name": "browser_click", "arguments": {"selector": "#l"}}),
+ &mut state,
+ )
+ .await
+ .result
+ .expect("click response");
+ assert_ne!(click["isError"], true, "{click}");
+ assert_eq!(state.page_mut().url_string(), web_url);
+
+ let snapshot = handle_tool_call(
+ json!(2),
+ &json!({"name": "browser_snapshot", "arguments": {}}),
+ &mut state,
+ )
+ .await
+ .result
+ .expect("snapshot response");
+ assert!(!snapshot.to_string().contains("local-secret"), "{snapshot}");
+
+ let _ = std::fs::remove_file(&path);
+ }
+
#[cfg(feature = "render")]
#[test]
fn render_tools_are_advertised_with_flat_schemas() {