The headless browser for AI agents and web scraping
Fetch modules as cached CORS subresources
SGavrl1d2dc4e36bea
diff --git a/crates/obscura-js/src/module_loader.rs b/crates/obscura-js/src/module_loader.rsindex 69f7daaa..7ce770f4 100644--- a/crates/obscura-js/src/module_loader.rs+++ b/crates/obscura-js/src/module_loader.rs@@ -175,11 +175,21 @@ impl ModuleLoader for ObscuraModuleLoader {fn load(&self,module_specifier: &ModuleSpecifier,- _maybe_referrer: Option<&ModuleSpecifier>,+ maybe_referrer: Option<&ModuleSpecifier>,is_dyn_import: bool,_requested_module_type: RequestedModuleType,) -> ModuleLoadResponse {let url = module_specifier.to_string();+ // Module-graph CORS and same-origin credentials are relative to the+ // owning document, not to the importing module. The importer remains+ // the HTTP referrer for a dependency; keeping these URLs distinct+ // prevents a cross-origin parent module from gaining CDN cookies when+ // it imports a sibling on that CDN.+ let document_url = ModuleSpecifier::parse(&self.base_url)+ .unwrap_or_else(|_| module_specifier.clone());+ let referrer = maybe_referrer+ .cloned()+ .unwrap_or_else(|| document_url.clone());// Capture the loader's proxy here so the async closure below owns a// plain Option<String> rather than borrowing &self across an `await`.let proxy_url = self.proxy_url.clone();@@ -226,7 +236,11 @@ impl ModuleLoader for ObscuraModuleLoader {let requested = ModuleSpecifier::parse(&url).map_err(|e| io_err(format!("Invalid module URL {}: {}", url, e)))?;let resp = client- .fetch_with_callbacks(&requested, callbacks.as_deref())+ .fetch_resource_with_callbacks(+ &requested,+ obscura_net::ResourceRequest::module_script(&document_url, &referrer),+ callbacks.as_deref(),+ ).await.map_err(|e| io_err(format!("Failed to fetch module {}: {}", url, e)))?;if !(200..=299).contains(&resp.status) {diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex f7e3d325..70c84e2e 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -12875,6 +12875,87 @@ mod tests {);}+ #[tokio::test(flavor = "current_thread")]+ async fn cross_origin_module_descendant_does_not_gain_module_origin_cookies() {+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let address = listener.local_addr().unwrap();+ let module_base = format!("http://{address}");+ let document_url = "http://127.0.0.1:1/page";+ let document_origin = "http://127.0.0.1:1";+ let (requests_tx, requests_rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ use std::io::{Read as _, Write as _};++ for _ in 0..2 {+ let (mut stream, _) = listener.accept().unwrap();+ let mut request = [0u8; 4096];+ let length = stream.read(&mut request).unwrap();+ let request = String::from_utf8_lossy(&request[..length]).to_string();+ let path = request+ .lines()+ .next()+ .and_then(|line| line.split_ascii_whitespace().nth(1))+ .unwrap_or("/");+ let body = match path {+ "/entry.js" => {+ "import { value } from './child.js'; globalThis.__cors_value = value;"+ }+ "/child.js" => "export const value = 'safe';",+ _ => "throw new Error('unexpected module path');",+ };+ requests_tx.send(request).unwrap();+ let response = format!(+ "HTTP/1.1 200 OK\r\n\+ Content-Type: application/javascript\r\n\+ Access-Control-Allow-Origin: {document_origin}\r\n\+ Cache-Control: public, max-age=3600\r\n\+ Content-Length: {}\r\n\+ Connection: close\r\n\r\n{body}",+ body.len(),+ );+ stream.write_all(response.as_bytes()).unwrap();+ }+ });++ let module_origin = url::Url::parse(&module_base).unwrap();+ let jar = std::sync::Arc::new(obscura_net::CookieJar::new());+ jar.set_cookie("cdn_session=secret; Path=/", &module_origin);+ let client = std::sync::Arc::new(obscura_net::ObscuraHttpClient::with_full_options(+ jar, None, true,+ ));+ let mut rt = ObscuraJsRuntime::with_base_url(document_url);+ rt.set_http_client(client);+ rt.load_module(&format!("{module_base}/entry.js"), 1_000)+ .await+ .unwrap();++ assert_eq!(+ rt.evaluate("globalThis.__cors_value").unwrap(),+ serde_json::json!("safe"),+ );+ let requests = (0..2)+ .map(|_| {+ requests_rx+ .recv_timeout(std::time::Duration::from_secs(1))+ .unwrap()+ })+ .collect::<Vec<_>>();+ for request in &requests {+ let lower = request.to_ascii_lowercase();+ assert!(lower.contains("\r\norigin: http://127.0.0.1:1\r\n"), "{request}");+ assert!(!lower.contains("\r\ncookie:"), "{request}");+ }+ let child = requests+ .iter()+ .find(|request| request.starts_with("GET /child.js "))+ .expect("child module request")+ .to_ascii_lowercase();+ assert!(+ child.contains(&format!("\r\nreferer: {module_base}/entry.js\r\n")),+ "{child}",+ );+ }+#[tokio::test(flavor = "current_thread")]async fn descendant_module_follows_page_client_redirects() {let (base, requests) = spawn_module_graph_server(ModuleGraphFixture::RedirectedChild);diff --git a/crates/obscura-net/src/client.rs b/crates/obscura-net/src/client.rsindex ddd55ffb..e5aac220 100644--- a/crates/obscura-net/src/client.rs+++ b/crates/obscura-net/src/client.rs@@ -168,7 +168,14 @@ impl RequestMode {#[derive(Debug, Clone, PartialEq, Eq)]pub struct ResourceRequest {pub resource_type: ResourceType,+ /// Origin-bearing environment that owns the request. This controls CORS,+ /// credentials, and Sec-Fetch-Site and must remain the document/realm for+ /// every descendant in a module graph.pub initiator: Option<Url>,+ /// URL used to derive the Referer header. Usually the same as `initiator`,+ /// but a module dependency is referred by its importing module while its+ /// credentials mode is still relative to the owning document.+ pub referrer: Option<Url>,pub mode: RequestMode,pub credentials: RequestCredentials,/// Hard limit for the decoded response body retained by this request.@@ -181,6 +188,7 @@ impl ResourceRequest {Self {resource_type: ResourceType::Document,initiator: None,+ referrer: None,mode: RequestMode::Navigate,credentials: RequestCredentials::Include,max_response_bytes: 64 * 1024 * 1024,@@ -209,6 +217,7 @@ impl ResourceRequest {Self {resource_type,initiator: Some(initiator.clone()),+ referrer: Some(initiator.clone()),mode,credentials,max_response_bytes: match resource_type {@@ -222,6 +231,21 @@ impl ResourceRequest {}}+ /// Fetch profile for JavaScript modules. Unlike classic scripts, module+ /// scripts are CORS-enabled and use `same-origin` credentials by default.+ /// Keep this separate from `subresource(Script, ..)`, whose no-CORS,+ /// include-credentials profile is still correct for classic scripts.+ pub fn module_script(initiator: &Url, referrer: &Url) -> Self {+ Self {+ resource_type: ResourceType::Script,+ initiator: Some(initiator.clone()),+ referrer: Some(referrer.clone()),+ mode: RequestMode::Cors,+ credentials: RequestCredentials::SameOrigin,+ max_response_bytes: 32 * 1024 * 1024,+ }+ }+pub fn with_max_response_bytes(mut self, max_response_bytes: usize) -> Self {self.max_response_bytes = max_response_bytes;self@@ -398,7 +422,10 @@ pub(crate) fn request_fetch_site(request: &ResourceRequest, target: &Url) -> &'s}pub(crate) fn request_referrer(request: &ResourceRequest, target: &Url) -> Option<String> {- let source = request.initiator.as_ref()?;+ let source = request+ .referrer+ .as_ref()+ .or(request.initiator.as_ref())?;if !matches!(source.scheme(), "http" | "https")|| !matches!(target.scheme(), "http" | "https")|| (source.scheme() == "https" && target.scheme() == "http")@@ -830,6 +857,7 @@ struct ResourceCacheKey {mode: RequestMode,credentials: RequestCredentials,initiator: Option<String>,+ referrer: Option<String>,user_agent: String,extra_headers: Vec<(String, String)>,max_response_bytes: usize,@@ -1177,6 +1205,7 @@ impl ObscuraHttpClient {mode: request.mode,credentials: request.credentials,initiator: request.initiator.as_ref().map(ToString::to_string),+ referrer: request.referrer.as_ref().map(ToString::to_string),user_agent: self.user_agent.read().await.clone(),extra_headers,max_response_bytes: request.max_response_bytes,@@ -1738,6 +1767,19 @@ mod ssrf_tests {assert!(!font.sends_credentials_to(&Url::parse("https://cdn.example/font.woff2").unwrap()));++ let module = ResourceRequest::module_script(&document, &document);+ assert_eq!(module.resource_type, ResourceType::Script);+ assert_eq!(module.mode, RequestMode::Cors);+ assert_eq!(module.credentials, RequestCredentials::SameOrigin);+ assert_eq!(module.destination(), "script");+ assert_eq!(module.accept(), "*/*");+ assert!(module.sends_credentials_to(+ &Url::parse("https://app.example/chunk.js").unwrap()+ ));+ assert!(!module.sends_credentials_to(+ &Url::parse("https://cdn.example/chunk.js").unwrap()+ ));}#[test]@@ -1835,6 +1877,37 @@ mod ssrf_tests {assert_eq!(jar.get_cookie_header(&target), "seed=1");}+ #[tokio::test]+ async fn cross_origin_module_uses_cors_script_profile_without_credentials() {+ let (target, mut received) = http_fixture(vec![ok_response(+ "Access-Control-Allow-Origin: *\r\nSet-Cookie: rejected=1; Path=/\r\n",+ "export default 1;",+ )])+ .await;+ let initiator = Url::parse("http://127.0.0.1:1/page").unwrap();+ let importing_module = target.join("/parent.js").unwrap();+ let jar = Arc::new(CookieJar::new());+ jar.set_cookie("seed=1; Path=/", &target);+ let client = ObscuraHttpClient::with_full_options(jar.clone(), None, true);++ let response = client+ .fetch_resource_with_callbacks(+ &target,+ ResourceRequest::module_script(&initiator, &importing_module),+ None,+ )+ .await+ .unwrap();+ assert_eq!(response.body, b"export default 1;");+ let request = received.recv().await.unwrap().to_ascii_lowercase();+ assert!(request.contains("origin: http://127.0.0.1:1\r\n"));+ assert!(request.contains("sec-fetch-mode: cors\r\n"));+ assert!(request.contains("sec-fetch-dest: script\r\n"));+ assert!(request.contains(&format!("referer: {}\r\n", importing_module)));+ assert!(!request.contains("cookie:"));+ assert_eq!(jar.get_cookie_header(&target), "seed=1");+ }+#[tokio::test]async fn credentialed_cors_rejects_wildcard_and_accepts_exact_origin() {let initiator = Url::parse("http://127.0.0.1:1/page").unwrap();@@ -2210,6 +2283,42 @@ mod ssrf_tests {assert_eq!(callback_responses.load(Ordering::SeqCst), 32);}+ #[tokio::test]+ async fn cacheable_identical_module_scripts_share_one_in_flight_request() {+ let (url, network_requests) = cacheable_resource_fixture(+ 200,+ "Cache-Control: public, max-age=3600\r\n",+ )+ .await;+ let initiator = url.join("/app.js").unwrap();+ let client = Arc::new(ObscuraHttpClient::with_full_options(+ Arc::new(CookieJar::new()),+ None,+ true,+ ));++ let mut fetches = tokio::task::JoinSet::new();+ for _ in 0..16 {+ let client = client.clone();+ let url = url.clone();+ let request = ResourceRequest::module_script(&initiator, &initiator);+ fetches.spawn(async move {+ client+ .fetch_resource_with_callbacks(&url, request, None)+ .await+ .unwrap()+ });+ }+ let mut responses = Vec::new();+ while let Some(response) = fetches.join_next().await {+ responses.push(response.unwrap());+ }++ assert_eq!(responses.len(), 16);+ assert!(responses.iter().all(|response| response.status == 200));+ assert_eq!(network_requests.load(Ordering::SeqCst), 1);+ }+#[tokio::test]async fn distinct_subresource_urls_do_not_coalesce() {let (url, network_requests) =