diff --git a/moli-renderer-v8/src/context_bootstrap/window_receiver.rs b/moli-renderer-v8/src/context_bootstrap/window_receiver.rs index 9d86e353656..a6d786b26fd 100644 --- a/moli-renderer-v8/src/context_bootstrap/window_receiver.rs +++ b/moli-renderer-v8/src/context_bootstrap/window_receiver.rs @@ -43,6 +43,22 @@ pub(crate) fn require_same_origin_window_receiver<'s>( if is_current_window_receiver(scope, receiver) { return true; } + if let Some(context) = receiver.get_creation_context(scope) + && !receiver.strict_equals(context.global(scope).into()) + && crate::native_bridge::lightweight_popup_id_from_window(scope, receiver).is_some() + { + let context = scope.get_current_context(); + if crate::native_bridge::synthetic_window_context_can_access(scope, context, receiver) { + return true; + } + crate::native_bridge::throw_dom_exception( + scope, + "SecurityError", + 18, + "Blocked access to a cross-origin Window.", + ); + return false; + } // An extracted method or accessor bypasses WindowProxy's property access check. // Authorize native globals before reading slots, which can themselves // trigger V8's cross-origin fallback. diff --git a/moli-renderer-v8/src/lib.rs b/moli-renderer-v8/src/lib.rs index db7d1c3b488..b673b4ac020 100644 --- a/moli-renderer-v8/src/lib.rs +++ b/moli-renderer-v8/src/lib.rs @@ -107,6 +107,7 @@ mod resource_ready; mod runtime; mod runtime_binding_data; mod script_cleanup; +mod script_continuation; mod script_execution; mod script_execution_control; mod script_provenance; diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs index 42a7e6d8d3f..ae264a1bf32 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs @@ -7,8 +7,9 @@ mod window; pub(in crate::native_bridge::context_host) use window::ChildWindowProxyRecords; pub(crate) use window::{ - caller_can_access_window, contexts_can_script_access, cross_origin_lightweight_popup_id, - install_child_window_proxy_access_check_handlers, is_cross_origin_location_proxy, - is_cross_origin_top_window_proxy, throw_cross_origin_location_security_error, + cross_origin_lightweight_popup_id, install_child_window_proxy_access_check_handlers, + install_synthetic_window_access_check_handlers, is_cross_origin_location_proxy, + is_cross_origin_top_window_proxy, mark_popup_window_access_check_initialized, + synthetic_window_context_can_access, throw_cross_origin_location_security_error, throw_cross_origin_type_error, }; 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 3d60a6bcc20..e74d61cf868 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 @@ -51,8 +51,6 @@ struct ChildWindowProxyRecord { browsing_context_parent_window: Option>, browsing_context_top_window: Option>, browsing_context_opener: Option, - cross_origin_endpoint_projections: - HashMap>, realm_top_window_wrapper: Option>, live_window_exposed_to_top: bool, cross_origin_window_proxy: Option>, @@ -110,10 +108,6 @@ impl ChildWindowProxyRecords { ) { let record = self.record_mut(handle); record.facade_context = Some(context); - // Endpoint projections are wrappers in the accessing child realm. A - // replacement LocalWindow gets fresh wrappers even though the stable - // target WindowProxy identities remain the same. - record.cross_origin_endpoint_projections.clear(); } pub(in crate::native_bridge::context_host) fn take_facade_context( @@ -217,31 +211,6 @@ impl ChildWindowProxyRecords { Some((opener.endpoint, v8::Local::new(scope, &opener.window))) } - fn cross_origin_endpoint_projection<'s>( - &self, - scope: &mut v8::PinScope<'s, '_>, - handle: DomHandle, - endpoint: PendingWindowMessageEndpoint, - ) -> Option> { - self.records - .get(&handle)? - .cross_origin_endpoint_projections - .get(&endpoint) - .map(|projection| v8::Local::new(scope, projection)) - } - - fn set_cross_origin_endpoint_projection( - &mut self, - scope: &mut v8::PinScope<'_, '_>, - handle: DomHandle, - endpoint: PendingWindowMessageEndpoint, - projection: v8::Local<'_, v8::Object>, - ) { - self.record_mut(handle) - .cross_origin_endpoint_projections - .insert(endpoint, v8::Global::new(scope, projection)); - } - pub(in crate::native_bridge::context_host) fn set_realm_top( &mut self, scope: &mut v8::PinScope<'_, '_>, @@ -618,14 +587,41 @@ const CROSS_ORIGIN_TOP_WINDOW_PROXY_SLOT: &str = "__moliCrossOriginTopWindowProx const CROSS_ORIGIN_LIGHTWEIGHT_POPUP_ID_SLOT: &str = "__moliCrossOriginLightweightPopupId"; const CROSS_ORIGIN_WINDOW_NAMED_CHILD_SLOTS: &str = "__moliCrossOriginWindowNamedChildSlots"; +const SYNTHETIC_WINDOW_ACCESS_INITIALIZED_SLOT: &str = "__moliSyntheticWindowAccessInitialized"; + const CROSS_ORIGIN_ACCESS_ERROR: &str = "Blocked a frame with a different origin from accessing a cross-origin frame."; pub(crate) fn install_child_window_proxy_access_check_handlers( global_template: v8::Local<'_, v8::ObjectTemplate>, +) { + install_window_access_check_handlers(global_template, window_access_check_callback); +} + +pub(crate) fn mark_popup_window_access_check_initialized( + scope: &mut v8::PinScope<'_, '_>, + window: v8::Local<'_, v8::Object>, +) { + set_private_value( + scope, + window, + SYNTHETIC_WINDOW_ACCESS_INITIALIZED_SLOT, + v8::Boolean::new(scope, true).into(), + ); +} + +pub(crate) fn install_synthetic_window_access_check_handlers( + template: v8::Local<'_, v8::ObjectTemplate>, +) { + install_window_access_check_handlers(template, synthetic_window_access_check_callback); +} + +fn install_window_access_check_handlers( + global_template: v8::Local<'_, v8::ObjectTemplate>, + access_check: v8::AccessCheckCallback, ) { global_template.set_security_token_access_check_and_handlers( - window_access_check_callback, + access_check, v8::NamedPropertyHandlerConfiguration::new() .getter(child_window_cross_origin_named_getter) .setter(child_window_cross_origin_named_setter) @@ -641,6 +637,48 @@ pub(crate) fn install_child_window_proxy_access_check_handlers( ); } +unsafe extern "C" fn synthetic_window_access_check_callback( + accessing_context: v8::Local<'_, v8::Context>, + accessed_object: v8::Local<'_, v8::Object>, + _data: v8::Local<'_, v8::Value>, +) -> bool { + let scope = std::pin::pin!(unsafe { v8::CallbackScope::new(accessing_context) }); + let scope = &mut scope.init(); + // A synthetic shell is initialized before it is exposed to script. Its + // private access surface marks the end of that native initialization. + if get_private_value( + scope, + accessed_object, + SYNTHETIC_WINDOW_ACCESS_INITIALIZED_SLOT, + ) + .is_none() + { + return true; + } + synthetic_window_context_can_access(scope, accessing_context, accessed_object) +} + +pub(crate) fn synthetic_window_context_can_access<'s>( + scope: &mut v8::PinScope<'s, '_>, + accessing_context: v8::Local<'s, v8::Context>, + window: v8::Local<'s, v8::Object>, +) -> bool { + let Some(popup_id) = crate::native_bridge::lightweight_popup_id_from_window(scope, window) + else { + return true; + }; + let Ok(host_ptr) = crate::native_bridge::runtime_ptr_from_object(scope, window) else { + return false; + }; + if crate::util::context_host_ptr_from_context_slot(accessing_context) != Some(host_ptr) { + return false; + } + let host = unsafe { &*host_ptr }; + host.window_security_origin_for_context(scope, accessing_context) + .zip(host.lightweight_popup_security_origin(popup_id)) + .is_some_and(|(source, target)| source.can_access(&target)) +} + unsafe extern "C" fn window_access_check_callback( accessing_context: v8::Local<'_, v8::Context>, accessed_object: v8::Local<'_, v8::Object>, @@ -674,6 +712,13 @@ pub(crate) fn caller_can_access_window<'s>( scope: &mut v8::PinScope<'s, '_>, window: v8::Local<'s, v8::Object>, ) -> bool { + if crate::native_bridge::lightweight_popup_id_from_window(scope, window).is_some() { + return synthetic_window_context_can_access( + scope, + cross_origin_accessing_context(scope), + window, + ); + } let Some(accessed) = window.get_creation_context(scope) else { return false; }; @@ -730,7 +775,7 @@ struct CrossOriginWindowMethodsDeclaration { post_message: (), #[webapi(method, callback = cross_origin_window_noop_callback, readonly, dont_delete)] blur: (), - #[webapi(method, callback = cross_origin_window_noop_callback, readonly, dont_delete)] + #[webapi(method, callback = cross_origin_window_close_callback, readonly, dont_delete)] close: (), #[webapi(method, callback = cross_origin_window_noop_callback, readonly, dont_delete)] focus: (), @@ -1554,31 +1599,18 @@ impl PageScriptHost { fn popup_window_for_child_realm<'s>( &mut self, scope: &mut v8::PinScope<'s, '_>, - handle: DomHandle, + _handle: DomHandle, popup_id: u64, ) -> Option> { - if self.child_window_can_access_lightweight_popup(handle, popup_id) { - return self.lightweight_popup_window(scope, popup_id); - } - self.cross_origin_window_endpoint_projection_for_child( - scope, - handle, - PendingWindowMessageEndpoint::LightweightPopup(popup_id), - ) + self.lightweight_popup_window(scope, popup_id) } fn cross_origin_window_endpoint_projection_for_child<'s>( &mut self, scope: &mut v8::PinScope<'s, '_>, - accessing_handle: DomHandle, + _accessing_handle: DomHandle, endpoint: PendingWindowMessageEndpoint, ) -> Option> { - if let Some(projection) = self - .child_window_proxy_records - .cross_origin_endpoint_projection(scope, accessing_handle, endpoint) - { - return Some(projection); - } match endpoint { PendingWindowMessageEndpoint::TopWindow => { let dispatch = super::super::OwnerDispatchScope::Top; @@ -1590,31 +1622,7 @@ impl PageScriptHost { self.child_browsing_context_cross_origin_window_proxy(scope, handle) } PendingWindowMessageEndpoint::LightweightPopup(popup_id) => { - let projection = build_cross_origin_popup_window_proxy(scope, popup_id)?; - self.child_window_proxy_records - .set_cross_origin_endpoint_projection( - scope, - accessing_handle, - endpoint, - projection, - ); - let opener = if let Some(opener_endpoint) = - self.lightweight_popup_opener_endpoint(popup_id) - && opener_endpoint != endpoint - { - self.cross_origin_window_endpoint_projection_for_child( - scope, - accessing_handle, - opener_endpoint, - ) - .map(v8::Local::::from) - .unwrap_or_else(|| v8::null(scope).into()) - } else { - v8::null(scope).into() - }; - let storage = cross_origin_proxy_storage_object(scope, projection); - set_cross_origin_object_slot(scope, storage, "opener", opener); - Some(projection) + self.lightweight_popup_window(scope, popup_id) } } } @@ -1875,75 +1883,6 @@ fn build_detached_cross_origin_window_index_proxy<'s>( Some(proxy) } -fn build_cross_origin_popup_window_proxy<'s>( - scope: &mut v8::PinScope<'s, '_>, - popup_id: u64, -) -> Option> { - build_cross_origin_top_level_window_proxy( - scope, - PendingWindowMessageEndpoint::LightweightPopup(popup_id), - ) -} - -fn build_cross_origin_top_level_window_proxy<'s>( - scope: &mut v8::PinScope<'s, '_>, - endpoint: PendingWindowMessageEndpoint, -) -> Option> { - let location = build_detached_cross_origin_location_proxy(scope)?; - let window = new_null_prototype_object(scope); - match endpoint { - PendingWindowMessageEndpoint::TopWindow => set_private_value( - scope, - window, - window_host::TOP_WINDOW_MESSAGE_ENDPOINT_SLOT, - v8::Boolean::new(scope, true).into(), - ), - PendingWindowMessageEndpoint::LightweightPopup(popup_id) => set_private_value( - scope, - window, - CROSS_ORIGIN_LIGHTWEIGHT_POPUP_ID_SLOT, - v8::BigInt::new_from_u64(scope, popup_id).into(), - ), - PendingWindowMessageEndpoint::ChildWindow(_) => { - unreachable!("top-level Window projection cannot target a child frame") - } - } - set_private_value( - scope, - window, - DETACHED_CROSS_ORIGIN_WINDOW_PROXY_SLOT, - v8::Boolean::new(scope, true).into(), - ); - set_private_value( - scope, - window, - CROSS_ORIGIN_TOP_WINDOW_PROXY_SLOT, - v8::Boolean::new(scope, true).into(), - ); - set_cross_origin_object_slot( - scope, - window, - "closed", - v8::Boolean::new(scope, false).into(), - ); - set_cross_origin_object_slot(scope, window, "then", v8::undefined(scope).into()); - location::set_slot( - scope, - window, - CROSS_ORIGIN_WINDOW_LOCATION_SLOT, - location.into(), - )?; - CrossOriginWindowLiveAccessorsDeclaration::default() - .initialize(scope, window) - .ok()?; - install_cross_origin_window_methods(scope, window)?; - install_cross_origin_denied_accessors(scope, window, CROSS_ORIGIN_DENIED_WINDOW_PROPERTIES)?; - install_cross_origin_symbol_slots(scope, window); - let proxy = wrap_cross_origin_window_with_has_trap(scope, window)?; - set_cross_origin_window_self_identity_slots(scope, window, proxy); - Some(proxy) -} - fn is_cross_origin_window_proxy<'s>( scope: &mut v8::PinScope<'s, '_>, object: v8::Local<'s, v8::Object>, @@ -2460,6 +2399,18 @@ fn cross_origin_location_proxy_set_callback<'s>( rv.set(v8::Boolean::new(scope, navigated).into()); } +fn cross_origin_window_close_callback<'s>( + scope: &mut v8::PinScope<'s, '_>, + args: v8::FunctionCallbackArguments<'s>, + rv: v8::ReturnValue<'_, v8::Value>, +) { + if crate::native_bridge::lightweight_popup_id_from_window(scope, args.this()).is_some() { + super::super::popups::lightweight_popup_close_callback(scope, args, rv); + } else { + crate::context_bootstrap::window_close_callback(scope, args, rv); + } +} + fn cross_origin_window_noop_callback<'s>( scope: &mut v8::PinScope<'s, '_>, args: v8::FunctionCallbackArguments<'s>, diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/cross_origin_bindings.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/cross_origin_bindings.rs index 764668947d6..bfc65cd23b3 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/cross_origin_bindings.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/cross_origin_bindings.rs @@ -16,7 +16,7 @@ pub(super) struct WindowMembers { self_window: (), #[webapi(accessor_property, getter = location::window_location, setter = location::set_window_location)] location: (), - #[webapi(method, callback = context_bootstrap::window_close_callback)] + #[webapi(method, callback = cross_origin_window_close_callback)] close: (), #[webapi(accessor_property, getter = closed_value)] closed: (), @@ -80,6 +80,7 @@ struct WindowTarget<'s> { context: v8::Local<'s, v8::Context>, host: *mut PageScriptHost, child: Option, + popup: Option, closed: bool, } @@ -91,6 +92,17 @@ impl<'s> WindowTarget<'s> { let context = receiver.get_creation_context(scope)?; let host = crate::util::context_host_ptr_from_context_slot(context)?; let owner = unsafe { &*host }; + if let Some(popup) = crate::native_bridge::lightweight_popup_id_from_window(scope, receiver) + { + return Some(Self { + window: receiver, + context, + host, + child: None, + popup: Some(popup), + closed: !owner.lightweight_popup_is_open(popup), + }); + } let identity = owner.window_execution_context_identity_for_access_check(context); let current = identity .filter(|identity| owner.window_execution_context_identity_is_current(*identity)); @@ -119,15 +131,20 @@ impl<'s> WindowTarget<'s> { context, host, child, + popup: None, closed, }) } fn sync_children(&self, scope: &mut v8::PinScope<'s, '_>) { let host = unsafe { &mut *self.host }; - let document = match self.child { - Some(handle) => host.child_browsing_context_document_handle(handle), - None => Some(host.document_handle()), + let document = if let Some(popup) = self.popup { + host.lightweight_popup_document_handle(popup) + } else { + match self.child { + Some(handle) => host.child_browsing_context_document_handle(handle), + None => Some(host.document_handle()), + } }; let scope = &mut v8::ContextScope::new(scope, self.context); if let Some(document) = document { @@ -141,6 +158,12 @@ impl<'s> WindowTarget<'s> { } self.sync_children(scope); let host = unsafe { &*self.host }; + if let Some(popup) = self.popup { + return host + .lightweight_popup_document_handle(popup) + .map(|document| host.window_child_browsing_context_handles_for_document(document)) + .unwrap_or_default(); + } match self.child { Some(handle) => host .child_browsing_context_direct_host_handles(handle) @@ -171,7 +194,14 @@ impl<'s> WindowTarget<'s> { } self.sync_children(scope); let host = unsafe { &mut *self.host }; - let handle = host.child_browsing_context_named_child_handle(self.child, name)?; + let handle = if let Some(popup) = self.popup { + host.child_browsing_context_named_child_handle_for_scope( + super::super::super::OwnerDispatchScope::LightweightPopup(popup), + name, + )? + } else { + host.child_browsing_context_named_child_handle(self.child, name)? + }; host.child_browsing_context_window_proxy_for_accessing_context(scope, handle) } } diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/lookup.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/lookup.rs index 5a887d95773..96d4b7a3a5a 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/lookup.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/lookup.rs @@ -281,6 +281,37 @@ impl PageScriptHost { Some(parent) => self.child_browsing_context_direct_host_handles(parent), None => self.top_level_child_browsing_context_handles_in_document_order(), }; + handles.into_iter().find(|handle| { + self.dom_host() + .node(*handle) + .is_some_and(|node| node.flags().in_document_tree()) + && self + .child_browsing_contexts + .get(handle) + .is_some_and(|entry| entry.matches_browsing_context_name(key)) + }) + } + + pub(crate) fn child_browsing_context_named_child_handle_for_scope( + &self, + parent: OwnerDispatchScope, + key: &str, + ) -> Option { + if key.is_empty() { + return None; + } + let handles = match parent { + OwnerDispatchScope::Child(parent) => { + self.child_browsing_context_direct_host_handles(parent) + } + OwnerDispatchScope::Top => { + self.top_level_child_browsing_context_handles_in_frame_tree_order() + } + OwnerDispatchScope::LightweightPopup(id) => self + .window_child_browsing_context_handles_for_document( + self.lightweight_popup_document_handle(id)?, + ), + }; let first = handles.into_iter().find(|handle| { self.dom_host() .node(*handle) @@ -290,12 +321,7 @@ impl PageScriptHost { .get(handle) .is_some_and(|entry| entry.matches_browsing_context_name(key)) })?; - // The target-name property set selects the first child for each name - // before filtering by origin. A cross-origin first match must not - // expose a later same-origin duplicate, and document.domain does not - // relax this same-origin check. - let parent_scope = parent.map_or(OwnerDispatchScope::Top, OwnerDispatchScope::Child); - self.window_scopes_have_same_origin(parent_scope, OwnerDispatchScope::Child(first)) + self.window_scopes_have_same_origin(parent, OwnerDispatchScope::Child(first)) .then_some(first) } 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 306d80b6903..ce21beaec3b 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 @@ -111,9 +111,7 @@ impl PageScriptHost { if let Some(domain) = self.lightweight_popup_document_domain_override(popup_id) { return domain; } - self.lightweight_popup_origin(popup_id) - .and_then(|origin| Url::parse(&origin).ok()) - .and_then(|origin| url_host_domain(&origin)) + self.lightweight_popup_document_domain_host(popup_id) .unwrap_or_default() } @@ -159,13 +157,8 @@ impl PageScriptHost { return false; } let Some(current_host) = self - .lightweight_popup_origin(popup_id) - .map(|origin| { - Url::parse(&origin) - .ok() - .and_then(|origin| url_host_domain(&origin)) - }) - .unwrap_or_else(|| { + .lightweight_popup_document_domain_host(popup_id) + .or_else(|| { self.dom_host() .dom() .node(document_handle) @@ -190,6 +183,15 @@ impl PageScriptHost { .and_then(|origin| url_host_domain(&origin)) } + fn lightweight_popup_document_domain_host(&self, popup_id: u64) -> Option { + // An about:blank Document has its creator's origin even though its + // URL has no host. Domain access follows that origin, not the URL. + let origin = self.lightweight_popup_origin(popup_id)?; + Url::parse(&origin) + .ok() + .and_then(|url| url_host_domain(&url)) + } + fn child_browsing_context_document_domain_host(&self, handle: DomHandle) -> Option { let origin = self.child_browsing_context_window_origin(handle)?; Url::parse(&origin) 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 f23a6c5d67a..9936e7bab63 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs @@ -81,6 +81,9 @@ mod child_frame_runtime; mod child_runtime_script_order; mod document_parser_owner; pub(crate) use child_frame_runtime::install_child_window_proxy_access_check_handlers; +pub(crate) use child_frame_runtime::{ + install_synthetic_window_access_check_handlers, synthetic_window_context_can_access, +}; mod child_frame_snapshots; mod child_frames; mod close_watchers; diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups.rs b/moli-renderer-v8/src/native_bridge/context_host/popups.rs index 6892ce216a8..86aca23e211 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/popups.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/popups.rs @@ -160,8 +160,7 @@ struct LightweightPopupWindowStateDeclaration { accessor_property, enumerable, getter = lightweight_popup_window_name_getter, - setter = lightweight_popup_window_name_setter - )] + setter = lightweight_popup_window_name_setter, access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] name: (), } @@ -175,8 +174,7 @@ struct LightweightPopupWindowOpenerDeclaration<'scope> { getter = lightweight_popup_window_opener_getter, setter = lightweight_popup_window_opener_setter, data = self.popup_id, - setter_data = self.popup_id - )] + setter_data = self.popup_id, setter_access_policy = crate::context_bootstrap::require_same_origin_window_receiver)] opener: (), } @@ -218,10 +216,20 @@ impl PendingLightweightPopupHistory { window: v8::Local<'s, v8::Object>, final_url: &Url, ) { - let Some(seed) = self.entry_seed() else { - return; + let mut seed = match self.entry_seed() { + Some(seed) => seed.clone(), + None => { + let Some(seed) = history_entry_seed_for_cross_document_location( + scope, + window, + final_url, + crate::context_bootstrap::LocationNavigationKind::Replace, + ) else { + return; + }; + seed + } }; - let mut seed = seed.clone(); if let Some(entry) = seed .entries .iter_mut() @@ -420,7 +428,7 @@ struct LightweightPopupDocumentRecord { // document.open() preserves whether navigation initialized Navigation entries. has_committed_navigation: bool, url: Url, - access_origin: Rc>, + access_origin: Rc>, secure_context: bool, state: LightweightPopupDocumentState, storage_scope: LightweightPopupStorageScope, @@ -490,6 +498,7 @@ pub(super) struct LightweightPopupBrowsingContextRecord { location_url: Url, opener_sandbox_policy: Option, lifecycle: LightweightPopupLifecycle, + closed_origin: Option, is_closing: bool, navigation_id: LightweightPopupNavigationId, } @@ -709,6 +718,9 @@ impl PageScriptHost { let LightweightPopupLifecycle::Open(open) = lifecycle else { return None; }; + record.closed_origin = Some(super::WindowSecurityOrigin::for_popup( + open.document.access_origin.clone(), + )); record.is_closing = false; record.navigation_id = LightweightPopupNavigationId::new( record @@ -752,6 +764,11 @@ impl PageScriptHost { self.cancel_lightweight_popup_classic_script_loads(popup_id); if let Some(window) = window { clear_lightweight_popup_window_document_event_state(scope, window); + with_lightweight_popup_scope(scope, popup_id, |scope| { + for property in ["parent", "top"] { + set_object_slot(scope, window, property, v8::null(scope).into()); + } + }); } if let Some(document_handle) = transition.retired_document_handle { self.retire_lightweight_popup_document_handle(popup_id, document_handle); @@ -960,10 +977,13 @@ impl PageScriptHost { response: Option, ) -> Option<(v8::Local<'s, v8::Object>, u64)> { let parsed_url = Url::parse(href).ok()?; - let initial_url = if parsed_url.scheme() == "javascript" { - about_blank_url() - } else { + // A pending navigation starts with an about:blank Document that + // inherits the creator's origin. Explicit about:blank URLs complete + // synchronously, including their query and fragment. + let initial_url = if moli_url::is_about_blank(&parsed_url) { parsed_url.clone() + } else { + about_blank_url() }; let initial_base_url = lightweight_popup_initial_base_url(&initial_url, creator_base_url); let initial_referrer = creator_policy_container.document_referrer.clone(); @@ -1112,6 +1132,16 @@ impl PageScriptHost { let initial_document_state = LightweightPopupDocumentState::new(initial_base_url.clone(), initial_policy_container); let initial_resource_origin = initial_origin.serialized_origin(); + let initial_domain = if !opener_sandbox_policy + .is_some_and(|policy| policy.forces_opaque_origin) + && moli_url::is_about_blank(&initial_url) + { + opener_endpoint + .and_then(|endpoint| self.window_document_domain_state(endpoint.dispatch_scope())) + } else { + None + } + .unwrap_or_default(); let session_storage_store = match opener { Some(opener) => self.cloned_lightweight_popup_session_storage_store( scope, @@ -1139,7 +1169,12 @@ impl PageScriptHost { is_initial_empty_document: true, has_committed_navigation: false, url: initial_url.clone(), - access_origin: Rc::new(RefCell::new(initial_origin)), + access_origin: Rc::new(RefCell::new( + super::window_security_tokens::PopupWindowSecurityOrigin { + origin: initial_origin, + domain: initial_domain, + }, + )), secure_context, state: initial_document_state.clone(), storage_scope, @@ -1159,6 +1194,7 @@ impl PageScriptHost { session_storage_store, })), is_closing: false, + closed_origin: None, navigation_id: LightweightPopupNavigationId::new(1), }, ); @@ -1233,18 +1269,23 @@ impl PageScriptHost { let navigation_id = self .lightweight_popup_navigation_id(popup_id) .expect("newly inserted popup record must have a navigation id"); - let navigation_task = + let mut navigation_task = LightweightPopupNavigationTaskToken::from_parts(initial_document_owner, navigation_id); let queue_synthetic_load = if parsed_url.scheme() == "javascript" { let source = crate::javascript_url::decoded_source(&parsed_url); self.queue_lightweight_popup_javascript_url_task(scope, navigation_task, source); true - } else if moli_url::is_about_blank(&initial_url) { + } else if moli_url::is_about_blank(&parsed_url) { false } else { + navigation_task = self.start_lightweight_popup_navigation_attempt( + popup_id, + parsed_url.clone(), + LightweightPopupNavigationDocumentTarget::NewDocument, + )?; self.start_lightweight_popup_document_load( navigation_task, - initial_url.clone(), + parsed_url, about_blank_url(), initial_document_state, response, @@ -1255,6 +1296,7 @@ impl PageScriptHost { if queue_synthetic_load { self.queue_lightweight_popup_load_event(navigation_task); } + super::child_frame_runtime::mark_popup_window_access_check_initialized(scope, window); Some((window, popup_id)) } @@ -1495,7 +1537,7 @@ impl PageScriptHost { popup_id: u64, ) -> Option { self.lightweight_popup_document_record(popup_id) - .map(|document| document.access_origin.borrow().clone()) + .map(|document| document.access_origin.borrow().current_origin()) } pub(crate) fn lightweight_popup_security_origin( @@ -1508,6 +1550,11 @@ impl PageScriptHost { document.access_origin.clone(), ) }) + .or_else(|| { + self.lightweight_popup_record(popup_id)? + .closed_origin + .clone() + }) } pub(crate) fn lightweight_popup_bound_web_storage_scope( @@ -2356,6 +2403,17 @@ impl PageScriptHost { scope: &mut v8::PinScope<'s, '_>, window: v8::Local<'s, v8::Object>, commit: LightweightPopupDocumentCommit, + ) -> bool { + with_lightweight_popup_scope(scope, commit.owner.popup_id(), |scope| { + self.commit_lightweight_popup_document_in_owner(scope, window, commit) + }) + } + + fn commit_lightweight_popup_document_in_owner<'s>( + &mut self, + scope: &mut v8::PinScope<'s, '_>, + window: v8::Local<'s, v8::Object>, + commit: LightweightPopupDocumentCommit, ) -> bool { let popup_id = commit.owner.popup_id(); let committed_document_url = commit.location_url.clone(); @@ -2368,6 +2426,14 @@ impl PageScriptHost { return false; }; let changed_document = current_document.owner != commit.owner; + let was_initial_empty = current_document.is_initial_empty_document; + let previous_local_window_id = current_document.local_window_id; + let document_domain_was_set = current_document + .access_origin + .borrow() + .domain + .get() + .is_some(); let inherited_resource_authority = (changed_document && commit.navigation_loader.is_none()) .then(|| { self.document_resource_loader_for_window_owner( @@ -2388,9 +2454,21 @@ impl PageScriptHost { moli_url::is_potentially_trustworthy_url(&committed_document_url) } }; - let retained_access_origin = current_document.access_origin.borrow().clone(); + let retained_access_origin = current_document.access_origin.borrow().current_origin(); let retained_origin_state = current_document.access_origin.clone(); - let current_local_window_id = if changed_document { + let domain = if matches!( + commit.origin, + LightweightPopupDocumentCommitOrigin::RetainCurrent + ) { + current_document.access_origin.borrow().domain.clone() + } else { + let domain = super::DocumentDomainState::default(); + if let Some(value) = commit.state.document_domain_override.clone() { + domain.set(value); + } + domain + }; + let mut current_local_window_id = if changed_document { self.allocate_lightweight_popup_local_window_id() } else { current_document.local_window_id @@ -2400,7 +2478,7 @@ impl PageScriptHost { local_window_id: current_local_window_id, }; let access_origin = match commit.origin { - LightweightPopupDocumentCommitOrigin::RetainCurrent => retained_access_origin, + LightweightPopupDocumentCommitOrigin::RetainCurrent => retained_access_origin.clone(), LightweightPopupDocumentCommitOrigin::InheritExact(origin) => origin, LightweightPopupDocumentCommitOrigin::FromNavigationResponse(serialized_origin) => { if serialized_origin == "null" { @@ -2420,8 +2498,29 @@ impl PageScriptHost { } } }; + // The first same-origin navigation can reuse the initial Window even + // though it commits a new Document and its own resource authority. + let reuse_initial_window = changed_document + && was_initial_empty + && !document_domain_was_set + && retained_access_origin.can_access(&access_origin); + if reuse_initial_window { + current_local_window_id = previous_local_window_id; + } + let changed_window = current_local_window_id != previous_local_window_id; let resource_context_origin = access_origin.serialized_origin(); - let access_origin = if changed_document { + if let super::window_security_tokens::WindowAccessOrigin::Tuple { + document_domain: Some(value), + .. + } = &access_origin + { + domain.set(value.clone()); + } + let access_origin = super::window_security_tokens::PopupWindowSecurityOrigin { + origin: access_origin, + domain, + }; + let access_origin = if changed_window { Rc::new(RefCell::new(access_origin)) } else { *retained_origin_state.borrow_mut() = access_origin; @@ -2463,13 +2562,12 @@ impl PageScriptHost { record.location_url = commit.location_url; LightweightPopupDocumentTransition { retired_owner: changed_document.then_some(retired_document.owner), - retired_local_window_id: changed_document - .then_some(retired_document.local_window_id), + retired_local_window_id: changed_window.then_some(retired_document.local_window_id), retired_document_handle: retired_document.handle, current_local_window_id, } }; - if changed_document { + if changed_window { if let Err(error) = crate::context_bootstrap::install_window_bar_props( scope, window, @@ -2768,6 +2866,23 @@ impl PageScriptHost { popup_id: u64, window: v8::Local<'s, v8::Object>, document_url: Url, + ) { + with_lightweight_popup_scope(scope, popup_id, |scope| { + self.install_lightweight_popup_empty_document_in_owner( + scope, + popup_id, + window, + document_url, + ) + }) + } + + fn install_lightweight_popup_empty_document_in_owner<'s>( + &mut self, + scope: &mut v8::PinScope<'s, '_>, + popup_id: u64, + window: v8::Local<'s, v8::Object>, + document_url: Url, ) { clear_lightweight_popup_window_document_event_state(scope, window); self.clear_lightweight_popup_document_projection(popup_id); @@ -3067,12 +3182,26 @@ impl PageScriptHost { .remove(&target.load_id()) .expect("authorized popup terminal must retain its exact pending load"); let popup_id = task.popup_id(); + with_lightweight_popup_scope(scope, popup_id, |scope| { + self.apply_lightweight_popup_document_load_completion_in_owner( + scope, completion, pending, + ) + }) + } + + fn apply_lightweight_popup_document_load_completion_in_owner( + &mut self, + scope: &mut v8::PinScope<'_, '_>, + completion: PopupDocumentLoadCompletion, + pending: PendingLightweightPopupDocumentLoad, + ) -> PopupDocumentLoadApplication { + let task = pending.target.task(); + let popup_id = task.popup_id(); let document_owner = task.document_owner(); let Some(window) = self.lightweight_popup_window(scope, popup_id) else { return PopupDocumentLoadApplication::NotApplied; }; let mut body_activity = PopupDocumentLoadBodyActivity::NoPageCodeOrEventDispatch; - let mut load_event_task = task; let mut classic_script_load_pending = false; match completion.result { Ok(PopupDocumentLoadOutcome::IgnoredNavigation) => { @@ -3081,12 +3210,18 @@ impl PageScriptHost { self, super::OwnerDispatchScope::LightweightPopup(popup_id), ); + // Same-document navigation can update the active Document + // while this request is pending. A 204 must preserve that URL. + let retained_url = self + .lightweight_popup_document_record(popup_id) + .map(|document| document.url.clone()) + .unwrap_or(pending.previous_url); if let Some(record) = self.lightweight_popup_record_mut(popup_id) { - record.location_url = pending.previous_url.clone(); + record.location_url = retained_url.clone(); } self.update_service_worker_popup_client_if_registered( popup_id, - pending.previous_url.clone(), + retained_url.clone(), ); let document_referrer = self .lightweight_popup_document_record(popup_id) @@ -3095,17 +3230,17 @@ impl PageScriptHost { sync_lightweight_popup_window_location( scope, window, - pending.previous_url.as_str(), + retained_url.as_str(), &document_referrer, ); if !self.lightweight_popup_has_document_projection(popup_id) - && moli_url::is_about_blank(&pending.previous_url) + && moli_url::is_about_blank(&retained_url) { self.install_lightweight_popup_empty_document( scope, popup_id, window, - pending.previous_url, + retained_url, ); } self.finish_service_worker_clients_open_window_popup(document_owner); @@ -3251,17 +3386,13 @@ impl PageScriptHost { self, super::OwnerDispatchScope::LightweightPopup(popup_id), ); - let Some(current_owner) = self.current_lightweight_popup_document_owner(popup_id) - else { - return PopupDocumentLoadApplication::Applied { - body_activity, - parser_completion: None, - }; + // The failed response did not create a Document. In particular, + // the initial about:blank Document must not receive lifecycle + // events belonging to this unsuccessful navigation. + return PopupDocumentLoadApplication::Applied { + body_activity, + parser_completion: None, }; - load_event_task = LightweightPopupNavigationTaskToken::from_parts( - current_owner, - task.navigation_id, - ); } } if classic_script_load_pending { @@ -3270,9 +3401,9 @@ impl PageScriptHost { parser_completion: None, }; } - let parser_completion = self.prepare_lightweight_popup_parser_completion(load_event_task); + let parser_completion = self.prepare_lightweight_popup_parser_completion(task); if parser_completion.is_none() { - self.queue_lightweight_popup_load_event(load_event_task); + self.queue_lightweight_popup_load_event(task); } self.finish_service_worker_clients_open_window_popup(document_owner); PopupDocumentLoadApplication::Applied { @@ -3320,8 +3451,16 @@ impl PageScriptHost { &self, popup_id: u64, ) -> Option { + self.lightweight_popup_document_domain_state(popup_id)? + .get() + } + + pub(super) fn lightweight_popup_document_domain_state( + &self, + popup_id: u64, + ) -> Option { self.lightweight_popup_document_record(popup_id) - .and_then(|document| document.state.document_domain_override.clone()) + .map(|document| document.access_origin.borrow().domain.clone()) } pub(crate) fn lightweight_popup_document_domain_is_sandboxed(&self, popup_id: u64) -> bool { @@ -3342,7 +3481,7 @@ impl PageScriptHost { ) -> bool { let Some(serialized_origin) = self .lightweight_popup_document_record(popup_id) - .map(|document| document.access_origin.borrow().serialized_origin()) + .map(|document| document.access_origin.borrow().origin.serialized_origin()) else { return false; }; @@ -3357,8 +3496,9 @@ impl PageScriptHost { let Some(document) = self.lightweight_popup_document_record_mut(popup_id) else { return false; }; + document.access_origin.borrow().domain.set(domain.clone()); document.state.document_domain_override = Some(domain); - *document.access_origin.borrow_mut() = access_origin; + document.access_origin.borrow_mut().origin = access_origin; true } @@ -3751,6 +3891,17 @@ impl PageScriptHost { scope: &mut v8::PinScope<'s, '_>, window: v8::Local<'s, v8::Object>, source: LightweightPopupDocumentProjectionSource<'_>, + ) -> Option { + with_lightweight_popup_scope(scope, source.task.popup_id(), |scope| { + self.install_lightweight_popup_document_projection_in_owner(scope, window, source) + }) + } + + fn install_lightweight_popup_document_projection_in_owner<'s>( + &mut self, + scope: &mut v8::PinScope<'s, '_>, + window: v8::Local<'s, v8::Object>, + source: LightweightPopupDocumentProjectionSource<'_>, ) -> Option { let popup_id = source.task.popup_id(); let use_live_parser = !crate::dom_parser::browsing_context_document_uses_xml_parser( @@ -3776,7 +3927,7 @@ impl PageScriptHost { self.dom_host_mut() .set_document_character_set_for_handle(handle, character_set); } - unsafe { &*self.runtime }.initialize_inherited_meta_content_security_policies( + unsafe { &*self.document_runtime }.initialize_inherited_meta_content_security_policies( handle, &source .policy_container @@ -4544,6 +4695,29 @@ impl PageScriptHost { document: v8::Local<'s, v8::Object>, current_script: Option>, source: &str, + ) -> Result<()> { + with_lightweight_popup_scope(scope, popup_id, |scope| { + self.execute_lightweight_popup_window_script_source_in_context_in_owner( + scope, + popup_id, + script_document_owner, + window, + document, + current_script, + source, + ) + }) + } + + fn execute_lightweight_popup_window_script_source_in_context_in_owner<'s>( + &mut self, + scope: &mut v8::PinScope<'s, '_>, + popup_id: u64, + script_document_owner: LightweightPopupDocumentOwner, + window: v8::Local<'s, v8::Object>, + document: v8::Local<'s, v8::Object>, + current_script: Option>, + source: &str, ) -> Result<()> { if !self.lightweight_popup_document_owner_is_current(script_document_owner) { anyhow::bail!("popup script document owner is no longer current"); @@ -4568,34 +4742,34 @@ impl PageScriptHost { .collect::>() .join(""); let exported_globals = exported_global_names - .into_iter() - .map(|name| { - format!( - "{{\ - let __moliExportedValue = typeof {name} !== 'undefined' ? {name} : window[{name:?}];\ - if (typeof __moliExportedValue !== 'undefined') {{ {name} = __moliExportedValue; __scope[{name:?}] = __moliExportedValue; window[{name:?}] = __moliExportedValue; }}\ - }}" - ) - }) - .collect::>() - .join(""); + .into_iter() + .map(|name| { + format!( + "{{\ + let __moliExportedValue = typeof {name} !== 'undefined' ? {name} : window[{name:?}];\ + if (typeof __moliExportedValue !== 'undefined') {{ {name} = __moliExportedValue; __scope[{name:?}] = __moliExportedValue; window[{name:?}] = __moliExportedValue; }}\ + }}" + ) + }) + .collect::>() + .join(""); let wrapped_source = format!( "(function(__scope, window, document, currentScript, __moliNativeEnterActivePopup, __moliNativeRestoreActivePopup) {{\ - const __prevCurrentScript = document.currentScript ?? null;\ - const __previousActivePopupForScript = __moliNativeEnterActivePopup();\ - try {{\ - Object.defineProperty(document, 'currentScript', {{ configurable: true, enumerable: false, writable: true, value: currentScript }});\ - if (!('onload' in window)) {{ window.onload = null; }}\ - with (__scope) {{\ - with (window) {{\ - {predeclared_globals}\ntry {{\n{source}\n{exported_globals}\n}} finally {{\n{exported_globals}\n}}\ - }}\ + const __prevCurrentScript = document.currentScript ?? null;\ + const __previousActivePopupForScript = __moliNativeEnterActivePopup();\ + try {{\ + Object.defineProperty(document, 'currentScript', {{ configurable: true, enumerable: false, writable: true, value: currentScript }});\ + if (!('onload' in window)) {{ window.onload = null; }}\ + with (__scope) {{\ + with (window) {{\ + {predeclared_globals}\ntry {{\n{source}\n{exported_globals}\n}} finally {{\n{exported_globals}\n}}\ }}\ - }} finally {{\ - __moliNativeRestoreActivePopup(__previousActivePopupForScript);\ - Object.defineProperty(document, 'currentScript', {{ configurable: true, enumerable: false, writable: true, value: __prevCurrentScript }});\ }}\ - }})" + }} finally {{\ + __moliNativeRestoreActivePopup(__previousActivePopupForScript);\ + Object.defineProperty(document, 'currentScript', {{ configurable: true, enumerable: false, writable: true, value: __prevCurrentScript }});\ + }}\ + }})" ); let Some(source) = v8_string(scope, &wrapped_source) else { anyhow::bail!("failed to allocate popup script wrapper source"); @@ -5417,6 +5591,21 @@ impl PageScriptHost { } } +// Synthetic popup Windows share a concrete V8 context with their creator. +// Native Document installation and script bookkeeping still belong to the +// popup's execution owner, including when navigation changed its origin. +fn with_lightweight_popup_scope<'s, 'i, R>( + scope: &mut v8::PinScope<'s, 'i>, + popup_id: u64, + operation: impl FnOnce(&mut v8::PinScope<'s, 'i>) -> R, +) -> R { + let owner = OwnerDispatchScope::LightweightPopup(popup_id); + let previous = owner.enter(scope); + let result = operation(scope); + owner.restore(scope, previous); + result +} + pub(crate) fn lightweight_popup_id_from_window<'s>( scope: &mut v8::PinScope<'s, '_>, window: v8::Local<'s, v8::Object>, @@ -5433,6 +5622,21 @@ pub(super) fn active_lightweight_popup_id_for_context<'s>( scope: &mut v8::PinScope<'s, '_>, context: v8::Local<'s, v8::Context>, ) -> Option { + // V8 restores continuation data separately for each reaction. A main + // Window reaction must not inherit an ambient popup marker from whichever + // native task happened to start this checkpoint. + if context == scope.get_current_context() + && context + .get_microtask_queue() + .is_some_and(v8::MicrotaskQueue::is_running_microtasks) + { + return crate::script_continuation::running_window(scope, context).and_then(|owner| { + match owner.identity.dispatch_scope() { + OwnerDispatchScope::LightweightPopup(popup_id) => Some(popup_id), + _ => None, + } + }); + } let global = context.global(scope); let value = get_private_value(scope, global, ACTIVE_LIGHTWEIGHT_POPUP_ID_SLOT)?; lightweight_popup_id_from_value(scope, value) @@ -5458,6 +5662,8 @@ pub(crate) fn enter_top_level_lightweight_popup_scope<'s>( let global = scope.get_current_context().global(scope); let previous = get_private_value(scope, global, ACTIVE_LIGHTWEIGHT_POPUP_ID_SLOT) .unwrap_or_else(|| v8::undefined(scope).into()); + let continuation = crate::script_continuation::base_url_value(scope); + let previous = enter_popup_continuation(scope, previous, continuation); set_private_value( scope, global, @@ -5471,13 +5677,16 @@ pub(crate) fn defer_active_lightweight_popup_restore<'s>( scope: &mut v8::PinScope<'s, '_>, previous: v8::Local<'s, v8::Value>, ) { - let previous_popup_id = lightweight_popup_id_from_value(scope, previous); + // V8 captured the popup data on the jobs queued inside this scope. Restore + // the caller's continuation immediately, even when the legacy native + // dispatch marker stays active until the checkpoint ends. + let previous = restore_popup_continuation(scope, previous); let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { restore_lightweight_popup_event_dispatch(scope, previous); return; }; - unsafe { &mut *host_ptr } - .defer_active_lightweight_popup_restore_after_microtasks(previous_popup_id); + let previous = lightweight_popup_id_from_value(scope, previous); + unsafe { &mut *host_ptr }.defer_active_lightweight_popup_restore_after_microtasks(previous); } pub(crate) fn restore_deferred_active_lightweight_popup_scope_if_present( @@ -5487,19 +5696,40 @@ pub(crate) fn restore_deferred_active_lightweight_popup_scope_if_present( let Some(previous) = host.take_deferred_active_lightweight_popup_restore() else { return false; }; - restore_active_lightweight_popup_scope_to_id(scope, previous); + let previous = previous + .map(|id| v8::BigInt::new_from_u64(scope, id).into()) + .unwrap_or_else(|| v8::undefined(scope).into()); + restore_lightweight_popup_event_dispatch(scope, previous); true } -fn restore_active_lightweight_popup_scope_to_id( - scope: &mut v8::PinScope<'_, '_>, - popup_id: Option, -) { - let value = popup_id - .map(|popup_id| v8::BigInt::new_from_u64(scope, popup_id).into()) - .unwrap_or_else(|| v8::undefined(scope).into()); - let global = scope.get_current_context().global(scope); - set_private_value(scope, global, ACTIVE_LIGHTWEIGHT_POPUP_ID_SLOT, value); +const POPUP_SCOPE_PREVIOUS_MARKER: &str = "moli.popupScopePreviousMarker"; +const POPUP_SCOPE_PREVIOUS_CONTINUATION: &str = "moli.popupScopePreviousContinuation"; + +fn enter_popup_continuation<'s>( + scope: &mut v8::PinScope<'s, '_>, + previous_marker: v8::Local<'s, v8::Value>, + continuation: v8::Local<'s, v8::Value>, +) -> v8::Local<'s, v8::Value> { + let previous_continuation = scope.get_continuation_preserved_embedder_data(); + if continuation.strict_equals(previous_continuation) { + return previous_marker; + } + let previous = v8::Object::new(scope); + set_private_value( + scope, + previous, + POPUP_SCOPE_PREVIOUS_MARKER, + previous_marker, + ); + set_private_value( + scope, + previous, + POPUP_SCOPE_PREVIOUS_CONTINUATION, + previous_continuation, + ); + scope.set_continuation_preserved_embedder_data(continuation); + previous.into() } fn enter_lightweight_popup_event_dispatch<'s>( @@ -5509,6 +5739,22 @@ fn enter_lightweight_popup_event_dispatch<'s>( let global = scope.get_current_context().global(scope); let previous = get_private_value(scope, global, ACTIVE_LIGHTWEIGHT_POPUP_ID_SLOT) .unwrap_or_else(|| v8::undefined(scope).into()); + let owner = context_host_ptr_from_global_bridge(scope).and_then(|host_ptr| { + let host = unsafe { &*host_ptr }; + Some(crate::script_continuation::WindowContinuation { + identity: host.current_runtime_window_execution_context_identity_for_dispatch_scope( + scope, + OwnerDispatchScope::LightweightPopup(popup_id), + )?, + origin: host.lightweight_popup_security_origin(popup_id)?, + }) + }); + let previous = if let Some(owner) = owner { + let continuation = crate::script_continuation::with_window(scope, owner); + enter_popup_continuation(scope, previous, continuation) + } else { + previous + }; let value = v8::BigInt::new_from_u64(scope, popup_id); set_private_value( scope, @@ -5523,10 +5769,35 @@ fn restore_lightweight_popup_event_dispatch<'s>( scope: &mut v8::PinScope<'s, '_>, previous: v8::Local<'s, v8::Value>, ) { + let previous = restore_popup_continuation(scope, previous); let global = scope.get_current_context().global(scope); set_private_value(scope, global, ACTIVE_LIGHTWEIGHT_POPUP_ID_SLOT, previous); } +fn restore_popup_continuation<'s>( + scope: &mut v8::PinScope<'s, '_>, + previous: v8::Local<'s, v8::Value>, +) -> v8::Local<'s, v8::Value> { + v8::Local::::try_from(previous) + .ok() + .and_then(|snapshot| { + // The ordinary helper treats undefined as a missing slot. Both + // saved values can legitimately be undefined when entering from + // the main Window, and must still be restored in that case. + let marker_key = moli_v8_util::private_key(scope, POPUP_SCOPE_PREVIOUS_MARKER)?; + if snapshot.has_private(scope, marker_key) != Some(true) { + return None; + } + let marker = snapshot.get_private(scope, marker_key)?; + let continuation_key = + moli_v8_util::private_key(scope, POPUP_SCOPE_PREVIOUS_CONTINUATION)?; + let continuation = snapshot.get_private(scope, continuation_key)?; + scope.set_continuation_preserved_embedder_data(continuation); + Some(marker) + }) + .unwrap_or(previous) +} + fn install_lightweight_popup_indexed_db_factory<'s>( scope: &mut v8::PinScope<'s, '_>, window: v8::Local<'s, v8::Object>, @@ -5701,14 +5972,14 @@ fn lightweight_popup_window_opener_setter<'s>( return; }; let host = unsafe { &mut *host_ptr }; + let Some(window) = host.lightweight_popup_window(scope, popup_id) else { + return; + }; let value = args.get(0); if value.is_null() { host.clear_lightweight_popup_opener(popup_id); return; } - let Some(window) = host.lightweight_popup_window(scope, popup_id) else { - return; - }; match window.define_own_property( scope, v8str(scope, "opener").into(), @@ -5721,7 +5992,7 @@ fn lightweight_popup_window_opener_setter<'s>( } } -fn lightweight_popup_close_callback<'s>( +pub(super) fn lightweight_popup_close_callback<'s>( scope: &mut v8::PinScope<'s, '_>, args: v8::FunctionCallbackArguments<'s>, _rv: v8::ReturnValue<'_, v8::Value>, @@ -5738,12 +6009,15 @@ fn lightweight_popup_close_callback<'s>( return; } host.dispatch_lightweight_popup_tree_beforeunload(scope, popup_id); + let owner = OwnerDispatchScope::LightweightPopup(popup_id); + let previous = owner.enter(scope); set_object_slot( scope, window, "closed", v8::Boolean::new(scope, true).into(), ); + owner.restore(scope, previous); if host.page_popup_close_sender().send(popup_id).is_err() { tracing::debug!( popup_id, diff --git a/moli-renderer-v8/src/native_bridge/context_host/runtime_observable.rs b/moli-renderer-v8/src/native_bridge/context_host/runtime_observable.rs index 1ed90e6e0ec..0403220e6c2 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/runtime_observable.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/runtime_observable.rs @@ -290,6 +290,11 @@ impl PageScriptHost { &self, scope: &mut v8::PinScope<'_, '_>, ) -> Option { + if let Some(owner) = + crate::script_continuation::running_window(scope, scope.get_current_context()) + { + return Some(owner.identity); + } let dispatch_scope = if let Some(popup_id) = active_lightweight_popup_id(scope) { OwnerDispatchScope::LightweightPopup(popup_id) } else if let Some(child_handle) = 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 7f4035ce433..a5470099635 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 @@ -130,7 +130,25 @@ pub(crate) struct WindowSecurityOrigin(WindowSecurityOriginSource); #[derive(Clone)] enum WindowSecurityOriginSource { Context(Rc), - Popup(Rc>), + Popup(Rc>), +} + +pub(super) struct PopupWindowSecurityOrigin { + pub(super) origin: WindowAccessOrigin, + pub(super) domain: DocumentDomainState, +} + +impl PopupWindowSecurityOrigin { + pub(super) fn current_origin(&self) -> WindowAccessOrigin { + let mut origin = self.origin.clone(); + if let WindowAccessOrigin::Tuple { + document_domain, .. + } = &mut origin + { + *document_domain = self.domain.get(); + } + origin + } } impl WindowSecurityOrigin { @@ -140,14 +158,14 @@ impl WindowSecurityOrigin { .map(|origin| Self(WindowSecurityOriginSource::Context(Rc::clone(&origin)))) } - pub(super) fn for_popup(origin: Rc>) -> Self { + pub(super) fn for_popup(origin: Rc>) -> Self { Self(WindowSecurityOriginSource::Popup(origin)) } fn current_origin(&self) -> WindowAccessOrigin { match &self.0 { WindowSecurityOriginSource::Context(origin) => origin.current_origin(), - WindowSecurityOriginSource::Popup(origin) => origin.borrow().clone(), + WindowSecurityOriginSource::Popup(origin) => origin.borrow().current_origin(), } } @@ -234,6 +252,19 @@ impl PageScriptHost { )) } + pub(super) fn window_document_domain_state( + &self, + owner: OwnerDispatchScope, + ) -> Option { + match owner { + OwnerDispatchScope::Top => Some(self.document_domain_override.clone()), + OwnerDispatchScope::Child(handle) => self.child_document_domain_state(handle), + OwnerDispatchScope::LightweightPopup(id) => { + self.lightweight_popup_document_domain_state(id) + } + } + } + pub(crate) fn window_dispatch_scope_for_context<'s>( &self, scope: &mut v8::PinScope<'s, '_>, @@ -252,6 +283,9 @@ impl PageScriptHost { scope: &mut v8::PinScope<'s, '_>, context: v8::Local<'s, v8::Context>, ) -> Option { + if let Some(owner) = crate::script_continuation::running_window(scope, context) { + return Some(owner.origin); + } // Read the scope of the requested realm, not the callback's current // realm: popup bindings can call into a real child, and a popup can // itself share a child opener's concrete V8 context. @@ -495,16 +529,19 @@ impl PageScriptHost { ) -> usize { let target_child = self.child_browsing_context_handle_for_stored_document(document_handle); let target_is_main = document_handle == self.document_handle(); - if !target_is_main && target_child.is_none() { - // Lightweight popups still share the opener V8 context. Until they have a concrete - // LocalWindow realm, changing that shared context token would also mutate the opener. + let target_popup = self.lightweight_popup_id_for_document_handle(document_handle); + if !target_is_main && target_child.is_none() && target_popup.is_none() { 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)) + target_child + .and_then(|handle| self.child_document_domain_state(handle)) + .or_else(|| { + target_popup.and_then(|id| self.lightweight_popup_document_domain_state(id)) + }) }; if let Some(domain) = domain { domain.invalidate_context_tokens(scope); @@ -750,20 +787,6 @@ impl PageScriptHost { top.has_same_origin(&child) } - pub(in crate::native_bridge::context_host) fn child_window_can_access_lightweight_popup( - &self, - handle: DomHandle, - popup_id: u64, - ) -> bool { - let Some(child) = self.child_window_access_origin(handle) else { - return false; - }; - let Some(popup) = self.lightweight_popup_window_access_origin(popup_id) else { - return false; - }; - child.can_access(&popup) - } - pub(crate) fn window_execution_context_can_access( &self, accessing: WindowExecutionContextIdentity, diff --git a/moli-renderer-v8/src/native_bridge/mod.rs b/moli-renderer-v8/src/native_bridge/mod.rs index fa53532bf19..172c5dec0f0 100644 --- a/moli-renderer-v8/src/native_bridge/mod.rs +++ b/moli-renderer-v8/src/native_bridge/mod.rs @@ -74,9 +74,9 @@ pub(crate) use context_host::{ lightweight_popup_id_from_window, remember_isolated_window_context, restore_active_lightweight_popup_scope, restore_deferred_active_lightweight_popup_scope_if_present, - throw_cross_origin_location_security_error, throw_cross_origin_type_error, - window_context_in_wrapper_world, window_contexts_allow_access, window_event_access, - window_in_wrapper_world, + synthetic_window_context_can_access, throw_cross_origin_location_security_error, + throw_cross_origin_type_error, window_context_in_wrapper_world, window_contexts_allow_access, + window_event_access, window_in_wrapper_world, }; #[cfg(test)] pub(crate) use context_host::{IsolatedWindowWorldId, install_isolated_window_world_for_context}; diff --git a/moli-renderer-v8/src/native_bridge/window.rs b/moli-renderer-v8/src/native_bridge/window.rs index 9dda688dbc5..fcfab86c603 100644 --- a/moli-renderer-v8/src/native_bridge/window.rs +++ b/moli-renderer-v8/src/native_bridge/window.rs @@ -17,6 +17,7 @@ pub(super) fn build_window_wrapper_template<'s, 'i>( // global interface surface from Window.prototype because [Global] // interface members are own properties in Blink and Web IDL. crate::context_bootstrap::install_window_own_template_bindings(scope, template); + super::context_host::install_synthetic_window_access_check_handlers(template); template } diff --git a/moli-renderer-v8/src/resource_initiator.rs b/moli-renderer-v8/src/resource_initiator.rs index 4fc343379e0..c60619ef519 100644 --- a/moli-renderer-v8/src/resource_initiator.rs +++ b/moli-renderer-v8/src/resource_initiator.rs @@ -11,15 +11,15 @@ use url::Url; const SEPARATOR: char = '\0'; pub(crate) fn anchor<'s>(scope: &mut v8::PinScope<'s, '_>) -> Option> { - let data = - v8::Local::::try_from(scope.get_continuation_preserved_embedder_data()).ok()?; + let data = v8::Local::::try_from(crate::script_continuation::base_url_value(scope)) + .ok()?; let data = data.to_rust_string_lossy(scope); let (_, anchor) = data.split_once(SEPARATOR)?; v8_string(scope, anchor) } pub(crate) fn base_url_value<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> { - let data = scope.get_continuation_preserved_embedder_data(); + let data = crate::script_continuation::base_url_value(scope); if let Ok(value) = v8::Local::::try_from(data) && let Some((base, _)) = value.to_rust_string_lossy(scope).split_once(SEPARATOR) { @@ -47,10 +47,11 @@ pub(crate) fn with_base_url<'s>( scope: &mut v8::PinScope<'s, '_>, base: v8::Local<'s, v8::Value>, ) -> v8::Local<'s, v8::Value> { - match anchor(scope) { + let data = match anchor(scope) { Some(anchor) => data_with_anchor(scope, base, anchor), None => base, - } + }; + crate::script_continuation::with_base_url(scope, data) } pub(crate) fn classic_data<'s>( @@ -88,7 +89,8 @@ pub(crate) fn classic_data<'s>( ), ) .expect("resource initiator URLs must fit in a V8 string"); - data_with_anchor(scope, base, anchor) + let data = data_with_anchor(scope, base, anchor); + crate::script_continuation::with_base_url(scope, data) } pub(crate) fn current_url(scope: &mut v8::PinScope<'_, '_>, origin: &WebOrigin) -> String { @@ -193,6 +195,7 @@ pub(crate) fn with_callback_anchor<'s, R>( let previous = scope.get_continuation_preserved_embedder_data(); let base = base_url_value(scope); let data = data_with_anchor(scope, base, anchor); + let data = crate::script_continuation::with_base_url(scope, data); scope.set_continuation_preserved_embedder_data(data); let result = invoke(scope); scope.set_continuation_preserved_embedder_data(previous); diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/hash_change_delivery.rs b/moli-renderer-v8/src/runtime/page_vm/tests/hash_change_delivery.rs index 0a8fce1252f..d289daabd3e 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/hash_change_delivery.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/hash_change_delivery.rs @@ -454,7 +454,24 @@ async fn hashchange_discards_a_retired_lightweight_popup_local_window() { r##" globalThis.__popupHashChanges = []; globalThis.__hashPopup = open("about:blank", "hashchange-owner-popup"); -__hashPopup.history.replaceState(null, "", "about:blank#popup-hashchange"); +__hashPopup.location.href = "about:blank?committed"; +"initial-window-reused" +"##, + )?; + // The first same-origin commit reuses the initial Window. Complete + // its lifecycle tasks before queuing the hashchange in the same lane. + while page_vm + .run_exact_selected_page_task_for_test( + PageSelectedTaskTestSelector::DomManipulation( + PageDomManipulationTestFamily::PopupDocumentLifecycle, + ), + &loader, + ) + .await? + {} + page_vm.vm_mut().eval( + r##" +__hashPopup.history.replaceState(null, "", "about:blank?committed#popup-hashchange"); __hashPopup.addEventListener("hashchange", () => __popupHashChanges.push("retired")); __hashPopup.location.hash = "#queued-before-replacement"; open("about:blank", "hashchange-owner-popup"); diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/popup_document_completion.rs b/moli-renderer-v8/src/runtime/page_vm/tests/popup_document_completion.rs index 195e6eec031..f549a6e53f2 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/popup_document_completion.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/popup_document_completion.rs @@ -1024,7 +1024,7 @@ async fn failed_popup_fetch_settles_only_its_exact_current_load() { ); assert!(!queue.has_ready_completion()); assert!( - page_vm + !page_vm .run_exact_selected_page_task_for_test( PageSelectedTaskTestSelector::DomManipulation( PageDomManipulationTestFamily::PopupDocumentLifecycle, @@ -1032,14 +1032,14 @@ async fn failed_popup_fetch_settles_only_its_exact_current_load() { &loader, ) .await?, - "the failed fetch must consume its queued completion without requiring a Document", + "a failed response must not queue a lifecycle event on the initial Document", ); assert_eq!( page_vm .vm_mut() .eval("JSON.stringify(__failedPopupEvents)")?, "[]", - "a popup with no materialized Document must not dispatch load events for its opener", + "a failed navigation must not dispatch load events on the initial Document", ); Ok::<_, anyhow::Error>(()) }) diff --git a/moli-renderer-v8/src/script_continuation.rs b/moli-renderer-v8/src/script_continuation.rs new file mode 100644 index 00000000000..a51327c8aec --- /dev/null +++ b/moli-renderer-v8/src/script_continuation.rs @@ -0,0 +1,116 @@ +//! Exact Window identity carried across Promise reactions without retaining a Realm. +use crate::native_bridge::{ + RuntimeObservableContextToken, WindowExecutionContextIdentity, WindowSecurityOrigin, +}; +use std::{ + cell::RefCell, + collections::HashMap, + rc::{Rc, Weak}, +}; + +#[derive(Clone)] +pub(crate) struct WindowContinuation { + pub(crate) identity: WindowExecutionContextIdentity, + pub(crate) origin: WindowSecurityOrigin, +} + +struct ContinuationData { + window: WindowContinuation, + // Resource provenance remains a primitive string, including its native NUL fields. + payload: Option>, +} + +type Continuations = Rc>>>; + +fn data(scope: &mut v8::PinScope<'_, '_>) -> Option> { + let external = + v8::Local::::try_from(scope.get_continuation_preserved_embedder_data()) + .ok()?; + // An External is only an opaque key. Validate it in this isolate's registry; + // no author value or unrelated native pointer is ever dereferenced. + let key = external.value() as usize; + let registry = scope.get_slot::()?; + registry.borrow().get(&key).and_then(Weak::upgrade) +} + +pub(crate) fn base_url_value<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> { + match data(scope) { + Some(data) => { + if let Some(payload) = data.payload.as_ref() { + v8::Local::new(scope, payload).into() + } else { + v8::undefined(scope).into() + } + } + None => scope.get_continuation_preserved_embedder_data(), + } +} + +fn window(scope: &mut v8::PinScope<'_, '_>) -> Option { + data(scope).map(|data| data.window.clone()) +} + +pub(crate) fn running_window<'s>( + scope: &mut v8::PinScope<'s, '_>, + context: v8::Local<'s, v8::Context>, +) -> Option { + if context != scope.get_current_context() + || !context + .get_microtask_queue() + .is_some_and(v8::MicrotaskQueue::is_running_microtasks) + { + return None; + } + let owner = window(scope)?; + let token = context.get_slot::()?; + (owner.identity.realm_token() == *token).then_some(owner) +} + +fn data_with_window<'s>( + scope: &mut v8::PinScope<'s, '_>, + payload: v8::Local<'s, v8::Value>, + window: WindowContinuation, +) -> v8::Local<'s, v8::Value> { + let registry = if let Some(registry) = scope.get_slot::() { + Rc::clone(registry) + } else { + let registry = Rc::new(RefCell::new(HashMap::new())); + scope.set_slot(Rc::clone(®istry)); + registry + }; + let data = Rc::new(ContinuationData { + window, + payload: v8::Local::::try_from(payload) + .ok() + .map(|payload| v8::Global::new(scope, payload)), + }); + let key = Rc::as_ptr(&data) as usize; + registry.borrow_mut().insert(key, Rc::downgrade(&data)); + let external = v8::External::new(scope, key as *mut std::ffi::c_void); + crate::v8_finalizer::track_context_owned_external_finalizer(scope, external, move || { + registry.borrow_mut().remove(&key); + drop(data); + }); + external.into() +} + +pub(crate) fn with_base_url<'s>( + scope: &mut v8::PinScope<'s, '_>, + payload: v8::Local<'s, v8::Value>, +) -> v8::Local<'s, v8::Value> { + match window(scope) { + Some(window) => data_with_window(scope, payload, window), + None => payload, + } +} + +pub(crate) fn with_window<'s>( + scope: &mut v8::PinScope<'s, '_>, + owner: WindowContinuation, +) -> v8::Local<'s, v8::Value> { + if window(scope).is_some_and(|current| current.identity == owner.identity) { + return scope.get_continuation_preserved_embedder_data(); + } + let payload = base_url_value(scope); + data_with_window(scope, payload, owner) +} diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/popup_window.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/popup_window.rs index f0185125390..9d8a6ee5e9a 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/popup_window.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/misc/extracted/popup_window.rs @@ -134,11 +134,35 @@ async fn window_open_lightweight_named_reuse_updates_dom_opener_synchronously() #[tokio::test] async fn retained_popup_storage_managers_use_bound_popup_owner() { + let server = StaticHttpServer::spawn_with_bodies(vec![ + "" + .to_owned(), + ]) + .await; + let popup_url = server.url_for_host("127.0.0.1", "/popup"); + let opener_url = server.url_for_host("localhost", "/opener"); let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader"); - loader.set_network_offline(true); - let mut vm = new_storage_page_task_executor_test_vm_with_loader( - "https://popup-storage-owner.test/page.html", + let mut vm = new_storage_page_task_executor_test_vm_with_loader(opener_url.as_str(), &loader); + vm.eval(&format!( + "globalThis.__popupStorageReady = false; \ + onmessage = e => __popupStorageReady = e.data === 'storage-ready'; \ + globalThis.__popupStorageOwnerPopup = open({:?}); true", + popup_url.as_str(), + )) + .unwrap(); + advance_page_task_executor_until_eval_equals( + &mut vm, &loader, + "String(__popupStorageReady)", + "true", + "popup storage owner response", + ) + .await; + assert_eq!( + vm.eval("try { __popupStorageOwnerPopup.navigator; 'accessible'; } catch (e) { e.name; }") + .unwrap(), + "SecurityError" ); // Seed quota-managed bytes for the popup's origin independently of the // retained JS receiver. Reading through the opener's owner would report 0. @@ -164,14 +188,53 @@ async fn retained_popup_storage_managers_use_bound_popup_owner() { .unwrap(); } + // Capture the actual native popup's managers under its owner. Page script + // cannot obtain these objects through a cross-origin Window, but this test + // exercises retained receiver ownership independently of Window access. + vm.with_default_context_scope(|scope, host_ptr| { + let host = unsafe { &*host_ptr }; + let popup_id = host.open_lightweight_popup_ids()[0]; + let owner = crate::native_bridge::OwnerDispatchScope::LightweightPopup(popup_id); + let previous = owner.enter(scope); + let popup = host.lightweight_popup_window(scope, popup_id).unwrap(); + let navigator = popup + .get(scope, crate::util::v8str(scope, "navigator").into()) + .and_then(|value| v8::Local::::try_from(value).ok()) + .unwrap(); + let storage = navigator + .get(scope, crate::util::v8str(scope, "storage").into()) + .unwrap(); + let buckets = navigator + .get(scope, crate::util::v8str(scope, "storageBuckets").into()) + .unwrap(); + owner.restore(scope, previous); + let global = scope.get_current_context().global(scope); + assert_eq!( + global.set( + scope, + crate::util::v8str(scope, "__retainedPopupStorage").into(), + storage + ), + Some(true) + ); + assert_eq!( + global.set( + scope, + crate::util::v8str(scope, "__retainedPopupBuckets").into(), + buckets + ), + Some(true) + ); + Ok(()) + }) + .unwrap(); + vm.exec( r#" globalThis.__popupStorageOwnerProbe = "pending"; (async () => { - const popup = open("https://popup-storage-owner-child.test/page.html"); - popup.localStorage.setItem("popup-local", "value"); - const storage = popup.navigator.storage; - const buckets = popup.navigator.storageBuckets; + const storage = __retainedPopupStorage; + const buckets = __retainedPopupBuckets; const bucket = await buckets.open("popup-retained", { quota: 2048 }); const popupEstimate = await storage.estimate(); const topEstimate = await navigator.storage.estimate(); @@ -210,24 +273,19 @@ globalThis.__popupStorageOwnerProbe = "pending"; ); assert_eq!( vm.storage_bucket_keys_for_test( - &moli_storage_key::MoliStorageKey::first_party_from_url( - &url::Url::parse("https://popup-storage-owner-child.test").unwrap(), - None, - ) - .serialized_storage_key() + &moli_storage_key::MoliStorageKey::first_party_from_url(&popup_url, None,) + .serialized_storage_key() ), vec!["popup-retained"] ); assert_eq!( vm.storage_bucket_keys_for_test( - &moli_storage_key::MoliStorageKey::first_party_from_url( - &url::Url::parse("https://popup-storage-owner.test").unwrap(), - None, - ) - .serialized_storage_key() + &moli_storage_key::MoliStorageKey::first_party_from_url(&opener_url, None,) + .serialized_storage_key() ), Vec::::new() ); + assert_eq!(server.finish_targets().await.len(), 1); } #[test] fn window_open_rejects_invalid_urls_before_selecting_a_target() { @@ -775,7 +833,7 @@ async fn window_open_named_lightweight_popup_reuse_pushes_history_and_back_trave globalThis.__namedPopupSecondUrl = URL.createObjectURL(new Blob([secondHtml], { type: "text/html" })); globalThis.__namedPopup = open(__namedPopupFirstUrl, "namedPopupHistoryWindow"); return [ - __namedPopup.location.href === __namedPopupFirstUrl, + __namedPopup.location.href === "about:blank", __namedPopup.history.length, __namedPopupHistoryEvents.length ].join("|"); @@ -793,6 +851,11 @@ async fn window_open_named_lightweight_popup_reuse_pushes_history_and_back_trave ) .await; + assert_eq!( + vm.eval("__namedPopup.location.href === __namedPopupFirstUrl") + .expect("first popup response URL should commit"), + "true" + ); let reopened = vm .eval( r#" @@ -1249,16 +1312,22 @@ async fn window_open_non_about_returns_lightweight_popup_and_dispatches_load() { globalThis.__popupLoadEvents = []; const url = URL.createObjectURL(new Blob(["popup"], { type: "text/html" })); const popup = open(url); + const initialLocation = popup.location; + const initialNavigator = popup.navigator; + const initialDocument = popup.document; popup.onload = () => { __popupLoadEvents.push([ popup.location.href.startsWith("blob:https://example.com/"), popup.opener === window, - typeof popup.close + typeof popup.close, + popup.location === initialLocation, + popup.navigator === initialNavigator, + popup.document === initialDocument ].join("|")); }; return [ String(popup), - popup.location.href.startsWith("blob:https://example.com/"), + popup.location.href === "about:blank", popup.opener === window, typeof popup.close ].join("|"); @@ -1279,7 +1348,7 @@ async fn window_open_non_about_returns_lightweight_popup_and_dispatches_load() { assert_eq!( vm.eval("globalThis.__popupLoadEvents.join(',')") .expect("popup load event log should evaluate"), - "true|true|function" + "true|true|function|true|true|false" ); } #[tokio::test] @@ -1916,7 +1985,7 @@ async fn window_open_204_popup_ignores_navigation_and_preserves_initial_empty_hi "# )) .expect("204 popup setup should evaluate"); - assert_eq!(setup, format!("{popup_url}|1")); + assert_eq!(setup, "about:blank|1"); let result = vm .eval( @@ -2957,9 +3026,16 @@ async fn lightweight_popup_document_domain_self_assignment_uses_popup_owner_stat const popup = open({popup_url_literal}); popup.onload = () => {{ try {{ - const initial = popup.document.domain; - popup.document.domain = popup.document.domain; - __popupDomainProbe.push(`${{initial}}|${{popup.document.domain}}`); + const retainedDocument = popup.document; + const initial = retainedDocument.domain; + retainedDocument.domain = retainedDocument.domain; + __popupDomainProbe.push(`${{initial}}|${{retainedDocument.domain}}`); + try {{ + popup.document; + __popupDomainProbe.push("unexpected-access"); + }} catch (error) {{ + __popupDomainProbe.push(error.name); + }} }} catch (error) {{ __popupDomainProbe.push(`${{error.name}}:${{error instanceof DOMException}}:${{error.code}}`); }} @@ -2984,7 +3060,7 @@ async fn lightweight_popup_document_domain_self_assignment_uses_popup_owner_stat &mut vm, &loader, "String(__popupDomainProbe.length)", - "1", + "2", "popup document-domain load event", ) .await; @@ -2992,7 +3068,7 @@ async fn lightweight_popup_document_domain_self_assignment_uses_popup_owner_stat assert_eq!( vm.eval("__popupDomainProbe.join('|')") .expect("popup document-domain result should evaluate"), - "127.0.0.1|127.0.0.1" + "127.0.0.1|127.0.0.1|SecurityError" ); } #[tokio::test] diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/user_activation.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/user_activation.rs index fbd7e6525c6..52f040fc01a 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/user_activation.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/user_activation.rs @@ -128,7 +128,7 @@ fn user_activation_isolated_realm_shares_the_window_state() { #[test] fn user_activation_popup_navigation_keeps_retained_state_separate_from_new_window() { let mut vm = activation_vm(); - vm.eval("globalThis.popup = open('about:blank'); globalThis.savedNavigator = popup.navigator; globalThis.savedActivation = savedNavigator.userActivation").unwrap(); + vm.eval("globalThis.popup = open('about:blank'); popup.location.href = 'about:blank?committed'; globalThis.savedNavigator = popup.navigator; globalThis.savedActivation = savedNavigator.userActivation").unwrap(); assert_eq!(vm.eval("typeof popup.UserActivation === 'function' && Object.getPrototypeOf(savedActivation) === popup.UserActivation.prototype").unwrap(), "true"); let popup_id = vm._context_host.borrow().open_lightweight_popup_ids()[0]; vm._context_host diff --git a/moli-renderer-v8/src/script_vm/tests/extracted/realms_and_teardown.rs b/moli-renderer-v8/src/script_vm/tests/extracted/realms_and_teardown.rs index 625b8838fca..77495833f65 100644 --- a/moli-renderer-v8/src/script_vm/tests/extracted/realms_and_teardown.rs +++ b/moli-renderer-v8/src/script_vm/tests/extracted/realms_and_teardown.rs @@ -2212,6 +2212,7 @@ async fn popup_replacement_retires_local_window_owned_webcrypto_tasks() { vm.eval( r#" globalThis.__ownerBoundCryptoPopup = open("about:blank", "crypto-owner-popup"); + __ownerBoundCryptoPopup.location.href = "about:blank?committed"; String(globalThis.__ownerBoundCryptoPopup !== null) "#, ) diff --git a/moli-renderer-v8/src/script_vm/tests/extracted/workers.rs b/moli-renderer-v8/src/script_vm/tests/extracted/workers.rs index e666a38913d..405a9aadc83 100644 --- a/moli-renderer-v8/src/script_vm/tests/extracted/workers.rs +++ b/moli-renderer-v8/src/script_vm/tests/extracted/workers.rs @@ -267,6 +267,7 @@ async fn popup_replacement_retires_local_window_owned_dedicated_worker() { "about:blank", "dedicated-worker-owner-popup" ); + __ownerBoundWorkerPopup.location.href = "about:blank?committed"; String(globalThis.__ownerBoundWorkerPopup !== null) "#, ) diff --git a/moli-renderer-v8/src/script_vm/tests/popup_root_window.rs b/moli-renderer-v8/src/script_vm/tests/popup_root_window.rs index c44b322e060..4ff82c3e310 100644 --- a/moli-renderer-v8/src/script_vm/tests/popup_root_window.rs +++ b/moli-renderer-v8/src/script_vm/tests/popup_root_window.rs @@ -1,5 +1,137 @@ use super::*; +#[tokio::test] +async fn initial_popup_aliases_its_creators_document_domain_in_both_directions() { + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap(); + let mut vm = new_storage_page_task_executor_test_vm_with_loader( + "https://www.example.test/opener", + &loader, + ); + assert_eq!( + vm.eval( + r#" + const popup = open(); + popup.document.body.textContent = 'popup'; + const initialDomain = popup.document.domain; + const frame = document.createElement('iframe'); + document.body.append(frame); + const childPopup = frame.contentWindow.open(); + document.domain = document.domain; + const before = [popup.document.domain, childPopup.document.domain]; + popup.document.domain = 'example.test'; + JSON.stringify([initialDomain, ...before, document.domain, frame.contentWindow.document.domain, + popup.document.domain, childPopup.document.domain, popup.document.body.textContent]); + "#, + ).unwrap(), + r#"["www.example.test","www.example.test","www.example.test","example.test","example.test","example.test","example.test","popup"]"# + ); +} + +#[tokio::test] +async fn popup_window_promise_reactions_keep_their_origin_without_granting_it_to_the_opener() { + const SOURCE: &str = include_str!("../../../tests/fixtures/popup-window-async.js"); + let server = StaticHttpServer::spawn_with_bodies(vec![format!( + "popup" + )]) + .await; + let loader = static_http_loader([ + server.resolve_entry("www.example.test"), + server.resolve_entry("remote.example.test"), + ]); + let mut vm = new_storage_page_task_executor_test_vm_with_loader( + server.url_for_host("www.example.test", "/opener").as_str(), + &loader, + ); + vm.eval(&format!( + r#" + globalThis.popupMessages = []; + onmessage = event => {{ + popupMessages.push(event.data); + Promise.resolve().then(() => {{ + let result; + try {{ result = popup.document.title; }} catch (error) {{ result = error.name; }} + popupMessages.push({{kind: "main-" + event.data.kind, result}}); + }}); + }}; + globalThis.popup = open({:?}); true; + "#, + server + .url_for_host("remote.example.test", "/popup") + .as_str() + )) + .unwrap(); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(popupMessages.length)", + "6", + "popup Promise reactions", + ) + .await; + let result: serde_json::Value = serde_json::from_str( + &vm.eval("JSON.stringify(popupMessages.sort((a, b) => a.kind.localeCompare(b.kind)))") + .unwrap(), + ) + .unwrap(); + assert_eq!( + result, + serde_json::json!([ + {"kind":"await", "title":"popup"}, + {"kind":"catch", "title":"popup"}, + {"kind":"main-await", "result":"SecurityError"}, + {"kind":"main-catch", "result":"SecurityError"}, + {"kind":"main-then", "result":"SecurityError"}, + {"kind":"then", "title":"popup", "self":true}, + ]) + ); + + let popup_id = vm._context_host.borrow().open_lightweight_popup_ids()[0]; + vm.with_default_context_scope_and_checkpoint_for_test(|scope, _| { + fn run_body(scope: &mut v8::PinScope<'_, '_>, source: &str) { + let source = crate::util::v8_string(scope, source).unwrap(); + let script = v8::Script::compile(scope, source, None).unwrap(); + crate::script_execution::execute_compiled_script(scope, script).unwrap(); + } + run_body( + scope, + r#" + globalThis.retainedPopupReaction = []; globalThis.newWindowReaction = []; + globalThis.popupNavigationError = null; + Promise.resolve().then(() => { + popup.location.href = "about:blank"; + }).catch(error => { popupNavigationError = error.name; }); + "#, + ); + let owner = crate::native_bridge::OwnerDispatchScope::LightweightPopup(popup_id); + let previous = owner.enter(scope); + // Keep this job queued while a new LocalWindow commits. Its origin + // must remain that of the old popup, even after the proxy becomes + // same-origin with the opener. + run_body( + scope, + r#"Promise.resolve().then(() => { + try { retainedPopupReaction.push(popup.document.URL); } + catch (error) { retainedPopupReaction.push(error.name); } + });"#, + ); + owner.restore(scope, previous); + run_body( + scope, + r#" + Promise.resolve().then(() => newWindowReaction.push(popup.document.URL)); + "#, + ); + Ok(()) + }) + .unwrap(); + assert_eq!( + vm.eval("JSON.stringify([retainedPopupReaction, newWindowReaction, popupNavigationError])") + .unwrap(), + r#"[["SecurityError"],["about:blank"],null]"# + ); + assert_eq!(server.finish_targets().await.len(), 1); +} + fn expected_location_surface(same_origin: bool, path: &str) -> serde_json::Value { let read = if same_origin { "ok" } else { "SecurityError" }; let convert = if same_origin { @@ -321,3 +453,167 @@ async fn popup_root_window_preserves_nested_parent_top_identity_and_origin_check assert_eq!(server.finish_targets().await.len(), hosts.len()); } } + +#[tokio::test] +async fn popup_window_keeps_canonical_identity_and_cross_origin_access_boundaries() { + const PROBE: &str = include_str!("../../../tests/fixtures/popup-window-access.js"); + const A: &str = "www.example.test"; + const B: &str = "remote.example.test"; + for has_same_origin_child in [false, true] { + let mut bodies = vec![format!( + r#""#, + )]; + if has_same_origin_child { + bodies.push("child".to_owned()); + } + let server = StaticHttpServer::spawn_with_bodies(bodies).await; + let loader = static_http_loader([server.resolve_entry(A), server.resolve_entry(B)]); + let mut vm = new_storage_page_task_executor_test_vm_with_loader( + server.url_for_host(A, "/opener").as_str(), + &loader, + ); + assert_eq!( + vm.eval(&format!( + "globalThis.ready = false; onmessage = event => ready = event.data === 'ready'; \ + globalThis.rootPopup = open({:?}, 'related-page'); String(rootPopup.document.URL);", + server.url_for_host(B, "/popup").as_str(), + )) + .unwrap(), + "about:blank" + ); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(ready)", + "true", + "cross-origin popup projection", + ) + .await; + vm.eval(PROBE).unwrap(); + let child_index = usize::from(has_same_origin_child); + let actual: serde_json::Value = serde_json::from_str( + &vm.eval(&format!( + "JSON.stringify(inspectPopupWindow(rootPopup, {child_index}))", + )) + .unwrap(), + ) + .unwrap(); + let expected: Vec<_> = ["popup", "parent", "top"].map(|path| serde_json::json!({ + "path": path, "identity": true, + "document": "SecurityError", "name": "SecurityError", "location": "SecurityError", + "expando": "SecurityError", "descriptor": "SecurityError", "set": "SecurityError", + "define": "SecurityError", "has": "SecurityError", "del": "SecurityError", + "closed": false, "self": true, "roots": true, "length": child_index + 1, + "opener": true, "postMessage": "function", "postMessageStable": true, + "postMessageRealm": true, "close": "function", "prototypeIsNull": true, + "then": "undefined", "iterator": "SecurityError", + })).into(); + assert_eq!( + actual, + serde_json::json!(expected), + "same-origin child: {has_same_origin_child}" + ); + assert_eq!( + vm.eval("rootPopup.close(); String(rootPopup.closed)") + .unwrap(), + "true" + ); + assert_eq!(server.finish_targets().await.len(), child_index + 1); + } +} + +#[tokio::test] +async fn popup_window_rechecks_borrowed_accessors_after_navigation_and_close() { + let server = StaticHttpServer::spawn_with_bodies(vec![ + "" + .to_owned(), + ]) + .await; + let loader = static_http_loader([server.resolve_entry("remote.example.test")]); + let mut vm = new_storage_page_task_executor_test_vm_with_loader( + server.url_for_host("www.example.test", "/opener").as_str(), + &loader, + ); + assert_eq!( + vm.eval(&format!( + r#" + globalThis.ready = false; onmessage = event => ready = event.data === 'ready'; + globalThis.popup = open({:?}, 'popup-transition'); + globalThis.originalPopup = popup; + globalThis.originalName = Object.getOwnPropertyDescriptor(popup, 'name'); + globalThis.originalOpener = Object.getOwnPropertyDescriptor(popup, 'opener'); + popup.document.URL; + "#, + server + .url_for_host("remote.example.test", "/popup") + .as_str() + )) + .unwrap(), + "about:blank" + ); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(ready)", + "true", + "popup cross-origin navigation", + ) + .await; + assert_eq!( + vm.eval( + r#"(() => { + const read = f => { try { return f(); } catch (error) { return error.name; } }; + let conversions = 0; + const value = {toString() { conversions++; return 'renamed'; }}; + globalThis.foreignLocation = popup.location; + return JSON.stringify([ + popup === originalPopup, + read(() => popup.document.URL), + read(() => originalName.get.call(popup)), + read(() => originalName.set.call(popup, value)), + conversions, + read(() => originalOpener.set.call(popup, null)), + popup.opener === window, + ]); + })()"# + ) + .unwrap(), + r#"[true,"SecurityError","SecurityError","SecurityError",0,"SecurityError",true]"# + ); + vm.eval("popup.location = 'about:blank'; true").unwrap(); + advance_page_task_executor_until_eval_equals( + &mut vm, &loader, + "(() => { try { return String(popup.document.URL === 'about:blank'); } catch (_) { return 'false'; } })()", + "true", "popup returns to same origin", + ).await; + assert_eq!( + vm.eval( + r#"JSON.stringify([ + popup === originalPopup, popup.document.URL, + originalName.get.call(popup), popup.location !== foreignLocation, + ])"# + ) + .unwrap(), + r#"[true,"about:blank","popup-transition",true]"# + ); + vm.eval("popup.close(); true").unwrap(); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(popup.closed && popup.parent === null && popup.top === null)", + "true", + "closed popup browsing context", + ) + .await; + assert_eq!(vm.eval("JSON.stringify([popup === originalPopup, popup.closed, popup.length, popup.self === popup])").unwrap(), "[true,true,0,true]"); + assert_eq!(server.finish_targets().await.len(), 1); +} diff --git a/moli-renderer-v8/src/v8_finalizer.rs b/moli-renderer-v8/src/v8_finalizer.rs index e94f97efc39..1c613905386 100644 --- a/moli-renderer-v8/src/v8_finalizer.rs +++ b/moli-renderer-v8/src/v8_finalizer.rs @@ -15,6 +15,16 @@ pub(crate) fn track_context_owned_v8_finalizer( V8FinalizerRegistry::track(&common.finalizers, scope, object, cleanup); } +pub(crate) fn track_context_owned_external_finalizer( + scope: &mut v8::PinScope<'_, '_>, + external: v8::Local<'_, v8::External>, + cleanup: impl FnOnce() + 'static, +) { + let common = crate::common_runtime::CommonRuntimeState::from_scope(scope) + .expect("V8 finalizer must belong to a page or worker context"); + V8FinalizerRegistry::track(&common.finalizers, scope, external, cleanup); +} + #[cfg(test)] mod tests { use super::*; diff --git a/moli-renderer-v8/tests/fixtures/popup-window-access.js b/moli-renderer-v8/tests/fixtures/popup-window-access.js new file mode 100644 index 00000000000..10a45e73f9a --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/popup-window-access.js @@ -0,0 +1,28 @@ +function inspectPopupWindow(popup, childIndex) { + const read = callback => { try { return callback(); } catch (error) { return error.name; } }; + const child = popup[childIndex]; + return Object.entries({popup, parent: child.parent, top: child.top}).map(([path, win]) => ({ + path, identity: win === popup, + document: read(() => typeof win.document), + name: read(() => typeof win.name), + location: read(() => typeof win.location.href), + expando: read(() => typeof win.__privateMarker), + descriptor: read(() => typeof Object.getOwnPropertyDescriptor(win, 'document')), + set: read(() => Reflect.set(win, '__probeValue', 1)), + define: read(() => Reflect.defineProperty(win, '__probeDefined', {value: 1, configurable: true})), + has: read(() => 'document' in win), + del: read(() => Reflect.deleteProperty(win, '__probeValue')), + closed: read(() => win.closed), + self: read(() => win.window === win && win.self === win && win.frames === win), + roots: read(() => win.top === win && win.parent === win), + length: read(() => win.length), + opener: read(() => win.opener === window), + postMessage: read(() => typeof win.postMessage), + postMessageStable: read(() => win.postMessage === win.postMessage), + postMessageRealm: read(() => win.postMessage instanceof Function), + close: read(() => typeof win.close), + prototypeIsNull: read(() => Object.getPrototypeOf(win) === null), + then: read(() => typeof win.then), + iterator: read(() => typeof win[Symbol.iterator]), + })); +} diff --git a/moli-renderer-v8/tests/fixtures/popup-window-async.js b/moli-renderer-v8/tests/fixtures/popup-window-async.js new file mode 100644 index 00000000000..d70dadfda71 --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/popup-window-async.js @@ -0,0 +1,8 @@ +Promise.resolve().then(() => { + opener.postMessage({kind: "then", title: window.document.title, self: window === window.parent}, "*"); + throw new Error("expected rejection"); +}).catch(() => opener.postMessage({kind: "catch", title: window.document.title}, "*")); +(async () => { + await 0; + opener.postMessage({kind: "await", title: window.document.title}, "*"); +})(); diff --git a/moli-v8-util/src/finalizers.rs b/moli-v8-util/src/finalizers.rs index 07fd350e297..8a65d3afc20 100644 --- a/moli-v8-util/src/finalizers.rs +++ b/moli-v8-util/src/finalizers.rs @@ -24,14 +24,14 @@ pub struct V8FinalizerRegistry { struct ContextOwnedV8Finalizer { // Keep the weak before the shared cleanup so field teardown resets the V8 // handle before releasing the final copy of the once-cell. - weak: v8::Weak, + weak: v8::Weak, cleanup: SharedFinalizerCleanup, } impl ContextOwnedV8Finalizer { fn new( scope: &mut v8::PinScope<'_, '_>, - object: v8::Local<'_, v8::Object>, + object: v8::Local<'_, v8::Value>, cleanup: FinalizerCleanup, ) -> Self { let cleanup = Rc::new(Cell::new(Some(cleanup))); @@ -57,13 +57,13 @@ impl Drop for ContextOwnedV8Finalizer { impl V8FinalizerRegistry { /// Register a weak handle without holding its registry borrow across V8. /// Retired cleanup callbacks may reenter the resource owner. - pub fn track( + pub fn track<'s>( registry: &RefCell, scope: &mut v8::PinScope<'_, '_>, - object: v8::Local<'_, v8::Object>, + object: impl Into>, cleanup: impl FnOnce() + 'static, ) { - let entry = ContextOwnedV8Finalizer::new(scope, object, Box::new(cleanup)); + let entry = ContextOwnedV8Finalizer::new(scope, object.into(), Box::new(cleanup)); let retired = registry.borrow_mut().push(entry); drop(retired); } @@ -119,7 +119,7 @@ mod tests { let cleanup_count_for_callback = Rc::clone(&cleanup_count); drop(registry.push(ContextOwnedV8Finalizer::new( scope, - object, + object.into(), Box::new(move || { cleanup_count_for_callback .set(cleanup_count_for_callback.get().saturating_add(1));