The headless browser for AI agents and web scraping
fix(cli): enforce --obey-robots
lisa031492a70fe69ff8
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex 975c6ec7..680294f5 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -2456,28 +2456,31 @@ impl Page {self.network_events.clear();if self.context.obey_robots {- if let Some(domain) = url.host_str() {- if self.context.robots_cache.is_allowed(domain, "/robots.txt") {- let robots_url = format!("{}://{}/robots.txt", url.scheme(), domain);- if let Ok(robots_url) = Url::parse(&robots_url) {- if let Ok(resp) = self- .http_client- .fetch_with_callbacks(&robots_url, Some(&self.callbacks))- .await- {- if resp.status == 200 {- let body = String::from_utf8_lossy(&resp.body);- self.context.robots_cache.parse_and_store(- domain,- &body,- &self.context.user_agent,- );- }+ if url.scheme() == "http" || url.scheme() == "https" {+ let origin = url.origin().ascii_serialization();+ if !self.context.robots_cache.contains(&origin) {+ let mut robots_url = url.clone();+ robots_url.set_path("/robots.txt");+ robots_url.set_query(None);+ robots_url.set_fragment(None);+ let body = match self+ .http_client+ .fetch_with_callbacks(&robots_url, Some(&self.callbacks))+ .await+ {+ Ok(resp) if resp.status == 200 => {+ String::from_utf8_lossy(&resp.body).into_owned()}- }+ _ => String::new(),+ };+ self.context.robots_cache.parse_and_store(+ &origin,+ &body,+ &self.context.user_agent,+ );}- if !self.context.robots_cache.is_allowed(domain, url.path()) {+ if !self.context.robots_cache.is_allowed(&origin, url.path()) {self.lifecycle = LifecycleState::Failed;return Err(PageError::NetworkError(format!("Blocked by robots.txt: {}",diff --git a/crates/obscura-cli/src/main.rs b/crates/obscura-cli/src/main.rsindex 21a2d965..5b0e0ec5 100644--- a/crates/obscura-cli/src/main.rs+++ b/crates/obscura-cli/src/main.rs@@ -32,7 +32,9 @@ struct Args {#[arg(long, global = true)]stealth: bool,- #[arg(long)]+ /// Respect robots.txt before navigating to an HTTP(S) URL.+ /// Global: applies to fetch and scrape.+ #[arg(long, global = true)]obey_robots: bool,#[arg(long)]@@ -353,6 +355,7 @@ async fn main() -> anyhow::Result<()> {let global_proxy = args.proxy.clone();let stealth = args.stealth;+ let obey_robots = args.obey_robots;match args.command {Some(Command::Serve {@@ -476,6 +479,7 @@ async fn main() -> anyhow::Result<()> {global_proxy,storage_dir,args.allow_private_network,+ obey_robots,screenshot,).await?;@@ -498,6 +502,7 @@ async fn main() -> anyhow::Result<()> {quiet,global_proxy,stealth,+ obey_robots,).await?;}@@ -686,6 +691,7 @@ async fn run_fetch(proxy: Option<String>,storage_dir: Option<std::path::PathBuf>,allow_private_network: bool,+ obey_robots: bool,screenshot: Option<std::path::PathBuf>,) -> anyhow::Result<()> {// Whether the user explicitly passed --dump. With --eval also present this@@ -704,14 +710,16 @@ async fn run_fetch(return Ok(());}- let context = Arc::new(BrowserContext::with_storage_and_network(+ let mut context = BrowserContext::with_storage_and_network("fetch".to_string(),proxy,stealth,user_agent.clone(),storage_dir.clone(),allow_private_network,- ));+ );+ context.obey_robots = obey_robots;+ 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// request deadline. Previously Page retained its independent 30s default,@@ -1480,6 +1488,7 @@ async fn run_parallel_scrape(quiet: bool,proxy: Option<String>,stealth: bool,+ obey_robots: bool,) -> anyhow::Result<()> {let total = urls.len();let start = Instant::now();@@ -1537,6 +1546,7 @@ async fn run_parallel_scrape(.stderr(std::process::Stdio::null()).env("OBSCURA_PROXY", proxy.as_deref().unwrap_or("")).env("OBSCURA_STEALTH", if stealth { "1" } else { "" })+ .env("OBSCURA_OBEY_ROBOTS", if obey_robots { "1" } else { "" }).spawn(){Ok(c) => c,diff --git a/crates/obscura-cli/src/worker.rs b/crates/obscura-cli/src/worker.rsindex 1e37d1ed..2b6964b3 100644--- a/crates/obscura-cli/src/worker.rs+++ b/crates/obscura-cli/src/worker.rs@@ -54,7 +54,12 @@ async fn main() {let stealth = std::env::var("OBSCURA_STEALTH").map(|v| matches!(v.trim(), "1" | "true" | "yes" | "on")).unwrap_or(false);- let context = Arc::new(BrowserContext::with_options("worker".to_string(), proxy, stealth));+ let obey_robots = std::env::var("OBSCURA_OBEY_ROBOTS")+ .map(|v| matches!(v.trim(), "1" | "true" | "yes" | "on"))+ .unwrap_or(false);+ let mut context = BrowserContext::with_options("worker".to_string(), proxy, stealth);+ context.obey_robots = obey_robots;+ let context = Arc::new(context);let mut page = Page::new("page-1".to_string(), context);let stdin = tokio::io::stdin();diff --git a/crates/obscura-cli/tests/obey_robots.rs b/crates/obscura-cli/tests/obey_robots.rsnew file mode 100644index 00000000..db33ef1c--- /dev/null+++ b/crates/obscura-cli/tests/obey_robots.rs@@ -0,0 +1,167 @@+use std::io::{Read, Write};+use std::net::{TcpListener, TcpStream};+use std::process::{Command, Output};+use std::sync::{Arc, Mutex};+use std::thread;+use std::time::{Duration, Instant};++struct RobotsServer {+ address: String,+ paths: Arc<Mutex<Vec<String>>>,+}++impl RobotsServer {+ fn spawn() -> Self {+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind robots fixture");+ listener+ .set_nonblocking(true)+ .expect("set fixture nonblocking");+ let address = listener.local_addr().expect("fixture address").to_string();+ let paths = Arc::new(Mutex::new(Vec::new()));+ let server_paths = Arc::clone(&paths);+ thread::spawn(move || {+ let deadline = Instant::now() + Duration::from_secs(15);+ while Instant::now() < deadline {+ match listener.accept() {+ Ok((stream, _)) => serve(stream, &server_paths),+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {+ thread::sleep(Duration::from_millis(5));+ }+ Err(error) => panic!("accept fixture connection: {error}"),+ }+ }+ });+ Self { address, paths }+ }++ fn url(&self, path: &str) -> String {+ format!("http://{}{}", self.address, path)+ }++ fn paths(&self) -> Vec<String> {+ self.paths.lock().expect("fixture paths").clone()+ }+}++fn serve(mut stream: TcpStream, paths: &Arc<Mutex<Vec<String>>>) {+ stream+ .set_nonblocking(false)+ .expect("set fixture connection blocking");+ stream+ .set_read_timeout(Some(Duration::from_secs(2)))+ .expect("set fixture read timeout");+ let mut request = [0_u8; 4096];+ let count = stream.read(&mut request).expect("read fixture request");+ let first_line = String::from_utf8_lossy(&request[..count])+ .lines()+ .next()+ .unwrap_or_default()+ .to_string();+ let path = first_line.split_whitespace().nth(1).unwrap_or("/");+ paths.lock().expect("fixture paths").push(path.to_string());+ let (content_type, body) = if path == "/robots.txt" {+ ("text/plain", "User-agent: *\nDisallow: /private\n")+ } else {+ ("text/html", "<!doctype html><title>target reached</title><p>private target</p>")+ };+ let response = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );+ stream+ .write_all(response.as_bytes())+ .expect("write fixture response");+}++fn obscura(args: &[&str]) -> Output {+ Command::new(env!("CARGO_BIN_EXE_obscura"))+ .args(args)+ .output()+ .expect("run obscura CLI")+}++#[test]+fn obey_robots_is_global_and_blocks_fetch_before_target_request() {+ let server = RobotsServer::spawn();+ let url = server.url("/private/page");+ let output = obscura(&[+ "fetch",+ "--obey-robots",+ "--allow-private-network",+ "--quiet",+ "--wait",+ "0",+ &url,+ ]);++ assert!(!output.status.success(), "disallowed fetch must fail");+ assert!(+ String::from_utf8_lossy(&output.stderr).contains("Blocked by robots.txt"),+ "stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert_eq!(server.paths(), vec!["/robots.txt"]);+}++#[test]+fn obey_robots_reaches_scrape_worker_and_blocks_target_request() {+ let server = RobotsServer::spawn();+ let url = server.url("/private/page");+ let output = obscura(&[+ "--obey-robots",+ "--allow-private-network",+ "scrape",+ "--quiet",+ "--timeout",+ "5",+ &url,+ ]);++ assert!(output.status.success(), "scrape reports per-URL errors as JSON");+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(stdout.contains("Blocked by robots.txt"), "stdout: {stdout}");+ assert_eq!(server.paths(), vec!["/robots.txt"]);+}++#[test]+fn fetch_without_obey_robots_keeps_existing_navigation_behavior() {+ let server = RobotsServer::spawn();+ let url = server.url("/private/page");+ let output = obscura(&[+ "--allow-private-network",+ "fetch",+ "--quiet",+ "--wait",+ "0",+ &url,+ ]);++ assert!(+ output.status.success(),+ "stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert_eq!(server.paths(), vec!["/private/page"]);+}++#[test]+fn obey_robots_fetches_an_allowed_target_after_loading_policy() {+ let server = RobotsServer::spawn();+ let url = server.url("/public/page");+ let output = obscura(&[+ "--obey-robots",+ "--allow-private-network",+ "fetch",+ "--quiet",+ "--wait",+ "0",+ &url,+ ]);++ assert!(+ output.status.success(),+ "stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert_eq!(server.paths(), vec!["/robots.txt", "/public/page"]);+}diff --git a/crates/obscura-net/src/robots.rs b/crates/obscura-net/src/robots.rsindex 2e700f9d..0a13959e 100644--- a/crates/obscura-net/src/robots.rs+++ b/crates/obscura-net/src/robots.rs@@ -23,6 +23,10 @@ impl RobotsCache {self.cache.write().unwrap().insert(domain.to_string(), rules);}+ pub fn contains(&self, origin: &str) -> bool {+ self.cache.read().unwrap().contains_key(origin)+ }+pub fn is_allowed(&self, domain: &str, path: &str) -> bool {let cache = self.cache.read().unwrap();let rules = match cache.get(domain) {@@ -150,6 +154,11 @@ mod tests {fn test_no_rules_means_allowed() {let cache = RobotsCache::new();assert!(cache.is_allowed("unknown.com", "/anything"));+ assert!(!cache.contains("unknown.com"));++ cache.parse_and_store("unknown.com", "", "Obscura");+ assert!(cache.contains("unknown.com"));+ assert!(cache.is_allowed("unknown.com", "/anything"));}#[test]