The headless browser for AI agents and web scraping
fix(cli): explain local network access denials
vvinayakkk9a6dd862dccc
diff --git a/crates/obscura-cli/src/main.rs b/crates/obscura-cli/src/main.rsindex 67852373..0cda44ec 100644--- a/crates/obscura-cli/src/main.rs+++ b/crates/obscura-cli/src/main.rs@@ -349,6 +349,14 @@ fn main() -> anyhow::Result<()> {.map_err(|_| anyhow::anyhow!("obscura main thread panicked"))?}+fn operator_network_error(error: impl std::fmt::Display) -> String {+ let message = error.to_string();+ match obscura_net::private_network_error_hint(&message) {+ Some(hint) => format!("{}\n{}", message, hint),+ None => message,+ }+}+#[tokio::main(flavor = "current_thread")]async fn run_cli() -> anyhow::Result<()> {let args = Args::parse();@@ -969,7 +977,7 @@ async fn run_fetch(.await{Ok(result) => {- result.map_err(|e| anyhow::anyhow!("Failed to navigate to {}: {}", url_str, e))?+ result.map_err(|e| anyhow::anyhow!("Failed to navigate to {}: {}", url_str, operator_network_error(e)))?}Err(_) => anyhow::bail!("Timed out navigating to {} after {}s",@@ -1265,7 +1273,7 @@ async fn fetch_original_response();return match timeout(Duration::from_secs(timeout_secs), client.fetch(&url)).await {Ok(Ok(resp)) => Ok(resp),- Ok(Err(e)) => anyhow::bail!("Failed to fetch {}: {}", url_str, e),+ Ok(Err(e)) => anyhow::bail!("Failed to fetch {}: {}", url_str, operator_network_error(e)),Err(_) => anyhow::bail!("Timed out fetching {} after {}s", url_str, timeout_secs),};}@@ -1281,7 +1289,7 @@ async fn fetch_original_response(match timeout(Duration::from_secs(timeout_secs), client.fetch(&url)).await {Ok(Ok(resp)) => Ok(resp),- Ok(Err(e)) => anyhow::bail!("Failed to fetch {}: {}", url_str, e),+ Ok(Err(e)) => anyhow::bail!("Failed to fetch {}: {}", url_str, operator_network_error(e)),Err(_) => anyhow::bail!("Timed out fetching {} after {}s", url_str, timeout_secs),}}diff --git a/crates/obscura-cli/tests/local_network_hints.rs b/crates/obscura-cli/tests/local_network_hints.rsnew file mode 100644index 00000000..4c905ad8--- /dev/null+++ b/crates/obscura-cli/tests/local_network_hints.rs@@ -0,0 +1,85 @@+use serde_json::json;+use std::io::Write;+use std::process::{Command, Stdio};++fn cli() -> Command {+ let mut command = Command::new(env!("CARGO_BIN_EXE_obscura"));+ for name in [+ "OBSCURA_ALLOW_PRIVATE_NETWORK",+ "OBSCURA_PROXY",+ "HTTP_PROXY",+ "HTTPS_PROXY",+ "ALL_PROXY",+ "http_proxy",+ "https_proxy",+ "all_proxy",+ ] {+ command.env_remove(name);+ }+ command.env("OBSCURA_STEALTH", "0");+ command+}++#[test]+fn local_cli_denials_explain_the_existing_opt_in_without_granting_access() {+ for host in ["localhost", "127.0.0.1", "[::1]"] {+ for dump in ["text", "original"] {+ let output = cli()+ .args(["fetch", &format!("http://{host}:9/"), "--dump", dump])+ .output()+ .unwrap();+ assert!(!output.status.success());+ let error = String::from_utf8(output.stderr).unwrap();+ assert!(error.contains("is not allowed"), "{error}");+ assert!(error.contains("--allow-private-network"), "{error}");+ assert!(error.contains("OBSCURA_ALLOW_PRIVATE_NETWORK=1"), "{error}");+ }+ }+}++#[test]+fn cli_metadata_denials_do_not_suggest_relaxing_the_guard() {+ for host in ["169.254.169.254", "100.100.100.200", "[fd00:ec2::254]"] {+ let output = cli()+ .args(["fetch", &format!("http://{host}/"), "--dump", "text"])+ .output()+ .unwrap();+ assert!(!output.status.success());+ let error = String::from_utf8(output.stderr).unwrap();+ assert!(error.contains("is not allowed"), "{error}");+ assert!(!error.contains("--allow-private-network"), "{error}");+ }+}++#[test]+fn stdio_mcp_denials_are_actionable_and_still_errors() {+ let mut child = cli()+ .arg("mcp")+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .unwrap();+ let mut input = child.stdin.take().unwrap();+ writeln!(input, "{}", json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"regression","version":"1"}}})).unwrap();+ for (id, url) in [(2, "http://localhost:9/"), (3, "http://169.254.169.254/")] {+ writeln!(input, "{}", json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":{"name":"browser_navigate","arguments":{"url":url}}})).unwrap();+ }+ drop(input);+ let output = child.wait_with_output().unwrap();+ assert!(output.status.success());+ let responses = String::from_utf8(output.stdout)+ .unwrap()+ .lines()+ .map(|line| serde_json::from_str::<serde_json::Value>(line).unwrap())+ .collect::<Vec<_>>();+ assert_eq!(responses.len(), 3);+ for (index, hint) in [(1, true), (2, false)] {+ assert_eq!(responses[index]["result"]["isError"], true);+ let error = responses[index]["result"]["content"][0]["text"]+ .as_str()+ .unwrap();+ assert!(error.contains("is not allowed"), "{error}");+ assert_eq!(error.contains("--allow-private-network"), hint, "{error}");+ }+}diff --git a/crates/obscura-mcp/src/lib.rs b/crates/obscura-mcp/src/lib.rsindex fcdae5bf..1bde0238 100644--- a/crates/obscura-mcp/src/lib.rs+++ b/crates/obscura-mcp/src/lib.rs@@ -70,6 +70,7 @@ pub struct BrowserState {tab_counter: u32,context: Arc<BrowserContext>,user_agent: Option<String>,+ operator_network_hints: bool,console_messages: Vec<String>,/// Element-ref table from the last `browser_snapshot` on the ACTIVE/// tab. Agents click / fill / type by `ref` (e.g. `"e3"`) instead of@@ -87,6 +88,7 @@ impl BrowserState {tab_counter: 0,context: Arc::new(BrowserContext::with_options("mcp".to_string(), proxy, stealth)),user_agent,+ operator_network_hints: false,console_messages: Vec::new(),interactive_refs: HashMap::new(),}@@ -243,6 +245,7 @@ pub async fn run(proxy: Option<String>, user_agent: Option<String>, stealth: boolet mut writer = stdout;let mut state = BrowserState::new(proxy, user_agent, stealth);+ state.operator_network_hints = true;let mut runtime_pump_armed = false;loop {@@ -947,13 +950,22 @@ async fn tool_navigate(args: &Value, state: &mut BrowserState) -> Result<String,let condition = obscura_browser::lifecycle::WaitUntil::from_str(wait_until);let ua = state.user_agent.clone();+ let operator_hints = state.operator_network_hints;let page = state.page_mut();if let Some(ref ua) = ua {page.http_client.set_user_agent(ua).await;}page.navigate_with_wait(url, condition).await- .map_err(|e| e.to_string())?;+ .map_err(|e| {+ let message = e.to_string();+ if operator_hints {+ if let Some(hint) = obscura_net::private_network_error_hint(&message) {+ return format!("{}\n{}", message, hint);+ }+ }+ message+ })?;let summary = format!("Navigated to {} — \"{}\"", page.url_string(), page.title);// DOM changed — invalidate the ref table. Next snapshot will rebuild.@@ -2191,6 +2203,24 @@ mod tests {}));}+ #[tokio::test]+ async fn local_network_hint_is_limited_to_operator_stdio_state() {+ std::env::remove_var("OBSCURA_ALLOW_PRIVATE_NETWORK");+ let mut state = BrowserState::new(None, None, false);+ let args = json!({"url": "http://localhost:9/"});+ let remote_error = tool_navigate(&args, &mut state).await.unwrap_err();+ assert!(remote_error.contains("is not allowed"));+ assert!(!remote_error.contains("--allow-private-network"));+ state.operator_network_hints = true;+ let local_error = tool_navigate(&args, &mut state).await.unwrap_err();+ assert!(local_error.contains("is not allowed"));+ assert!(local_error.contains("--allow-private-network"));+ assert!(local_error.contains("OBSCURA_ALLOW_PRIVATE_NETWORK=1"));+ let metadata_error = tool_navigate(&json!({"url":"http://169.254.169.254/latest/meta-data/"}), &mut state).await.unwrap_err();+ assert!(metadata_error.contains("is not allowed"));+ assert!(!metadata_error.contains("--allow-private-network"));+ }+#[tokio::test(flavor = "current_thread")]async fn mcp_navigation_rejects_local_files() {let mut state = BrowserState::new(None, None, false);diff --git a/crates/obscura-net/src/lib.rs b/crates/obscura-net/src/lib.rsindex 2b8c18fb..75661e59 100644--- a/crates/obscura-net/src/lib.rs+++ b/crates/obscura-net/src/lib.rs@@ -26,3 +26,6 @@ pub use wreq_client::{StealthHttpClient, STEALTH_NAVIGATOR_PLATFORM, STEALTH_UA_PLATFORM,STEALTH_UA_PLATFORM_VERSION, STEALTH_USER_AGENT,};++mod operator_hint;+pub use operator_hint::private_network_error_hint;diff --git a/crates/obscura-net/src/operator_hint.rs b/crates/obscura-net/src/operator_hint.rsnew file mode 100644index 00000000..45261843--- /dev/null+++ b/crates/obscura-net/src/operator_hint.rs@@ -0,0 +1,84 @@+use std::net::{IpAddr, Ipv6Addr};++const PRIVATE_NETWORK_HINT: &str = "Local/private network access is blocked by the SSRF guard. For your own local services, start Obscura with --allow-private-network or set OBSCURA_ALLOW_PRIVATE_NETWORK=1.";++/// Hint for an operator-facing error, not a policy change. CLI and stdio MCP+/// opt into presenting it; remote transports should keep the original error.+/// Inspect the actual denied host, not the initial navigation URL, since a+/// redirect can lead elsewhere. Metadata and other special-purpose ranges+/// deliberately receive no opt-out suggestion.+pub fn private_network_error_hint(mut error: &str) -> Option<&'static str> {+ while let Some(inner) = error.strip_prefix("Network error: ") {+ error = inner;+ }+ if let Some(domain) = error+ .strip_prefix("Access to localhost domain '")+ .and_then(|value| value.strip_suffix("' is not allowed"))+ {+ let domain = domain.to_ascii_lowercase();+ return (domain == "localhost" || domain.ends_with(".localhost"))+ .then_some(PRIVATE_NETWORK_HINT);+ }+ let address = error+ .strip_prefix("Access to private/internal IP address ")+ .or_else(|| error.strip_prefix("Access to private/internal IPv6 address "))?+ .strip_suffix(" is not allowed")?+ .parse::<IpAddr>()+ .ok()?;+ let local = match address {+ IpAddr::V4(ip) => ip.is_loopback() || ip.is_private(),+ IpAddr::V6(ip) => {+ // AWS's IPv6 instance metadata endpoint is in the ULA range.+ let metadata = Ipv6Addr::new(0xfd00, 0x0ec2, 0, 0, 0, 0, 0, 0x0254);+ ip != metadata+ && (ip.is_loopback()+ || ip.is_unique_local()+ || ip+ .to_ipv4_mapped()+ .or_else(|| ip.to_ipv4())+ .is_some_and(|v4| v4.is_loopback() || v4.is_private()))+ }+ };+ local.then_some(PRIVATE_NETWORK_HINT)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn local_denials_offer_the_existing_operator_opt_in() {+ for message in [+ "Access to localhost domain 'localhost' is not allowed",+ "Network error: Network error: Access to localhost domain 'app.localhost' is not allowed",+ "Access to private/internal IP address 127.0.0.1 is not allowed",+ "Access to private/internal IP address 192.168.1.1 is not allowed",+ "Access to private/internal IP address 10.0.0.1 is not allowed",+ "Access to private/internal IPv6 address ::1 is not allowed",+ "Access to private/internal IPv6 address fd12::1 is not allowed",+ "Access to private/internal IPv6 address ::ffff:127.0.0.1 is not allowed",+ ] {+ let hint = private_network_error_hint(message).expect(message);+ assert!(hint.contains("--allow-private-network"));+ assert!(hint.contains("OBSCURA_ALLOW_PRIVATE_NETWORK=1"));+ }+ }++ #[test]+ fn metadata_special_ranges_and_unrelated_errors_do_not_get_a_hint() {+ for message in [+ "Access to private/internal IP address 169.254.169.254 is not allowed",+ "Access to private/internal IP address 100.100.100.200 is not allowed",+ "Access to private/internal IPv6 address fd00:ec2::254 is not allowed",+ "Access to private/internal IPv6 address fe80::1 is not allowed",+ "Access to private/internal IPv6 address ::ffff:169.254.169.254 is not allowed",+ "Access to private/internal IP address 198.18.0.1 is not allowed",+ "Access to private/internal IP address 0.0.0.0 is not allowed",+ "Access to localhost domain 'example.com' is not allowed",+ "Network error: certificate verify failed",+ "Access to private/internal IP address invalid is not allowed",+ ] {+ assert_eq!(private_network_error_hint(message), None, "{message}");+ }+ }+}diff --git a/docs/Use-the-MCP-server.md b/docs/Use-the-MCP-server.mdindex 5cd0a6da..9bb46bce 100644--- a/docs/Use-the-MCP-server.md+++ b/docs/Use-the-MCP-server.md@@ -128,3 +128,9 @@ claude mcp add obscura /path/to/obscura mcp}}```++Local and private network addresses are blocked by default. CLI and stdio MCP+navigation errors explain the existing `--allow-private-network` /+`OBSCURA_ALLOW_PRIVATE_NETWORK=1` opt-in for your own local services. The hint+does not grant access, is omitted for known metadata endpoints and special+address ranges, and is not shown by the HTTP MCP transport.