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.
This commit is contained in:
ldm0
2026-11-24 14:41:42 +08:00
parent cb5bddd740
commit 4e73609d71
15 changed files with 351 additions and 13 deletions
+2
View File
@@ -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],
+26
View File
@@ -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,
+1
View File
@@ -9,6 +9,7 @@ pub enum ContentSecurityPolicyResourceKind {
DocumentImage,
DocumentManifest,
DocumentMedia,
DocumentObject,
DocumentPrefetch,
DocumentScriptElement,
DocumentStyleElement,
@@ -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,
}
}
}
@@ -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,
);
@@ -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 {
@@ -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;
@@ -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<ChildFrameOwnerElementKind> {
@@ -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<Url> {
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")
@@ -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<String>,
}
/// 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<EmbeddedContentRequest> {
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)
})
}
}
@@ -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<DomHandle>) {
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
@@ -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(),
@@ -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<DomHandle, ChildBrowsingContextBootstrap>,
embedded_content_csp_admissions: HashMap<DomHandle, child_frames::EmbeddedContentCspAdmission>,
frame_owner_store: FrameOwnerStore,
inert_document_execution_contexts:
Option<Box<document_execution_context::InertDocumentExecutionContexts>>,
@@ -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<DocumentContentSecurityPolicyViolation> {
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<DocumentContentSecurityPolicyViolation> {
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,
@@ -1,5 +1,6 @@
use super::*;
mod embedded_content;
mod iframe_navigation;
mod inline_tasks;
mod parser_positions;
@@ -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,<p>document</p>');
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,<p>original</p>';
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,<p>replacement</p>';
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}"
);
}
}