fix(dom): preserve windowless event policy and node ownership

This commit is contained in:
ldm0
2026-11-21 20:03:33 +08:00
parent 5c4a2239d6
commit ff148ae4b3
23 changed files with 718 additions and 46 deletions
+17
View File
@@ -470,6 +470,23 @@ impl NativeDom {
self.create_template_contents_fragment_for_document(self.document_node_id, Some(host))
}
pub fn is_inert_template_document(&self, document_handle: NativeNodeId) -> bool {
self.node(document_handle)
.and_then(Node::as_document)
.is_some_and(Document::is_inert_template_document)
}
/// Template contents keep their original creator's realm policy.
pub fn inert_template_document_creator(
&self,
document_handle: NativeNodeId,
) -> Option<NativeNodeId> {
self.nodes().find_map(|node| {
(node.as_document()?.associated_inert_template_document() == Some(document_handle))
.then_some(node.id())
})
}
pub fn create_template_contents_fragment_for_document(
&mut self,
document_handle: NativeNodeId,
@@ -10,3 +10,40 @@ async fn windowless_documents_adopt_native_nodes_across_real_pages() {
)
.await;
}
#[tokio::test(flavor = "multi_thread")]
async fn windowless_handlers_preserve_native_state_across_real_pages() {
assert_page_fixture(
include_str!(
"../../../../../moli-renderer-v8/tests/fixtures/windowless-cross-page-handlers.js"
),
208,
)
.await;
}
#[tokio::test(flavor = "multi_thread")]
async fn windowless_attributes_follow_the_native_owner_across_real_pages() {
assert_page_fixture(
include_str!(
"../../../../../moli-renderer-v8/tests/fixtures/windowless-cross-page-attributes.js"
),
80,
)
.await;
}
#[tokio::test(flavor = "multi_thread")]
async fn windowless_handler_policy_survives_real_popup_retirement() {
let fixture = include_str!(
"../../../../../moli-renderer-v8/tests/fixtures/windowless-handler-csp-retirement.js"
);
assert_page_fixture(
&format!(
"const passed = {fixture}; globalThis.__uiEventResults = \
{{total:1, passed:passed ? 1 : 0, checks:[{{name:'retained global policy',passed}}]}};"
),
1,
)
.await;
}
@@ -588,6 +588,15 @@ impl DocumentRuntime {
.document_character_set_for_handle(handle)
.map(str::to_owned);
let clone = self.dom_host.clone_node(handle, deep)?;
if self.dom_host.node(clone).is_some_and(Node::is_document) {
let host = unsafe { &mut *host_ptr };
let context = host
.native_bridge()
.cached_handle_wrapper(scope, handle)
.and_then(|document| document.get_creation_context(scope))
.unwrap_or_else(|| scope.get_current_context());
host.register_windowless_document_csp_context(clone, context);
}
if let Some(character_set) = character_set {
self.dom_host
.set_document_character_set_for_handle(clone, &character_set);
+6 -7
View File
@@ -15,7 +15,7 @@ use super::{
native_bridge::{
OwnerDispatchScope,
document::{
build_detached_document_object_from_dom_host,
DetachedDocumentBuildContext, build_detached_document_object_from_dom_host,
build_detached_document_object_from_dom_host_with_content_type,
},
},
@@ -394,8 +394,9 @@ pub(crate) fn parse_browsing_context_document_projection_from_source<'s>(
parsed,
content_type,
character_set,
true,
Some(inherited_meta_policies),
DetachedDocumentBuildContext::BrowsingContextProjection {
inherited_meta_policies,
},
)
}
@@ -466,8 +467,7 @@ fn build_detached_document_with_content_type<'s>(
DomHost::from_dom(parsed),
content_type,
None,
false,
None,
DetachedDocumentBuildContext::Windowless,
)
}
@@ -496,8 +496,7 @@ fn build_detached_document_from_dom_host_with_content_type<'s>(
parsed,
content_type,
character_set,
false,
None,
DetachedDocumentBuildContext::Windowless,
)
}
@@ -624,6 +624,7 @@ impl PageScriptHost {
command_turn_output: None,
runtime_binding_execution_context_owners: HashMap::new(),
window_execution_context_realms: Default::default(),
document_global_csp_contexts: Default::default(),
#[cfg(test)]
pending_runtime_binding_calls: Vec::new(),
next_runtime_observable_context_token: super::RuntimeObservableContextToken::first(),
@@ -1151,6 +1151,8 @@ pub(crate) struct PageScriptHost {
runtime_binding_execution_context_owners:
HashMap<RuntimeBindingExecutionContext, FrameDocumentTaskOwner>,
window_execution_context_realms: WindowExecutionContextRealmRecords,
document_global_csp_contexts:
RefCell<HashMap<DomHandle, std::rc::Rc<RefCell<security_policy::WindowGlobalCspContext>>>>,
#[cfg(test)]
pending_runtime_binding_calls: Vec<PendingRuntimeBindingCall>,
next_runtime_observable_context_token: RuntimeObservableContextToken,
@@ -1,7 +1,7 @@
use super::PageScriptHost;
use crate::{
custom_elements, document_runtime::DomHandle,
native_bridge::node_runtime_and_handle_from_object,
native_bridge::node_runtime_and_handle_from_object_or_detached,
};
impl PageScriptHost {
@@ -11,7 +11,7 @@ impl PageScriptHost {
document: DomHandle,
object: v8::Local<'_, v8::Object>,
) -> Option<DomHandle> {
let (source, root) = node_runtime_and_handle_from_object(scope, object).ok()?;
let (source, root) = node_runtime_and_handle_from_object_or_detached(scope, object).ok()?;
if source == target {
return Some(root);
}
@@ -30,7 +30,7 @@ impl PageScriptHost {
// Removal may synchronously run focus/resource cleanup. Resolve the
// original object again rather than trusting a pre-callback ID.
let (current_source, current_root) =
node_runtime_and_handle_from_object(scope, object).ok()?;
node_runtime_and_handle_from_object_or_detached(scope, object).ok()?;
if current_source != source || current_root != root {
return Self::adopt_node_from_host(scope, target, document, object);
}
@@ -40,6 +40,12 @@ struct OwnerDocumentPolicySnapshot {
policy_container: DocumentPolicyContainer,
}
#[derive(Clone)]
pub(super) struct WindowGlobalCspContext {
identity: super::WindowExecutionContextIdentity,
retained_policy: OwnerDocumentPolicySnapshot,
}
const JAVASCRIPT_URL_TRUSTED_TYPES_SINK: &str = "Location href";
fn security_origin_from_serialized(origin: &str) -> url::Origin {
@@ -116,6 +122,149 @@ impl PageScriptHost {
}))
}
/// Retain CSP settings as native data, without keeping the V8 realm alive.
/// Every Document in this global shares the record, including updates when
/// an initial empty Window receives its committed Document.
pub(crate) fn retain_window_global_csp_context(&self, context: v8::Local<'_, v8::Context>) {
let Some(identity) = self
.window_execution_context_identity_for_access_check(context)
.filter(|identity| self.window_execution_context_identity_is_current(*identity))
else {
return;
};
let Some(retained_policy) = self.owner_document_policy_snapshot(identity.dispatch_scope())
else {
return;
};
let document = retained_policy.document_handle;
let replacement = WindowGlobalCspContext {
identity,
retained_policy,
};
let record = match context.get_slot::<std::cell::RefCell<WindowGlobalCspContext>>() {
Some(record) if record.borrow().identity == identity => {
*record.borrow_mut() = replacement;
record
}
_ => {
let record = std::rc::Rc::new(std::cell::RefCell::new(replacement));
context.set_slot(record.clone());
record
}
};
if let Some(document) = document {
self.document_global_csp_contexts
.borrow_mut()
.insert(document, record);
}
}
/// Inline checks use the Document's relevant global, independently of the
/// calling realm, a synthetic defaultView, or a future adopter.
pub(crate) fn register_windowless_document_csp_context(
&mut self,
document: DomHandle,
context: v8::Local<'_, v8::Context>,
) {
self.retain_window_global_csp_context(context);
if let Some(record) = context.get_slot::<std::cell::RefCell<WindowGlobalCspContext>>() {
self.document_global_csp_contexts
.borrow_mut()
.insert(document, record);
}
}
pub(crate) fn windowless_inline_event_handler_csp_admission(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
element: DomHandle,
source: &str,
) -> Option<bool> {
let document = self.dom_host().owner_document_handle(element)?;
let mut context = self
.document_global_csp_contexts
.borrow()
.get(&document)
.cloned();
if context.is_none()
&& let Some(creator) = self
.dom_host()
.dom()
.inert_template_document_creator(document)
{
context = self
.document_global_csp_contexts
.borrow()
.get(&creator)
.cloned();
if context.is_none()
&& let Some(owner) = self.owner_dispatch_scope_for_node(creator)
&& let Some(identity) = self
.current_runtime_window_execution_context_identity_for_dispatch_scope(
scope, owner,
)
&& let Some(retained_policy) = self.owner_document_policy_snapshot(owner)
{
let record = std::rc::Rc::new(std::cell::RefCell::new(WindowGlobalCspContext {
identity,
retained_policy,
}));
self.document_global_csp_contexts
.borrow_mut()
.insert(creator, record.clone());
context = Some(record);
}
if let Some(context) = &context {
self.document_global_csp_contexts
.borrow_mut()
.insert(document, context.clone());
}
}
let context = context?.borrow().clone();
let mut snapshot = if self.window_execution_context_identity_is_current(context.identity) {
self.owner_document_policy_snapshot(context.identity.dispatch_scope())?
} else {
// Retained realms keep their outgoing settings and native meta
// policy delivery. Reusing an iframe cannot lend a new Window's CSP.
context.retained_policy
};
if !self.window_execution_context_identity_is_current(context.identity)
&& let Some(url) = snapshot
.document_handle
.and_then(|document| self.dom_host().document_url_for_handle(document))
{
snapshot.document_url = url.clone();
}
let check = unsafe { &*self.document_runtime }.inline_source_csp_check_for_document(
snapshot.document_handle,
&snapshot.document_url,
&snapshot.policy_container.response_content_security_policies,
&snapshot
.policy_container
.response_content_security_report_only_policies,
&snapshot
.policy_container
.content_security_reporting_endpoints,
ContentSecurityPolicyNonUrlKind::DocumentInlineEventHandler,
source,
);
let reporting_context = self
.window_execution_context_identity_for_access_check(scope.get_current_context())
.filter(|identity| self.window_execution_context_identity_is_current(*identity));
Some(match reporting_context {
Some(identity) => self.report_inline_csp_check(
scope,
identity.dispatch_scope(),
Some(element),
check,
None,
),
// An inactive global cannot dispatch a reporting task through a
// replacement Window, but enforce and report-only remain distinct.
None => check.into_violations().1.into_iter().next().is_none(),
})
}
pub(crate) fn document_allows_autofocus(&self, document: DomHandle) -> bool {
let Some(endpoint) = self.window_endpoint_for_document(document) else {
return false;
@@ -45,6 +45,7 @@ impl WindowEnvironmentSettings {
.child_document_domain_owner_document(child_handle)
.unwrap_or(document);
let context = scope.get_current_context();
host.retain_window_global_csp_context(context);
let _previous = context.set_slot(Rc::new(Self {
document,
origin,
@@ -72,6 +73,7 @@ impl WindowEnvironmentSettings {
return None;
}
let access_origin = host.main_window_access_origin()?;
host.retain_window_global_csp_context(context);
let _previous = context.set_slot(Rc::new(Self {
document: host.document_handle(),
origin: WebOrigin::from_serialized(&host.main_document_security_origin()),
@@ -421,6 +421,7 @@ impl PageScriptHost {
domain,
access_policy,
}));
self.retain_window_global_csp_context(context);
}
pub(in crate::native_bridge::context_host) fn window_context_origins_allow_access(
@@ -174,7 +174,8 @@ use detached_install::{
};
pub(in crate::native_bridge::document) use detached_objects::*;
pub(crate) use detached_objects::{
build_detached_cdata_section_object, build_detached_document_object_from_dom_host,
DetachedDocumentBuildContext, build_detached_cdata_section_object,
build_detached_document_object_from_dom_host,
build_detached_document_object_from_dom_host_with_content_type, detached_node_is_connected,
detached_record_native_tree_mutations, is_valid_pi_target,
preserve_detached_element_bridge_for_custom_prototype, read_detached_native_attribute,
@@ -15,7 +15,8 @@ mod text_content;
pub(in crate::native_bridge::document) use self::attributes::*;
pub(crate) use self::builders::{
build_detached_cdata_section_object, build_detached_document_object_from_dom_host,
DetachedDocumentBuildContext, build_detached_cdata_section_object,
build_detached_document_object_from_dom_host,
build_detached_document_object_from_dom_host_with_content_type, is_valid_pi_target,
preserve_detached_element_bridge_for_custom_prototype,
};
@@ -12,14 +12,14 @@ pub(in crate::native_bridge::document) use character_data::{
build_detached_comment_object, build_detached_processing_instruction_object,
build_detached_text_object,
};
pub(crate) use documents::{
DetachedDocumentBuildContext, build_detached_document_object_from_dom_host,
build_detached_document_object_from_dom_host_with_content_type,
};
pub(in crate::native_bridge::document) use documents::{
build_detached_document_clone_shell, build_detached_document_object,
build_detached_html_document_object,
};
pub(crate) use documents::{
build_detached_document_object_from_dom_host,
build_detached_document_object_from_dom_host_with_content_type,
};
pub(crate) use elements::preserve_detached_element_bridge_for_custom_prototype;
pub(in crate::native_bridge::document) use elements::{
build_detached_element_object, copy_detached_element_bridge_members,
@@ -5,6 +5,14 @@ use crate::web_api_interfaces;
use moli_webapi_declare::WebApiObject;
use url::Url;
#[derive(Clone, Copy)]
pub(crate) enum DetachedDocumentBuildContext<'a> {
Windowless,
BrowsingContextProjection {
inherited_meta_policies: &'a [String],
},
}
#[derive(WebApiObject)]
#[webapi(plain, scope_lifetime = 'scope)]
struct DetachedDocumentObjectDeclaration<'scope, 'tag> {
@@ -89,6 +97,7 @@ fn new_detached_document_shell<'s>(
content_type: &str,
url: Url,
scripting_enabled: bool,
build_context: DetachedDocumentBuildContext<'_>,
) -> Option<v8::Local<'s, v8::Object>> {
let to_string_tag = if kind == "html" {
Some("HTMLDocument")
@@ -112,6 +121,11 @@ fn new_detached_document_shell<'s>(
define_detached_state(scope, document, state);
let handle =
create_native_detached_document_handle_with_url(scope, kind, url, scripting_enabled)?;
if matches!(build_context, DetachedDocumentBuildContext::Windowless) {
let runtime_ptr = context_host_ptr_from_global_bridge(scope)?;
let context = document.get_creation_context(scope)?;
unsafe { &mut *runtime_ptr }.register_windowless_document_csp_context(handle, context);
}
define_detached_native_handle(scope, document, handle);
set_detached_document_content_type(scope, document, content_type)?;
install_detached_document_instance_properties(scope, document, kind);
@@ -179,7 +193,14 @@ pub(in crate::native_bridge::document) fn build_detached_document_clone_shell<'s
// Start with an empty, inert Document. Only the metadata required by the
// DOM cloning algorithm is inherited, before any cloned children are added.
let cloned = new_detached_document_shell(scope, &kind, &content_type, url, false)?;
let cloned = new_detached_document_shell(
scope,
&kind,
&content_type,
url,
false,
DetachedDocumentBuildContext::Windowless,
)?;
set_detached_document_parse_metadata(
scope,
cloned,
@@ -242,6 +263,15 @@ fn import_detached_document_children_from_host_with_reaction_policy<'s>(
true,
&mut imported_handles,
)?;
if !preserve_parser_frames {
// Admit these attributes using the new Document's relevant global
// before insertion reactions or adoption can change their owner.
unsafe { &mut *runtime_ptr }.initialize_cloned_event_handler_content_attributes(
scope,
runtime_ptr,
imported,
);
}
if preserve_parser_frames {
// This is a navigation Document projection, not author importNode.
// Preserve parser frame identity before insertion can discover its
@@ -301,7 +331,12 @@ pub(crate) fn build_detached_document_object_from_dom_host<'s>(
parsed: DomHost,
) -> Option<v8::Local<'s, v8::Object>> {
build_detached_document_object_from_dom_host_with_content_type(
scope, kind, parsed, None, None, false, None,
scope,
kind,
parsed,
None,
None,
DetachedDocumentBuildContext::Windowless,
)
}
@@ -311,8 +346,7 @@ pub(crate) fn build_detached_document_object_from_dom_host_with_content_type<'s>
parsed: DomHost,
content_type: Option<&str>,
character_set: Option<&str>,
preserve_parser_frames: bool,
inherited_meta_policies: Option<&[String]>,
build_context: DetachedDocumentBuildContext<'_>,
) -> Option<v8::Local<'s, v8::Object>> {
let url = detached_document_url(&parsed);
let quirks_mode = parsed.dom().document()?.quirks_mode();
@@ -320,14 +354,26 @@ pub(crate) fn build_detached_document_object_from_dom_host_with_content_type<'s>
let content_type = content_type.unwrap_or(parsed.dom().document()?.content_type());
let character_set = character_set.unwrap_or(parsed.dom().document()?.character_set());
let allow_declarative_shadow_roots = parsed.dom().document()?.allow_declarative_shadow_roots();
let document = new_detached_document_shell(scope, kind, content_type, url, scripting_enabled)?;
if let Some(policies) = inherited_meta_policies {
let document = new_detached_document_shell(
scope,
kind,
content_type,
url,
scripting_enabled,
build_context,
)?;
if let DetachedDocumentBuildContext::BrowsingContextProjection {
inherited_meta_policies,
} = build_context
{
let runtime_ptr = context_host_ptr_from_global_bridge(scope)?;
let document_handle = detached_native_handle(scope, document)?;
// Importing the parsed tree can deliver its own meta policies. Seed
// inherited policies first so both sets retain their delivery order.
unsafe { &*runtime_ptr }
.initialize_inherited_meta_content_security_policies(document_handle, policies);
unsafe { &*runtime_ptr }.initialize_inherited_meta_content_security_policies(
document_handle,
inherited_meta_policies,
);
}
set_detached_document_parse_metadata(
scope,
@@ -336,7 +382,10 @@ pub(crate) fn build_detached_document_object_from_dom_host_with_content_type<'s>
character_set,
allow_declarative_shadow_roots,
)?;
if preserve_parser_frames {
if matches!(
build_context,
DetachedDocumentBuildContext::BrowsingContextProjection { .. }
) {
import_detached_document_children_from_host_with_reaction_policy(
scope, document, &parsed, false, true,
)?;
@@ -437,6 +486,7 @@ pub(in crate::native_bridge::document) fn build_detached_html_document_object<'s
"text/html",
Url::parse("about:blank").expect("static about:blank parses"),
false,
DetachedDocumentBuildContext::Windowless,
)?;
populate_native_html_document_shell(scope, document, title)?;
Some(document)
@@ -463,6 +513,7 @@ pub(in crate::native_bridge::document) fn build_detached_document_object<'s>(
content_type,
Url::parse("about:blank").expect("static about:blank parses"),
false,
DetachedDocumentBuildContext::Windowless,
)?;
if let Some(doctype) = doctype {
let doctype = if detached_is_node(scope, doctype) {
@@ -940,8 +940,8 @@ pub(in crate::native_bridge::document) fn detached_native_element_runtime_and_ha
scope: &mut v8::PinScope<'s, '_>,
element: v8::Local<'s, v8::Object>,
) -> Option<(*mut PageScriptHost, DomHandle)> {
let runtime_ptr = context_host_ptr_from_global_bridge(scope)?;
let handle = detached_native_handle_for_runtime(scope, runtime_ptr, element)?;
let (runtime_ptr, handle) =
node_runtime_and_handle_from_object_or_detached(scope, element).ok()?;
unsafe { &*runtime_ptr }
.dom_host()
.node(handle)
@@ -954,8 +954,7 @@ pub(crate) fn read_detached_native_attribute<'s>(
element: v8::Local<'s, v8::Object>,
name: &str,
) -> Option<String> {
let runtime_ptr = context_host_ptr_from_global_bridge(scope)?;
let handle = detached_native_handle_for_runtime(scope, runtime_ptr, element)?;
let (runtime_ptr, handle) = detached_native_element_runtime_and_handle(scope, element)?;
let dom_host = unsafe { &*runtime_ptr }.dom_host();
dom_host.get_attribute(handle, name)
}
@@ -966,8 +965,7 @@ pub(crate) fn read_detached_native_attribute_ns<'s>(
namespace: Option<&str>,
local_name: &str,
) -> Option<String> {
let runtime_ptr = context_host_ptr_from_global_bridge(scope)?;
let handle = detached_native_handle_for_runtime(scope, runtime_ptr, element)?;
let (runtime_ptr, handle) = detached_native_element_runtime_and_handle(scope, element)?;
let dom_host = unsafe { &*runtime_ptr }.dom_host();
dom_host.get_attribute_ns(handle, namespace, local_name)
}
@@ -976,8 +974,7 @@ pub(crate) fn read_detached_native_attribute_names<'s>(
scope: &mut v8::PinScope<'s, '_>,
element: v8::Local<'s, v8::Object>,
) -> Option<Vec<String>> {
let runtime_ptr = context_host_ptr_from_global_bridge(scope)?;
let handle = detached_native_handle_for_runtime(scope, runtime_ptr, element)?;
let (runtime_ptr, handle) = detached_native_element_runtime_and_handle(scope, element)?;
let dom_host = unsafe { &*runtime_ptr }.dom_host();
dom_host.dom().get_attribute_names(handle)
}
@@ -995,8 +992,7 @@ pub(crate) fn read_detached_native_attribute_snapshot<'s>(
scope: &mut v8::PinScope<'s, '_>,
element: v8::Local<'s, v8::Object>,
) -> Option<Vec<DetachedNativeAttributeSnapshot>> {
let runtime_ptr = context_host_ptr_from_global_bridge(scope)?;
let handle = detached_native_handle_for_runtime(scope, runtime_ptr, element)?;
let (runtime_ptr, handle) = detached_native_element_runtime_and_handle(scope, element)?;
let dom_host = unsafe { &*runtime_ptr }.dom_host();
let element = dom_host.node(handle).and_then(|node| node.as_element())?;
Some(
@@ -1023,8 +1019,7 @@ pub(crate) fn read_detached_native_has_attribute<'s>(
element: v8::Local<'s, v8::Object>,
name: &str,
) -> Option<bool> {
let runtime_ptr = context_host_ptr_from_global_bridge(scope)?;
let handle = detached_native_handle_for_runtime(scope, runtime_ptr, element)?;
let (runtime_ptr, handle) = detached_native_element_runtime_and_handle(scope, element)?;
let dom_host = unsafe { &*runtime_ptr }.dom_host();
dom_host
.node(handle)
@@ -1038,8 +1033,7 @@ pub(crate) fn read_detached_native_has_attribute_ns<'s>(
namespace: Option<&str>,
local_name: &str,
) -> Option<bool> {
let runtime_ptr = context_host_ptr_from_global_bridge(scope)?;
let handle = detached_native_handle_for_runtime(scope, runtime_ptr, element)?;
let (runtime_ptr, handle) = detached_native_element_runtime_and_handle(scope, element)?;
let dom_host = unsafe { &*runtime_ptr }.dom_host();
dom_host
.node(handle)
@@ -515,7 +515,9 @@ fn detached_surface_runtime_and_handle<'s>(
bridge: v8::Local<'s, v8::Object>,
element: v8::Local<'s, v8::Object>,
) -> Option<(*mut PageScriptHost, DomHandle)> {
if let Ok((runtime_ptr, handle)) = node_runtime_and_handle_from_object(scope, element) {
if let Ok((runtime_ptr, handle)) =
node_runtime_and_handle_from_object_or_detached(scope, element)
{
return Some((runtime_ptr, handle));
}
let runtime_ptr = runtime_ptr_from_object(scope, bridge)
+3 -3
View File
@@ -760,9 +760,9 @@ pub(crate) fn object_is_node_wrapper_or_detached<'s>(
|| receiver_has_detached_state(scope, object)
}
pub(crate) fn node_runtime_and_handle_from_object_or_detached<'s>(
scope: &mut v8::PinScope<'s, '_>,
object: v8::Local<'s, v8::Object>,
pub(crate) fn node_runtime_and_handle_from_object_or_detached(
scope: &mut v8::PinScope<'_, '_>,
object: v8::Local<'_, v8::Object>,
) -> anyhow::Result<(*mut PageScriptHost, DomHandle)> {
let object = v8::Local::new(scope, object);
let object =
@@ -132,7 +132,11 @@ fn resolve_node_argument<'s>(
let Some(object) = node_backing_object(scope, object) else {
return NodeArgumentResolution::Invalid;
};
if let Ok((object_runtime_ptr, handle)) = node_runtime_and_handle_from_object(scope, object) {
// Windowless nodes can already have native identity and event state. Move
// that identity between Pages instead of cloning their detached facade.
if let Ok((object_runtime_ptr, handle)) =
node_runtime_and_handle_from_object_or_detached(scope, object)
{
if object_runtime_ptr == runtime_ptr {
return NodeArgumentResolution::SameRuntimeNative(handle);
}
@@ -81,13 +81,49 @@ fn unmodeled_document_handler_sources_keep_their_fallback_csp_check_after_adopti
vm.set_response_content_security_policies(&[
"script-src-attr 'none' 'report-sample'".to_owned()
]);
vm.with_default_context_scope_and_checkpoint_for_test(|scope, _host_ptr| {
for (name, mime, source) in [
(
"pendingHtmlProjection",
"text/html",
"<!doctype html><body>",
),
(
"pendingXmlProjection",
"application/xhtml+xml",
"<html xmlns='http://www.w3.org/1999/xhtml'/>",
),
] {
let document =
crate::dom_parser::parse_browsing_context_document_projection_from_source(
scope,
url::Url::parse("https://inert-handler-admission.test/pending").unwrap(),
source,
Some(mime),
None,
crate::parser::HtmlParser::with_scripting_enabled(false),
&[],
)
.expect("uncommitted browsing-context projection");
let global = scope.get_current_context().global(scope);
assert_eq!(
global.set(
scope,
crate::util::v8str(scope, name).into(),
document.into()
),
Some(true)
);
}
Ok(())
})
.unwrap();
vm.eval(
r#"
globalThis.inertAdmissionEvents = [];
document.addEventListener('securitypolicyviolation', event =>
inertAdmissionEvents.push([event.target.id, event.sample]));
const template = document.createElement('template');
const inertDocuments = [document.implementation.createHTMLDocument(''), template.content.ownerDocument];
const inertDocuments = [pendingHtmlProjection, pendingXmlProjection];
const inertButtons = inertDocuments.map((doc, index) => {
const button = doc.createElement('button');
button.id = 'inert-' + index;
@@ -118,6 +154,93 @@ const inertButtons = inertDocuments.map((doc, index) => {
);
}
#[test]
fn windowless_documents_check_their_relevant_global_before_adoption_for_each_window_realm() {
let fixture = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/windowless-handler-csp-realms.js"
));
for owner in ["window", "frame.contentWindow", "popup"] {
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
let mut vm = new_parsed_page_task_executor_test_vm(
"https://windowless-handler-admission.test/",
"<!doctype html><body></body>",
&loader,
);
let result = vm.eval(&format!(
"const frame = document.createElement('iframe'); document.body.appendChild(frame); \
const popup = open(); \
const result = ({fixture})({owner}); \
JSON.stringify({{total:result.total, passed:result.passed, failures:result.checks.filter(row => !row.passed)}})"
)).expect("shared windowless handler admission fixture");
let result: serde_json::Value = serde_json::from_str(&result).unwrap();
assert_eq!(result["total"], 684, "{owner}: {result:#}");
assert_eq!(result["passed"], result["total"], "{owner}: {result:#}");
assert_eq!(
result["failures"],
serde_json::json!([]),
"{owner}: {result:#}"
);
vm.eval("popup.close(); frame.remove()").unwrap();
}
}
#[test]
fn windowless_handler_policy_tracks_its_global_and_survives_window_retirement() {
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
let mut vm = new_parsed_page_task_executor_test_vm(
"https://windowless-handler-policy.test/",
"<!doctype html><body></body>",
&loader,
);
let result = vm
.eval(include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/windowless-handler-csp-retirement.js"
)))
.unwrap();
assert_eq!(result, "true");
}
#[test]
fn windowless_handler_policy_report_only_admits_and_reports_before_adoption() {
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
let mut vm = new_parsed_page_task_executor_test_vm(
"https://windowless-handler-report-only.test/",
"<!doctype html><body></body>",
&loader,
);
vm.set_response_content_security_report_only_policies(&[
"script-src-attr 'none' 'report-sample'".to_owned(),
]);
vm.eval(
r#"
globalThis.windowlessReports = [];
document.addEventListener('securitypolicyviolation', event =>
windowlessReports.push([event.target === document, event.disposition, event.sample]));
const inert = document.implementation.createHTMLDocument('');
const button = inert.createElement('button');
button.setAttribute('onclick', 'return 5');
if (button.onclick !== null) throw Error('windowless source compiled before adoption');
const frame = document.createElement('iframe');
document.body.appendChild(frame);
const child = frame.contentDocument;
const policy = child.createElement('meta');
policy.httpEquiv = 'Content-Security-Policy';
policy.content = "script-src-attr 'none'";
child.head.appendChild(policy);
child.body.appendChild(button);
if (button.onclick() !== 5) throw Error('report-only admission was blocked by the adopter');
"#,
)
.unwrap();
assert_eq!(
vm.eval_after_selected_page_tasks("JSON.stringify(windowlessReports)")
.unwrap(),
r#"[[true,"report","return 5"]]"#,
);
}
#[test]
fn inline_handler_admission_only_checks_content_attributes_supported_by_the_element() {
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
@@ -0,0 +1,46 @@
(() => {
const checks = [];
const check = (name, passed) => checks.push({name, passed: !!passed});
const popup = open();
try {
const factories = {
html: realm => realm.document.implementation.createHTMLDocument(''),
xml: realm => realm.document.implementation.createDocument(null, 'root'),
parsed: realm => new realm.DOMParser().parseFromString('<body>', 'text/html'),
template: realm => realm.document.createElement('template').content.ownerDocument,
};
const ns = 'urn:windowless-attributes';
for (const [direction, source, target] of [
['to-popup', window, popup], ['from-popup', popup, window],
]) {
for (const [kind, create] of Object.entries(factories)) {
const prefix = `${direction}:${kind}:`;
const element = create(source).createElementNS('http://www.w3.org/1999/xhtml', 'div');
element.setAttribute('data-value', 'before\uD800');
element.setAttributeNS(ns, 'p:value', 'before\uDC00');
target.document.adoptNode(element);
check(prefix + 'get', element.getAttribute('data-value') === 'before\uD800');
check(prefix + 'get-ns', element.getAttributeNS(ns, 'value') === 'before\uDC00');
check(prefix + 'names', element.getAttributeNames().join(',') === 'data-value,p:value');
check(prefix + 'has', element.hasAttribute('data-value'));
check(prefix + 'has-ns', element.hasAttributeNS(ns, 'value'));
element.setAttribute('data-value', 'after\uD800');
element.setAttributeNS(ns, 'p:value', 'after\uDC00');
check(prefix + 'set', target.Element.prototype.getAttribute.call(element, 'data-value') === 'after\uD800');
check(prefix + 'set-ns', target.Element.prototype.getAttributeNS.call(element, ns, 'value') === 'after\uDC00');
element.removeAttribute('data-value');
element.removeAttributeNS(ns, 'value');
check(prefix + 'remove', !element.hasAttribute('data-value') && element.getAttribute('data-value') === null);
check(prefix + 'remove-ns', !element.hasAttributeNS(ns, 'value') && element.getAttributeNS(ns, 'value') === null);
element.setAttribute('data-return', 'retained\uD800');
check(prefix + 'return', source.document.adoptNode(element) === element && element.getAttribute('data-return') === 'retained\uD800');
}
}
} catch (error) {
checks.push({name:'fixture-completed-without-exception',passed:false,details:String(error.stack || error)});
} finally {
popup?.close();
}
globalThis.__uiEventResults = {complete:true,checks,total:checks.length,passed:checks.filter(row => row.passed).length};
return checks.every(row => row.passed);
})()
@@ -0,0 +1,67 @@
(() => {
const checks = [];
const check = (name, passed) => checks.push({name, passed: !!passed});
const popup = open();
try {
const meta = popup.document.createElement('meta');
meta.httpEquiv = 'Content-Security-Policy';
meta.content = "script-src-attr 'none'";
popup.document.head.appendChild(meta);
const factories = {
html: realm => realm.document.implementation.createHTMLDocument(''),
xml: realm => realm.document.implementation.createDocument(null, 'root'),
parsed: realm => new realm.DOMParser().parseFromString('<body>', 'text/html'),
template: realm => realm.document.createElement('template').content.ownerDocument,
};
for (const [direction, source, target, allowed] of [
['allowed-to-blocked', window, popup, true],
['blocked-to-allowed', popup, window, false],
]) {
for (const [kind, create] of Object.entries(factories)) {
for (const operation of ['adoptNode', 'appendChild']) {
const prefix = `${direction}:${kind}:${operation}:`;
const doc = create(source);
const parent = doc.createElementNS('http://www.w3.org/1999/xhtml', 'div');
const prior = doc.createElementNS('http://www.w3.org/1999/xhtml', 'button');
const fresh = doc.createElementNS('http://www.w3.org/1999/xhtml', 'button');
parent.append(prior, fresh);
prior.callOrder = [];
prior.addEventListener('click', () => prior.callOrder.push('before'));
const idl = () => prior.callOrder.push('prior');
prior.onclick = idl;
prior.addEventListener('click', () => prior.callOrder.push('after'));
prior.setAttribute('onclick', "this.callOrder.push('content')");
const code = "this.setAttribute('data-called', 'yes')";
fresh.setAttribute('onclick', code);
check(prefix + 'windowless', doc.defaultView === null);
check(prefix + 'admission-preserves-idl', (prior.onclick === idl) === !allowed);
const adopted = operation === 'adoptNode'
? target.document.adoptNode(parent)
: target.document.body.appendChild(parent);
check(prefix + 'identity', adopted === parent);
if (operation === 'adoptNode') target.document.body.appendChild(parent);
check(prefix + 'descendant-owners', [parent, prior, fresh].every(node => node.ownerDocument === target.document));
check(prefix + 'descendant-wrappers', parent.firstChild === prior && parent.lastChild === fresh);
check(prefix + 'original-prototype', parent instanceof source.HTMLElement);
const admitted = prior.onclick;
const freshHandler = fresh.onclick;
check(prefix + 'retained-idl', (admitted === idl) === !allowed);
prior.dispatchEvent(new target.Event('click'));
fresh.dispatchEvent(new target.Event('click'));
check(prefix + 'listener-order', prior.callOrder.join(',') === (allowed ? 'before,content,after' : 'before,prior,after'));
check(prefix + 'fresh-source-execution', (fresh.getAttribute('data-called') === 'yes') === allowed);
check(prefix + 'fresh-handler', allowed ? typeof freshHandler === 'function' : freshHandler === null);
check(prefix + 'attribute-retained', fresh.getAttribute('onclick') === code);
check(prefix + 'return-identity', source.document.adoptNode(parent) === parent);
check(prefix + 'return-state', prior.ownerDocument === source.document && prior.onclick === admitted && fresh.onclick === freshHandler);
}
}
}
} catch (error) {
checks.push({name:'fixture-completed-without-exception',passed:false,details:String(error.stack || error)});
} finally {
popup?.close();
}
globalThis.__uiEventResults = {complete:true,checks,total:checks.length,passed:checks.filter(row => row.passed).length};
return checks.every(row => row.passed);
})()
@@ -0,0 +1,91 @@
(owner => {
const checks = [];
const check = (name, passed, observed = null) => checks.push({name, passed, observed});
const frames = [owner.document.createElement('iframe'), owner.document.createElement('iframe')];
frames.forEach(frame => owner.document.body.appendChild(frame));
const allowed = frames[0].contentWindow, blocked = frames[1].contentWindow;
const policy = blocked.document.createElement('meta');
policy.httpEquiv = 'Content-Security-Policy';
policy.content = "script-src-attr 'none' 'report-sample'";
blocked.document.head.appendChild(policy);
const source = "this.setAttribute('data-called', 'yes')";
const factories = [
['Document', realm => new realm.Document()],
['createHTMLDocument', realm => realm.document.implementation.createHTMLDocument('')],
['createDocument', realm => realm.document.implementation.createDocument(null, '', null)],
['DOMParser-HTML', realm => new realm.DOMParser().parseFromString('<!doctype html><body>', 'text/html')],
['DOMParser-XHTML', realm => new realm.DOMParser().parseFromString('<html xmlns="http://www.w3.org/1999/xhtml"/>', 'application/xhtml+xml')],
['DOMParser-SVG', realm => new realm.DOMParser().parseFromString('<svg xmlns="http://www.w3.org/2000/svg"/>', 'image/svg+xml')],
['clone-Document', realm => realm.document.cloneNode(false)],
['clone-windowless', realm => realm.document.implementation.createHTMLDocument('').cloneNode(true)],
['parseHTMLUnsafe', realm => realm.Document.parseHTMLUnsafe('<!doctype html><body>')],
['template-owner', realm => realm.document.createElement('template').content.ownerDocument],
];
const mutations = [
['setAttribute', (caller, doc, node) => caller.Element.prototype.setAttribute.call(node, 'onclick', source)],
['setAttributeNS', (caller, doc, node) => caller.Element.prototype.setAttributeNS.call(node, null, 'onclick', source)],
['Attr.value', (caller, doc, node) => {
node.setAttribute('onclick', 'return 1');
Object.getOwnPropertyDescriptor(caller.Attr.prototype, 'value').set.call(node.getAttributeNode('onclick'), source);
}],
['setAttributeNode', (caller, doc, node) => {
const attr = doc.createAttribute('onclick'); attr.value = source;
caller.Element.prototype.setAttributeNode.call(node, attr);
}],
['importNode', (caller, doc, node) => {
node.setAttribute('onclick', source);
return caller.Document.prototype.importNode.call(doc, node, true);
}],
];
for (const [label, creator, destination, permitted] of [
['allowed-to-blocked', allowed, blocked, true],
['blocked-to-allowed', blocked, allowed, false],
]) {
for (const [factory, make] of factories) {
for (const [mutation, mutate] of mutations) {
const key = label + ':' + factory + ':' + mutation;
try {
const doc = make(creator);
let node = doc.createElementNS('http://www.w3.org/1999/xhtml', 'button');
node = mutate(destination, doc, node) || node;
check(key + ':windowless', doc.defaultView === null);
check(key + ':attribute-retained', node.getAttribute('onclick') === source);
check(key + ':inert-getter', node.onclick === null);
destination.document.body.appendChild(node);
check(key + ':adopted', node.ownerDocument === destination.document);
node.dispatchEvent(new destination.Event('click'));
check(key + ':creation-global-policy', (node.getAttribute('data-called') === 'yes') === permitted);
check(key + ':handler-value', permitted ? typeof node.onclick === 'function' : node.onclick === null);
node.remove();
} catch (error) {check(key + ':unexpected-exception', false, String(error));}
}
}
const markup = '<button xmlns="http://www.w3.org/1999/xhtml" onclick="' + source + '"></button>';
const parsed = [
['parsed-HTML', () => new creator.DOMParser().parseFromString(markup, 'text/html')],
['parsed-XHTML', () => new creator.DOMParser().parseFromString(markup, 'application/xhtml+xml')],
['parsed-XML', () => new creator.DOMParser().parseFromString(markup, 'application/xml')],
['parsed-SVG', () => new creator.DOMParser().parseFromString('<svg xmlns="http://www.w3.org/2000/svg">' + markup + '</svg>', 'image/svg+xml')],
['parsed-static', () => creator.Document.parseHTMLUnsafe(markup)],
['parsed-innerHTML', () => {const doc=creator.document.implementation.createHTMLDocument(''); doc.body.innerHTML=markup; return doc;}],
['parsed-template', () => {const template=creator.document.createElement('template'); template.innerHTML=markup; return template.content;}],
];
for (const [name, make] of parsed) {
const key = label + ':' + name;
try {
const root = make(), node = root.querySelector('[onclick]');
check(key + ':windowless', node.ownerDocument.defaultView === null);
check(key + ':attribute-retained', node.getAttribute('onclick') === source);
check(key + ':inert-getter', node.onclick === null);
destination.document.body.appendChild(node);
check(key + ':adopted', node.ownerDocument === destination.document);
node.dispatchEvent(new destination.Event('click'));
check(key + ':creation-global-policy', (node.getAttribute('data-called') === 'yes') === permitted);
check(key + ':handler-value', permitted ? typeof node.onclick === 'function' : node.onclick === null);
node.remove();
} catch (error) {check(key + ':unexpected-exception', false, String(error));}
}
}
frames.forEach(frame => frame.remove());
return {complete:true, total:checks.length, passed:checks.filter(row => row.passed).length, checks};
})
@@ -0,0 +1,75 @@
(() => {
const frame = document.createElement('iframe');
document.body.appendChild(frame);
const creator = frame.contentWindow;
const inert = creator.document.implementation.createHTMLDocument('');
const before = inert.createElement('button');
before.setAttribute('onclick', 'return 11');
const meta = creator.document.createElement('meta');
meta.httpEquiv = 'Content-Security-Policy';
meta.content = "script-src-attr 'none' 'report-sample'";
creator.document.head.appendChild(meta);
const synthetic = inert.createElement('iframe');
inert.body.appendChild(synthetic);
if (synthetic.contentWindow === null) throw Error('missing synthetic Window');
const target = inert.createElement('button');
const prior = () => 17;
target.onclick = prior;
target.setAttribute('onclick', 'return 42');
if (target.onclick !== prior) throw Error('blocked mutation replaced an IDL handler');
frame.remove();
document.body.appendChild(frame);
const after = inert.createElement('button');
after.setAttribute('onclick', 'return 43');
document.body.append(before, target, after);
if (before.onclick() !== 11) throw Error('later global policy retroactively blocked admission');
if (target.onclick !== prior) throw Error('adoption lost the preserved IDL handler');
if (after.onclick !== null) throw Error('replacement realm lent its policy to a retained Document');
const written = creator.document.implementation.createHTMLDocument('');
const directWritten = written.createElement('button');
directWritten.setAttribute('onclick', 'return 52');
document.body.appendChild(directWritten);
if (directWritten.onclick !== null) throw Error('a new Document in a retired global borrowed replacement policy');
written.open(); written.write('<!doctype html><button onclick="return 53"></button>'); written.close();
const writtenButton = written.querySelector('button');
document.body.appendChild(writtenButton);
if (writtenButton.onclick !== null) throw Error('document.open/write forgot its relevant global');
const stillRetained = inert.createElement('button');
stillRetained.setAttribute('onclick', 'return 54');
document.body.appendChild(stillRetained);
if (stillRetained.onclick !== null) throw Error('a new Document changed the old shared global policy');
const second = document.createElement('iframe');
document.body.appendChild(second);
const secondRealm = second.contentWindow;
const secondMeta = secondRealm.document.createElement('meta');
secondMeta.httpEquiv = 'Content-Security-Policy';
secondMeta.content = "script-src-attr 'none'";
secondRealm.document.head.appendChild(secondMeta);
const implementation = secondRealm.document.implementation;
const makeRetained = implementation.createHTMLDocument.bind(implementation);
const retainedTemplate = secondRealm.document.createElement('template');
second.remove(); document.body.appendChild(second);
const firstAfterRetirement = makeRetained('');
const retainedButton = firstAfterRetirement.createElement('button');
retainedButton.setAttribute('onclick', 'return 59');
document.body.appendChild(retainedButton);
if (retainedButton.onclick !== null) throw Error('first windowless Document after retirement lost the outgoing global');
const templateButton = retainedTemplate.content.ownerDocument.createElement('button');
templateButton.setAttribute('onclick', 'return 60');
document.body.appendChild(templateButton);
if (templateButton.onclick !== null) throw Error('retained template contents lost their original global');
const popup = open();
const popupMeta = popup.document.createElement('meta');
popupMeta.httpEquiv = 'Content-Security-Policy';
popupMeta.content = "script-src-attr 'none'";
popup.document.head.appendChild(popupMeta);
const popupImplementation = popup.document.implementation;
const makeClosed = popupImplementation.createHTMLDocument.bind(popupImplementation);
popup.close();
const closedDocument = makeClosed('');
const closedButton = closedDocument.createElement('button');
closedButton.setAttribute('onclick', 'return 61');
document.body.appendChild(closedButton);
if (closedButton.onclick !== null) throw Error('closed popup lost its relevant global policy');
return true;
})()