From 6e2ecccbd8a5d56eddf18fda1876b6d6902f47f8 Mon Sep 17 00:00:00 2001 From: ldm0 Date: Sun, 20 Sep 2026 05:49:57 +0800 Subject: [PATCH] fix(runtime): preserve origin-domain access for retired windows --- .../wpt-cross-current/passed-cases.txt | 2 - .../context_host/child_documents/commit.rs | 8 + .../realm_state/initialize.rs | 7 + .../child_frame_runtime/window.rs | 63 ++++---- .../context_host/child_frames.rs | 14 +- .../src/native_bridge/context_host/core.rs | 4 +- .../context_host/document_domain.rs | 26 +-- .../src/native_bridge/context_host/mod.rs | 3 +- .../window_execution_context/settings.rs | 4 +- .../context_host/window_security_tokens.rs | 150 +++++++++++++++++- moli-renderer-v8/src/native_bridge/mod.rs | 2 +- moli-renderer-v8/src/script_vm.rs | 2 +- .../src/script_vm/initial_window_document.rs | 2 +- moli-renderer-v8/src/script_vm/post_parse.rs | 18 +++ .../src/script_vm/related_page.rs | 2 +- .../script_vm/tests/retained_child_window.rs | 134 ++++++++++++++++ .../fixtures/retained-document-domain.js | 103 ++++++++++++ 17 files changed, 477 insertions(+), 67 deletions(-) create mode 100644 moli-renderer-v8/tests/fixtures/retained-document-domain.js diff --git a/moli-benchmark/wpt-cross-current/passed-cases.txt b/moli-benchmark/wpt-cross-current/passed-cases.txt index 207fb702bef..ca927791e36 100644 --- a/moli-benchmark/wpt-cross-current/passed-cases.txt +++ b/moli-benchmark/wpt-cross-current/passed-cases.txt @@ -8056,11 +8056,9 @@ html/webappapis/dynamic-markup-insertion/opening-the-input-stream/016.html html/webappapis/dynamic-markup-insertion/opening-the-input-stream/document-open-cancels-javascript-url-navigation.html html/webappapis/dynamic-markup-insertion/opening-the-input-stream/document.open-02.html html/webappapis/dynamic-markup-insertion/opening-the-input-stream/document.open-03.html -html/webappapis/dynamic-markup-insertion/opening-the-input-stream/event-listeners.window.js?moli-wpt-script=window html/webappapis/dynamic-markup-insertion/opening-the-input-stream/form-control-state.html html/webappapis/dynamic-markup-insertion/opening-the-input-stream/location-set-and-document-open.html html/webappapis/dynamic-markup-insertion/opening-the-input-stream/origin-check-in-document-open-basic.html -html/webappapis/dynamic-markup-insertion/opening-the-input-stream/url.window.js?moli-wpt-script=window html/webappapis/dynamic-markup-insertion/the-outerhtml-property/outerhtml-documentfragment.html html/webappapis/dynamic-markup-insertion/the-outerhtml-property/outerhtml-no-parent.html html/webappapis/microtask-queuing/queue-microtask-cross-realm-callback-report-exception.html diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs index 5f7d3491737..061a0e4685c 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs @@ -421,6 +421,14 @@ impl PageScriptHost { ), resource_authority, ); + if matches!( + owner_transition.local_window_owner_transition(), + FrameLocalWindowOwnerTransition::Preserved { .. } + ) { + // Reusing the initial inner global still gives it the newly + // committed Document's origin and mutable domain state. + self.refresh_child_default_world_security_token(scope, handle); + } // A preserved initial LocalWindow may already have a history surface // without running realm bootstrap again. Commit its Document seed here; // subsequent view refreshes must never replay this history transition. diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/realm_state/initialize.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/realm_state/initialize.rs index b32d7845b91..b954cd85fac 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/realm_state/initialize.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/realm_state/initialize.rs @@ -104,6 +104,13 @@ pub(in crate::native_bridge::context_host::child_frame_runtime) fn rebind_child_ }; validate_registered_realm(host, scope, init)?; let snapshot = capture_child_window_realm_snapshot(host, init)?; + let context = scope.get_current_context(); + host.install_window_context_security_origin( + scope, + context, + OwnerDispatchScope::Child(init.handle), + init.world.access_policy(), + ); rebind_child_window_document_environment(scope, global, rebind.handle)?; bind_window_name(scope, global, &snapshot.window_name); diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs index 85544af5006..930987c554d 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs @@ -667,45 +667,42 @@ pub(crate) fn contexts_can_script_access<'s>( return true; } - let Some((accessing_host_ptr, accessing_identity)) = (|| { - let host_ptr = crate::util::context_host_ptr_from_context_slot(accessing_context)?; - let identity = unsafe { &*host_ptr } - .window_execution_context_identity_for_access_check(accessing_context); - Some((host_ptr, identity)) - })() else { + let Some(accessing_host_ptr) = + crate::util::context_host_ptr_from_context_slot(accessing_context) + else { return false; }; - let Some((accessed_host_ptr, accessed_identity)) = (|| { - let host_ptr = crate::util::context_host_ptr_from_context_slot(accessed_context)?; - let identity = unsafe { &*host_ptr } - .window_execution_context_identity_for_access_check(accessed_context)?; - Some((host_ptr, identity)) - })() else { + let Some(accessed_host_ptr) = crate::util::context_host_ptr_from_context_slot(accessed_context) + else { return false; }; let host = unsafe { &*accessing_host_ptr }; - let Some(accessing_identity) = accessing_identity - .filter(|identity| host.window_execution_context_identity_is_current(*identity)) - else { - return accessing_context - .get_slot::() - .is_some_and(|settings| { - settings.can_access_current_window( - host, - unsafe { &*accessed_host_ptr }, - accessed_identity, - ) - }); - }; - if accessing_host_ptr != accessed_host_ptr { - return host.window_execution_context_can_access_other_host( - accessing_identity, - unsafe { &*accessed_host_ptr }, - accessed_identity, - ); + let accessed_host = unsafe { &*accessed_host_ptr }; + let accessing_identity = host + .window_execution_context_identity_for_access_check(accessing_context) + .filter(|identity| host.window_execution_context_identity_is_current(*identity)); + let accessed_identity = accessed_host + .window_execution_context_identity_for_access_check(accessed_context) + .filter(|identity| accessed_host.window_execution_context_identity_is_current(*identity)); + if let (Some(accessing), Some(accessed)) = (accessing_identity, accessed_identity) { + return if accessing_host_ptr == accessed_host_ptr { + host.window_execution_context_can_access(accessing, accessed) + } else { + host.window_execution_context_can_access_other_host(accessing, accessed_host, accessed) + }; } - - host.window_execution_context_can_access(accessing_identity, accessed_identity) + if accessing_host_ptr == accessed_host_ptr { + // Domain state survives execution retirement, without granting a task route. + return host.window_context_origins_allow_access(accessing_context, accessed_context); + } + accessing_identity.is_none() + && accessed_identity.is_some_and(|accessed| { + accessing_context + .get_slot::() + .is_some_and(|settings| { + settings.can_access_current_window(host, accessed_host, accessed) + }) + }) } pub(crate) fn caller_can_access_window<'s>( diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs index 1e87b6ef72b..ec326376cac 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs @@ -67,7 +67,7 @@ pub(super) struct ChildBrowsingContextEntry { performance_time_origin: ChildPerformanceTimeOrigin, pending_document_load_id: Option, classic_script_document_state: classic_scripts::ChildClassicScriptDocumentState, - document_domain_override: Rc>>, + document_domain_override: super::DocumentDomainState, credentialless: bool, service_worker_client_id: Option, pending_service_worker_client_id: Option, @@ -123,20 +123,18 @@ impl ChildBrowsingContextEntry { self.clear_document_domain_override(); } - pub(super) fn document_domain_override(&self) -> Option { - self.document_domain_override.borrow().clone() - } - - pub(super) fn shared_document_domain_override(&self) -> Rc>> { + pub(super) fn document_domain_state(&self) -> super::DocumentDomainState { self.document_domain_override.clone() } pub(super) fn set_document_domain_override(&mut self, domain: String) { - *self.document_domain_override.borrow_mut() = Some(domain); + self.document_domain_override.set(domain); } pub(super) fn clear_document_domain_override(&mut self) { - self.document_domain_override = Rc::new(RefCell::new(None)); + // A new Document gets its own mutable domain. Retained realms keep + // the previous origin, including any inherited references to it. + self.document_domain_override = super::DocumentDomainState::default(); } pub(super) fn window_name(&self) -> &str { 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 780c0c9ee1d..acd68525605 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/core.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs @@ -61,7 +61,7 @@ impl PageScriptHost { inherited_document_domain: Option<&str>, policy: &crate::document_runtime::DocumentPolicyContainer, ) -> crate::frame_owner_model::FrameDocumentLocalWindowTransition { - let same_origin = self.document_domain_override.borrow().as_deref() + let same_origin = self.document_domain_override.get().as_deref() == inherited_document_domain && (inherited_opaque_origin_matches || moli_url::WebOrigin::from_serialized(&self.main_document_security_origin()) @@ -431,7 +431,7 @@ impl PageScriptHost { #[cfg(test)] force_reused_isolated_proxy_bootstrap_failure: std::cell::Cell::new(false), child_browsing_context_document_handles: HashMap::new(), - document_domain_override: Rc::new(RefCell::new(None)), + document_domain_override: DocumentDomainState::default(), next_child_document_load_id: 0, next_child_classic_script_load_id: 0, pending_child_document_navigations: HashMap::new(), diff --git a/moli-renderer-v8/src/native_bridge/context_host/document_domain.rs b/moli-renderer-v8/src/native_bridge/context_host/document_domain.rs index efdb2ad3e85..306d80b6903 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/document_domain.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/document_domain.rs @@ -4,17 +4,17 @@ use std::net::IpAddr; use url::{Host, Url}; impl PageScriptHost { - pub(crate) fn inherit_document_domain_override(&mut self, domain: Rc>>) { + pub(crate) fn inherit_document_domain_override(&mut self, domain: DocumentDomainState) { self.document_domain_override = domain; } pub(crate) fn inherited_document_domain( &self, child: Option, - ) -> Rc>> { + ) -> DocumentDomainState { match child.and_then(|handle| self.child_browsing_context_security_origin_owner(handle)) { Some(ChildSecurityOriginOwner::Child(owner)) => { - self.child_browsing_contexts[&owner].shared_document_domain_override() + self.child_browsing_contexts[&owner].document_domain_state() } Some(ChildSecurityOriginOwner::Main) | None => self.document_domain_override.clone(), } @@ -27,8 +27,7 @@ impl PageScriptHost { if document_handle == self.document_handle() { return self .document_domain_override - .borrow() - .clone() + .get() .unwrap_or_else(|| self.main_document_domain_host().unwrap_or_default()); } if let Some(child_handle) = @@ -65,7 +64,7 @@ impl PageScriptHost { if !document_domain_is_allowed_for_host(¤t_host, &domain) { return false; } - *self.document_domain_override.borrow_mut() = Some(domain); + self.document_domain_override.set(domain); return true; } let Some(child_handle) = @@ -84,12 +83,19 @@ impl PageScriptHost { &self, handle: DomHandle, ) -> Option { + self.child_document_domain_state(handle)?.get() + } + + pub(super) fn child_document_domain_state( + &self, + handle: DomHandle, + ) -> Option { match self.child_browsing_context_security_origin_owner(handle)? { - ChildSecurityOriginOwner::Main => self.document_domain_override.borrow().clone(), + ChildSecurityOriginOwner::Main => Some(self.document_domain_override.clone()), ChildSecurityOriginOwner::Child(owner) => self .child_browsing_contexts .get(&owner) - .and_then(|entry| entry.document_domain_override()), + .map(|entry| entry.document_domain_state()), } } @@ -132,9 +138,7 @@ impl PageScriptHost { return false; }; match origin_owner { - ChildSecurityOriginOwner::Main => { - *self.document_domain_override.borrow_mut() = Some(domain); - } + ChildSecurityOriginOwner::Main => self.document_domain_override.set(domain), ChildSecurityOriginOwner::Child(owner) => { let Some(entry) = self.child_browsing_contexts.get_mut(&owner) else { return false; 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 53198c4116d..ae205f42d42 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs @@ -179,6 +179,7 @@ mod window_execution_context; mod window_security_tokens; mod window_world; mod workers; +pub(crate) use window_security_tokens::DocumentDomainState; pub(crate) use window_security_tokens::set_window_security_token; #[cfg(test)] @@ -931,7 +932,7 @@ pub(crate) struct PageScriptHost { #[cfg(test)] force_reused_isolated_proxy_bootstrap_failure: std::cell::Cell, child_browsing_context_document_handles: HashMap, - document_domain_override: Rc>>, + document_domain_override: DocumentDomainState, next_child_document_load_id: u64, next_child_classic_script_load_id: u64, pending_child_document_navigations: HashMap, 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 de72e1918e1..bdcdd881b19 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 @@ -105,7 +105,7 @@ impl WindowEnvironmentSettings { } = &mut origin { if self.domain_owner_document == host.document_handle() { - *document_domain = host.document_domain_override.borrow().clone(); + *document_domain = host.document_domain_override.get(); } else if let Some(handle) = host.child_browsing_context_handle_for_stored_document(self.domain_owner_document) { @@ -135,7 +135,7 @@ impl WindowEnvironmentSettings { } = &mut origin { if self.domain_owner_document == host.document_handle() { - *document_domain = host.document_domain_override.borrow().clone(); + *document_domain = host.document_domain_override.get(); } else if let Some(handle) = host.child_browsing_context_handle_for_stored_document(self.domain_owner_document) { 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 127409871ad..9302bf26114 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 @@ -1,13 +1,96 @@ use super::{ - OwnerDispatchScope, PageScriptHost, WindowEnvironmentSettings, WindowExecutionContextIdentity, + OwnerDispatchScope, PageScriptHost, WindowEnvironmentSettings, + WindowExecutionContextAccessPolicy, WindowExecutionContextIdentity, WindowExecutionContextOwner, child_frames::{ChildAncestorOriginsReferrerPolicy, ChildBrowsingContextEntry}, }; use crate::document_runtime::DomHandle; +use std::{cell::RefCell, rc::Rc}; const WINDOW_SECURITY_TOKEN_PREFIX: &str = "moli-window-origin-v1:"; const WINDOW_ISOLATED_WORLD_SECURITY_TOKEN_PREFIX: &str = "moli-window-isolated-origin-v1:"; +#[derive(Clone, Default)] +pub(crate) struct DocumentDomainState(Rc); + +#[derive(Default)] +struct DocumentDomainStateData { + value: RefCell>, + contexts: RefCell>>, +} + +impl std::fmt::Debug for DocumentDomainState { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_tuple("DocumentDomainState") + .field(&self.get()) + .finish() + } +} + +impl DocumentDomainState { + pub(crate) fn get(&self) -> Option { + self.0.value.borrow().clone() + } + + pub(super) fn set(&self, domain: String) { + *self.0.value.borrow_mut() = Some(domain); + } + + fn register_context( + &self, + scope: &mut v8::PinScope<'_, '_, ()>, + context: v8::Local<'_, v8::Context>, + ) { + let mut contexts = self.0.contexts.borrow_mut(); + contexts.retain(|weak| { + weak.to_local(scope) + .is_some_and(|current| current != context) + }); + contexts.push(v8::Weak::new(scope, context)); + } + + fn invalidate_context_tokens(&self, scope: &mut v8::PinScope<'_, '_>) { + // Inherited origins can still be shared with a retired realm. Its old + // tuple token must not bypass the changed origin-domain check. Weak + // handles keep this propagation independent of execution registrations. + self.0.contexts.borrow_mut().retain(|weak| { + let Some(context) = weak.to_local(scope) else { + return false; + }; + let shares_domain = context + .get_slot::() + .as_deref() + .and_then(|origin| origin.domain.as_ref()) + .is_some_and(|domain| Rc::ptr_eq(&self.0, &domain.0)); + if shares_domain { + context.use_default_security_token(); + } + shares_domain + }); + } +} + +struct WindowContextSecurityOrigin { + origin: WindowAccessOrigin, + domain: Option, + access_policy: WindowExecutionContextAccessPolicy, +} + +impl WindowContextSecurityOrigin { + fn current_origin(&self) -> WindowAccessOrigin { + let mut origin = self.origin.clone(); + if let WindowAccessOrigin::Tuple { + document_domain, .. + } = &mut origin + && let Some(domain) = &self.domain + { + *document_domain = domain.get(); + } + origin + } +} + impl PageScriptHost { /// Static pure APIs use their concrete function realm, including retained /// Document settings, without reading author-visible Window properties. @@ -70,6 +153,50 @@ impl PageScriptHost { )) } + pub(crate) fn install_window_context_security_origin( + &self, + scope: &mut v8::PinScope<'_, '_, ()>, + context: v8::Local<'_, v8::Context>, + dispatch_scope: OwnerDispatchScope, + access_policy: WindowExecutionContextAccessPolicy, + ) { + let Some(origin) = self.window_access_origin_for_dispatch_scope(dispatch_scope) else { + context.remove_slot::(); + return; + }; + let domain = match dispatch_scope { + OwnerDispatchScope::Top => Some(self.document_domain_override.clone()), + OwnerDispatchScope::Child(handle) => self.child_document_domain_state(handle), + // Popups currently alias their opener's concrete realm. + OwnerDispatchScope::LightweightPopup(_) => return, + }; + if let Some(domain) = &domain { + domain.register_context(scope, context); + } + context.set_slot(Rc::new(WindowContextSecurityOrigin { + origin, + domain, + access_policy, + })); + } + + pub(in crate::native_bridge::context_host) fn window_context_origins_allow_access( + &self, + accessing_context: v8::Local<'_, v8::Context>, + accessed_context: v8::Local<'_, v8::Context>, + ) -> bool { + let Some(accessing) = accessing_context.get_slot::() else { + return false; + }; + let Some(accessed) = accessed_context.get_slot::() else { + return false; + }; + accessing.access_policy == WindowExecutionContextAccessPolicy::Universal + || accessing + .current_origin() + .can_access(&accessed.current_origin()) + } + pub(in crate::native_bridge::context_host) fn child_ancestor_origins_referrer_policy_from_owner_attribute( &self, handle: DomHandle, @@ -148,7 +275,7 @@ impl PageScriptHost { return None; } let origin = self.main_document_security_origin(); - if self.document_domain_override.borrow().is_some() { + if self.document_domain_override.get().is_some() { return None; } window_security_token_key(origin) @@ -177,7 +304,7 @@ impl PageScriptHost { } window_isolated_world_security_token_key( self.main_document_security_origin(), - self.document_domain_override.borrow().is_some(), + self.document_domain_override.get().is_some(), ) } @@ -209,6 +336,15 @@ impl PageScriptHost { return 0; } + let domain = if target_is_main { + Some(self.document_domain_override.clone()) + } else { + target_child.and_then(|handle| self.child_document_domain_state(handle)) + }; + if let Some(domain) = domain { + domain.invalidate_context_tokens(scope); + } + let mut dispatch_scopes = vec![OwnerDispatchScope::Top]; dispatch_scopes.extend( self.child_browsing_context_handles_in_document_order() @@ -324,6 +460,12 @@ impl PageScriptHost { let Some((_, context)) = self.window_execution_context(scope, owner, dispatch_scope) else { return false; }; + self.install_window_context_security_origin( + scope, + context, + dispatch_scope, + WindowExecutionContextAccessPolicy::EnforceWebOrigin, + ); set_window_security_token( scope, context, @@ -630,7 +772,7 @@ impl PageScriptHost { } WindowAccessOrigin::from_serialized_origin( serialized_origin, - self.document_domain_override.borrow().clone(), + self.document_domain_override.get(), ) } diff --git a/moli-renderer-v8/src/native_bridge/mod.rs b/moli-renderer-v8/src/native_bridge/mod.rs index 4070aedea5d..df2a557dcb9 100644 --- a/moli-renderer-v8/src/native_bridge/mod.rs +++ b/moli-renderer-v8/src/native_bridge/mod.rs @@ -9,7 +9,7 @@ mod current_input; #[cfg(feature = "devtools")] pub(crate) use context_host::MouseReleaseFollowUp; pub(crate) use context_host::{ - ChildDocumentFetch, PageScriptHost, PageScriptHostTaskCapabilities, + ChildDocumentFetch, DocumentDomainState, PageScriptHost, PageScriptHostTaskCapabilities, PendingScrollObservableEffects, PostParseAutofocusAdmission, ServiceWorkerWindowOwner, SharedResourceTimingBufferRegistry, }; diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rs index 9f7d6189baa..1b9aea124be 100644 --- a/moli-renderer-v8/src/script_vm.rs +++ b/moli-renderer-v8/src/script_vm.rs @@ -2005,7 +2005,7 @@ impl ScriptVm { pub(crate) struct ScriptVmInitialDocumentEnvironment { security_token: Option>, opaque_origin: Option>, - document_domain_override: Rc>>, + document_domain_override: crate::native_bridge::DocumentDomainState, origin: String, pub(crate) policy_container: crate::document_runtime::DocumentPolicyContainer, fallback_base_url: Option, diff --git a/moli-renderer-v8/src/script_vm/initial_window_document.rs b/moli-renderer-v8/src/script_vm/initial_window_document.rs index 9f1f4cd0fb8..55722a909df 100644 --- a/moli-renderer-v8/src/script_vm/initial_window_document.rs +++ b/moli-renderer-v8/src/script_vm/initial_window_document.rs @@ -32,7 +32,7 @@ impl ScriptVm { false }; let inherited_domain = - inherited.map(|environment| environment.document_domain_override.borrow()); + inherited.map(|environment| environment.document_domain_override.get()); Ok(self ._context_host .borrow() diff --git a/moli-renderer-v8/src/script_vm/post_parse.rs b/moli-renderer-v8/src/script_vm/post_parse.rs index 244083ee243..8022f179116 100644 --- a/moli-renderer-v8/src/script_vm/post_parse.rs +++ b/moli-renderer-v8/src/script_vm/post_parse.rs @@ -318,6 +318,24 @@ impl ScriptVmContextBootstrap { child_handle: None, .. } => unsafe { &*host_ptr }.main_isolated_world_security_token_key(), }; + let dispatch_scope = match mode { + WindowContextBootstrapMode::ChildDefault { child_handle, .. } + | WindowContextBootstrapMode::Isolated { + child_handle: Some(child_handle), + .. + } => crate::native_bridge::OwnerDispatchScope::Child(child_handle), + _ => crate::native_bridge::OwnerDispatchScope::Top, + }; + let access_policy = match mode { + WindowContextBootstrapMode::Isolated { access_policy, .. } => access_policy, + _ => crate::native_bridge::WindowExecutionContextAccessPolicy::EnforceWebOrigin, + }; + unsafe { &*host_ptr }.install_window_context_security_origin( + scope, + local_context, + dispatch_scope, + access_policy, + ); if !crate::native_bridge::set_window_security_token( scope, local_context, diff --git a/moli-renderer-v8/src/script_vm/related_page.rs b/moli-renderer-v8/src/script_vm/related_page.rs index 5c68493f8c0..2555038accb 100644 --- a/moli-renderer-v8/src/script_vm/related_page.rs +++ b/moli-renderer-v8/src/script_vm/related_page.rs @@ -43,7 +43,7 @@ impl ScriptVmDefaultWorldBootstrap { Some(ScriptVmInitialDocumentEnvironment { security_token: None, opaque_origin, - document_domain_override: Rc::default(), + document_domain_override: Default::default(), fallback_base_url: None, storage_key: None, origin: inherited_origin.clone(), diff --git a/moli-renderer-v8/src/script_vm/tests/retained_child_window.rs b/moli-renderer-v8/src/script_vm/tests/retained_child_window.rs index 5a16bd00166..b6c180d5dfa 100644 --- a/moli-renderer-v8/src/script_vm/tests/retained_child_window.rs +++ b/moli-renderer-v8/src/script_vm/tests/retained_child_window.rs @@ -1,5 +1,139 @@ use super::*; +#[cfg(feature = "devtools")] +#[tokio::test(flavor = "current_thread")] +async fn retained_child_window_origin_rebinds_default_and_isolated_realms() { + let server = StaticHttpServer::spawn_with_bodies(vec![ + "".to_owned(), + ]) + .await; + let loader = static_http_loader([server.resolve_entry("www.example.test")]); + let parent_url = server.url_for_host("www.example.test", "/page.html"); + let mut vm = new_storage_page_task_executor_test_vm_with_loader(parent_url.as_str(), &loader); + vm.exec( + r#" +const root = document.documentElement || document.appendChild(document.createElement('html')); +const body = document.body || root.appendChild(document.createElement('body')); +globalThis.frame = document.createElement('iframe'); +body.append(frame); +globalThis.heldWindow = frame.contentWindow; +"#, + None, + ) + .unwrap(); + vm.drain_ready_page_task_executor_turns_for_setup(&loader, 16) + .await + .expect("initial child realm should materialize through Page tasks"); + let child_realm = vm + .live_child_default_runtime_realm_inventory() + .into_iter() + .next() + .expect("initial child realm"); + let child_context_id = child_realm.context_id; + let frame_id = child_realm.frame_id.expect("initial child frame id"); + for (name, universal) in [("enforcedRead", false), ("universalRead", true)] { + let context_id = vm + .create_isolated_world_for_frame(&frame_id, name, universal) + .expect("initial child isolated world"); + vm.eval_in_isolated_context( + context_id, + &format!( + "parent.{name} = ((target) => () => {{ try {{ return target.status; }} catch (error) {{ return error.name; }} }})(parent); 'installed'" + ), + ) + .expect("retain a callback from the initial isolated realm"); + } + vm.exec( + "globalThis.loaded = false; frame.onload = () => { loaded = true; }; frame.src = '/child.html';", + None, + ) + .unwrap(); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(loaded)", + "true", + "network document should replace the initial about:blank document", + ) + .await; + assert_eq!( + vm.live_child_default_runtime_realm_inventory()[0].context_id, + child_context_id, + "the first same-origin navigation must reuse the initial realm" + ); + const PROBE: &str = r#"JSON.stringify([ +(() => { try { return heldWindow.status; } catch (error) { return error.name; } })(), +enforcedRead(), +universalRead() +])"#; + let expected = r#"["SecurityError","SecurityError",""]"#; + assert_eq!(vm.eval(PROBE).unwrap(), expected); + vm.eval("frame.remove()").unwrap(); + assert_eq!(vm.child_frame_realm_store.len(), 0); + assert_eq!(vm.page_isolated_world_contexts.len(), 0); + assert_eq!( + vm.eval(PROBE).unwrap(), + expected, + "retired realms must keep the committed origin and their own access policy" + ); + assert_eq!(server.finish_targets().await, vec!["/child.html"]); +} + +#[tokio::test(flavor = "current_thread")] +async fn retained_child_windows_keep_shared_origin_domain_access() { + const BODY: &str = r#""#; + let server = StaticHttpServer::spawn_with_bodies(vec![BODY.to_owned(); 26]).await; + let second_server = StaticHttpServer::spawn_with_bodies(vec![BODY.to_owned()]).await; + let loader = static_http_loader([ + server.resolve_entry("www.example.test"), + server.resolve_entry("sub.example.test"), + server.resolve_entry("other.test"), + second_server.resolve_entry("www.example.test"), + ]); + let parent_url = server.url_for_host("www.example.test", "/page.html"); + let mut vm = new_storage_page_task_executor_test_vm_with_loader(parent_url.as_str(), &loader); + let script = include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixtures/retained-document-domain.js" + )); + vm.exec( + &format!( + r#" +if (!document.documentElement) document.appendChild(document.createElement('html')); +if (!document.body) document.documentElement.appendChild(document.createElement('body')); +globalThis.__retainedDomainResult = null; +({script})({port}).then( + result => {{ globalThis.__retainedDomainResult = result; }}, + error => {{ globalThis.__retainedDomainResult = {{error: String(error)}}; }} +); +"#, + port = second_server.base_url().port().unwrap(), + ), + None, + ) + .expect("retained origin-domain probe should start"); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(__retainedDomainResult !== null)", + "true", + "retained origin-domain probe should finish", + ) + .await; + let result: serde_json::Value = serde_json::from_str( + &vm.eval("JSON.stringify(__retainedDomainResult)") + .expect("retained origin-domain observations"), + ) + .unwrap(); + assert_eq!(result["checks"], 85, "{result}"); + assert_eq!(result["failures"], serde_json::json!([]), "{result}"); + assert_eq!(server.finish_targets().await.len(), 26); + assert_eq!(second_server.finish_targets().await.len(), 1); +} + #[test] fn retained_child_window_survives_context_retirement() { for materialized in [false, true] { diff --git a/moli-renderer-v8/tests/fixtures/retained-document-domain.js b/moli-renderer-v8/tests/fixtures/retained-document-domain.js new file mode 100644 index 00000000000..82cb1bdd270 --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/retained-document-domain.js @@ -0,0 +1,103 @@ +(async (otherPort) => { + const result = {checks: 0, failures: [], observations: []}; + const check = (name, actual, expected) => { + result.checks++; + if (actual !== expected) result.failures.push({name, actual, expected}); + }; + const exercise = async config => { + const observations = []; + const documentDiagnostics = []; + const read = action => { + try { return action(); } catch (error) { return error.name; } + }; + const record = (name, action, expected) => observations.push([name, read(action), expected]); + const observeDocument = (name, action, expected) => documentDiagnostics.push([name, read(action), expected]); + const peerRead = parent.Function('target', 'try { return target.status; } catch (error) { return error.name; }'); + const frame = document.createElement('iframe'); + if (config.sandbox) frame.sandbox = 'allow-scripts'; + if (config.inherit === 'srcdoc') frame.srcdoc = 'inherited'; + else if (!config.inherit) { + const childURL = new URL('/domain-fixture.html', location.href); + if (config.childHost) childURL.hostname = config.childHost; + if (config.childPort) childURL.port = config.childPort; + if (config.childDomain) childURL.searchParams.set('domain', config.childDomain); + frame.src = childURL.href; + } + const loaded = new Promise(resolve => frame.onload = resolve); + document.body.append(frame); + await loaded; + const view = frame.contentWindow; + if (config.parentDomain) document.domain = config.parentDomain; + record('live-access', () => view.status, config.allow ? '' : 'SecurityError'); + const doc = config.allow ? view.document : null; + const reverse = config.allow ? view.Function('other', 'return () => other.document.domain;')(window) : null; + frame.remove(); + if (config.afterDomain) document.domain = config.afterDomain; + const allowedAfter = config.allowAfter ?? config.allow; + record('removed-access', () => view.status, allowedAfter ? '' : 'SecurityError'); + const childDomainAfter = config.inherit ? (config.afterDomain || config.parentDomain) : config.childDomain; + const peerAllowed = !config.sandbox && !childDomainAfter && !config.childPort + && (!config.childHost || config.childHost === location.hostname); + record('independent-peer-access', () => peerRead(view), peerAllowed ? '' : 'SecurityError'); + if (doc) { + const expectedDomain = config.inherit + ? (config.afterDomain || config.parentDomain || location.hostname) + : (config.childDomain || config.childHost || location.hostname); + observeDocument('retained-document-domain', () => doc.domain, expectedDomain); + record('retained-document-view', () => doc.defaultView, null); + record('retained-document-setter', () => { doc.domain = expectedDomain; return 'accepted'; }, 'SecurityError'); + observeDocument('cloned-document-domain', () => doc.cloneNode(false).domain, expectedDomain); + } + if (reverse) record('retired-caller', reverse, allowedAfter ? document.domain : 'SecurityError'); + if (config.reinsert) { + const newURL = new URL('/domain-fixture.html', location.href); + newURL.searchParams.set('domain', location.hostname); + const reloaded = new Promise(resolve => frame.onload = resolve); + frame.src = newURL.href; + document.body.append(frame); + await reloaded; + record('old-window-after-reinsert', () => view.status, ''); + record('replacement-remains-one-sided', () => frame.contentWindow.status, 'SecurityError'); + observeDocument('old-document-domain-after-reinsert', () => doc.domain, config.childDomain); + } + return {observations, documentDiagnostics, late: () => read(() => view.status), allowedAfter}; + }; + const host = location.hostname; + const relaxed = 'example.test'; + const scenarios = [ + {name: 'tuple', allow: true}, + {name: 'exact-domain', parentDomain: host, childDomain: host, allow: true}, + {name: 'relaxed-domain', parentDomain: relaxed, childDomain: relaxed, allow: true}, + {name: 'subdomain', childHost: 'sub.example.test', parentDomain: relaxed, childDomain: relaxed, allow: true}, + {name: 'port', childPort: otherPort, parentDomain: relaxed, childDomain: relaxed, allow: true}, + {name: 'parent-only', parentDomain: relaxed, allow: false}, + {name: 'child-only', childDomain: relaxed, allow: false}, + {name: 'cross-origin', childHost: 'other.test', allow: false}, + {name: 'opaque', sandbox: true, allow: false}, + {name: 'parent-changes', allow: true, afterDomain: relaxed, allowAfter: false}, + {name: 'parent-catches-up', childDomain: relaxed, allow: false, afterDomain: relaxed, allowAfter: true}, + {name: 'inherited-blank', inherit: 'blank', allow: true, afterDomain: relaxed}, + {name: 'inherited-srcdoc', inherit: 'srcdoc', allow: true, afterDomain: relaxed}, + {name: 'reinsert', parentDomain: relaxed, childDomain: relaxed, allow: true, reinsert: true}, + ]; + for (const config of scenarios) { + const outer = document.createElement('iframe'); + const loaded = new Promise(resolve => outer.onload = resolve); + outer.src = '/domain-fixture.html'; + document.body.append(outer); + await loaded; + try { + const observed = await outer.contentWindow.eval('(' + exercise.toString() + ')(' + JSON.stringify(config) + ')'); + result.observations.push({scenario: config.name, document: observed.documentDiagnostics}); + for (const [name, actual, expected] of observed.observations) check(config.name + ':' + name, actual, expected); + outer.remove(); + await new Promise(resolve => setTimeout(resolve, 0)); + check(config.name + ':both-retired', observed.late(), observed.allowedAfter ? '' : 'SecurityError'); + } catch (error) { + check(config.name + ':setup', error.name + ': ' + error.message, 'no exception'); + } finally { + outer.remove(); + } + } + return result; +})