From 4e73609d71138af2fa8cb10ebb305a34f46043bb Mon Sep 17 00:00:00 2001 From: ldm0 Date: Sun, 15 Nov 2026 17:42:07 +0800 Subject: [PATCH] fix(csp): enforce object-src during embedded resource selection Check object and embed URLs against object-src before MIME-based child navigable selection, including image resources. Use the resource element's Document policy and queue violations through its native owner task lane. Retain admission for one resource selection to avoid duplicate reports and retroactive meta-policy checks. Source/type changes and reinsertion create new admissions; later script navigations still check their current policy. Cover directive fallback, frame/popup ownership, report-only policies, resource reselection, positive object sources, and the existing CDP bypass. --- moli-csp/src/checks.rs | 2 + moli-csp/src/tests.rs | 26 ++++ moli-csp/src/types.rs | 1 + .../src/document_runtime/security_policy.rs | 2 + .../child_documents/bootstrap_commit.rs | 6 +- .../context_host/child_documents/loads.rs | 5 +- .../context_host/child_frames.rs | 2 + .../context_host/child_frames/discovery.rs | 32 ++++- .../context_host/child_frames/embedded_csp.rs | 95 +++++++++++++ .../context_host/child_frames/registry.rs | 3 + .../src/native_bridge/context_host/core.rs | 1 + .../src/native_bridge/context_host/mod.rs | 1 + .../context_host/security_policy.rs | 58 +++++++- .../tests/browser_api/security_policy.rs | 1 + .../security_policy/embedded_content.rs | 129 ++++++++++++++++++ 15 files changed, 351 insertions(+), 13 deletions(-) create mode 100644 moli-renderer-v8/src/native_bridge/context_host/child_frames/embedded_csp.rs create mode 100644 moli-renderer-v8/src/script_vm/tests/browser_api/security_policy/embedded_content.rs diff --git a/moli-csp/src/checks.rs b/moli-csp/src/checks.rs index c0a738a16ec..e8484e8db17 100644 --- a/moli-csp/src/checks.rs +++ b/moli-csp/src/checks.rs @@ -1422,6 +1422,7 @@ impl ContentSecurityPolicyResourceKind { Self::DocumentImage => IMG_SRC, Self::DocumentManifest => MANIFEST_SRC, Self::DocumentMedia => MEDIA_SRC, + Self::DocumentObject => OBJECT_SRC, Self::DocumentPrefetch => DEFAULT_SRC, Self::DocumentScriptElement | Self::WorkerDynamicModuleImport | Self::WorkerScript => { SCRIPT_SRC_ELEM @@ -1441,6 +1442,7 @@ impl ContentSecurityPolicyResourceKind { Self::DocumentImage => &[IMG_SRC, DEFAULT_SRC], Self::DocumentManifest => &[MANIFEST_SRC, DEFAULT_SRC], Self::DocumentMedia => &[MEDIA_SRC, DEFAULT_SRC], + Self::DocumentObject => &[OBJECT_SRC, DEFAULT_SRC], Self::DocumentPrefetch => &[DEFAULT_SRC], Self::DocumentScriptElement => &[SCRIPT_SRC_ELEM, SCRIPT_SRC, DEFAULT_SRC], Self::DocumentStyleElement => &[STYLE_SRC_ELEM, STYLE_SRC, DEFAULT_SRC], diff --git a/moli-csp/src/tests.rs b/moli-csp/src/tests.rs index 97f8461f23f..55ff969bf17 100644 --- a/moli-csp/src/tests.rs +++ b/moli-csp/src/tests.rs @@ -13,6 +13,31 @@ fn request_url(raw: &str) -> Url { Url::parse(raw).unwrap() } +#[test] +fn object_requests_use_object_src_and_default_src_without_frame_or_image_fallbacks() { + let kind = ContentSecurityPolicyResourceKind::DocumentObject; + for (policy, expected) in [ + ("object-src 'self'; frame-src 'none'; img-src 'none'", true), + ("object-src 'none'; frame-src *; img-src *", false), + ("default-src 'none'; frame-src *; img-src *", false), + ("default-src 'none'; object-src 'self'", true), + ("child-src 'none'; frame-src 'none'; img-src 'none'", true), + ] { + let policy = ContentSecurityPolicy::from(policy); + let violation = content_security_policy_url_violation_with_redirect_status( + &[policy], + &protected_url(), + &request_url("https://app.test/object.html"), + kind, + ContentSecurityPolicyRedirectStatus::NoRedirect, + ); + assert_eq!(violation.is_none(), expected); + if let Some(violation) = violation { + assert_eq!(violation.effective_directive, "object-src"); + } + } +} + #[test] fn inherited_policy_self_origin_is_independent_of_document_url() { let policy = @@ -1684,6 +1709,7 @@ fn exact_host_port_wildcards_apply_across_resource_kinds() { ContentSecurityPolicyResourceKind::DocumentImage, ContentSecurityPolicyResourceKind::DocumentManifest, ContentSecurityPolicyResourceKind::DocumentMedia, + ContentSecurityPolicyResourceKind::DocumentObject, ContentSecurityPolicyResourceKind::DocumentScriptElement, ContentSecurityPolicyResourceKind::DocumentStyleElement, ContentSecurityPolicyResourceKind::WorkerConnect, diff --git a/moli-csp/src/types.rs b/moli-csp/src/types.rs index a394a4f6117..23346a8ec8f 100644 --- a/moli-csp/src/types.rs +++ b/moli-csp/src/types.rs @@ -9,6 +9,7 @@ pub enum ContentSecurityPolicyResourceKind { DocumentImage, DocumentManifest, DocumentMedia, + DocumentObject, DocumentPrefetch, DocumentScriptElement, DocumentStyleElement, diff --git a/moli-renderer-v8/src/document_runtime/security_policy.rs b/moli-renderer-v8/src/document_runtime/security_policy.rs index 7dfd0640e5c..9942ee9a32c 100644 --- a/moli-renderer-v8/src/document_runtime/security_policy.rs +++ b/moli-renderer-v8/src/document_runtime/security_policy.rs @@ -58,6 +58,7 @@ pub(crate) enum DocumentSubresourceCspKind { Image, Manifest, Media, + Object, } impl DocumentSubresourceCspKind { @@ -66,6 +67,7 @@ impl DocumentSubresourceCspKind { Self::Image => ContentSecurityPolicyResourceKind::DocumentImage, Self::Manifest => ContentSecurityPolicyResourceKind::DocumentManifest, Self::Media => ContentSecurityPolicyResourceKind::DocumentMedia, + Self::Object => ContentSecurityPolicyResourceKind::DocumentObject, } } } diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/bootstrap_commit.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/bootstrap_commit.rs index 2bc777740de..ede6e724a74 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/bootstrap_commit.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/bootstrap_commit.rs @@ -54,13 +54,15 @@ impl PageScriptHost { let mut creation_kind = child_document_creation_kind_for_bootstrap(&bootstrap); if let Some(request_url) = child_document_frame_csp_request_url(&bootstrap) { if let Some(violation) = - self.frame_navigation_csp_report_only_violation(handle, request_url) + self.frame_navigation_csp_report_only_violation(handle, request_url, initiator) { self.dispatch_frame_navigation_csp_violation_event_best_effort( scope, handle, &violation, ); } - if let Some(violation) = self.frame_navigation_csp_violation(handle, request_url) { + if let Some(violation) = + self.frame_navigation_csp_violation(handle, request_url, initiator) + { self.dispatch_frame_navigation_csp_violation_event_best_effort( scope, handle, &violation, ); diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/loads.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/loads.rs index 88491921fc0..3456117b85c 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/loads.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/loads.rs @@ -636,7 +636,10 @@ impl PageScriptHost { true, ) } - Ok(redirect @ ChildDocumentLoadOutcome::Redirect(_)) => (Ok(redirect), false), + Ok( + outcome @ (ChildDocumentLoadOutcome::Redirect(_) + | ChildDocumentLoadOutcome::Download(_)), + ) => (Ok(outcome), false), Err(error) => (Err(error), true), } } else { diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs index 2b571c5c166..854914a8b5c 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs @@ -31,6 +31,7 @@ use url::Url; mod classic_scripts; mod discovery; +mod embedded_csp; mod local_history; mod lookup; mod module_scripts; @@ -39,6 +40,7 @@ mod registry; mod request_scope; mod stylesheets; mod target_snapshot; +pub(in crate::native_bridge::context_host) use embedded_csp::EmbeddedContentCspAdmission; pub(in crate::native_bridge::context_host) use target_snapshot::ChildNavigationTargetSnapshot; pub(in crate::native_bridge::context_host) use classic_scripts::ChildParserClassicScriptCandidate; diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/discovery.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/discovery.rs index 0e5adec82ba..a6190a39cca 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/discovery.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/discovery.rs @@ -8,7 +8,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; static NEXT_CHILD_BROWSING_CONTEXT_ID: AtomicU64 = AtomicU64::new(1); #[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum ChildFrameOwnerElementKind { +pub(super) enum ChildFrameOwnerElementKind { Iframe, Frame, Embed, @@ -16,7 +16,7 @@ enum ChildFrameOwnerElementKind { } impl ChildFrameOwnerElementKind { - fn navigation_attribute(self) -> &'static str { + pub(super) fn navigation_attribute(self) -> &'static str { match self { Self::Iframe | Self::Frame | Self::Embed => "src", Self::Object => "data", @@ -152,7 +152,7 @@ impl PageScriptHost { self.child_frame_owner_element_kind(handle) == Some(ChildFrameOwnerElementKind::Object) } - fn child_frame_owner_element_kind( + pub(super) fn child_frame_owner_element_kind( &self, handle: DomHandle, ) -> Option { @@ -207,6 +207,13 @@ impl PageScriptHost { handle: DomHandle, attribute_name: &str, ) { + if matches!( + self.child_frame_owner_element_kind(handle), + Some(ChildFrameOwnerElementKind::Object | ChildFrameOwnerElementKind::Embed) + ) && matches!(attribute_name, "data" | "src" | "type") + { + self.embedded_content_csp_admissions.remove(&handle); + } if self.child_browsing_context_host_is_object_element(handle) && ["data", "type"] .into_iter() @@ -277,10 +284,18 @@ impl PageScriptHost { .unwrap_or_else(|_| Url::parse("about:blank").expect("static about:blank should parse")) } - fn resolve_child_frame_owner_attribute_url(&self, handle: DomHandle, raw: &str) -> Url { + pub(super) fn parse_child_frame_owner_attribute_url( + &self, + handle: DomHandle, + raw: &str, + ) -> Option { let base = self.document_base_url_for_child_context(handle); - parse_url_with_document_query_encoding(self, handle, &base, raw) - .unwrap_or_else(|_| Url::parse("about:blank").expect("static about:blank should parse")) + parse_url_with_document_query_encoding(self, handle, &base, raw).ok() + } + + fn resolve_child_frame_owner_attribute_url(&self, handle: DomHandle, raw: &str) -> Url { + self.parse_child_frame_owner_attribute_url(handle, raw) + .unwrap_or_else(|| Url::parse("about:blank").expect("static about:blank should parse")) } pub(in crate::native_bridge::context_host) fn child_browsing_context_bootstrap_for_handle( @@ -291,6 +306,9 @@ impl PageScriptHost { if !self.child_browsing_context_host_is_active(handle) { return None; } + if self.embedded_content_request_is_csp_blocked(handle) { + return None; + } let owner_dispatch_scope = self .owner_dispatch_scope_for_node(handle) .unwrap_or(crate::native_bridge::OwnerDispatchScope::Top); @@ -340,7 +358,7 @@ impl PageScriptHost { Some(bootstrap) } - fn embedded_content_is_inside_media_element(&self, handle: DomHandle) -> bool { + pub(super) fn embedded_content_is_inside_media_element(&self, handle: DomHandle) -> bool { let mut current = self.dom_host().parent_node(handle); while let Some(ancestor) = current { if self.dom_host().is_html_element_named(ancestor, "audio") diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/embedded_csp.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/embedded_csp.rs new file mode 100644 index 00000000000..48dce2f9a2d --- /dev/null +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/embedded_csp.rs @@ -0,0 +1,95 @@ +use super::super::PageScriptHost; +use super::discovery::ChildFrameOwnerElementKind; +use crate::document_runtime::{DocumentSubresourceCspKind, DomHandle}; +use url::Url; + +#[derive(Debug, PartialEq, Eq)] +struct EmbeddedContentRequest { + document: DomHandle, + url: Url, + type_hint: Option, +} + +/// One resource-selection attempt, including image resources which do not +/// create a child navigable. Wrapper discovery must not repeat its CSP reports +/// or apply a later meta policy to an already admitted request. +pub(in crate::native_bridge::context_host) struct EmbeddedContentCspAdmission { + request: EmbeddedContentRequest, + allowed: bool, +} + +impl PageScriptHost { + fn embedded_content_csp_request(&self, handle: DomHandle) -> Option { + let kind = self.child_frame_owner_element_kind(handle)?; + if !matches!( + kind, + ChildFrameOwnerElementKind::Object | ChildFrameOwnerElementKind::Embed + ) || !self.child_browsing_context_host_is_active(handle) + || self.embedded_content_is_inside_media_element(handle) + { + return None; + } + let source = self + .dom_host() + .get_attribute(handle, kind.navigation_attribute())?; + if source.trim().is_empty() { + return None; + } + Some(EmbeddedContentRequest { + document: self.dom_host().owner_document_handle(handle)?, + url: self.parse_child_frame_owner_attribute_url(handle, source.trim())?, + type_hint: self.dom_host().get_attribute(handle, "type"), + }) + } + + pub(super) fn refresh_embedded_content_csp_admission( + &mut self, + scope: &mut v8::PinScope<'_, '_>, + handle: DomHandle, + ) { + let Some(request) = self.embedded_content_csp_request(handle) else { + self.embedded_content_csp_admissions.remove(&handle); + return; + }; + if let Some(admission) = self.embedded_content_csp_admissions.get(&handle) + && admission.request == request + { + return; + } + let allowed = self.bypass_content_security_policy() + || !self + .check_element_subresource_csp( + scope, + handle, + &request.url, + DocumentSubresourceCspKind::Object, + ) + .blocks_request(); + self.embedded_content_csp_admissions + .insert(handle, EmbeddedContentCspAdmission { request, allowed }); + } + + pub(super) fn embedded_content_request_is_csp_blocked(&self, handle: DomHandle) -> bool { + self.embedded_content_csp_admissions + .get(&handle) + .is_some_and(|admission| { + !admission.allowed + && self.embedded_content_csp_request(handle).as_ref() + == Some(&admission.request) + }) + } + + pub(in crate::native_bridge::context_host) fn embedded_content_request_was_csp_checked( + &self, + handle: DomHandle, + url: &Url, + ) -> bool { + self.embedded_content_csp_admissions + .get(&handle) + .is_some_and(|admission| { + admission.request.url == *url + && self.embedded_content_csp_request(handle).as_ref() + == Some(&admission.request) + }) + } +} diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs index 4dad8e13a4b..50aae938ba1 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs @@ -178,6 +178,7 @@ impl PageScriptHost { { Self::drop_child_browsing_context_subtree_with_window_realm(scope, self, handle); } + self.refresh_embedded_content_csp_admission(scope, handle); match self.child_browsing_context_bootstrap_for_handle(handle) { Some(attribute_bootstrap) => { self.object_fallback_bootstraps.remove(&handle); @@ -950,6 +951,7 @@ impl PageScriptHost { // Mark the whole batch before the first callback: a handler for A // can reattach B before B reaches its own cancellation boundary. for handle in handles { + host.embedded_content_csp_admissions.remove(&handle); let Some(entry) = host.child_browsing_contexts.get_mut(&handle) else { continue; }; @@ -1067,6 +1069,7 @@ impl PageScriptHost { fn drop_child_browsing_context_handles(&mut self, handles: Vec) { for handle in handles { self.object_fallback_bootstraps.remove(&handle); + self.embedded_content_csp_admissions.remove(&handle); let document_handle_before_drop = self.child_browsing_context_document_handle(handle); let frame_id = self .child_browsing_contexts diff --git a/moli-renderer-v8/src/native_bridge/context_host/core.rs b/moli-renderer-v8/src/native_bridge/context_host/core.rs index f25e17a5213..70354e3e73a 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/core.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs @@ -441,6 +441,7 @@ impl PageScriptHost { observers: ObserverStore::default(), child_browsing_contexts: IndexMap::new(), object_fallback_bootstraps: HashMap::new(), + embedded_content_csp_admissions: HashMap::new(), frame_owner_store, inert_document_execution_contexts: None, frame_parser_classic_scripts: FrameParserClassicScriptRunnerStore::default(), diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rs index 9364485c739..c5f6a12fa69 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs @@ -993,6 +993,7 @@ pub(crate) struct PageScriptHost { // resource selection is invalidated; ordinary context discovery must not // recreate its nested browsing context in the meantime. object_fallback_bootstraps: HashMap, + embedded_content_csp_admissions: HashMap, frame_owner_store: FrameOwnerStore, inert_document_execution_contexts: Option>, 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.rs index 73b954a03ae..88611ccc36d 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 @@ -1,4 +1,6 @@ -use super::{OwnerDispatchScope, PageScriptHost}; +use super::{ + OwnerDispatchScope, PageScriptHost, child_documents::ChildDocumentNavigationInitiator, +}; use crate::network_host::controlled_resource::{ControlledXhrContext, XhrInterceptionRoute}; use crate::types::SubresourceResourceType; use crate::{ @@ -1425,13 +1427,38 @@ impl PageScriptHost { .unwrap_or(true) } - pub(crate) fn frame_navigation_csp_violation( + pub(in crate::native_bridge::context_host) fn frame_navigation_csp_violation( &self, frame_handle: DomHandle, request_url: &url::Url, + initiator: ChildDocumentNavigationInitiator, ) -> Option { let owner = self.owner_dispatch_scope_for_node(frame_handle)?; let snapshot = self.owner_document_policy_snapshot(owner)?; + if self + .dom_host() + .is_html_element_named(frame_handle, "object") + || self.dom_host().is_html_element_named(frame_handle, "embed") + { + if self.bypass_content_security_policy() + || (initiator == ChildDocumentNavigationInitiator::FrameOwnerElement + && self.embedded_content_request_was_csp_checked(frame_handle, request_url)) + { + return None; + } + return unsafe { &*self.document_runtime } + .document_subresource_csp_check_for_document( + snapshot.document_handle, + &snapshot.document_url, + &snapshot.policy_container, + request_url, + DocumentSubresourceCspKind::Object, + ) + .into_violations() + .1 + .into_iter() + .next(); + } // SAFETY: PageScriptHost is owned by the ScriptVm that owns this DocumentRuntime. unsafe { &*self.document_runtime }.document_frame_csp_violation_for_document( snapshot.document_handle, @@ -1444,13 +1471,38 @@ impl PageScriptHost { ) } - pub(crate) fn frame_navigation_csp_report_only_violation( + pub(in crate::native_bridge::context_host) fn frame_navigation_csp_report_only_violation( &self, frame_handle: DomHandle, request_url: &url::Url, + initiator: ChildDocumentNavigationInitiator, ) -> Option { let owner = self.owner_dispatch_scope_for_node(frame_handle)?; let snapshot = self.owner_document_policy_snapshot(owner)?; + if self + .dom_host() + .is_html_element_named(frame_handle, "object") + || self.dom_host().is_html_element_named(frame_handle, "embed") + { + if self.bypass_content_security_policy() + || (initiator == ChildDocumentNavigationInitiator::FrameOwnerElement + && self.embedded_content_request_was_csp_checked(frame_handle, request_url)) + { + return None; + } + return unsafe { &*self.document_runtime } + .document_subresource_csp_check_for_document( + snapshot.document_handle, + &snapshot.document_url, + &snapshot.policy_container, + request_url, + DocumentSubresourceCspKind::Object, + ) + .into_violations() + .0 + .into_iter() + .next(); + } // SAFETY: PageScriptHost is owned by the ScriptVm that owns this DocumentRuntime. unsafe { &*self.document_runtime }.document_frame_csp_report_only_violation_for_document( &snapshot.document_url, diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy.rs index 35947f20b88..41c132b65a4 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy.rs @@ -1,5 +1,6 @@ use super::*; +mod embedded_content; mod iframe_navigation; mod inline_tasks; mod parser_positions; diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy/embedded_content.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy/embedded_content.rs new file mode 100644 index 00000000000..7eab71af41a --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy/embedded_content.rs @@ -0,0 +1,129 @@ +use super::*; + +#[tokio::test] +async fn embedded_object_csp_uses_resource_document_before_mime_selection() { + for (owner, report_only) in [ + ("window", false), + ("frame.contentWindow", false), + ("popup", false), + ("window", true), + ] { + let mut vm = new_storage_page_task_executor_test_vm("https://object-policy.test/"); + if report_only { + vm.set_response_content_security_report_only_policies( + &["object-src 'none'".to_owned()], + ); + } + vm.eval(&format!(r#" + const frame = document.createElement('iframe'); document.body.appendChild(frame); + const popup = open(); const owner = {owner}; const doc = owner.document; + globalThis.objectReports = []; + doc.addEventListener('securitypolicyviolation', event => objectReports.push({{ + directive: event.effectiveDirective, + disposition: event.disposition, + targetIsDocument: event.target === doc, + documentURI: event.documentURI + }})); + if (!{report_only}) {{ + const meta = doc.createElement('meta'); + meta.httpEquiv = 'Content-Security-Policy'; + meta.content = "object-src 'none'; frame-src *; img-src *"; + doc.head.appendChild(meta); + }} + globalThis.objects = ['object', 'embed', 'object'].map((name, index) => {{ + const element = doc.createElement(name); + if (index < 2) element.type = 'image/png'; + element.setAttribute(name === 'object' ? 'data' : 'src', + index < 2 ? 'https://object-policy.test/image.png' : 'data:text/html,

document

'); + doc.body.appendChild(element); + // Discovery and named-property updates keep the same request. + for (let i = 0; i < 3; ++i) {{ element.id = 'object-' + index + '-' + i; void element.contentDocument; }} + return element; + }}); + globalThis.immediateObjectReports = objectReports.length; + "#)).unwrap(); + assert_eq!(vm.eval("String(immediateObjectReports)").unwrap(), "0"); + inline_tasks::drain_inline_csp_page_tasks_for_test(&mut vm).await; + let reports: serde_json::Value = + serde_json::from_str(&vm.eval("JSON.stringify(objectReports)").unwrap()).unwrap(); + assert_eq!( + reports.as_array().unwrap().len(), + 3, + "{owner}/{report_only}: {reports}" + ); + for report in reports.as_array().unwrap() { + assert_eq!(report["directive"], "object-src"); + assert_eq!( + report["disposition"], + if report_only { "report" } else { "enforce" } + ); + assert_eq!( + report["targetIsDocument"], true, + "{owner}/{report_only}: {report}" + ); + } + if !report_only { + assert_eq!( + vm.eval("objects[2].contentDocument === null").unwrap(), + "true" + ); + } + vm.eval("popup.close(); frame.remove()").unwrap(); + } +} + +#[tokio::test] +async fn embedded_object_csp_keeps_admission_until_resource_selection_changes() { + let mut vm = new_storage_page_task_executor_test_vm("https://object-policy-admission.test/"); + vm.eval(r#" + globalThis.reports = []; + document.addEventListener('securitypolicyviolation', event => reports.push(event.effectiveDirective)); + const object = document.createElement('object'); + object.data = 'data:text/html,

original

'; + document.body.appendChild(object); + globalThis.originalDocument = object.contentDocument; + const meta = document.createElement('meta'); + meta.httpEquiv = 'Content-Security-Policy'; + meta.content = "object-src 'none'"; + document.head.appendChild(meta); + object.id = 'same-resource'; + globalThis.existingResourceRetained = object.contentDocument === originalDocument; + object.data = 'data:text/html,

replacement

'; + globalThis.replacementBlocked = object.contentDocument === null; + for (let i = 0; i < 3; ++i) {object.id = 'still-blocked-' + i; void object.contentDocument;} + object.remove(); document.body.appendChild(object); + globalThis.reinsertedResourceBlocked = object.contentDocument === null; + "#).unwrap(); + assert_eq!(vm.eval("JSON.stringify([originalDocument !== null, existingResourceRetained, replacementBlocked, reinsertedResourceBlocked])").unwrap(), "[true,true,true,true]"); + inline_tasks::drain_inline_csp_page_tasks_for_test(&mut vm).await; + assert_eq!( + vm.eval("JSON.stringify(reports)").unwrap(), + r#"["object-src","object-src"]"# + ); +} + +#[tokio::test] +async fn embedded_object_csp_allows_object_sources_independently_of_frame_sources_and_bypass() { + for (policy, bypass) in [ + ("object-src about:; frame-src 'none'", false), + ("object-src 'none'; frame-src 'none'", true), + ] { + let mut vm = new_storage_page_task_executor_test_vm("https://object-policy-allowed.test/"); + vm.set_response_content_security_policies(&[policy.to_owned()]); + vm.set_bypass_content_security_policy(bypass); + vm.eval(r#" + globalThis.reports = []; + document.addEventListener('securitypolicyviolation', event => reports.push(event.effectiveDirective)); + globalThis.object = document.createElement('object'); + object.data = 'about:blank#object'; + document.body.appendChild(object); + "#).unwrap(); + assert_eq!(vm.eval("object.contentDocument !== null").unwrap(), "true"); + inline_tasks::drain_inline_csp_page_tasks_for_test(&mut vm).await; + assert_eq!( + vm.eval("JSON.stringify(reports)").unwrap(), + "[]", + "{policy}/{bypass}" + ); + } +}