Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(csp): enforce image policies for the owning document
ldm05399724fb07a
diff --git a/moli-renderer-v8/src/document_runtime/security_policy.rs b/moli-renderer-v8/src/document_runtime/security_policy.rsindex d1457a7e7..acea42bba 100644--- a/moli-renderer-v8/src/document_runtime/security_policy.rs+++ b/moli-renderer-v8/src/document_runtime/security_policy.rs@@ -789,11 +789,27 @@ impl DocumentRuntime {request_url: &Url,kind: DocumentSubresourceCspKind,) -> DocumentContentSecurityPolicyCheck {- let document_url = self.document_url();- let policies = self.document_content_security_policy_strings_for_optional_document(+ self.document_subresource_csp_check_for_document(Some(self.document_handle()),- &self.policy_container.response_content_security_policies,- &self.policy_container.content_security_reporting_endpoints,+ self.document_url(),+ &self.policy_container,+ request_url,+ kind,+ )+ }++ pub(crate) fn document_subresource_csp_check_for_document(+ &self,+ document_handle: Option<DomHandle>,+ document_url: &Url,+ policy_container: &DocumentPolicyContainer,+ request_url: &Url,+ kind: DocumentSubresourceCspKind,+ ) -> DocumentContentSecurityPolicyCheck {+ let policies = self.document_content_security_policy_strings_for_optional_document(+ document_handle,+ &policy_container.response_content_security_policies,+ &policy_container.content_security_reporting_endpoints,);let enforced_violation = document_url_policy_violation_from_document_policies(policies,@@ -804,10 +820,8 @@ impl DocumentRuntime {ContentSecurityPolicyDisposition::Enforce,);let report_only_violation = document_url_policy_violation(- &self- .policy_container- .response_content_security_report_only_policies,- &self.policy_container.content_security_reporting_endpoints,+ &policy_container.response_content_security_report_only_policies,+ &policy_container.content_security_reporting_endpoints,document_url,request_url,kind.resource_kind(),@@ -1688,10 +1702,7 @@ impl DocumentRuntime {.map(|policy| DocumentContentSecurityPolicyString {policy,report_uri_enabled: false,- reporting_endpoints: self- .policy_container- .content_security_reporting_endpoints- .clone(),+ reporting_endpoints: response_reporting_endpoints.clone(),}),);}@@ -2473,6 +2484,83 @@ mod tests {);}+ #[test]+ fn child_image_meta_csp_uses_own_reporting_endpoints() {+ let mut runtime = runtime_for_html(+ r#"<!doctype html>+ <meta http-equiv="Content-Security-Policy" content="img-src 'none'; report-to csp">+ "#,+ );+ runtime.set_content_security_reporting_endpoints(reporting_endpoints());+ let child_document = runtime.dom_host_mut().create_detached_html_document();+ let child_meta = runtime.dom_host_mut().create_element("meta");+ assert_eq!(+ runtime+ .dom_host_mut()+ .adopt_node(child_document, child_meta),+ Some(child_meta)+ );+ assert!(runtime.dom_host_mut().set_attribute(+ child_meta,+ "http-equiv",+ "Content-Security-Policy"+ ));+ assert!(runtime.dom_host_mut().set_attribute(+ child_meta,+ "content",+ "img-src 'none'; report-to csp; report-uri /ignored-meta-report"+ ));+ assert!(+ runtime+ .dom_host_mut()+ .append_child(child_document, child_meta)+ );++ let child_url = Url::parse("https://child.example.test/page").unwrap();+ let request_url = child_url.join("image.png").unwrap();+ let child_policy = DocumentPolicyContainer::from_navigation_response_headers(+ &[(+ "Reporting-Endpoints".to_owned(),+ b"csp=\"/child-reports\"".to_vec(),+ )],+ &child_url,+ );+ for (policy, expected) in [+ (+ child_policy,+ vec!["https://child.example.test/child-reports".to_owned()],+ ),+ (DocumentPolicyContainer::default(), Vec::new()),+ ] {+ let check = runtime.document_subresource_csp_check_for_document(+ Some(child_document),+ &child_url,+ &policy,+ &request_url,+ DocumentSubresourceCspKind::Image,+ );+ let violation = check+ .enforced_violation()+ .expect("child meta CSP must block");+ assert_eq!(+ violation.report_to_endpoints, expected,+ "a child must not resolve its report group using the parent's endpoints"+ );+ assert!(violation.report_uri_endpoints.is_empty());+ }++ let parent_check =+ runtime.document_subresource_csp_check(&request_url, DocumentSubresourceCspKind::Image);+ assert_eq!(+ parent_check+ .enforced_violation()+ .expect("parent meta CSP must block")+ .report_to_endpoints,+ vec!["https://example.test/reports/csp".to_owned()],+ "checking the child must preserve the parent's own report group"+ );+ }+#[test]fn document_open_does_not_reuse_replaced_document_meta_csp() {let mut runtime = runtime_for_html(diff --git a/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs b/moli-renderer-v8/src/native_bridge/context_host/security_policy.rsindex 5b94a742b..8c0e5eb1b 100644--- a/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs@@ -343,6 +343,46 @@ impl JsContextHost {DocumentCspOutcome::Blocked(violation)}+ pub(crate) fn check_element_subresource_csp<'s>(+ &mut self,+ scope: &mut v8::PinScope<'s, '_>,+ element: DomHandle,+ request_url: &url::Url,+ kind: DocumentSubresourceCspKind,+ ) -> DocumentCspOutcome {+ let Some(owner) = self.owner_dispatch_scope_for_node(element) else {+ return DocumentCspOutcome::Allowed;+ };+ let Some(snapshot) = self.owner_document_policy_snapshot(owner) else {+ return DocumentCspOutcome::Allowed;+ };+ // The element's Document owns this request even when a different+ // Window's script changes its source or queues the update microtask.+ // SAFETY: this host and its DocumentRuntime are owned by the same ScriptVm.+ let (report_only_violation, enforced_violation) = unsafe { &*self.runtime }+ .document_subresource_csp_check_for_document(+ snapshot.document_handle,+ &snapshot.document_url,+ &snapshot.policy_container,+ request_url,+ kind,+ )+ .into_violations();+ let host_ptr: *mut JsContextHost = self;+ if let Some(violation) = report_only_violation {+ self.dispatch_content_security_policy_violation_event_for_owner_best_effort(+ scope, host_ptr, owner, &violation,+ );+ }+ let Some(violation) = enforced_violation else {+ return DocumentCspOutcome::Allowed;+ };+ self.dispatch_content_security_policy_violation_event_for_owner_best_effort(+ scope, host_ptr, owner, &violation,+ );+ DocumentCspOutcome::Blocked(violation)+ }+pub(crate) fn owner_dispatch_scope_for_node(&self,handle: DomHandle,diff --git a/moli-renderer-v8/src/native_bridge/element/images/src.rs b/moli-renderer-v8/src/native_bridge/element/images/src.rsindex ce9873cba..45353fd83 100644--- a/moli-renderer-v8/src/native_bridge/element/images/src.rs+++ b/moli-renderer-v8/src/native_bridge/element/images/src.rs@@ -163,6 +163,32 @@ fn queue_image_load_event(let _ = runtime.process_image_decode_requests_for_element(scope, handle);return;};+ let request_url = if invalid_empty_source {+ Err("an empty image source cannot be fetched".to_owned())+ } else {+ url::Url::parse(&selected_source).map_err(|error| error.to_string())+ };+ // Cached pixels must pass the requesting element's current Document policy+ // before they can satisfy its load or decode work.+ if let Ok(request_url) = &request_url+ && runtime+ .check_element_subresource_csp(+ scope,+ handle,+ request_url,+ DocumentSubresourceCspKind::Image,+ )+ .blocks_request()+ {+ let followup = runtime.complete_pending_image_load_local_resource_if_matches(+ handle,+ pending.id(),+ false,+ );+ queue_image_load_terminal_followup_if_ready(runtime_ptr, handle, pending.id(), followup);+ let _ = runtime.process_image_decode_requests_for_element(scope, handle);+ return;+ }// Register the current request before reconsidering decode() promises. An// image may receive src and decode() while detached, then be inserted in// the same script job. Processing the promise before this registration@@ -176,46 +202,17 @@ fn queue_image_load_event(queue_image_load_terminal_followup_if_ready(runtime_ptr, handle, pending.id(), followup);return;}- let start = if invalid_empty_source {- Err("an empty image source cannot be fetched".to_owned())- } else {- url::Url::parse(&selected_source)- .map_err(|error| error.to_string())- .and_then(|request_url| {- if runtime- .check_top_document_subresource_csp(- scope,- &request_url,- DocumentSubresourceCspKind::Image,- )- .blocks_request()- {- return Ok(crate::network_host::ImageElementResourceFetchStart::Failed);- }- crate::network_host::start_image_element_resource_fetch(- scope,- runtime,- handle,- pending.id(),- request_url,- )- })- };+ let start = request_url.and_then(|request_url| {+ crate::network_host::start_image_element_resource_fetch(+ scope,+ runtime,+ handle,+ pending.id(),+ request_url,+ )+ });match start {Ok(crate::network_host::ImageElementResourceFetchStart::Pending) => {}- Ok(crate::network_host::ImageElementResourceFetchStart::Failed) => {- let followup = runtime.complete_pending_image_load_local_resource_if_matches(- handle,- pending.id(),- false,- );- queue_image_load_terminal_followup_if_ready(- runtime_ptr,- handle,- pending.id(),- followup,- );- }Ok(crate::network_host::ImageElementResourceFetchStart::PolicySkipped) => {let followup = runtime.complete_pending_image_load_local_resource_if_matches(handle,diff --git a/moli-renderer-v8/src/network_host/image.rs b/moli-renderer-v8/src/network_host/image.rsindex 1f04fc9ae..f2c328c1f 100644--- a/moli-renderer-v8/src/network_host/image.rs+++ b/moli-renderer-v8/src/network_host/image.rs@@ -21,7 +21,6 @@ pub(crate) enum ImageElementResourceFetchStart {descriptor: Option<crate::native_bridge::ImageResponseDescriptor>,encoded: moli_parkable_image::ParkableImage,},- Failed,PolicySkipped,Pending,}diff --git a/moli-renderer-v8/src/script_vm/tests/canvas_webgl.rs b/moli-renderer-v8/src/script_vm/tests/canvas_webgl.rsindex a0ae073db..4c2c8a350 100644--- a/moli-renderer-v8/src/script_vm/tests/canvas_webgl.rs+++ b/moli-renderer-v8/src/script_vm/tests/canvas_webgl.rs@@ -2929,6 +2929,299 @@ async fn html_image_report_only_csp_reports_without_blocking_load() {);}+const IMAGE_CSP_CROSS_REALM_PROBE: &str = r#"+(() => {+ const root = top;+ const frame = root.__imageCspFrame;+ const events = root.__imageCspEvents;+ root.document.addEventListener('securitypolicyviolation', event => {+ events.push(`parent-csp:${event.disposition}:${event.effectiveDirective}`);+ });+ frame.contentWindow.addEventListener('securitypolicyviolation', event => {+ events.push(`child-csp:${event.disposition}:${event.effectiveDirective}`);+ });+ for (const [label, owner] of [['child', frame.contentDocument], ['parent', root.document]]) {+ const image = owner.createElement('img');+ image.onload = () => { events.push(`${label}:load`); ++root.__imageCspTerminalCount; };+ image.onerror = () => { events.push(`${label}:error`); ++root.__imageCspTerminalCount; };+ image.src = root.__imageCspSource ?? '/asset.png';+ owner.body.appendChild(image);+ if (root.__imageCspProbeDecode) {+ image.decode().then(+ () => events.push(`${label}:decode:resolve`),+ error => events.push(`${label}:decode:${error.name}`)+ );+ }+ }+})()+"#;++#[tokio::test]+async fn html_image_csp_uses_owner_document_across_realms() {+ for from_child in [false, true] {+ for bypass in [false, true] {+ let loader =+ ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");+ let mut vm = new_storage_page_task_executor_test_vm_with_loader(+ "https://image-csp-owner.test/page.html",+ &loader,+ );+ vm.set_bypass_content_security_policy(bypass);+ vm.eval(+ r#"+globalThis.__imageCspEvents = [];+globalThis.__imageCspTerminalCount = 0;+globalThis.__imageCspFrameLoaded = false;+globalThis.__imageCspFrame = document.createElement('iframe');+__imageCspFrame.onload = () => { __imageCspFrameLoaded = true; };+__imageCspFrame.srcdoc = '<!doctype html><meta http-equiv="Content-Security-Policy" content="img-src \'none\'"><body>';+document.body.appendChild(__imageCspFrame);+"#,+ )+ .expect("image CSP child fixture should evaluate");+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(__imageCspFrameLoaded)",+ "true",+ "the child policy must be committed before selecting image requests",+ )+ .await;+ let source = if from_child {+ format!("__imageCspFrame.contentWindow.eval({IMAGE_CSP_CROSS_REALM_PROBE:?})")+ } else {+ IMAGE_CSP_CROSS_REALM_PROBE.to_owned()+ };+ vm.eval(&source)+ .expect("cross-realm image probe should evaluate");+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(__imageCspTerminalCount)",+ "2",+ "both owner-bound image requests must finish",+ )+ .await;+ vm.drain_ready_page_task_executor_turns_for_setup(&loader, 32)+ .await+ .expect("image CSP reports should drain");+ drain_pre_domcontentloaded_non_script_page_tasks_for_test(&mut vm);+ assert_eq!(+ vm.eval("__imageCspEvents.slice().sort().join('|')")+ .expect("cross-realm image results should evaluate"),+ if bypass {+ "child:load|parent:load"+ } else {+ "child-csp:enforce:img-src|child:error|parent:load"+ },+ "image ownership must select both policy and report recipient; from_child={from_child}, bypass={bypass}"+ );+ }+ }+}++#[tokio::test]+async fn html_image_csp_rechecks_shared_ready_resource_before_reuse() {+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");+ let mut vm = new_storage_page_task_executor_test_vm_with_loader(+ "https://image-csp-cache.test/page.html",+ &loader,+ );+ vm.eval(+ r#"+globalThis.__imageCspEvents = [];+globalThis.__imageCspTerminalCount = 0;+globalThis.__imageCspFrameLoaded = false;+globalThis.__imageCspSource = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';+globalThis.__imageCspWarmLoaded = false;+globalThis.__imageCspWarm = new Image();+__imageCspWarm.onload = () => { __imageCspWarmLoaded = true; };+__imageCspWarm.src = __imageCspSource;+document.body.appendChild(__imageCspWarm);+globalThis.__imageCspFrame = document.createElement('iframe');+__imageCspFrame.onload = () => { __imageCspFrameLoaded = true; };+__imageCspFrame.srcdoc = '<!doctype html><meta http-equiv="Content-Security-Policy" content="img-src \'none\'"><body>';+document.body.appendChild(__imageCspFrame);+"#,+ )+ .expect("shared image cache fixture should evaluate");+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(__imageCspWarmLoaded && __imageCspFrameLoaded)",+ "true",+ "the ready image and child policy must exist before cache reuse",+ )+ .await;+ assert_eq!(+ vm.eval("String(__imageCspWarm.naturalWidth)")+ .expect("the cache must contain a real available image"),+ "1"+ );+ vm.eval(+ r#"+globalThis.__imageCspProbeDecode = true;+const meta = document.createElement('meta');+meta.httpEquiv = 'Content-Security-Policy';+meta.content = "img-src 'none'";+document.head.appendChild(meta);+"#,+ )+ .expect("a later main-document policy should apply to new requests");+ vm.eval(IMAGE_CSP_CROSS_REALM_PROBE)+ .expect("both documents should attempt the cached URL");+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(__imageCspTerminalCount)",+ "2",+ "blocked cache reuse must settle both image requests",+ )+ .await;+ vm.drain_ready_page_task_executor_turns_for_setup(&loader, 32)+ .await+ .expect("cached image policy reports should drain");+ drain_pre_domcontentloaded_non_script_page_tasks_for_test(&mut vm);+ assert_eq!(+ vm.eval("__imageCspEvents.slice().sort().join('|')")+ .expect("cached image policy results should evaluate"),+ "child-csp:enforce:img-src|child:decode:EncodingError|child:error|parent-csp:enforce:img-src|parent:decode:EncodingError|parent:error"+ );+ assert_eq!(+ vm.eval("String(__imageCspWarm.naturalWidth)")+ .expect("the previously loaded resource should remain available"),+ "1"+ );+}++#[tokio::test]+async fn html_image_csp_report_only_uses_child_owner_without_blocking() {+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");+ let mut vm = new_storage_page_task_executor_test_vm_with_loader(+ "https://image-csp-child-report.test/page.html",+ &loader,+ );+ vm.set_response_content_security_report_only_policies(&["img-src 'none'".to_owned()]);+ vm.eval(+ r#"+globalThis.__imageCspEvents = [];+globalThis.__imageCspFrameLoaded = false;+globalThis.__imageCspFrame = document.createElement('iframe');+__imageCspFrame.onload = () => { __imageCspFrameLoaded = true; };+__imageCspFrame.srcdoc = '<!doctype html><body>';+document.body.appendChild(__imageCspFrame);+"#,+ )+ .expect("report-only child fixture should evaluate");+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(__imageCspFrameLoaded)",+ "true",+ "the child must inherit the report-only policy before loading an image",+ )+ .await;+ vm.eval(+ r#"+document.addEventListener('securitypolicyviolation', () => __imageCspEvents.push('parent-csp'));+__imageCspFrame.contentWindow.addEventListener('securitypolicyviolation', event => {+ __imageCspEvents.push(`child-csp:${event.disposition}:${event.effectiveDirective}`);+});+const image = __imageCspFrame.contentDocument.createElement('img');+image.onload = () => __imageCspEvents.push('load');+image.onerror = () => __imageCspEvents.push('error');+image.src = '/asset.png';+__imageCspFrame.contentDocument.body.appendChild(image);+"#,+ )+ .expect("report-only child image probe should evaluate");+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(__imageCspEvents.includes('load'))",+ "true",+ "report-only CSP must not block the child image",+ )+ .await;+ vm.drain_ready_page_task_executor_turns_for_setup(&loader, 32)+ .await+ .expect("child report-only image reports should drain");+ drain_pre_domcontentloaded_non_script_page_tasks_for_test(&mut vm);+ assert_eq!(+ vm.eval("__imageCspEvents.slice().sort().join('|')")+ .expect("child report-only image results should evaluate"),+ "child-csp:report:img-src|load",+ "the initiating parent realm must not receive the child's violation"+ );+}++#[tokio::test]+async fn html_image_csp_does_not_apply_parent_policy_to_navigated_child() {+ let (child_url, request_rx, release_tx, server) =+ spawn_gated_image_csp_child_document_server().await;+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");+ let mut vm = new_storage_page_task_executor_test_vm_with_loader(+ &child_url.replace("/child.html", "/page.html"),+ &loader,+ );+ vm.set_response_content_security_policies(&["img-src 'none'".to_owned()]);+ vm.eval(&format!(+ r#"+globalThis.__imageCspEvents = [];+globalThis.__imageCspTerminalCount = 0;+globalThis.__imageCspFrameLoaded = false;+globalThis.__imageCspFrame = document.createElement('iframe');+__imageCspFrame.onload = () => {{ __imageCspFrameLoaded = true; }};+__imageCspFrame.src = {child_url:?};+document.body.appendChild(__imageCspFrame);+"#,+ ))+ .expect("navigated child image CSP fixture should evaluate");+ run_page_realm_prerequisite_then_expected_child_frame_semantic_turn(+ &mut vm,+ &loader,+ ChildFrameSemanticTurnKind::NavigationCommit,+ "the child navigation must start its response request",+ )+ .await;+ let request = tokio::time::timeout(std::time::Duration::from_secs(2), request_rx)+ .await+ .expect("child response request should arrive")+ .expect("child response server should observe the request");+ assert!(request.starts_with("GET /child.html "));+ release_tx.send(()).expect("release child response");+ server.await.expect("child response server should finish");+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(__imageCspFrameLoaded)",+ "true",+ "the HTTP child must commit its own policy container",+ )+ .await;+ vm.eval(&format!(+ "__imageCspFrame.contentWindow.eval({IMAGE_CSP_CROSS_REALM_PROBE:?})"+ ))+ .expect("the child should be able to change both documents' images");+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(__imageCspTerminalCount)",+ "2",+ "both documents' image requests must finish",+ )+ .await;+ vm.drain_ready_page_task_executor_turns_for_setup(&loader, 32)+ .await+ .expect("parent image CSP reports should drain");+ drain_pre_domcontentloaded_non_script_page_tasks_for_test(&mut vm);+ assert_eq!(+ vm.eval("__imageCspEvents.slice().sort().join('|')")+ .expect("navigated child image results should evaluate"),+ "child:load|parent-csp:enforce:img-src|parent:error"+ );+}+#[tokio::test]async fn html_image_invalid_base_url_fails_before_csp_check() {let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");@@ -3903,3 +4196,56 @@ fn detached_html_image_src_does_not_synchronously_dispatch_load() {assert_eq!(result, "0");}++async fn spawn_gated_image_csp_child_document_server() -> (+ String,+ tokio::sync::oneshot::Receiver<String>,+ tokio::sync::oneshot::Sender<()>,+ tokio::task::JoinHandle<()>,+) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind gated child document resource server");+ let addr = listener+ .local_addr()+ .expect("gated child document resource server addr");+ let (request_tx, request_rx) = tokio::sync::oneshot::channel();+ let (release_tx, release_rx) = tokio::sync::oneshot::channel();+ let server = tokio::spawn(async move {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};++ let (mut stream, _) = listener+ .accept()+ .await+ .expect("accept gated child document resource request");+ let mut request = Vec::new();+ let mut buffer = [0_u8; 1024];+ loop {+ let read = stream+ .read(&mut buffer)+ .await+ .expect("read gated child document resource request");+ if read == 0 {+ break;+ }+ request.extend_from_slice(&buffer[..read]);+ if request.windows(4).any(|window| window == b"\r\n\r\n") {+ break;+ }+ }+ let _ = request_tx.send(String::from_utf8_lossy(&request).into_owned());+ let _ = release_rx.await;+ let body = "<!doctype html><p>child document</p>";+ let response = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );+ let _ = stream.write_all(response.as_bytes()).await;+ });+ (+ format!("http://{addr}/child.html"),+ request_rx,+ release_tx,+ server,+ )+}