diff --git a/moli-dom/src/native/mod.rs b/moli-dom/src/native/mod.rs index 0f28bf0a505..8dafdaff3f8 100644 --- a/moli-dom/src/native/mod.rs +++ b/moli-dom/src/native/mod.rs @@ -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 { + 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, diff --git a/moli-protocol/src/domains/runtime/tests/windowless_adoption.rs b/moli-protocol/src/domains/runtime/tests/windowless_adoption.rs index a8794b35f02..9f890ab4624 100644 --- a/moli-protocol/src/domains/runtime/tests/windowless_adoption.rs +++ b/moli-protocol/src/domains/runtime/tests/windowless_adoption.rs @@ -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; +} diff --git a/moli-renderer-v8/src/document_runtime/dom_facade.rs b/moli-renderer-v8/src/document_runtime/dom_facade.rs index 6528a10712f..1c81ab51b77 100644 --- a/moli-renderer-v8/src/document_runtime/dom_facade.rs +++ b/moli-renderer-v8/src/document_runtime/dom_facade.rs @@ -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); diff --git a/moli-renderer-v8/src/dom_parser.rs b/moli-renderer-v8/src/dom_parser.rs index 8a54c72f2b4..1faa0e6ac2d 100644 --- a/moli-renderer-v8/src/dom_parser.rs +++ b/moli-renderer-v8/src/dom_parser.rs @@ -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, ) } 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 d7b70c64466..c5f786f825d 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/core.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs @@ -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(), 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 49eef45c015..1745df4ce1b 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs @@ -1151,6 +1151,8 @@ pub(crate) struct PageScriptHost { runtime_binding_execution_context_owners: HashMap, window_execution_context_realms: WindowExecutionContextRealmRecords, + document_global_csp_contexts: + RefCell>>>, #[cfg(test)] pending_runtime_binding_calls: Vec, next_runtime_observable_context_token: RuntimeObservableContextToken, diff --git a/moli-renderer-v8/src/native_bridge/context_host/node_adoption.rs b/moli-renderer-v8/src/native_bridge/context_host/node_adoption.rs index 3ec8fb1654d..ef8da65e2c3 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/node_adoption.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/node_adoption.rs @@ -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 { - 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); } 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 e72bb3a7f08..42b3788a5d0 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 @@ -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::>() { + 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::>() { + 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 { + 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; diff --git a/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/settings.rs b/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/settings.rs index 1d9b20ef2ef..5f29833f79a 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/settings.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/settings.rs @@ -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()), diff --git a/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs b/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs index 700116fba2d..5aba47111d6 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs @@ -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( diff --git a/moli-renderer-v8/src/native_bridge/document.rs b/moli-renderer-v8/src/native_bridge/document.rs index da72d7e917f..18089fb281d 100644 --- a/moli-renderer-v8/src/native_bridge/document.rs +++ b/moli-renderer-v8/src/native_bridge/document.rs @@ -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, diff --git a/moli-renderer-v8/src/native_bridge/document/detached_objects.rs b/moli-renderer-v8/src/native_bridge/document/detached_objects.rs index d3ce41e3a42..6313d39dfd9 100644 --- a/moli-renderer-v8/src/native_bridge/document/detached_objects.rs +++ b/moli-renderer-v8/src/native_bridge/document/detached_objects.rs @@ -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, }; diff --git a/moli-renderer-v8/src/native_bridge/document/detached_objects/builders.rs b/moli-renderer-v8/src/native_bridge/document/detached_objects/builders.rs index 6a0ba06470c..678c9637c8d 100644 --- a/moli-renderer-v8/src/native_bridge/document/detached_objects/builders.rs +++ b/moli-renderer-v8/src/native_bridge/document/detached_objects/builders.rs @@ -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, diff --git a/moli-renderer-v8/src/native_bridge/document/detached_objects/builders/documents.rs b/moli-renderer-v8/src/native_bridge/document/detached_objects/builders/documents.rs index 875caf5df38..e37fa51d907 100644 --- a/moli-renderer-v8/src/native_bridge/document/detached_objects/builders/documents.rs +++ b/moli-renderer-v8/src/native_bridge/document/detached_objects/builders/documents.rs @@ -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> { 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> { 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> { 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) { diff --git a/moli-renderer-v8/src/native_bridge/document/detached_objects/state_tree.rs b/moli-renderer-v8/src/native_bridge/document/detached_objects/state_tree.rs index b2a903e2725..25196321f89 100644 --- a/moli-renderer-v8/src/native_bridge/document/detached_objects/state_tree.rs +++ b/moli-renderer-v8/src/native_bridge/document/detached_objects/state_tree.rs @@ -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 { - 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 { - 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> { - 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> { - 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 { - 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 { - 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) diff --git a/moli-renderer-v8/src/native_bridge/document/detached_surface/element_attributes.rs b/moli-renderer-v8/src/native_bridge/document/detached_surface/element_attributes.rs index fe3f1ac4914..5207ecadb07 100644 --- a/moli-renderer-v8/src/native_bridge/document/detached_surface/element_attributes.rs +++ b/moli-renderer-v8/src/native_bridge/document/detached_surface/element_attributes.rs @@ -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) diff --git a/moli-renderer-v8/src/native_bridge/node.rs b/moli-renderer-v8/src/native_bridge/node.rs index a0d86abe9a8..126a8a5aa0c 100644 --- a/moli-renderer-v8/src/native_bridge/node.rs +++ b/moli-renderer-v8/src/native_bridge/node.rs @@ -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 = diff --git a/moli-renderer-v8/src/native_bridge/node/foreign/arg.rs b/moli-renderer-v8/src/native_bridge/node/foreign/arg.rs index b5a77a26cab..8bb34148c56 100644 --- a/moli-renderer-v8/src/native_bridge/node/foreign/arg.rs +++ b/moli-renderer-v8/src/native_bridge/node/foreign/arg.rs @@ -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); } diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/event_handlers/csp_admission.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/event_handlers/csp_admission.rs index 99b4f935037..b3622ce0da8 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/event_handlers/csp_admission.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/event_handlers/csp_admission.rs @@ -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", + "", + ), + ( + "pendingXmlProjection", + "application/xhtml+xml", + "", + ), + ] { + 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/", + "", + &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/", + "", + &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/", + "", + &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(); diff --git a/moli-renderer-v8/tests/fixtures/windowless-cross-page-attributes.js b/moli-renderer-v8/tests/fixtures/windowless-cross-page-attributes.js new file mode 100644 index 00000000000..50ef1b181ea --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/windowless-cross-page-attributes.js @@ -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('', '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); +})() diff --git a/moli-renderer-v8/tests/fixtures/windowless-cross-page-handlers.js b/moli-renderer-v8/tests/fixtures/windowless-cross-page-handlers.js new file mode 100644 index 00000000000..1c7c7ccc2ca --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/windowless-cross-page-handlers.js @@ -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('', '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); +})() diff --git a/moli-renderer-v8/tests/fixtures/windowless-handler-csp-realms.js b/moli-renderer-v8/tests/fixtures/windowless-handler-csp-realms.js new file mode 100644 index 00000000000..12257d1370c --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/windowless-handler-csp-realms.js @@ -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('', 'text/html')], + ['DOMParser-XHTML', realm => new realm.DOMParser().parseFromString('', 'application/xhtml+xml')], + ['DOMParser-SVG', realm => new realm.DOMParser().parseFromString('', 'image/svg+xml')], + ['clone-Document', realm => realm.document.cloneNode(false)], + ['clone-windowless', realm => realm.document.implementation.createHTMLDocument('').cloneNode(true)], + ['parseHTMLUnsafe', realm => realm.Document.parseHTMLUnsafe('')], + ['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 = ''; + 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('' + markup + '', '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}; +}) diff --git a/moli-renderer-v8/tests/fixtures/windowless-handler-csp-retirement.js b/moli-renderer-v8/tests/fixtures/windowless-handler-csp-retirement.js new file mode 100644 index 00000000000..94bacf4bf1b --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/windowless-handler-csp-retirement.js @@ -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(''); 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; +})()