diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs index 24c4d200cdd..0ed755205b3 100644 --- a/moli-renderer-v8/src/context_bootstrap.rs +++ b/moli-renderer-v8/src/context_bootstrap.rs @@ -49,7 +49,6 @@ pub(crate) use picture_in_picture_tests::closed_window_for_test as closed_pictur pub(crate) mod web_mcp; pub(crate) use history_runtime::state::bind_isolated_window_history_owner; mod idle_detection; -mod javascript_url; pub(crate) use self::idle_detection::{ apply_idle_override_to_current_context, retire_idle_detectors_in_current_context, }; @@ -389,8 +388,8 @@ pub(crate) use self::file_api::{build_clipboard_data_transfer, clipboard_data_tr pub(crate) use self::file_api::{ FileReaderReadMode, FileReadingTask, build_file_list_object, build_file_object, build_file_object_unpublished, file_clone_metadata, file_list_files_from_object, - finish_file_reader_read, flush_one_pending_file_reading_task, is_file_list_object, - queue_file_reading_task, selected_file_from_object, set_file_relative_path, + finish_file_reader_read, flush_one_pending_file_reading_task, queue_file_reading_task, + selected_file_from_object, set_file_relative_path, }; pub(crate) use self::form_data_runtime::form_data_request_body; pub(crate) use self::geometry_clone::{ @@ -430,10 +429,6 @@ pub(crate) use self::indexed_db::{ pub(in crate::context_bootstrap) use self::indexed_db::{ indexed_db_usage_bytes_for_storage_key, scoped_storage_bucket_indexed_db_factory, }; -pub(crate) use self::javascript_url::{ - arm_internal_javascript_url_eval, consume_internal_javascript_url_eval, - restore_internal_javascript_url_eval, -}; pub(crate) use self::location_runtime::refresh_global_location_security_origin; pub(crate) use self::location_runtime::sync_global_location_runtime_state; pub(crate) use self::location_runtime::{ @@ -473,7 +468,6 @@ pub(crate) use self::microtask_checkpoint::{ install_agent_microtask_checkpoint_tasks, run_end_of_microtask_checkpoint_tasks, }; pub(crate) use self::navigation_bootstrap::{ - install_window_location_history_navigation_runtime_state, reset_window_location_history_navigation_runtime_state, reset_window_location_runtime_state, }; pub(crate) use self::navigation_events::dispatch_cross_document_navigation_navigate_event_for_window; @@ -521,6 +515,7 @@ pub(crate) use self::runtime_state::install_webassembly_runtime_state; #[cfg(feature = "wpt-extensions")] pub(crate) use self::runtime_state::install_wpt_webdriver_runtime_state; pub(crate) use self::runtime_state::set_window_origin_runtime_state; +pub(crate) use self::runtime_state::window_realm_secure_context_available; pub(crate) use self::runtime_state::{ ORIGINAL_WEBASSEMBLY_COMPILE_ERROR_CONSTRUCTOR_SLOT, ORIGINAL_WEBASSEMBLY_GLOBAL_VALUE_GETTER_SLOT, ORIGINAL_WEBASSEMBLY_INSTANCE_CONSTRUCTOR_SLOT, diff --git a/moli-renderer-v8/src/context_bootstrap/css_runtime/lazy_state.rs b/moli-renderer-v8/src/context_bootstrap/css_runtime/lazy_state.rs index 83eb52ea156..3f2c2332b7c 100644 --- a/moli-renderer-v8/src/context_bootstrap/css_runtime/lazy_state.rs +++ b/moli-renderer-v8/src/context_bootstrap/css_runtime/lazy_state.rs @@ -159,10 +159,7 @@ fn css_highlights_lazy_getter<'s>( } // Keep the CSS namespace cache on the concrete Window that owns the lazy -// global property. Lightweight popups share their opener's V8 context, but -// still have a distinct Window and Document; a Context::Global()-keyed cache -// would collapse their observable CSS namespaces and register properties in -// the opener document. +// global property, including when a borrowed accessor runs in another realm. fn ensure_css_namespace<'s>( scope: &mut v8::PinScope<'s, '_>, owner: v8::Local<'s, v8::Object>, diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/database/factory.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/database/factory.rs index d30d9924e9b..5a97c785b02 100644 --- a/moli-renderer-v8/src/context_bootstrap/indexed_db/database/factory.rs +++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/database/factory.rs @@ -13,29 +13,6 @@ pub(in crate::context_bootstrap::indexed_db) use self::databases::{ pub(in crate::context_bootstrap::indexed_db) use self::delete_database::idb_factory_delete_database_callback; pub(in crate::context_bootstrap::indexed_db) use self::open::idb_factory_open_callback; -fn idb_factory_effective_execution_owner<'s>( - scope: &mut v8::PinScope<'s, '_>, - factory: v8::Local<'s, v8::Object>, -) -> Option { - let stored_owner = indexed_db_typed_execution_owner(scope, factory)?; - let Some(popup_id) = crate::native_bridge::active_lightweight_popup_id(scope) else { - return Some(stored_owner); - }; - let runtime_factory = indexed_db_runtime_factory(scope)?; - if !factory.strict_equals(runtime_factory.into()) { - return Some(stored_owner); - } - let host_ptr = context_host_ptr_from_global_bridge(scope)?; - let execution_context = unsafe { &*host_ptr } - .current_runtime_window_execution_context_identity_for_dispatch_scope( - scope, - crate::native_bridge::OwnerDispatchScope::LightweightPopup(popup_id), - )?; - Some(IndexedDbExecutionOwner::for_window_execution_context( - execution_context, - )) -} - fn idb_factory_effective_storage_scope<'s>( scope: &mut v8::PinScope<'s, '_>, factory: v8::Local<'s, v8::Object>, diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/database/factory/databases.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/database/factory/databases.rs index 04607583836..61d4832269e 100644 --- a/moli-renderer-v8/src/context_bootstrap/indexed_db/database/factory/databases.rs +++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/database/factory/databases.rs @@ -20,7 +20,7 @@ pub(in crate::context_bootstrap::indexed_db) fn idb_factory_databases_callback<' let promise = resolver.get_promise(scope); rv.set(promise.into()); - let Some(owner) = idb_factory_effective_execution_owner(scope, args.this()) else { + let Some(owner) = indexed_db_typed_execution_owner(scope, args.this()) else { let exception = dom_exception_value( scope, "Failed to execute 'databases' on 'IDBFactory': access to the Indexed Database API is denied in this context.", diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/database/factory/delete_database.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/database/factory/delete_database.rs index fdf22520e8c..6be186b5042 100644 --- a/moli-renderer-v8/src/context_bootstrap/indexed_db/database/factory/delete_database.rs +++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/database/factory/delete_database.rs @@ -18,7 +18,7 @@ pub(in crate::context_bootstrap::indexed_db) fn idb_factory_delete_database_call return; }; let name = IndexedDbName::from_utf16(parsed.name.0); - let Some(owner) = idb_factory_effective_execution_owner(scope, args.this()) else { + let Some(owner) = indexed_db_typed_execution_owner(scope, args.this()) else { let exception = dom_exception_value( scope, "Failed to execute 'deleteDatabase' on 'IDBFactory': access to the Indexed Database API is denied in this context.", diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/database/factory/open.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/database/factory/open.rs index b44da41068f..6afe7a222c6 100644 --- a/moli-renderer-v8/src/context_bootstrap/indexed_db/database/factory/open.rs +++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/database/factory/open.rs @@ -28,7 +28,7 @@ pub(in crate::context_bootstrap::indexed_db) fn idb_factory_open_callback<'s>( ); return; } - let Some(owner) = idb_factory_effective_execution_owner(scope, args.this()) else { + let Some(owner) = indexed_db_typed_execution_owner(scope, args.this()) else { let exception = dom_exception_value( scope, "Failed to execute 'open' on 'IDBFactory': access to the Indexed Database API is denied in this context.", diff --git a/moli-renderer-v8/src/context_bootstrap/indexed_db/typed_state.rs b/moli-renderer-v8/src/context_bootstrap/indexed_db/typed_state.rs index c9bab95fdba..2b217a05298 100644 --- a/moli-renderer-v8/src/context_bootstrap/indexed_db/typed_state.rs +++ b/moli-renderer-v8/src/context_bootstrap/indexed_db/typed_state.rs @@ -2121,18 +2121,16 @@ pub(super) fn indexed_db_index_info( pub(super) fn current_indexed_db_execution_owner( scope: &mut v8::PinScope<'_, '_>, ) -> IndexedDbExecutionOwner { - let dispatch_scope = inferred_indexed_db_dispatch_scope(scope); if let Some(host_ptr) = crate::util::context_host_ptr_from_global_bridge(scope) { let host = unsafe { &*host_ptr }; let execution_context = host - .window_execution_context_identity_for_v8_context(scope, scope.get_current_context()) - .filter(|identity| identity.dispatch_scope() == dispatch_scope); + .window_execution_context_identity_for_v8_context(scope, scope.get_current_context()); if let Some(execution_context) = execution_context { return IndexedDbExecutionOwner::Window(execution_context); } } - IndexedDbExecutionOwner::PendingWindow(dispatch_scope) + IndexedDbExecutionOwner::PendingWindow(inferred_indexed_db_dispatch_scope(scope)) } pub(super) fn indexed_db_execution_owner_for_object( diff --git a/moli-renderer-v8/src/context_bootstrap/javascript_url.rs b/moli-renderer-v8/src/context_bootstrap/javascript_url.rs deleted file mode 100644 index 5b15ce56b48..00000000000 --- a/moli-renderer-v8/src/context_bootstrap/javascript_url.rs +++ /dev/null @@ -1,67 +0,0 @@ -use crate::util::{get_private_value, set_private_value}; - -const INTERNAL_JAVASCRIPT_URL_EVAL_PERMIT_SLOT: &str = "__moliInternalJavascriptUrlEvalPermit"; - -/// Scoped permission for the direct eval used by the lightweight-popup -/// javascript-URL adapter. -/// -/// Lightweight popups do not own a V8 Context, so their adapter uses direct -/// eval to recover Script completion semantics while resolving globals -/// through the popup Window object. The source has already passed the target -/// Document's CSP and Trusted Types checks. The isolate callback consumes the -/// private marker on the first compilation; nested page-authored eval calls -/// therefore go through the normal policy path. -pub(crate) struct InternalJavascriptUrlEvalPermit { - previous: Option>, -} - -pub(crate) fn arm_internal_javascript_url_eval( - scope: &mut v8::PinScope<'_, '_>, -) -> InternalJavascriptUrlEvalPermit { - let global = scope.get_current_context().global(scope); - let previous = get_private_value(scope, global, INTERNAL_JAVASCRIPT_URL_EVAL_PERMIT_SLOT) - .map(|value| v8::Global::new(scope, value)); - let marker = v8::Object::new(scope); - set_private_value( - scope, - global, - INTERNAL_JAVASCRIPT_URL_EVAL_PERMIT_SLOT, - marker.into(), - ); - InternalJavascriptUrlEvalPermit { previous } -} - -pub(crate) fn restore_internal_javascript_url_eval( - scope: &mut v8::PinScope<'_, '_>, - permit: InternalJavascriptUrlEvalPermit, -) { - let global = scope.get_current_context().global(scope); - let previous = permit - .previous - .as_ref() - .map(|value| v8::Local::new(scope, value)) - .unwrap_or_else(|| v8::undefined(scope).into()); - set_private_value( - scope, - global, - INTERNAL_JAVASCRIPT_URL_EVAL_PERMIT_SLOT, - previous, - ); -} - -pub(crate) fn consume_internal_javascript_url_eval(scope: &mut v8::PinScope<'_, '_>) -> bool { - let global = scope.get_current_context().global(scope); - let armed = get_private_value(scope, global, INTERNAL_JAVASCRIPT_URL_EVAL_PERMIT_SLOT) - .is_some_and(|marker| marker.is_object()); - if !armed { - return false; - } - let empty = v8::undefined(scope); - set_private_value( - scope, - global, - INTERNAL_JAVASCRIPT_URL_EVAL_PERMIT_SLOT, - empty.into(), - ); - true -} diff --git a/moli-renderer-v8/src/context_bootstrap/location_navigation.rs b/moli-renderer-v8/src/context_bootstrap/location_navigation.rs index 051a4c56faa..60945a9e3e3 100644 --- a/moli-renderer-v8/src/context_bootstrap/location_navigation.rs +++ b/moli-renderer-v8/src/context_bootstrap/location_navigation.rs @@ -1371,26 +1371,10 @@ fn location_navigation_initiator_scope( scope: &mut v8::PinScope<'_, '_>, host: &PageScriptHost, ) -> crate::native_bridge::OwnerDispatchScope { - let incumbent = scope + scope .get_incumbent_context() - .and_then(|context| host.window_dispatch_scope_for_context(scope, context)); - // A popup can share its opener's concrete realm. Preserve its own source - // identity, as well as that of a real child calling an ancestor's binding. - if let Some( - source @ (crate::native_bridge::OwnerDispatchScope::Child(_) - | crate::native_bridge::OwnerDispatchScope::LightweightPopup(_)), - ) = incumbent - { - return source; - } - if let Some(popup_id) = crate::native_bridge::active_lightweight_popup_id(scope) { - return crate::native_bridge::OwnerDispatchScope::LightweightPopup(popup_id); - } - incumbent - .or_else(|| { - crate::context_bootstrap::current_child_browsing_context_handle_for_runtime_scope(scope) - .map(crate::native_bridge::OwnerDispatchScope::Child) - }) + .and_then(|context| host.window_dispatch_scope_for_context(scope, context)) + .or_else(|| host.window_dispatch_scope_for_context(scope, scope.get_current_context())) .unwrap_or(crate::native_bridge::OwnerDispatchScope::Top) } diff --git a/moli-renderer-v8/src/context_bootstrap/location_runtime/access.rs b/moli-renderer-v8/src/context_bootstrap/location_runtime/access.rs index 0207edff8a4..bedc107d606 100644 --- a/moli-renderer-v8/src/context_bootstrap/location_runtime/access.rs +++ b/moli-renderer-v8/src/context_bootstrap/location_runtime/access.rs @@ -81,9 +81,8 @@ fn location_proxy_set<'s>( .unwrap_or_else(|| scope.get_current_context()); if super::origin::context_can_access(scope, caller, target) { // Reflect.set itself performs the target access check in its own - // realm. Use the caller's captured intrinsic when the handler belongs - // to a popup that shares an unrelated opener realm. Calling it without - // entering a ContextScope preserves the original entry settings. + // realm. Use the caller's captured intrinsic without entering a + // ContextScope so the original entry settings are preserved. let global = caller.global(scope); let reflect_set = get_private_value(scope, global, REFLECT_SET_SLOT).unwrap_or_else(|| args.data()); diff --git a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs index 3e1dc505a1e..503a6248f45 100644 --- a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs +++ b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs @@ -25,7 +25,7 @@ use super::{ }; use crate::web_api_interfaces; use crate::{ - document_runtime::{DocumentRuntime, DomHandle}, + document_runtime::DomHandle, native_bridge::{ self, PageScriptHost, document::{ @@ -848,8 +848,7 @@ fn window_surface_slot_getter<'s>( } return; } - // Lightweight popup shells share their opener's V8 realm but have their - // own associated objects. Do not materialize the opener's lazy surface. + // Popup bootstrap installs these Window-associated objects explicitly. if matches!(slot, WINDOW_NAVIGATOR_SLOT | WINDOW_EXTERNAL_SLOT) && crate::native_bridge::lightweight_popup_id_from_window(scope, receiver).is_some() { @@ -1494,7 +1493,7 @@ pub(crate) fn install_wpt_webdriver_runtime_state( pub(crate) fn finish_context_bootstrap( scope: &mut v8::PinScope<'_, '_>, document_runtime: &mut PageScriptHost, - secure_context_url: &url::Url, + secure_context_available: bool, ) -> Result<()> { super::exposed_interfaces::initialize_realm_interface_registry( scope, @@ -1517,7 +1516,7 @@ pub(crate) fn finish_context_bootstrap( ); } let _ = global.delete(scope, console_key.into()); - install_window_runtime_state(scope, global, document_runtime, secure_context_url)?; + install_window_runtime_state(scope, global, document_runtime, secure_context_available)?; // WPT harness helper only. Normal builds keep the feature disabled so pages // do not observe non-standard `webdriver` / `WebDriver` globals. #[cfg(feature = "wpt-extensions")] @@ -1852,10 +1851,9 @@ pub(crate) fn window_realm_secure_context_available<'s>( fn install_window_runtime_state<'s>( scope: &mut v8::PinScope<'s, '_>, global: v8::Local<'s, v8::Object>, - runtime: &DocumentRuntime, - secure_context_url: &url::Url, + runtime: &PageScriptHost, + secure_context_available: bool, ) -> Result<()> { - let secure_context_available = moli_url::is_potentially_trustworthy_url(secure_context_url); set_private_value( scope, global, @@ -1865,20 +1863,23 @@ fn install_window_runtime_state<'s>( install_webassembly_runtime_state(scope, global)?; install_webidl_collection_iterator_intrinsics(scope, global)?; + let dispatch_scope = super::navigation_window::runtime_window_dispatch_scope(scope, global) + .unwrap_or(crate::native_bridge::OwnerDispatchScope::Top); + let document_loader = runtime + .document_resource_loader_for_dispatch_scope(dispatch_scope) + .ok_or_else(|| { + anyhow!("Window bootstrap requires its committed Document resource authority") + })?; + let document_context = document_loader.fetch_context(); install_window_location_history_navigation_runtime_state( scope, global, - runtime.document_url().as_str(), + document_context.document_url().as_str(), )?; - let origin = context_host_ptr_from_global_bridge(scope) - .map(|host| unsafe { &*host }.main_document_origin()) - .unwrap_or_else(|| { - if runtime.document_sandbox_policy().forces_opaque_origin { - "null".into() - } else { - moli_url::origin_ascii_serialization(runtime.document_url()) - } - }); + let origin = + crate::native_bridge::WindowSecurityOrigin::for_context(scope.get_current_context()) + .map(|origin| origin.serialized_origin()) + .unwrap_or_else(|| document_context.origin().to_owned()); set_window_origin_runtime_state(scope, global, &origin)?; let console = ConsoleObjectDeclaration::default() @@ -1923,9 +1924,6 @@ fn install_window_runtime_state<'s>( .map_err(|error| anyhow!(error.to_string()))?; install_document_runtime_state(scope, global)?; install_navigator_runtime_state(scope, global, secure_context_available)?; - let document_loader = runtime - .current_document_resource_loader() - .expect("Window bootstrap requires the committed Document resource authority"); bind_window_navigator_identity_seed( scope, global, diff --git a/moli-renderer-v8/src/context_bootstrap/window_receiver.rs b/moli-renderer-v8/src/context_bootstrap/window_receiver.rs index a6d786b26fd..72485b3dad6 100644 --- a/moli-renderer-v8/src/context_bootstrap/window_receiver.rs +++ b/moli-renderer-v8/src/context_bootstrap/window_receiver.rs @@ -23,6 +23,9 @@ fn is_current_window_receiver<'s>( let current_context = scope.get_current_context(); receiver.strict_equals(current_context.global(scope).into()) && context_host_ptr_from_context_slot(current_context).is_some() + && receiver + .get_creation_context(scope) + .is_none_or(|context| context == current_context) } /// Apply Window access policy to the Window subtype of EventTarget receivers. diff --git a/moli-renderer-v8/src/context_bootstrap/window_runtime/dialogs.rs b/moli-renderer-v8/src/context_bootstrap/window_runtime/dialogs.rs index 9315163d1d9..6330b95f828 100644 --- a/moli-renderer-v8/src/context_bootstrap/window_runtime/dialogs.rs +++ b/moli-renderer-v8/src/context_bootstrap/window_runtime/dialogs.rs @@ -528,6 +528,7 @@ pub(crate) fn window_open_callback<'s>( id, opener, opener_child_handle, + popup_source_scope, url.as_deref(), entered_base_url, creator_policy_container, @@ -535,7 +536,6 @@ pub(crate) fn window_open_callback<'s>( ), _ => host.open_lightweight_popup_window( scope, - host_ptr, opener, opener_child_handle, Some(popup_source_scope), diff --git a/moli-renderer-v8/src/context_bootstrap/window_runtime/navigator.rs b/moli-renderer-v8/src/context_bootstrap/window_runtime/navigator.rs index e962c1b478a..4ba44132548 100644 --- a/moli-renderer-v8/src/context_bootstrap/window_runtime/navigator.rs +++ b/moli-renderer-v8/src/context_bootstrap/window_runtime/navigator.rs @@ -982,18 +982,15 @@ fn storage_bucket_manager_owner_is_live<'s>( scope: &mut v8::PinScope<'s, '_>, manager: v8::Local<'s, v8::Object>, ) -> bool { + if !storage_bucket_receiver_execution_context_is_live(scope, manager) { + return false; + } if let Some(popup_id) = storage_bucket_manager_popup_id(scope, manager) { return context_host_ptr_from_global_bridge(scope).is_some_and(|host_ptr| { // SAFETY: the current V8 context owns a bridge ref for this host pointer. - // Lightweight popups still share the opener's concrete realm, so - // their explicit popup owner remains authoritative until P2 gives - // them an independent execution context. unsafe { (&*host_ptr).lightweight_popup_is_open(popup_id) } }); } - if !storage_bucket_receiver_execution_context_is_live(scope, manager) { - return false; - } if let Some(handle) = storage_bucket_manager_child_handle(scope, manager) { return context_host_ptr_from_global_bridge(scope).is_some_and(|host_ptr| { // SAFETY: context_host_ptr_from_global_bridge returns the live diff --git a/moli-renderer-v8/src/host/timers.rs b/moli-renderer-v8/src/host/timers.rs index 5665a2308c7..8ff65366044 100644 --- a/moli-renderer-v8/src/host/timers.rs +++ b/moli-renderer-v8/src/host/timers.rs @@ -1112,30 +1112,6 @@ fn scheduled_timer_owner_for_target<'s>( ), }; - // Lightweight popups share the renderer isolate and install their context - // lazily. Capture the popup object's exact creation context before queueing. - let binding = - if binding.is_none() && matches!(dispatch_scope, OwnerDispatchScope::LightweightPopup(_)) { - let context = receiver - .and_then(|receiver| receiver.get_creation_context(scope)) - .unwrap_or(fallback_context); - let realm_token = timer_context_realm_token(scope, context)?; - let binding = WindowExecutionContextBinding::new( - execution_context_owner, - dispatch_scope, - realm_token, - v8::Global::new(scope, context), - ); - host.register_window_execution_context(WindowExecutionContextBinding::new( - execution_context_owner, - dispatch_scope, - realm_token, - v8::Global::new(scope, context), - )); - Some(binding) - } else { - binding - }; Some(ScheduledTimerOwner::Window( ScheduledWindowTimerTarget::new(execution_context_owner, dispatch_scope, binding), )) diff --git a/moli-renderer-v8/src/native_bridge/bindings.rs b/moli-renderer-v8/src/native_bridge/bindings.rs index 2007fb8bdb3..96f6d2aa110 100644 --- a/moli-renderer-v8/src/native_bridge/bindings.rs +++ b/moli-renderer-v8/src/native_bridge/bindings.rs @@ -356,31 +356,6 @@ impl NativeBridgeTemplates { wrapper } - pub(super) fn instantiate_window_shell<'s, 'i>( - &mut self, - scope: &mut v8::PinScope<'s, 'i>, - host_ptr: *mut PageScriptHost, - ) -> v8::Local<'s, v8::Object> { - let wrapper = self - .window_wrapper_template() - .new_instance(scope) - .expect("failed to instantiate synthetic Window wrapper"); - let host_external = v8::External::new(scope, host_ptr as *mut c_void); - assert!( - wrapper.set_internal_field(0, host_external.into()), - "synthetic Window wrapper must expose its runtime field" - ); - assert!( - wrapper.set_internal_field(1, v8::Number::new(scope, 0.0).into()), - "synthetic Window wrapper must expose its shell marker" - ); - web_api_interfaces::Window::DESCRIPTOR - .initialize(scope, wrapper) - .expect("synthetic Window identity should initialize"); - set_named_constructor_prototype(scope, wrapper, "Window"); - wrapper - } - pub(super) fn instantiate_window_proxy_shell<'s, 'i>( &mut self, scope: &mut v8::PinScope<'s, 'i>, diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/isolated_world.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/isolated_world.rs index 8984a9a7aee..5989288d0c4 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/isolated_world.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/isolated_world.rs @@ -1,6 +1,6 @@ use super::super::{ - ChildDefaultContextBootstrapConfig, PageScriptHost, PrebootstrappedChildDefaultContext, - WeakPrebootstrappedChildDefaultContexts, WindowExecutionContextAccessPolicy, + PageScriptHost, PrebootstrappedChildDefaultContext, WeakPrebootstrappedChildDefaultContexts, + WindowDefaultContextBootstrapConfig, WindowExecutionContextAccessPolicy, WindowExecutionContextBinding, WindowExecutionContextOwner, }; use super::realm_state::{ @@ -46,16 +46,18 @@ impl PageScriptHost { Ok(()) } - pub(crate) fn install_child_default_context_bootstrap( + pub(crate) fn install_window_default_context_bootstrap( &mut self, host: Weak>, pending_contexts: WeakPrebootstrappedChildDefaultContexts, + popup_contexts: super::super::popups::realm::WeakPopupDefaultContexts, resource_owner_id: crate::resource_owner::ResourceOwnerId, promise_reject_dispatch: crate::script_vm::PromiseRejectDispatchSlot, ) { - self.child_default_context_bootstrap = Some(ChildDefaultContextBootstrapConfig { + self.window_default_context_bootstrap = Some(WindowDefaultContextBootstrapConfig { host, pending_contexts, + popup_contexts, resource_owner_id, promise_reject_dispatch, }); @@ -96,7 +98,7 @@ impl PageScriptHost { return Ok(context); } let config = self - .child_default_context_bootstrap + .window_default_context_bootstrap .clone() .ok_or_else(|| anyhow::anyhow!("child default context bootstrap is unavailable"))?; let host = config @@ -250,8 +252,6 @@ impl PageScriptHost { ) -> Result<()> { let projection = initialize_child_window_realm_state(self, scope, global, init)?; if init.world.is_default() { - self.child_window_proxy_records - .set_realm_top(scope, init.handle, projection.top); self.install_default_world_state_for_child_window( scope, init.handle, 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 e74d61cf868..28de0fcc085 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,7 +51,6 @@ struct ChildWindowProxyRecord { browsing_context_parent_window: Option>, browsing_context_top_window: Option>, browsing_context_opener: Option, - realm_top_window_wrapper: Option>, live_window_exposed_to_top: bool, cross_origin_window_proxy: Option>, default_execution_context_id: Option, @@ -211,36 +210,6 @@ impl ChildWindowProxyRecords { Some((opener.endpoint, v8::Local::new(scope, &opener.window))) } - pub(in crate::native_bridge::context_host) fn set_realm_top( - &mut self, - scope: &mut v8::PinScope<'_, '_>, - handle: DomHandle, - top: v8::Local<'_, v8::Object>, - ) { - if moli_trace::window_message_trace_enabled() { - let global = scope.get_current_context().global(scope); - tracing::info!( - target: "moli_window_message_trace", - handle = handle.index(), - top_is_target_global = top.strict_equals(global.into()), - stage = "child_window_proxy_realm_top_installed", - ); - } - self.record_mut(handle).realm_top_window_wrapper = Some(v8::Global::new(scope, top)); - } - - pub(in crate::native_bridge::context_host) fn realm_top<'s>( - &self, - scope: &mut v8::PinScope<'s, '_>, - handle: DomHandle, - ) -> Option> { - self.records - .get(&handle)? - .realm_top_window_wrapper - .as_ref() - .map(|top| v8::Local::new(scope, top)) - } - pub(in crate::native_bridge::context_host) fn mark_live_window_exposed_to_top( &mut self, handle: DomHandle, @@ -294,7 +263,6 @@ impl ChildWindowProxyRecords { return; }; record.default_execution_context_id = None; - record.realm_top_window_wrapper = None; } pub(in crate::native_bridge::context_host) fn clear_default_execution_context_id_if_matches( @@ -311,7 +279,6 @@ impl ChildWindowProxyRecords { return false; } record.default_execution_context_id = None; - record.realm_top_window_wrapper = None; true } @@ -1334,14 +1301,6 @@ impl PageScriptHost { self.child_window_proxy_records.live_window(scope, handle) } - pub(crate) fn child_browsing_context_top_window_for_current_realm<'s>( - &self, - scope: &mut v8::PinScope<'s, '_>, - handle: DomHandle, - ) -> Option> { - self.child_window_proxy_records.realm_top(scope, handle) - } - pub(crate) fn set_child_browsing_context_opener<'s>( &mut self, scope: &mut v8::PinScope<'s, '_>, @@ -2470,12 +2429,6 @@ fn live_location_for_cross_origin_window<'s>( }; let host_ptr = context_host_ptr_from_global_bridge(scope)?; let host = unsafe { &mut *host_ptr }; - if let super::super::OwnerDispatchScope::LightweightPopup(popup_id) = dispatch_scope { - // Lightweight popups share a V8 realm with the opener. Its global is - // not the popup's Window and must not supply this proxy's Location. - let window = host.lightweight_popup_window(scope, popup_id)?; - return crate::context_bootstrap::window_location_for_holder(scope, window); - } let owner = host.current_window_execution_context_owner(dispatch_scope)?; let (_, context) = host.window_execution_context(scope, owner, dispatch_scope)?; crate::context_bootstrap::window_location_for_holder(scope, context.global(scope)) 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 2b868953245..8483f3b1ee2 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/core.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs @@ -418,7 +418,7 @@ impl PageScriptHost { child_document_parsers: ChildDocumentParserStore::default(), child_window_proxy_records: ChildWindowProxyRecords::default(), top_window_opener: None, - child_default_context_bootstrap: None, + window_default_context_bootstrap: None, #[cfg(test)] force_child_default_context_preflight_failure: false, #[cfg(test)] diff --git a/moli-renderer-v8/src/native_bridge/context_host/indexed_db_tasks.rs b/moli-renderer-v8/src/native_bridge/context_host/indexed_db_tasks.rs index 7caf77407f0..2142552a3f4 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/indexed_db_tasks.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/indexed_db_tasks.rs @@ -1,7 +1,4 @@ -use super::{ - PageScriptHost, RuntimeObservableContextToken, WindowExecutionContextIdentity, - WindowExecutionContextOwner, -}; +use super::{PageScriptHost, RuntimeObservableContextToken, WindowExecutionContextIdentity}; use moli_indexeddb::{ DatabaseHandle, sqlite::service::{DatabaseConnection, WeakDatabaseConnection}, @@ -90,10 +87,4 @@ impl PageScriptHost { self.signal_page_indexed_db_task_reconsideration_if_installed(); retired } - - pub(super) fn retire_indexed_db_owner(&self, owner: WindowExecutionContextOwner) { - self.indexed_db_context_tasks - .retire_matching(|candidate| candidate.owner() == owner); - self.signal_page_indexed_db_task_reconsideration_if_installed(); - } } 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 a499f9a5769..1aae30d7ebe 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs @@ -263,7 +263,6 @@ pub(crate) use window_execution_context::{ }; use window_execution_context::{ WindowExecutionContextRealmRecords, WindowExecutionContextRealmRegistration, - WindowExecutionContextScopedRealmRegistration, }; #[cfg(test)] pub(crate) use window_world::install_isolated_window_world_for_context; @@ -295,10 +294,13 @@ pub(crate) type SharedPrebootstrappedChildDefaultContexts = pub(crate) type WeakPrebootstrappedChildDefaultContexts = Weak>; +pub(crate) use popups::realm::SharedPopupDefaultContexts; + #[derive(Clone)] -struct ChildDefaultContextBootstrapConfig { +struct WindowDefaultContextBootstrapConfig { host: Weak>, pending_contexts: WeakPrebootstrappedChildDefaultContexts, + popup_contexts: popups::realm::WeakPopupDefaultContexts, resource_owner_id: crate::resource_owner::ResourceOwnerId, promise_reject_dispatch: crate::script_vm::PromiseRejectDispatchSlot, } @@ -936,7 +938,7 @@ pub(crate) struct PageScriptHost { child_document_parsers: ChildDocumentParserStore, child_window_proxy_records: ChildWindowProxyRecords, top_window_opener: Option<(PendingWindowMessageEndpoint, v8::Global)>, - child_default_context_bootstrap: Option, + window_default_context_bootstrap: Option, #[cfg(test)] force_child_default_context_preflight_failure: bool, #[cfg(test)] @@ -1149,8 +1151,7 @@ pub(crate) struct PageScriptHost { lightweight_popup_browsing_contexts: HashMap, lightweight_popup_document_handles: HashMap, - // Popup Documents share a concrete realm with the opener. Keep their own - // origins for as long as their native Document handles can be retained. + // Retain each popup Document's origin after its Window has navigated away. lightweight_popup_document_origins: HashMap, pending_lightweight_popup_document_loads: 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 a78a69e5ce1..b79203c529b 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/popups.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/popups.rs @@ -16,8 +16,7 @@ use crate::{ finish_cross_document_navigation_for_window, history_entry_seed_for_cross_document_location, initialize_simple_event_target, install_navigation_bootstrap_entry_for_holder, install_simple_window_event_handlers, - install_storage_aliases_for_window, - install_window_location_history_navigation_runtime_state, navigation_unload_event_active, + install_storage_aliases_for_window, navigation_unload_event_active, new_shared_web_storage_store, scoped_indexed_db_factory, sync_document_location_runtime_state_from_window, sync_window_location_history_navigation_runtime_surface, @@ -41,8 +40,7 @@ use crate::{ PopupDocumentLoadCompletion, PopupDocumentLoadOutcome, }, util::{ - context_host_ptr_from_global_bridge, define_non_enumerable_static_property, - get_private_value, global_constructor_object, new_null_prototype_object, set_private_value, + context_host_ptr_from_global_bridge, get_private_value, set_private_value, throw_type_error, v8_string, v8str, }, window_document_identity::{ @@ -64,6 +62,7 @@ use url::Url; mod document_stream; mod event_handlers; mod lifecycle; +pub(super) mod realm; use document_stream::{PopupDocumentStream, PopupStreamScriptMode}; use event_handlers::{ PopupWindowContentEventHandlers, clear_lightweight_popup_window_document_event_state, @@ -77,13 +76,6 @@ const LIGHTWEIGHT_POPUP_JAVASCRIPT_DOCUMENT_ID_SLOT: &str = const LIGHTWEIGHT_POPUP_JAVASCRIPT_NAVIGATION_ID_SLOT: &str = "__lmLightweightPopupJavascriptNavigationId"; const LIGHTWEIGHT_POPUP_JAVASCRIPT_SOURCE_SLOT: &str = "__lmLightweightPopupJavascriptSource"; -const LIGHTWEIGHT_POPUP_VIEWPORT_SURFACE_PROPERTIES: &[&str] = &[ - "innerWidth", - "innerHeight", - "outerWidth", - "outerHeight", - "devicePixelRatio", -]; /// Whether applying a popup response entered author code or an event-dispatch /// algorithm before returning to the enclosing Page resource task. @@ -151,11 +143,7 @@ struct LightweightPopupWindowMethodsDeclaration { #[derive(Default, WebApiObject)] #[webapi(fragment)] -struct LightweightPopupWindowStateDeclaration { - #[webapi(accessor_property, enumerable, getter = lightweight_popup_closed_getter)] - closed: (), - #[webapi(accessor_property, enumerable, getter = lightweight_popup_opener_getter, setter = lightweight_popup_opener_setter)] - opener: (), +struct LightweightPopupWindowNameDeclaration { #[webapi( accessor_property, enumerable, @@ -428,6 +416,9 @@ pub(super) struct LightweightPopupStorageScope { #[derive(Debug, Clone, PartialEq, Eq)] pub(super) struct LightweightPopupDocumentState { pub(super) base_url: Url, + // Initial about:blank inherits its creator's native secure-context state. + // Unlike the base URL, this is not changed by author markup or document.open(). + pub(super) secure_context_available: bool, pub(super) policy_container: DocumentPolicyContainer, pub(super) document_domain_override: Option, } @@ -507,6 +498,7 @@ pub(super) struct LightweightPopupBrowsingContextRecord { auxiliary_window: crate::runtime::RendererAuxiliaryWindow, name_lookup_allowed: bool, window_proxy: v8::Global, + facade_context: Option>, opener: Option, opener_window: Option>, location_url: Url, @@ -562,9 +554,14 @@ fn inherit_lightweight_popup_opener_sandbox( } impl LightweightPopupDocumentState { - fn new(base_url: Url, policy_container: DocumentPolicyContainer) -> Self { + fn new( + base_url: Url, + policy_container: DocumentPolicyContainer, + secure_context_available: bool, + ) -> Self { Self { base_url, + secure_context_available, policy_container, document_domain_override: None, } @@ -580,6 +577,7 @@ impl LightweightPopupDocumentState { base_url: Url, response: DocumentPolicyContainer, ) -> Self { + self.secure_context_available = moli_url::is_potentially_trustworthy_url(&base_url); self.base_url = base_url; self.document_domain_override = None; self.policy_container.referrer_policy = response.referrer_policy; @@ -777,10 +775,13 @@ impl PageScriptHost { self.unregister_service_worker_popup_client(popup_id); self.cancel_lightweight_popup_document_loads(popup_id); self.cancel_lightweight_popup_classic_script_loads(popup_id); - if let Some(window) = window { + if let Some(window) = window + && let Some(context) = window.get_creation_context(scope) + { + let scope = &mut v8::ContextScope::new(scope, context); clear_lightweight_popup_window_document_event_state(scope, window); with_lightweight_popup_scope(scope, popup_id, |scope| { - for property in ["parent", "top"] { + for property in ["__moliWindowParent", "__moliWindowTop", "parent"] { set_object_slot(scope, window, property, v8::null(scope).into()); } }); @@ -881,7 +882,6 @@ impl PageScriptHost { pub(crate) fn open_lightweight_popup_window<'s>( &mut self, scope: &mut v8::PinScope<'s, '_>, - host_ptr: *mut PageScriptHost, opener: Option>, opener_child_handle: Option, source_scope: Option, @@ -891,12 +891,15 @@ impl PageScriptHost { creator_policy_container: DocumentPolicyContainer, update_existing_opener: bool, ) -> Option> { + let creator_scope = + source_scope.unwrap_or_else(|| self.entered_owner_dispatch_scope(scope)); if let Some(popup_id) = self.named_lightweight_popup_id(target_name) && let Some(opened) = self.reuse_lightweight_popup_window( scope, popup_id, opener, opener_child_handle, + creator_scope, href, creator_base_url.clone(), creator_policy_container.clone(), @@ -907,9 +910,9 @@ impl PageScriptHost { } let href = href.unwrap_or("about:blank"); let (document_response, receiver) = self.auxiliary_document_response_channel(href); + let creator_is_secure_context = self.popup_creator_is_secure_context(scope, creator_scope); let (window, popup_id) = self.create_lightweight_popup_window( scope, - host_ptr, opener, opener_child_handle, target_name, @@ -917,6 +920,7 @@ impl PageScriptHost { source_scope.and_then(|scope| self.popup_sandbox_policy_for_source(scope)), creator_base_url, creator_policy_container, + creator_is_secure_context, receiver, )?; Some(OpenedLightweightPopup { @@ -944,12 +948,33 @@ impl PageScriptHost { (policy.sandboxes_document_domain && !policy.allows_popups_to_escape).then_some(policy) } + fn popup_creator_is_secure_context( + &self, + scope: &mut v8::PinScope<'_, '_>, + creator: OwnerDispatchScope, + ) -> bool { + if let OwnerDispatchScope::LightweightPopup(id) = creator { + return self + .lightweight_popup_document_record(id) + .is_some_and(|document| document.state.secure_context_available); + } + let Some(owner) = self.current_window_execution_context_owner(creator) else { + return false; + }; + let Some((_, context)) = self.window_execution_context(scope, owner, creator) else { + return false; + }; + let window = context.global(scope); + crate::context_bootstrap::window_realm_secure_context_available(scope, window) + } + pub(crate) fn reuse_lightweight_popup_window<'s>( &mut self, scope: &mut v8::PinScope<'s, '_>, popup_id: u64, opener: Option>, opener_child_handle: Option, + creator_scope: OwnerDispatchScope, href: Option<&str>, creator_base_url: Url, creator_policy_container: DocumentPolicyContainer, @@ -958,6 +983,7 @@ impl PageScriptHost { if !self.lightweight_popup_is_open(popup_id) { return None; } + let creator_is_secure_context = self.popup_creator_is_secure_context(scope, creator_scope); let window = self.lightweight_popup_window(scope, popup_id)?; if update_existing_opener && let Some(opener) = opener { set_private_value(scope, window, LIGHTWEIGHT_POPUP_OPENER_SLOT, opener.into()); @@ -985,6 +1011,7 @@ impl PageScriptHost { href, creator_base_url.clone(), creator_policy_container.clone(), + creator_is_secure_context, receiver, )?; Some(OpenedLightweightPopup { @@ -998,7 +1025,6 @@ impl PageScriptHost { pub(crate) fn create_lightweight_popup_window<'s>( &mut self, scope: &mut v8::PinScope<'s, '_>, - host_ptr: *mut PageScriptHost, opener: Option>, opener_child_handle: Option, target_name: &str, @@ -1006,6 +1032,7 @@ impl PageScriptHost { opener_sandbox_policy: Option, creator_base_url: Url, creator_policy_container: DocumentPolicyContainer, + creator_is_secure_context: bool, response: Option, ) -> Option<(v8::Local<'s, v8::Object>, u64)> { let parsed_url = Url::parse(href).ok()?; @@ -1060,80 +1087,7 @@ impl PageScriptHost { .set(trackable_lightweight_popup_window_name(target_name).unwrap_or_default()); let auxiliary_window = self.browser_context_runtime.new_auxiliary_window(); let popup_id = auxiliary_window.id(); - let window = self - .bridge - .bindings - .instantiate_window_shell(scope, host_ptr); - crate::web_api_interfaces::Window::DESCRIPTOR - .initialize(scope, window) - .ok()?; - let user_activation = crate::context_bootstrap::ensure_intrinsic_interface_constructor( - scope, - "UserActivation", - ) - .ok()?; - define_non_enumerable_static_property( - scope, - window, - "UserActivation", - user_activation.into(), - ); - if let Some(dom_exception) = global_constructor_object(scope, "DOMException") { - // Lightweight popups share the opener's V8 realm, so their - // synthetic Window shell must expose the same realm constructor - // used by DOM exceptions thrown from popup-owned callbacks. - define_non_enumerable_static_property( - scope, - window, - "DOMException", - dom_exception.into(), - ); - } - let popup_id_private_value = v8::BigInt::new_from_u64(scope, popup_id); - set_private_value( - scope, - window, - LIGHTWEIGHT_POPUP_ID_SLOT, - popup_id_private_value.into(), - ); - let initial_window_name = - trackable_lightweight_popup_window_name(target_name).unwrap_or_default(); - let initial_window_name = v8_string(scope, &initial_window_name)?; - set_private_value(scope, window, WINDOW_NAME_SLOT, initial_window_name.into()); - LightweightPopupWindowStateDeclaration::default() - .initialize(scope, window) - .ok()?; - LightweightPopupWindowOriginDeclaration::default() - .initialize(scope, window) - .ok()?; - LightweightPopupWindowOpenerDeclaration { - popup_id: popup_id_private_value, - opener: (), - } - .initialize(scope, window) - .ok()?; - set_object_slot(scope, window, "__moliWindowSelf", window.into()); - set_object_slot(scope, window, "__moliWindowParent", window.into()); - set_object_slot(scope, window, "__moliWindowTop", window.into()); - set_object_slot(scope, window, "__moliWindowFrames", window.into()); - - set_object_slot(scope, window, "self", window.into()); - set_object_slot(scope, window, "window", window.into()); - set_object_slot(scope, window, "globalThis", window.into()); - set_object_slot(scope, window, "parent", window.into()); - set_object_slot(scope, window, "top", window.into()); - set_object_slot(scope, window, "frames", window.into()); - if let Some(opener) = opener { - set_private_value(scope, window, LIGHTWEIGHT_POPUP_OPENER_SLOT, opener.into()); - install_lightweight_popup_viewport_surface_from_opener(scope, opener, window); - } else { - let opener = v8::null(scope); - set_private_value(scope, window, LIGHTWEIGHT_POPUP_OPENER_SLOT, opener.into()); - } - let _ = install_storage_aliases_for_window(scope, window); - initialize_simple_event_target(scope, window); - install_simple_window_event_handlers(scope, window); - let _ = LightweightPopupWindowMethodsDeclaration::default().initialize(scope, window); + let (window, facade_context) = self.bridge.bindings.instantiate_window_proxy_shell(scope); let initial_document_owner = self.allocate_lightweight_popup_document_owner(popup_id); let initial_local_window_id = self.allocate_lightweight_popup_local_window_id(); let initial_execution_context_owner = @@ -1161,17 +1115,16 @@ impl PageScriptHost { None, )? }; - let creator_scope = opener_endpoint - .map(|endpoint| endpoint.dispatch_scope()) - .unwrap_or_else(|| self.entered_owner_dispatch_scope(scope)); let secure_context = if moli_url::is_about_blank(&initial_url) { - self.window_is_secure_context(scope, creator_scope) - .unwrap_or(false) + creator_is_secure_context } else { moli_url::is_potentially_trustworthy_url(&initial_url) }; - let initial_document_state = - LightweightPopupDocumentState::new(initial_base_url.clone(), initial_policy_container); + let initial_document_state = LightweightPopupDocumentState::new( + initial_base_url.clone(), + initial_policy_container, + secure_context, + ); let initial_resource_origin = initial_origin.serialized_origin(); let initial_domain = if !initial_forces_opaque_origin && moli_url::is_about_blank(&initial_url) @@ -1198,6 +1151,7 @@ impl PageScriptHost { name_lookup_allowed: opener.is_some(), name: browsing_context_name, window_proxy: v8::Global::new(scope, window), + facade_context: Some(facade_context), opener: opener_endpoint, opener_window: opener.map(|opener| v8::Global::new(scope, opener)), location_url: initial_url.clone(), @@ -1239,19 +1193,6 @@ impl PageScriptHost { navigation_id: LightweightPopupNavigationId::new(1), }, ); - install_window_location_history_navigation_runtime_state( - scope, - window, - initial_url.as_str(), - ) - .ok()?; - sync_window_location_history_navigation_runtime_surface(scope, window); - crate::context_bootstrap::install_window_bar_props( - scope, - window, - Some((popup_id, initial_local_window_id)), - ) - .ok()?; self.register_committed_document_resource_loader( crate::network::context::DocumentFetchContext::new( super::WindowDocumentOwner::LightweightPopup(initial_document_owner), @@ -1263,6 +1204,14 @@ impl PageScriptHost { creator_resource_authority, ), ); + let context = match self.ensure_popup_default_context(scope, popup_id) { + Ok(context) => context, + Err(error) => { + tracing::error!(%error, popup_id, "failed to initialize popup realm"); + return None; + } + }; + let scope = &mut v8::ContextScope::new(scope, context); self.refresh_lightweight_popup_navigator(scope, popup_id, window); self.refresh_lightweight_popup_indexed_db_factory(scope, popup_id, window); if matches!(initial_url.scheme(), "http" | "https") { @@ -1303,7 +1252,6 @@ impl PageScriptHost { window, &initial_referrer, ); - set_object_slot(scope, window, "document", document.into()); let _ = self .set_lightweight_popup_document_wrapper(popup_id, v8::Global::new(scope, document)); } @@ -1350,6 +1298,7 @@ impl PageScriptHost { href: &str, creator_base_url: Url, creator_policy_container: DocumentPolicyContainer, + creator_is_secure_context: bool, response: Option, ) -> Option> { let parsed_url = Url::parse(href).ok()?; @@ -1358,8 +1307,11 @@ impl PageScriptHost { if navigation_unload_event_active(scope, window) { return Some(window); } - let mut navigation_state = - LightweightPopupDocumentState::new(initial_base_url, creator_policy_container); + let mut navigation_state = LightweightPopupDocumentState::new( + initial_base_url, + creator_policy_container, + creator_is_secure_context, + ); navigation_state.policy_container.sandbox = DocumentSandboxPolicy::from_response_content_security_policies( &navigation_state @@ -2170,6 +2122,8 @@ impl PageScriptHost { else { return false; }; + let creator_scope = self.entered_owner_dispatch_scope(scope); + let creator_is_secure_context = self.popup_creator_is_secure_context(scope, creator_scope); let Some(navigation_task) = self.start_lightweight_popup_navigation_attempt( popup_id, target_url.clone(), @@ -2187,6 +2141,7 @@ impl PageScriptHost { return false; } navigation_state.reset_for_empty_document(target_url.clone()); + navigation_state.secure_context_available = creator_is_secure_context; let inherited_origin = self .window_access_origin_for_dispatch_scope(self.entered_owner_dispatch_scope(scope)); if !self.commit_lightweight_popup_document( @@ -2617,16 +2572,6 @@ impl PageScriptHost { current_local_window_id, } }; - if changed_window { - if let Err(error) = crate::context_bootstrap::install_window_bar_props( - scope, - window, - Some((popup_id, current_local_window_id)), - ) { - tracing::warn!(%error, "failed to initialize popup BarProp objects"); - } - clear_lightweight_popup_window_document_event_state(scope, window); - } if let Some(retired_document_handle) = transition.retired_document_handle { self.retire_lightweight_popup_document_handle(popup_id, retired_document_handle); self.clear_custom_element_registry_associations_for_document(retired_document_handle); @@ -2659,8 +2604,27 @@ impl PageScriptHost { } if let Some(retired_local_window_id) = transition.retired_local_window_id { self.retire_lightweight_popup_local_window(popup_id, retired_local_window_id); - self.refresh_lightweight_popup_navigator(scope, popup_id, window); } + let context = match self.ensure_popup_default_context(scope, popup_id) { + Ok(context) => context, + Err(error) => { + tracing::error!(%error, popup_id, "failed to replace popup realm"); + return false; + } + }; + let scope = &mut v8::ContextScope::new(scope, context); + self.install_window_context_security_origin( + scope, + context, + OwnerDispatchScope::LightweightPopup(popup_id), + super::WindowExecutionContextAccessPolicy::EnforceWebOrigin, + ); + super::window_security_tokens::set_window_security_token( + scope, + context, + self.popup_default_world_security_token_key(popup_id) + .as_deref(), + ); self.refresh_lightweight_popup_indexed_db_factory(scope, popup_id, window); // Every committed LocalWindow needs its own Location, including // history restores and blank navigations that bypass parser bootstrap. @@ -2787,7 +2751,7 @@ impl PageScriptHost { .lightweight_popup_document_record(popup_id) .map(|document| document.storage_scope.clone()); let execution_context = self - .register_lightweight_popup_execution_context(scope, popup_id) + .ensure_lightweight_popup_execution_context(scope, popup_id) .then(|| self.current_registered_window_execution_context_identity(dispatch_scope)) .flatten(); let (Some(storage_scope), Some(execution_context)) = (storage_scope, execution_context) @@ -2917,6 +2881,10 @@ impl PageScriptHost { window: v8::Local<'s, v8::Object>, document_url: Url, ) { + let Ok(context) = self.ensure_popup_default_context(scope, popup_id) else { + return; + }; + let scope = &mut v8::ContextScope::new(scope, context); with_lightweight_popup_scope(scope, popup_id, |scope| { self.install_lightweight_popup_empty_document_in_owner( scope, @@ -2977,7 +2945,6 @@ impl PageScriptHost { install_lightweight_popup_get_computed_style(scope, window); } sync_lightweight_popup_document_window_slots(scope, document, window, &document_referrer); - set_object_slot(scope, window, "document", document.into()); let _ = self.set_lightweight_popup_document_wrapper(popup_id, v8::Global::new(scope, document)); } @@ -3356,6 +3323,10 @@ impl PageScriptHost { parser_completion: None, }; } + let Ok(context) = self.ensure_popup_default_context(scope, popup_id) else { + return PopupDocumentLoadApplication::NotApplied; + }; + let scope = &mut v8::ContextScope::new(scope, context); finish_cross_document_navigation_for_window( scope, window, @@ -3712,7 +3683,7 @@ impl PageScriptHost { }; let scope = &mut v8::ContextScope::new(scope, context); let popup_id = target.document_owner.popup_id(); - if !self.register_lightweight_popup_execution_context(scope, popup_id) { + if !self.ensure_lightweight_popup_execution_context(scope, popup_id) { return DispatchStatus::StopPropagation; } let previous = enter_lightweight_popup_event_dispatch(scope, popup_id); @@ -3798,7 +3769,7 @@ impl PageScriptHost { let window = v8::Local::new(popup_scope, &window); let original_target = v8::Local::new(popup_scope, &original_target); let event = v8::Local::new(popup_scope, &event); - if !self.register_lightweight_popup_execution_context(popup_scope, popup_id) { + if !self.ensure_lightweight_popup_execution_context(popup_scope, popup_id) { return true; } let previous = enter_lightweight_popup_event_dispatch(popup_scope, popup_id); @@ -3960,6 +3931,10 @@ impl PageScriptHost { window: v8::Local<'s, v8::Object>, source: LightweightPopupDocumentProjectionSource<'_>, ) -> Option { + let context = self + .ensure_popup_default_context(scope, source.task.popup_id()) + .ok()?; + let scope = &mut v8::ContextScope::new(scope, context); with_lightweight_popup_scope(scope, source.task.popup_id(), |scope| { self.install_lightweight_popup_document_projection_in_owner(scope, window, source) }) @@ -4035,7 +4010,6 @@ impl PageScriptHost { .map(|document| document.state.policy_container.document_referrer.clone()) .unwrap_or_default(); sync_lightweight_popup_document_window_slots(scope, document, window, &document_referrer); - set_object_slot(scope, window, "document", document.into()); self.forget_lightweight_popup_document_handle(popup_id); let document_handle = self.remember_lightweight_popup_document_handle(scope, popup_id, document); @@ -4740,7 +4714,7 @@ impl PageScriptHost { let current_script = current_script .as_ref() .map(|script| v8::Local::new(popup_scope, script)); - if !self.register_lightweight_popup_execution_context(popup_scope, popup_id) { + if !self.ensure_lightweight_popup_execution_context(popup_scope, popup_id) { anyhow::bail!("popup execution context owner is not current"); } self.execute_lightweight_popup_window_script_source_in_context( @@ -4995,7 +4969,7 @@ impl PageScriptHost { let context = v8::Local::new(scope, &context); let popup_scope = &mut v8::ContextScope::new(scope, context); let window = v8::Local::new(popup_scope, &window); - if !self.register_lightweight_popup_execution_context(popup_scope, popup_id) { + if !self.ensure_lightweight_popup_execution_context(popup_scope, popup_id) { anyhow::bail!("popup execution context owner is not current"); } self.execute_lightweight_popup_window_javascript_url_source_in_context( @@ -5022,31 +4996,14 @@ impl PageScriptHost { let Some(source_value) = v8_string(scope, &source) else { anyhow::bail!("failed to allocate popup javascript URL source"); }; - let Some(wrapper_source) = v8_string( - scope, - "(function(window, __moliSource) { with (window) { return eval(__moliSource); } })", - ) else { - anyhow::bail!("failed to allocate popup javascript URL wrapper"); - }; - let Some(function) = v8::Script::compile(scope, wrapper_source, None) - .and_then(|script| crate::script_execution::execute_compiled_script(scope, script)) - .and_then(|value| v8::Local::::try_from(value).ok()) - else { - anyhow::bail!("v8 failed to compile popup javascript URL wrapper"); + let Some(script) = v8::Script::compile(scope, source_value, None) else { + anyhow::bail!("v8 failed to compile popup javascript URL"); }; let previous_popup = enter_active_lightweight_popup_scope(scope, popup_id); let previous_message_source = self.enter_window_message_source_scope( super::PendingWindowMessageEndpoint::LightweightPopup(popup_id), ); - let eval_permit = crate::context_bootstrap::arm_internal_javascript_url_eval(scope); - let completion = crate::util::call_script_visible_function( - scope, - function, - window.into(), - &[window.into(), source_value.into()], - "popup javascript URL", - ); - crate::context_bootstrap::restore_internal_javascript_url_eval(scope, eval_permit); + let completion = crate::script_execution::execute_compiled_script(scope, script); self.restore_window_message_source_scope(previous_message_source); restore_active_lightweight_popup_scope(scope, previous_popup); let Some(completion) = completion else { @@ -5223,6 +5180,13 @@ impl PageScriptHost { let Some(document) = self.lightweight_popup_document_wrapper(scope, popup_id) else { return; }; + let Some(window) = self.lightweight_popup_window(scope, popup_id) else { + return; + }; + let Some(context) = window.get_creation_context(scope) else { + return; + }; + let scope = &mut v8::ContextScope::new(scope, context); let (bubbles, cancelable) = crate::host::host_event_defaults(event_type); let Ok(event) = crate::host::create_host_event( scope, @@ -5681,9 +5645,8 @@ 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. +// Native Document installation and script bookkeeping 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, @@ -5910,21 +5873,6 @@ fn install_lightweight_popup_indexed_db_factory<'s>( true } -fn install_lightweight_popup_viewport_surface_from_opener<'s>( - scope: &mut v8::PinScope<'s, '_>, - opener: v8::Local<'s, v8::Object>, - window: v8::Local<'s, v8::Object>, -) { - for property in LIGHTWEIGHT_POPUP_VIEWPORT_SURFACE_PROPERTIES { - let Some(value) = opener.get(scope, v8str(scope, property).into()) else { - continue; - }; - if value.is_number() { - set_object_slot(scope, window, property, value); - } - } -} - fn lightweight_popup_window_name_getter<'s>( scope: &mut v8::PinScope<'s, '_>, args: v8::FunctionCallbackArguments<'s>, @@ -6136,15 +6084,6 @@ pub(super) 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, @@ -6217,6 +6156,12 @@ fn sync_lightweight_popup_document_window_slots<'s>( window: v8::Local<'s, v8::Object>, referrer: &str, ) { + set_private_value( + scope, + window, + crate::context_bootstrap::WINDOW_DOCUMENT_SLOT, + document.into(), + ); sync_document_location_runtime_state_from_window(scope, document, window); if let Some(href) = crate::context_bootstrap::window_location_href(scope, window) .and_then(|href| v8_string(scope, &href)) diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups/realm.rs b/moli-renderer-v8/src/native_bridge/context_host/popups/realm.rs new file mode 100644 index 00000000000..80b4ce1dc06 --- /dev/null +++ b/moli-renderer-v8/src/native_bridge/context_host/popups/realm.rs @@ -0,0 +1,185 @@ +use super::*; +use crate::native_bridge::context_host::{ + WindowExecutionContextBinding, WindowExecutionContextOwner, +}; +use std::rc::Weak; + +pub(crate) struct PopupDefaultContext { + local_window_id: LightweightPopupLocalWindowId, + // A stable allocation retains main's failure-safe Realm lifecycle owner. + runtime: Box, +} + +impl std::ops::Deref for PopupDefaultContext { + type Target = crate::script_vm::WindowRealmRuntime; + fn deref(&self) -> &Self::Target { + &self.runtime + } +} + +pub(crate) type SharedPopupDefaultContexts = Rc>>; +pub(in crate::native_bridge::context_host) type WeakPopupDefaultContexts = + Weak>>; + +impl PageScriptHost { + pub(crate) fn popup_secure_context_available(&self, popup_id: u64) -> bool { + self.lightweight_popup_document_record(popup_id) + .is_some_and(|document| document.state.secure_context_available) + } + + pub(crate) fn take_popup_window_proxy_for_realm<'s>( + &mut self, + scope: &mut v8::PinScope<'s, '_, ()>, + popup_id: u64, + ) -> Option> { + let record = self + .lightweight_popup_browsing_contexts + .get_mut(&popup_id)?; + if let Some(context) = record.facade_context.take() { + v8::Local::new(scope, &context).detach_global(); + } + Some(v8::Local::new(scope, &record.window_proxy)) + } + + pub(crate) fn bind_popup_window_context_owner_before_runtime_bootstrap( + &self, + scope: &mut v8::PinScope<'_, '_>, + window: v8::Local<'_, v8::Object>, + popup_id: u64, + ) -> Result<()> { + anyhow::ensure!( + self.lightweight_popup_is_open(popup_id), + "missing popup LocalWindow" + ); + set_private_value( + scope, + window, + LIGHTWEIGHT_POPUP_ID_SLOT, + v8::BigInt::new_from_u64(scope, popup_id).into(), + ); + Ok(()) + } + + pub(crate) fn ensure_popup_default_context<'s>( + &mut self, + scope: &mut v8::PinScope<'s, '_>, + popup_id: u64, + ) -> Result> { + let local_window_id = self + .lightweight_popup_document_record(popup_id) + .ok_or_else(|| anyhow::anyhow!("missing popup Document"))? + .local_window_id; + let owner = WindowExecutionContextOwner::LightweightPopup { + popup_id, + local_window_id, + }; + if let Some((_, context)) = self.window_execution_context( + scope, + owner, + OwnerDispatchScope::LightweightPopup(popup_id), + ) { + return Ok(context); + } + let config = self + .window_default_context_bootstrap + .clone() + .ok_or_else(|| anyhow::anyhow!("Window realm bootstrap is unavailable"))?; + let contexts = config + .popup_contexts + .upgrade() + .ok_or_else(|| anyhow::anyhow!("popup realm owner was retired"))?; + if let Some(context) = contexts.borrow().get(&popup_id) + && context.local_window_id == local_window_id + { + return Ok(v8::Local::new(scope, &context.context)); + } + let retired = contexts.borrow_mut().remove(&popup_id); + if let Some(retired) = retired { + let context = v8::Local::new(scope, &retired.context); + context.detach_global(); + // Drop queues native resource retirement on the entered-isolate owner lane. + drop(retired); + } + let host = config + .host + .upgrade() + .ok_or_else(|| anyhow::anyhow!("popup context host was retired"))?; + let global_template = self.bridge.bindings.window_global_template(scope); + let runtime = crate::script_vm::bootstrap_popup_default_context_in_scope( + scope, + global_template, + host, + config.resource_owner_id, + &config.promise_reject_dispatch, + self.indexed_db_manager.clone(), + Some(self.storage_bucket_store.clone()), + popup_id, + local_window_id, + )?; + let local_context = v8::Local::new(scope, &runtime.context); + self.register_window_execution_context(WindowExecutionContextBinding::new( + WindowExecutionContextOwner::LightweightPopup { + popup_id, + local_window_id, + }, + OwnerDispatchScope::LightweightPopup(popup_id), + realm_token, + v8::Global::new(scope, local_context), + )); + contexts.borrow_mut().insert( + popup_id, + PopupDefaultContext { + local_window_id, + runtime: Box::new(runtime), + }, + ); + Ok(local_context) + } + + pub(crate) fn configure_popup_default_world_global<'s>( + &mut self, + scope: &mut v8::PinScope<'s, '_>, + window: v8::Local<'s, v8::Object>, + popup_id: u64, + ) -> Result<()> { + let document = self + .lightweight_popup_document_record(popup_id) + .ok_or_else(|| anyhow::anyhow!("missing popup Document during bootstrap"))?; + let url = document.url.clone(); + let local_window_id = document.local_window_id; + let name = self + .lightweight_popup_browsing_contexts + .get(&popup_id) + .ok_or_else(|| anyhow::anyhow!("missing popup browsing context"))? + .name + .get(); + let name = v8_string(scope, &name) + .ok_or_else(|| anyhow::anyhow!("popup name allocation failed"))?; + set_private_value(scope, window, WINDOW_NAME_SLOT, name.into()); + LightweightPopupWindowNameDeclaration::default().initialize(scope, window)?; + LightweightPopupWindowOriginDeclaration::default().initialize(scope, window)?; + LightweightPopupWindowOpenerDeclaration { + popup_id: v8::BigInt::new_from_u64(scope, popup_id), + opener: (), + } + .initialize(scope, window)?; + install_simple_event_target_methods(scope, window); + install_simple_window_event_handlers(scope, window); + LightweightPopupWindowMethodsDeclaration::default().initialize(scope, window)?; + install_storage_aliases_for_window(scope, window)?; + crate::context_bootstrap::reset_window_location_runtime_state(scope, window, url.as_str())?; + sync_window_location_history_navigation_runtime_surface(scope, window); + crate::context_bootstrap::install_window_bar_props( + scope, + window, + Some((popup_id, local_window_id)), + )?; + self.refresh_lightweight_popup_navigator(scope, popup_id, window); + self.refresh_lightweight_popup_indexed_db_factory(scope, popup_id, window); + + super::super::child_frame_runtime::mark_popup_window_access_check_initialized( + scope, window, + ); + Ok(()) + } +} 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 65de23b52c9..bc71f9d1d6a 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 @@ -235,42 +235,12 @@ impl PageScriptHost { self.bridge.abort.clear_for_context_teardown(); } - pub(crate) fn register_lightweight_popup_execution_context( - &mut self, - scope: &mut v8::PinScope<'_, '_>, - popup_id: u64, - ) -> bool { - let dispatch_scope = OwnerDispatchScope::LightweightPopup(popup_id); - let Some(owner) = self.current_window_execution_context_owner(dispatch_scope) else { - return false; - }; - let Some(realm_token) = current_runtime_observable_context_token(scope) else { - return false; - }; - self.register_window_execution_context(WindowExecutionContextBinding::new( - owner, - dispatch_scope, - realm_token, - v8::Global::new(scope, scope.get_current_context()), - )); - true - } - pub(crate) fn ensure_lightweight_popup_execution_context( &mut self, scope: &mut v8::PinScope<'_, '_>, popup_id: u64, ) -> bool { - let Some(window) = self.lightweight_popup_window(scope, popup_id) else { - return false; - }; - let Some(context) = window.get_creation_context(scope) else { - return false; - }; - let context = v8::Global::new(scope, context); - let context = v8::Local::new(scope, &context); - let popup_scope = &mut v8::ContextScope::new(scope, context); - self.register_lightweight_popup_execution_context(popup_scope, popup_id) + self.ensure_popup_default_context(scope, popup_id).is_ok() } pub(crate) fn current_runtime_window_execution_context_binding( @@ -295,7 +265,11 @@ impl PageScriptHost { { return Some(owner.identity); } - let dispatch_scope = if let Some(popup_id) = active_lightweight_popup_id(scope) { + let dispatch_scope = if let Some(identity) = + self.window_execution_context_identity_for_access_check(scope.get_current_context()) + { + identity.dispatch_scope() + } else if let Some(popup_id) = active_lightweight_popup_id(scope) { OwnerDispatchScope::LightweightPopup(popup_id) } else if let Some(child_handle) = crate::context_bootstrap::child_browsing_context_handle_for_current_realm_scope(scope) @@ -318,26 +292,7 @@ impl PageScriptHost { let realm_token = current_runtime_observable_context_token(scope)?; let registration = self .window_execution_context_realms - .registration(dispatch_scope, realm_token) - .or_else(|| { - // Lightweight popups still share their opener's concrete V8 context. Until P2 - // gives each popup a LocalWindow realm, the active popup scope is the only exact - // address available at API acceptance. - matches!(dispatch_scope, OwnerDispatchScope::LightweightPopup(_)) - .then(|| { - self.current_window_execution_context_owner(dispatch_scope) - .map(|owner| { - WindowExecutionContextRealmRegistration::new( - owner, - self.effective_window_access_policy( - dispatch_scope, - WindowExecutionContextAccessPolicy::EnforceWebOrigin, - ), - ) - }) - }) - .flatten() - })?; + .registration(dispatch_scope, realm_token)?; let owner = registration.owner; if !self.window_execution_context_owner_is_current(owner, dispatch_scope) { return None; @@ -399,28 +354,16 @@ impl PageScriptHost { pub(crate) fn window_execution_context_identity_for_v8_context( &self, - scope: &mut v8::PinScope<'_, '_>, + _scope: &mut v8::PinScope<'_, '_>, context: v8::Local<'_, v8::Context>, ) -> Option { let realm_token = context .get_slot::() .as_deref() .copied()?; - let registered = match active_lightweight_popup_id(scope) { - Some(popup_id) => { - let dispatch_scope = OwnerDispatchScope::LightweightPopup(popup_id); - let registration = self - .window_execution_context_realms - .registration(dispatch_scope, realm_token)?; - super::WindowExecutionContextScopedRealmRegistration::new( - dispatch_scope, - registration, - ) - } - None => self - .window_execution_context_realms - .concrete_registration(realm_token)?, - }; + let registered = self + .window_execution_context_realms + .concrete_registration(realm_token)?; Some(WindowExecutionContextIdentity::new( registered.registration.owner, registered.dispatch_scope, @@ -556,19 +499,9 @@ impl PageScriptHost { crate::observer_runtime::retire_execution_context_owner(self, owner); let retired = self.window_execution_contexts.remove(&owner); if let Some(binding) = retired.as_ref() { - // A lightweight popup is an owner alias over its opener's concrete - // realm. Retire its exact-owner state without destroying the - // opener's realm-wide wrappers and IndexedDB state. - if matches!( - binding.dispatch_scope(), - OwnerDispatchScope::LightweightPopup(_) - ) { - self.retire_indexed_db_owner(owner); - } else { - self.retire_indexed_db_context(binding.realm_token()); - self.bridge - .retire_default_world_wrappers_for_realm(binding.realm_token()); - } + self.retire_indexed_db_context(binding.realm_token()); + self.bridge + .retire_default_world_wrappers_for_realm(binding.realm_token()); } self.window_execution_context_realms.retire_owner(owner); if retired.is_some() { @@ -817,13 +750,14 @@ mod tests { document_runtime::DomHandle, frame_owner_model::LocalWindowId, native_bridge::context_host::{ - WindowExecutionContextRealmRecords, WindowExecutionContextScopedRealmRegistration, + WindowExecutionContextRealmRecords, + window_execution_context::WindowExecutionContextScopedRealmRegistration, }, window_document_identity::LightweightPopupLocalWindowId, }; #[test] - fn concrete_realm_identity_and_lightweight_popup_alias_share_one_context_token() { + fn popup_and_opener_have_distinct_concrete_realm_tokens() { let mut records = WindowExecutionContextRealmRecords::default(); let token = RuntimeObservableContextToken::from_raw(17); let top_scope = OwnerDispatchScope::Top; @@ -832,6 +766,7 @@ mod tests { WindowExecutionContextAccessPolicy::EnforceWebOrigin, ); let popup_scope = OwnerDispatchScope::LightweightPopup(7); + let popup_token = RuntimeObservableContextToken::from_raw(18); let popup_registration = WindowExecutionContextRealmRegistration::new( WindowExecutionContextOwner::LightweightPopup { popup_id: 7, @@ -844,8 +779,21 @@ mod tests { assert!( records .register(popup_scope, token, popup_registration) + .is_err() + ); + assert!( + records + .register(popup_scope, popup_token, popup_registration) .is_ok() ); + assert_eq!( + records.concrete_registration(popup_token), + Some(WindowExecutionContextScopedRealmRegistration::new( + popup_scope, + popup_registration + )) + ); + assert_eq!( records.concrete_registration(token), Some(WindowExecutionContextScopedRealmRegistration::new( @@ -854,7 +802,7 @@ mod tests { )) ); assert_eq!( - records.registration(popup_scope, token), + records.registration(popup_scope, popup_token), Some(popup_registration) ); @@ -866,7 +814,9 @@ mod tests { "one V8 context token must have exactly one concrete Window realm" ); - assert_eq!(records.remove_token(token), 2); + assert_eq!(records.remove_token(token), 1); + assert!(records.registration(popup_scope, popup_token).is_some()); + assert_eq!(records.remove_token(popup_token), 1); assert!(records.concrete_registration(token).is_none()); assert!(records.registration(popup_scope, token).is_none()); } diff --git a/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs b/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs index f193ac668c5..00a2a85c486 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/security_policy.rs @@ -968,6 +968,10 @@ impl PageScriptHost { &self, scope: &mut v8::PinScope<'_, '_>, ) -> OwnerDispatchScope { + let context = scope.get_entered_or_microtask_context(); + if let Some(identity) = self.window_execution_context_identity_for_access_check(context) { + return identity.dispatch_scope(); + } if let Some(handle) = entered_child_window_handle(scope) { return OwnerDispatchScope::Child(handle); } diff --git a/moli-renderer-v8/src/native_bridge/context_host/window_execution_context.rs b/moli-renderer-v8/src/native_bridge/context_host/window_execution_context.rs index e049dcabe2b..fed82e7bab5 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/window_execution_context.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/window_execution_context.rs @@ -22,11 +22,12 @@ mod settings; pub(crate) use binding::WindowExecutionContextBinding; pub(crate) use fetch::{DetachedWindowFetchContext, WindowFetchContext, WindowTaskTarget}; pub(crate) use operation_receiver::WindowOperationReceiver; +#[cfg(test)] +pub(super) use registry::WindowExecutionContextScopedRealmRegistration; pub(crate) use registry::{ WindowExecutionContextAccessPolicy, WindowExecutionContextIdentity, WindowExecutionContextOwner, }; pub(super) use registry::{ WindowExecutionContextRealmRecords, WindowExecutionContextRealmRegistration, - WindowExecutionContextScopedRealmRegistration, }; pub(crate) use settings::WindowEnvironmentSettings; diff --git a/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/binding.rs b/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/binding.rs index a9b190c2ef4..713f3497009 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/binding.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/binding.rs @@ -8,9 +8,7 @@ use super::{WindowExecutionContextIdentity, WindowExecutionContextOwner}; /// /// The registry remains authoritative for the access policy. Keeping policy /// out of this locator prevents copied bindings from becoming a second source -/// of truth. A lightweight popup is the one temporary exception to "concrete -/// realm": until popups own V8 contexts, the registry gives each popup an -/// explicit alias over its opener's context token. +/// of truth. Each Window, including a popup, registers its own concrete realm. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub(super) struct WindowExecutionContextLocator { owner: WindowExecutionContextOwner, diff --git a/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/registry.rs b/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/registry.rs index 2968feba8cb..20ea735f67e 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/registry.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/registry.rs @@ -58,15 +58,9 @@ impl WindowExecutionContextScopedRealmRegistration { #[derive(Default)] pub(in crate::native_bridge::context_host) struct WindowExecutionContextRealmRecords { - // A V8 context token identifies one concrete realm. Lightweight popups - // currently share their opener's concrete context, so their entries are - // explicitly scoped aliases rather than competing concrete registrations. + // Every Window owns a concrete V8 realm, including popup Windows. pub(in crate::native_bridge::context_host) concrete_by_token: HashMap, - lightweight_popup_aliases: HashMap< - (OwnerDispatchScope, RuntimeObservableContextToken), - WindowExecutionContextRealmRegistration, - >, } impl WindowExecutionContextRealmRecords { @@ -75,17 +69,10 @@ impl WindowExecutionContextRealmRecords { dispatch_scope: OwnerDispatchScope, realm_token: RuntimeObservableContextToken, ) -> Option { - match dispatch_scope { - OwnerDispatchScope::LightweightPopup(_) => self - .lightweight_popup_aliases - .get(&(dispatch_scope, realm_token)) - .copied(), - OwnerDispatchScope::Top | OwnerDispatchScope::Child(_) => self - .concrete_by_token - .get(&realm_token) - .filter(|registered| registered.dispatch_scope == dispatch_scope) - .map(|registered| registered.registration), - } + self.concrete_by_token + .get(&realm_token) + .filter(|registered| registered.dispatch_scope == dispatch_scope) + .map(|registered| registered.registration) } pub(in crate::native_bridge::context_host) fn concrete_registration( @@ -103,33 +90,12 @@ impl WindowExecutionContextRealmRecords { ) -> Result<(), WindowExecutionContextScopedRealmRegistration> { let candidate = WindowExecutionContextScopedRealmRegistration::new(dispatch_scope, registration); - match dispatch_scope { - OwnerDispatchScope::LightweightPopup(_) => { - match self - .lightweight_popup_aliases - .get(&(dispatch_scope, realm_token)) - { - Some(registered) if *registered != registration => { - return Err(WindowExecutionContextScopedRealmRegistration::new( - dispatch_scope, - *registered, - )); - } - Some(_) => return Ok(()), - None => {} - } - self.lightweight_popup_aliases - .insert((dispatch_scope, realm_token), registration); - } - OwnerDispatchScope::Top | OwnerDispatchScope::Child(_) => { - match self.concrete_by_token.get(&realm_token) { - Some(registered) if *registered != candidate => return Err(*registered), - Some(_) => return Ok(()), - None => {} - } - self.concrete_by_token.insert(realm_token, candidate); - } + match self.concrete_by_token.get(&realm_token) { + Some(registered) if *registered != candidate => return Err(*registered), + Some(_) => return Ok(()), + None => {} } + self.concrete_by_token.insert(realm_token, candidate); Ok(()) } @@ -138,20 +104,12 @@ impl WindowExecutionContextRealmRecords { dispatch_scope: OwnerDispatchScope, realm_token: RuntimeObservableContextToken, ) { - match dispatch_scope { - OwnerDispatchScope::LightweightPopup(_) => { - self.lightweight_popup_aliases - .remove(&(dispatch_scope, realm_token)); - } - OwnerDispatchScope::Top | OwnerDispatchScope::Child(_) => { - if self - .concrete_by_token - .get(&realm_token) - .is_some_and(|registered| registered.dispatch_scope == dispatch_scope) - { - self.concrete_by_token.remove(&realm_token); - } - } + if self + .concrete_by_token + .get(&realm_token) + .is_some_and(|registered| registered.dispatch_scope == dispatch_scope) + { + self.concrete_by_token.remove(&realm_token); } } @@ -159,11 +117,7 @@ impl WindowExecutionContextRealmRecords { &mut self, realm_token: RuntimeObservableContextToken, ) -> usize { - let concrete_count = usize::from(self.concrete_by_token.remove(&realm_token).is_some()); - let alias_count_before = self.lightweight_popup_aliases.len(); - self.lightweight_popup_aliases - .retain(|(_, token), _| *token != realm_token); - concrete_count + alias_count_before.saturating_sub(self.lightweight_popup_aliases.len()) + usize::from(self.concrete_by_token.remove(&realm_token).is_some()) } pub(in crate::native_bridge::context_host) fn retire_owner( @@ -172,8 +126,6 @@ impl WindowExecutionContextRealmRecords { ) { self.concrete_by_token .retain(|_, registered| registered.registration.owner != owner); - self.lightweight_popup_aliases - .retain(|_, registered| registered.owner != owner); } } @@ -217,9 +169,8 @@ impl WindowExecutionContextIdentity { } /// Encodes an exact callback-realm identity for storage in an internal V8 - /// private slot. Lightweight popup realms alias their opener's V8 context, - /// so retaining only that context would lose the LocalWindow generation - /// and dispatch address captured when the callback was converted. + /// private slot. It preserves the LocalWindow generation and dispatch + /// address captured when the callback was converted. pub(crate) fn serialize_for_internal_slot(self) -> String { let policy = u8::from(self.grants_universal_access()); match (self.owner, self.dispatch_scope) { 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 ecc341673db..ccb0a27f93b 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 @@ -271,15 +271,11 @@ impl PageScriptHost { pub(crate) fn window_dispatch_scope_for_context<'s>( &self, - scope: &mut v8::PinScope<'s, '_>, + _scope: &mut v8::PinScope<'s, '_>, context: v8::Local<'s, v8::Context>, ) -> Option { - super::popups::active_lightweight_popup_id_for_context(scope, context) - .map(OwnerDispatchScope::LightweightPopup) - .or_else(|| { - self.window_execution_context_identity_for_access_check(context) - .map(|identity| identity.dispatch_scope()) - }) + self.window_execution_context_identity_for_access_check(context) + .map(|identity| identity.dispatch_scope()) } pub(crate) fn window_security_origin_for_context<'s>( @@ -290,14 +286,6 @@ impl PageScriptHost { 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. - if let Some(popup_id) = - super::popups::active_lightweight_popup_id_for_context(scope, context) - { - return self.lightweight_popup_security_origin(popup_id); - } WindowSecurityOrigin::for_context(context) } @@ -340,17 +328,10 @@ impl PageScriptHost { .get_slot::() .map(|security| security.origin.clone()) }); - let entry_origin = match crate::native_bridge::active_lightweight_popup_id(scope) { - Some(popup_id) => self.lightweight_popup_window_access_origin(popup_id), - None => { - // Borrowed functions run in their callee realm, but HTML checks - // the entry global's Document, including when entered by a microtask. - let context = scope.get_entered_or_microtask_context(); - context - .get_slot::() - .map(|security| security.origin.clone()) - } - }; + let context = scope.get_entered_or_microtask_context(); + let entry_origin = context + .get_slot::() + .map(|security| security.origin.clone()); origin .zip(entry_origin) .is_some_and(|(origin, entry)| origin.has_same_origin(&entry)) @@ -370,8 +351,9 @@ impl PageScriptHost { 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, + OwnerDispatchScope::LightweightPopup(id) => { + self.lightweight_popup_document_domain_state(id) + } }; if let Some(domain) = &domain { domain.register_context(scope, context); @@ -484,6 +466,18 @@ impl PageScriptHost { window_security_token_key(origin) } + pub(crate) fn popup_default_world_security_token_key(&self, popup_id: u64) -> Option { + let origin = self.lightweight_popup_access_origin(popup_id)?; + if self + .lightweight_popup_document_domain_state(popup_id)? + .get() + .is_some() + { + return None; + } + window_security_token_key(origin.serialized_origin()) + } + pub(crate) fn child_default_world_security_token_key( &self, handle: DomHandle, diff --git a/moli-renderer-v8/src/native_bridge/document/lifecycle.rs b/moli-renderer-v8/src/native_bridge/document/lifecycle.rs index bac7b9f3337..ad9f1828960 100644 --- a/moli-renderer-v8/src/native_bridge/document/lifecycle.rs +++ b/moli-renderer-v8/src/native_bridge/document/lifecycle.rs @@ -395,9 +395,6 @@ impl PageScriptHost { &self, scope: &mut v8::PinScope<'_, '_>, ) -> Option { - if let Some(popup_id) = crate::native_bridge::active_lightweight_popup_id(scope) { - return self.lightweight_popup_document_handle(popup_id); - } // Borrowed methods execute in their callee realm. HTML instead uses // the Window that entered this script or microtask. let context = scope.get_entered_or_microtask_context(); diff --git a/moli-renderer-v8/src/native_bridge/element/activation/targets.rs b/moli-renderer-v8/src/native_bridge/element/activation/targets.rs index 9e95a27b6d0..5279795f209 100644 --- a/moli-renderer-v8/src/native_bridge/element/activation/targets.rs +++ b/moli-renderer-v8/src/native_bridge/element/activation/targets.rs @@ -345,7 +345,6 @@ fn navigate_element_popup_target( } let Some(opened_popup) = runtime.open_lightweight_popup_window( scope, - runtime_ptr, opener, opener_child_handle, Some(dispatch_scope), @@ -484,13 +483,13 @@ pub(in crate::native_bridge) fn choose_form_navigation_target( id, opener, opener_child_handle, + source, None, creator.base_url, creator.policy_container, ), _ => runtime.open_lightweight_popup_window( scope, - runtime_ptr, opener, opener_child_handle, Some(source), diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/fetch_xhr/fetch.rs b/moli-renderer-v8/src/runtime/page_vm/tests/fetch_xhr/fetch.rs index 115097191fb..11b16b11c67 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/fetch_xhr/fetch.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/fetch_xhr/fetch.rs @@ -1124,7 +1124,7 @@ async fn opener_calling_popup_fetch_uses_popup_response_csp() { blockedURI: event.blockedURI, effectiveDirective: event.effectiveDirective, disposition: event.disposition, - instance: event instanceof SecurityPolicyViolationEvent, + instance: event instanceof popup.SecurityPolicyViolationEvent, }); }); popup.fetch("data:text/plain,blocked").then( @@ -1137,7 +1137,7 @@ async fn opener_calling_popup_fetch_uses_popup_response_csp() { error => { globalThis.__popupFetchCspObserved = JSON.stringify({ name: error && error.name, - isTypeError: error instanceof TypeError, + isTypeError: error instanceof popup.TypeError, hasCspMessage: String(error && error.message) .includes("Content Security Policy"), events: globalThis.__popupFetchCspEvents, diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rs index b686bb2693e..f0e63ca75a3 100644 --- a/moli-renderer-v8/src/script_vm.rs +++ b/moli-renderer-v8/src/script_vm.rs @@ -854,6 +854,7 @@ pub(crate) use worker_host_bridge_body::WorkerHostBridgeBodyEffect; pub(crate) use post_parse::{ bootstrap_child_default_context_in_scope, bootstrap_isolated_window_context_in_scope, + bootstrap_popup_default_context_in_scope, }; #[cfg(feature = "devtools")] @@ -1000,6 +1001,7 @@ pub(super) struct ScriptVm { page_isolated_world_contexts: PageIsolatedWorldRegistry, child_frame_realm_store: child_frame_realm::ChildFrameRealmStore, prebootstrapped_child_default_contexts: SharedPrebootstrappedChildDefaultContexts, + pub(super) popup_default_contexts: crate::native_bridge::SharedPopupDefaultContexts, child_document_modulator_store: ChildDocumentModulatorStore, root_frame_id: Option, // `PageScriptHost` stores a non-owning pointer into `document_runtime`, so it @@ -1232,23 +1234,11 @@ impl ScriptVm { self._context_host .borrow_mut() .set_indexed_db_manager(manager.clone()); - let mut context_ptrs: Vec<*const v8::Global> = Vec::with_capacity( - 1 + self.page_isolated_world_contexts.len() + self.child_frame_realm_store.len(), - ); - context_ptrs.extend( - self.current_main_world() - .map(WindowRealmRuntime::context_ptr), - ); - context_ptrs.extend( - self.page_isolated_world_contexts - .contexts() - .map(|world| &world.context as *const _), - ); - context_ptrs.extend( - self.child_frame_realm_store - .values() - .map(|world| &world.context as *const _), - ); + let context_ptrs = self + .page_runtime_observable_contexts() + .into_iter() + .map(|context| context.context) + .collect::>(); let _ = self .renderer_document_isolate @@ -1274,23 +1264,11 @@ impl ScriptVm { self._context_host .borrow_mut() .set_storage_bucket_store(store.clone()); - let mut context_ptrs: Vec<*const v8::Global> = Vec::with_capacity( - 1 + self.page_isolated_world_contexts.len() + self.child_frame_realm_store.len(), - ); - context_ptrs.extend( - self.current_main_world() - .map(WindowRealmRuntime::context_ptr), - ); - context_ptrs.extend( - self.page_isolated_world_contexts - .contexts() - .map(|world| &world.context as *const _), - ); - context_ptrs.extend( - self.child_frame_realm_store - .values() - .map(|world| &world.context as *const _), - ); + let context_ptrs = self + .page_runtime_observable_contexts() + .into_iter() + .map(|context| context.context) + .collect::>(); let _ = self .renderer_document_isolate @@ -2248,11 +2226,13 @@ impl ScriptVmPageRealmBootstrap { } let promise_reject_dispatch = promise_reject_dispatch_slot(context_host.clone()); let prebootstrapped_child_default_contexts = Rc::new(RefCell::new(Default::default())); + let popup_default_contexts = Rc::new(RefCell::new(HashMap::new())); context_host .borrow_mut() - .install_child_default_context_bootstrap( + .install_window_default_context_bootstrap( Rc::downgrade(&context_host), Rc::downgrade(&prebootstrapped_child_default_contexts), + Rc::downgrade(&popup_default_contexts), resource_owner_id, promise_reject_dispatch.clone(), ); @@ -2272,6 +2252,7 @@ impl ScriptVmPageRealmBootstrap { root_frame_id, context_host, prebootstrapped_child_default_contexts, + popup_default_contexts, page_context_cancel_tx, post_domcontentloaded_page_task_tx, page_runtime_wake_tx, @@ -2296,6 +2277,7 @@ impl ScriptVmPageRealmBootstrap { root_frame_id, context_host, prebootstrapped_child_default_contexts, + popup_default_contexts, page_context_cancel_tx, post_domcontentloaded_page_task_tx, page_runtime_wake_tx, @@ -2351,6 +2333,7 @@ impl ScriptVmPageRealmBootstrap { root_frame_id, context_host, prebootstrapped_child_default_contexts, + popup_default_contexts, page_context_cancel_tx, post_domcontentloaded_page_task_tx, page_runtime_wake_tx, @@ -2537,6 +2520,7 @@ impl ScriptVmDefaultWorldBootstrap { document_runtime, context_host, prebootstrapped_child_default_contexts, + popup_default_contexts, page_context_cancel_tx, post_domcontentloaded_page_task_tx, page_runtime_wake_tx, @@ -2556,6 +2540,7 @@ impl ScriptVmDefaultWorldBootstrap { page_isolated_world_contexts: PageIsolatedWorldRegistry::new(), child_frame_realm_store: child_frame_realm::ChildFrameRealmStore::default(), prebootstrapped_child_default_contexts, + popup_default_contexts, child_document_modulator_store: ChildDocumentModulatorStore::default(), root_frame_id, document_runtime: ScriptVmDocumentRuntimeOwner::new(document_runtime), @@ -2785,6 +2770,13 @@ impl ScriptVm { .map(|world| &world.runtime.context as *const _), ); + context_ptrs.extend( + self.popup_default_contexts + .borrow() + .values() + .map(|realm| &realm.context as *const _), + ); + for (index, context_ptr) in context_ptrs.into_iter().enumerate() { self.clear_context_wrapper_cache_for_context_ptr(context_ptr, index == 0); } diff --git a/moli-renderer-v8/src/script_vm/context_scope.rs b/moli-renderer-v8/src/script_vm/context_scope.rs index 39a4fd6524d..a3eed1087cd 100644 --- a/moli-renderer-v8/src/script_vm/context_scope.rs +++ b/moli-renderer-v8/src/script_vm/context_scope.rs @@ -239,6 +239,20 @@ impl ScriptVm { }) } + #[cfg(test)] + pub(super) fn with_popup_context_scope_and_checkpoint_for_test( + &mut self, + popup_id: u64, + op: impl FnOnce(&mut v8::PinScope<'_, '_>, *mut PageScriptHost) -> Result, + ) -> Result { + self.with_default_context_scope_and_checkpoint_for_test(|scope, host_ptr| { + let context = + unsafe { &mut *host_ptr }.ensure_popup_default_context(scope, popup_id)?; + let scope = &mut v8::ContextScope::new(scope, context); + op(scope, host_ptr) + }) + } + #[cfg(test)] pub(super) fn with_frame_realm_scope_and_checkpoint_for_test( &mut self, diff --git a/moli-renderer-v8/src/script_vm/document_isolate.rs b/moli-renderer-v8/src/script_vm/document_isolate.rs index 02fd9e38cfb..d965ef0e40c 100644 --- a/moli-renderer-v8/src/script_vm/document_isolate.rs +++ b/moli-renderer-v8/src/script_vm/document_isolate.rs @@ -186,6 +186,7 @@ pub(super) struct ScriptVmPageRealmBootstrap { pub(super) renderer_document_isolate_teardown: RendererDocumentIsolateTeardown, pub(super) root_frame_id: Option, pub(super) prebootstrapped_child_default_contexts: SharedPrebootstrappedChildDefaultContexts, + pub(super) popup_default_contexts: crate::native_bridge::SharedPopupDefaultContexts, pub(super) page_context_cancel_tx: RendererPageContextCancelSender, pub(super) post_domcontentloaded_page_task_tx: PageTaskSender, pub(super) page_runtime_wake_tx: PageRuntimeWakeSender, @@ -588,6 +589,7 @@ pub(crate) struct ScriptVmDefaultWorldBootstrap { pub(super) renderer_page_script_environment: Option, pub(super) root_frame_id: Option, pub(super) prebootstrapped_child_default_contexts: SharedPrebootstrappedChildDefaultContexts, + pub(super) popup_default_contexts: crate::native_bridge::SharedPopupDefaultContexts, pub(super) page_context_cancel_tx: RendererPageContextCancelSender, pub(super) post_domcontentloaded_page_task_tx: PageTaskSender, pub(super) page_runtime_wake_tx: PageRuntimeWakeSender, diff --git a/moli-renderer-v8/src/script_vm/indexed_db_task_body.rs b/moli-renderer-v8/src/script_vm/indexed_db_task_body.rs index 1f124f7dd5d..f205262a4d1 100644 --- a/moli-renderer-v8/src/script_vm/indexed_db_task_body.rs +++ b/moli-renderer-v8/src/script_vm/indexed_db_task_body.rs @@ -93,8 +93,7 @@ impl ScriptVm { /// Executes one exact Page-side IndexedDB task after Page-root and Window /// realm authorization. The local task id is consumed by identity rather - /// than by queue head so a stale alias can never steal another realm's - /// task from a shared V8 context. + /// than by queue head so a stale ticket cannot consume another task. pub(crate) fn apply_current_indexed_db_task_body( &mut self, authorization: AuthorizedCurrentPageIndexedDbTask, diff --git a/moli-renderer-v8/src/script_vm/post_parse.rs b/moli-renderer-v8/src/script_vm/post_parse.rs index 8623a64cbbf..db28bd1ffed 100644 --- a/moli-renderer-v8/src/script_vm/post_parse.rs +++ b/moli-renderer-v8/src/script_vm/post_parse.rs @@ -215,6 +215,9 @@ impl ScriptVmContextBootstrap { unsafe { &mut *host_ptr } .take_child_window_proxy_shell_for_realm(scope, child_handle) } + WindowContextBootstrapMode::PopupDefault { popup_id, .. } => { + unsafe { &mut *host_ptr }.take_popup_window_proxy_for_realm(scope, popup_id) + } WindowContextBootstrapMode::Isolated { child_handle: Some(child_handle), expected_owner, @@ -310,6 +313,9 @@ impl ScriptVmContextBootstrap { WindowContextBootstrapMode::ChildDefault { child_handle, .. } => { unsafe { &*host_ptr }.child_default_world_security_token_key(child_handle) } + WindowContextBootstrapMode::PopupDefault { popup_id, .. } => { + unsafe { &*host_ptr }.popup_default_world_security_token_key(popup_id) + } WindowContextBootstrapMode::Isolated { child_handle: Some(child_handle), .. @@ -319,6 +325,9 @@ impl ScriptVmContextBootstrap { } => unsafe { &*host_ptr }.main_isolated_world_security_token_key(), }; let dispatch_scope = match mode { + WindowContextBootstrapMode::PopupDefault { popup_id, .. } => { + crate::native_bridge::OwnerDispatchScope::LightweightPopup(popup_id) + } WindowContextBootstrapMode::ChildDefault { child_handle, .. } | WindowContextBootstrapMode::Isolated { child_handle: Some(child_handle), @@ -348,7 +357,8 @@ impl ScriptVmContextBootstrap { } match mode { WindowContextBootstrapMode::MainDefault - | WindowContextBootstrapMode::ChildDefault { .. } => { + | WindowContextBootstrapMode::ChildDefault { .. } + | WindowContextBootstrapMode::PopupDefault { .. } => { unsafe { &*host_ptr } .install_default_world_wrapper_cache_for_context(local_context); } @@ -367,6 +377,13 @@ impl ScriptVmContextBootstrap { // Window-owned accessors installed below must resolve against this // context's LocalWindow from their first observable bootstrap call. match mode { + WindowContextBootstrapMode::PopupDefault { popup_id, .. } => { + unsafe { &*host_ptr }.bind_popup_window_context_owner_before_runtime_bootstrap( + scope, + bootstrap_global, + popup_id, + )?; + } WindowContextBootstrapMode::ChildDefault { child_handle, .. } | WindowContextBootstrapMode::Isolated { child_handle: Some(child_handle), @@ -393,24 +410,48 @@ impl ScriptVmContextBootstrap { runtime_observable_context_token, resource_owner_id, )?; + if let WindowContextBootstrapMode::PopupDefault { + popup_id, + local_window_id, + } = mode + { + unsafe { &mut *host_ptr }.register_window_execution_context( + crate::native_bridge::WindowExecutionContextBinding::new( + crate::native_bridge::WindowExecutionContextOwner::LightweightPopup { + popup_id, + local_window_id, + }, + dispatch_scope, + runtime_observable_context_token, + v8::Global::new(scope, local_context), + ), + ); + } // SecureContext is origin-based, not document-URL-based. Initial // about:blank/srcdoc child contexts can keep about:* document URLs while // inheriting the creator's origin, so child bootstrap must ask the // context host for the origin-aware URL instead of using current_url(). - let secure_context_url = match mode { + let secure_context_available = match mode { + WindowContextBootstrapMode::PopupDefault { popup_id, .. } => { + unsafe { &*host_ptr }.popup_secure_context_available(popup_id) + } WindowContextBootstrapMode::Isolated { child_handle: Some(child_handle), .. } | WindowContextBootstrapMode::ChildDefault { child_handle, .. } => { - unsafe { &*host_ptr } - .child_browsing_context_secure_context_url(child_handle) - .unwrap_or_else(|| unsafe { &*host_ptr }.document_url().clone()) + moli_url::is_potentially_trustworthy_url( + &unsafe { &*host_ptr } + .child_browsing_context_secure_context_url(child_handle) + .unwrap_or_else(|| unsafe { &*host_ptr }.document_url().clone()), + ) } WindowContextBootstrapMode::MainDefault | WindowContextBootstrapMode::Isolated { child_handle: None, .. - } => unsafe { &*host_ptr }.main_document_secure_context_url(), + } => moli_url::is_potentially_trustworthy_url( + &unsafe { &*host_ptr }.main_document_secure_context_url(), + ), }; if let WindowContextBootstrapMode::Isolated { child_handle, .. } = mode { let owner_context = match child_handle { @@ -426,8 +467,12 @@ impl ScriptVmContextBootstrap { crate::context_bootstrap::bind_isolated_window_history_owner(scope, global, owner); crate::context_bootstrap::bind_isolated_window_selection_owner(scope, global, owner); } - finish_context_bootstrap(scope, unsafe { &mut *host_ptr }, &secure_context_url)?; + finish_context_bootstrap(scope, unsafe { &mut *host_ptr }, secure_context_available)?; match mode { + WindowContextBootstrapMode::PopupDefault { popup_id, .. } => { + unsafe { &mut *host_ptr } + .configure_popup_default_world_global(scope, global, popup_id)?; + } WindowContextBootstrapMode::Isolated { child_handle: Some(child_handle), expected_owner, @@ -554,9 +599,43 @@ pub(crate) fn bootstrap_isolated_window_context_in_scope<'s>( .into_runtime()) } +pub(crate) fn bootstrap_popup_default_context_in_scope<'s>( + scope: &mut v8::PinScope<'s, '_, ()>, + global_template: v8::Local<'s, v8::ObjectTemplate>, + context_host: Rc>, + resource_owner_id: ResourceOwnerId, + promise_reject_dispatch: &PromiseRejectDispatchSlot, + indexed_db_manager: Option, + storage_bucket_store: Option, + popup_id: u64, + local_window_id: crate::window_document_identity::LightweightPopupLocalWindowId, +) -> Result { + Ok(ScriptVmContextBootstrap::new_in_scope( + scope, + global_template, + context_host, + resource_owner_id, + promise_reject_dispatch, + indexed_db_manager, + storage_bucket_store, + WindowContextBootstrapMode::PopupDefault { + popup_id, + local_window_id, + }, + None, + false, + None, + )? + .into_runtime()) +} + #[derive(Clone, Copy, Debug)] enum WindowContextBootstrapMode { MainDefault, + PopupDefault { + popup_id: u64, + local_window_id: crate::window_document_identity::LightweightPopupLocalWindowId, + }, ChildDefault { child_handle: DomHandle, expected_owner: crate::frame_owner_model::FrameDocumentTaskOwner, @@ -627,6 +706,17 @@ impl WindowContextBootstrapMode { )> { match self { Self::MainDefault => None, + Self::PopupDefault { + popup_id, + local_window_id, + } => Some(( + crate::native_bridge::WindowExecutionContextOwner::LightweightPopup { + popup_id, + local_window_id, + }, + crate::native_bridge::OwnerDispatchScope::LightweightPopup(popup_id), + crate::native_bridge::WindowExecutionContextAccessPolicy::EnforceWebOrigin, + )), Self::ChildDefault { child_handle, expected_owner, diff --git a/moli-renderer-v8/src/script_vm/runtime_observability.rs b/moli-renderer-v8/src/script_vm/runtime_observability.rs index ec25d4bff09..59ebefd6012 100644 --- a/moli-renderer-v8/src/script_vm/runtime_observability.rs +++ b/moli-renderer-v8/src/script_vm/runtime_observability.rs @@ -199,6 +199,17 @@ impl ScriptVm { }); } } + let popups = self.popup_default_contexts.borrow(); + let mut popup_ids = popups.keys().copied().collect::>(); + popup_ids.sort_unstable(); + for popup_id in popup_ids { + let popup = &popups[&popup_id]; + contexts.push(PageRuntimeObservableContext { + execution_context_id: None, + context_token: popup.realm_token, + context: &popup.context as *const _, + }); + } contexts } diff --git a/moli-renderer-v8/src/script_vm/security_policy.rs b/moli-renderer-v8/src/script_vm/security_policy.rs index eab7c22291f..c9319acace8 100644 --- a/moli-renderer-v8/src/script_vm/security_policy.rs +++ b/moli-renderer-v8/src/script_vm/security_policy.rs @@ -244,9 +244,6 @@ fn check_string_code_generation<'s>( let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else { return code_generation_result(true, None); }; - if crate::context_bootstrap::consume_internal_javascript_url_eval(scope) { - return code_generation_result(true, None); - } ( unsafe { &*host_ptr }.trusted_types_for_script_requirements(scope), unsafe { &*host_ptr }.allows_trusted_types_eval(scope), diff --git a/moli-renderer-v8/src/script_vm/service_worker_internal_client_request_body.rs b/moli-renderer-v8/src/script_vm/service_worker_internal_client_request_body.rs index 2f842c69135..5cf16b9e170 100644 --- a/moli-renderer-v8/src/script_vm/service_worker_internal_client_request_body.rs +++ b/moli-renderer-v8/src/script_vm/service_worker_internal_client_request_body.rs @@ -247,7 +247,6 @@ impl ScriptVm { let previous_owner_context = host_scope.enter(scope); let opened_popup = host.open_lightweight_popup_window( scope, - host_ptr, None, None, None, @@ -332,7 +331,6 @@ impl ScriptVm { let previous_owner_context = host_scope.enter(scope); let opened_popup = host.open_lightweight_popup_window( scope, - host_ptr, None, None, None, diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/events_selection_storage/postmessage_selection_and_errors.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/events_selection_storage/postmessage_selection_and_errors.rs index 387d7eac491..a8c0569de7d 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/events_selection_storage/postmessage_selection_and_errors.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/events_selection_storage/postmessage_selection_and_errors.rs @@ -221,37 +221,16 @@ fn message_channel_construction_keeps_popup_realm_with_ambient_child_marker() { ) }; - let top_context_ptr = - &vm.current_main_world().unwrap().context as *const v8::Global; - vm.with_context_scope_by_ptr(top_context_ptr, |scope, _host_ptr| { - let _previous_child = + let result = vm.with_popup_context_scope_and_checkpoint_for_test(popup_id, |scope, _| { + let previous_child = crate::native_bridge::enter_active_child_window_scope(scope, Some(child_handle)); - let _previous_popup = - crate::native_bridge::enter_active_lightweight_popup_scope(scope, popup_id); - Ok(()) - }) - .expect("overlapping ambient owner markers should install"); - - let result = vm - .eval( - r#" -(() => { - const channel = new MessageChannel(); - return [ - channel.port1 instanceof MessagePort, - channel.port2 instanceof MessagePort - ].join("|"); -})() -"#, - ) - .expect("MessageChannel should construct in the popup realm"); - - vm.with_context_scope_by_ptr(top_context_ptr, |scope, _host_ptr| { - let _previous_child = crate::native_bridge::enter_active_child_window_scope(scope, None); - let _previous_popup = crate::native_bridge::enter_top_level_lightweight_popup_scope(scope); - Ok(()) - }) - .expect("ambient owner markers should clear"); + let source = crate::util::v8str(scope, "(() => { const c = new MessageChannel(); return [c.port1 instanceof MessagePort, c.port2 instanceof MessagePort].join('|'); })()"); + let script = v8::Script::compile(scope, source, None).unwrap(); + let value = crate::script_execution::execute_compiled_script(scope, script).unwrap(); + let result = value.to_rust_string_lossy(scope); + crate::native_bridge::restore_active_child_window_scope(scope, previous_child); + Ok(result) + }).expect("MessageChannel should construct in the popup's actual realm"); assert_eq!(result, "true|true"); let owners = vm diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/events_selection_storage/window_security_and_domain.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/events_selection_storage/window_security_and_domain.rs index 4ec94865a2c..3d82fcd277a 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/events_selection_storage/window_security_and_domain.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/events_selection_storage/window_security_and_domain.rs @@ -498,7 +498,7 @@ const popup = open("about:blank"); const popupTimer = popup.setTimeout(() => __scopedTimerEvents.push("popup"), 1); clearTimeout(popupTimer); const popupSourceTimer = popup.setTimeout( - "globalThis.__scopedTimerEvents.push('popup-source')", + "opener.__scopedTimerEvents.push(globalThis === opener ? 'wrong-realm' : 'popup-source')", 1 ); clearTimeout(popupSourceTimer); 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 125f86b1baf..d91172330bf 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 @@ -194,20 +194,27 @@ async fn retained_popup_storage_managers_use_bound_popup_owner() { 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 (storage, buckets) = { + let popup = host.lightweight_popup_window(scope, popup_id).unwrap(); + let context = popup.get_creation_context(scope).unwrap(); + let scope = &mut v8::ContextScope::new(scope, context); + let navigator = popup + .get(scope, crate::util::v8str(scope, "navigator").into()) + .and_then(|v| v8::Local::::try_from(v).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(); + ( + v8::Global::new(scope, storage), + v8::Global::new(scope, buckets), + ) + }; + let storage = v8::Local::new(scope, &storage); + let buckets = v8::Local::new(scope, &buckets); let global = scope.get_current_context().global(scope); assert_eq!( global.set( @@ -1260,43 +1267,27 @@ async fn lightweight_popup_local_storage_events_fire_on_opener() { ); } #[test] -fn window_open_lightweight_popup_inherits_opener_viewport_surface() { +fn window_open_popup_uses_native_viewport_without_reading_opener_expandos() { let mut vm = new_storage_test_vm("https://example.com/"); - - let result = vm - .eval( - r##" - (() => { - for (const [name, value] of Object.entries({ - innerWidth: 320, - innerHeight: 240, - outerWidth: 321, - outerHeight: 241, - devicePixelRatio: 2.5 - })) { - Object.defineProperty(globalThis, name, { - configurable: true, - get: () => value - }); - } - const popup = open("about:blank#surface"); - return JSON.stringify({ - width: popup.innerWidth, - height: popup.innerHeight, - outerWidth: popup.outerWidth, - outerHeight: popup.outerHeight, - dpr: popup.devicePixelRatio - }); - })() - "##, - ) - .expect("popup viewport surface probe should evaluate"); - assert_eq!( - result, - r#"{"width":320,"height":240,"outerWidth":321,"outerHeight":241,"dpr":2.5}"# + vm.eval( + r#"(() => { + const names = ['innerWidth','innerHeight','outerWidth','outerHeight','devicePixelRatio']; + const expected = names.map(name => window[name]); + let reads = 0; + for (const name of names) Object.defineProperty(window, name, { + configurable:true, get(){ ++reads; throw new Error('opener viewport getter'); } + }); + const popup = open(); + try { return JSON.stringify([reads, names.every((name,i) => popup[name] === expected[i])]); } + finally { popup.close(); } + })()"# + ) + .unwrap(), + "[0,true]" ); } + #[tokio::test] async fn window_open_non_about_returns_lightweight_popup_and_dispatches_load() { let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader"); @@ -2445,19 +2436,14 @@ async fn lightweight_popup_javascript_url_uses_inline_navigation_csp_not_eval_cs .expect("allowed javascript URL setup should evaluate"), "true" ); - for _ in 0..4 { - if allowed - .eval("__javascriptUrlMessages.length") - .expect("javascript URL message count should evaluate") - == "1" - { - break; - } - let _ = allowed - .run_one_oldest_ready_page_task_executor_turn(&loader) - .await - .expect("wait driver should advance javascript URL task"); - } + advance_page_task_executor_until_eval_equals( + &mut allowed, + &loader, + "String(__javascriptUrlMessages.length)", + "1", + "allowed popup javascript URL message", + ) + .await; assert_eq!( allowed .eval("JSON.stringify([__javascriptUrlMessages, __javascriptUrlViolations])") @@ -3097,7 +3083,7 @@ async fn lightweight_popup_response_csp_sandbox_disallows_document_domain_setter popup.document.domain = popup.document.domain; __popupResponseSandboxDomainProbe.push(`${{initial}}|${{popup.document.domain}}`); }} catch (error) {{ - __popupResponseSandboxDomainProbe.push(`${{error.name}}:${{error instanceof DOMException}}:${{error.code}}`); + __popupResponseSandboxDomainProbe.push(`${{error.name}}:${{error instanceof popup.DOMException}}:${{error instanceof DOMException}}:${{error.code}}`); }} }}; return __popupResponseSandboxDomainProbe.length; @@ -3128,7 +3114,7 @@ async fn lightweight_popup_response_csp_sandbox_disallows_document_domain_setter assert_eq!( vm.eval("__popupResponseSandboxDomainProbe.join('|')") .expect("popup response CSP sandbox document-domain result should evaluate"), - "SecurityError:true:18" + "SecurityError:true:false:18" ); } #[tokio::test] diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/popup_document_stream.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/popup_document_stream.rs index af47badf5f4..592a05b0a32 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/popup_document_stream.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/popup_document_stream.rs @@ -25,7 +25,7 @@ fn popup_document_stream_methods_use_native_document_receiver_checks() { for (const receiver of [{}, Object.create(d), proxy, revoked.proxy]) { let error; try { d[name].call(receiver, value); } catch (caught) { error = caught; } - if (!(error instanceof TypeError) || conversions !== 0 || traps !== 0) { + if (!(error instanceof w.TypeError) || error instanceof TypeError || conversions !== 0 || traps !== 0) { failures.push([name, String(error), conversions, traps]); } } @@ -53,7 +53,7 @@ fn popup_document_stream_methods_reject_xml_receivers_without_mutation() { const doc = new DOMParser().parseFromString('', 'text/xml'); let error; try { w.document[name].call(doc, 'text'); } catch (caught) { error = caught; } - if (!(error instanceof DOMException) || error.name !== 'InvalidStateError' || + if (!(error instanceof w.DOMException) || error instanceof DOMException || error.name !== 'InvalidStateError' || new XMLSerializer().serializeToString(doc) !== '') { failures.push([name, String(error)]); } 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 77495833f65..4de0890b23e 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 @@ -2231,14 +2231,11 @@ async fn popup_replacement_retires_local_window_owned_webcrypto_tasks() { .current_lightweight_popup_local_window_id(popup_id) .expect("initial popup LocalWindow owner"); - vm.with_default_context_scope_and_checkpoint_for_test(|scope, host_ptr| { - let previous_popup = - crate::native_bridge::enter_active_lightweight_popup_scope(scope, popup_id); + vm.with_popup_context_scope_and_checkpoint_for_test(popup_id, |scope, host_ptr| { let resolver = v8::PromiseResolver::new(scope).expect("popup WebCrypto test resolver"); let registered = unsafe { &mut *host_ptr } .register_pending_webcrypto_task(scope, resolver) .is_some(); - crate::native_bridge::restore_active_lightweight_popup_scope(scope, previous_popup); assert!( registered, "popup WebCrypto task should bind a Window execution context" @@ -2363,15 +2360,12 @@ fn popup_replacement_retires_local_window_owned_xhr() { .expect("initial popup LocalWindow owner"); let cancel_handle = moli_fetch::FetchCancelHandle::new(); let (_, owner, _) = vm - .with_default_context_scope_and_checkpoint_for_test(|scope, host_ptr| { - let previous_popup = - crate::native_bridge::enter_active_lightweight_popup_scope(scope, popup_id); + .with_popup_context_scope_and_checkpoint_for_test(popup_id, |scope, host_ptr| { let registered = register_pending_window_xhr_for_test( scope, unsafe { &mut *host_ptr }, cancel_handle.clone(), ); - crate::native_bridge::restore_active_lightweight_popup_scope(scope, previous_popup); Ok(registered) }) .expect("popup XHR should register"); @@ -2529,9 +2523,7 @@ fn popup_replacement_aborts_fetch_and_detaches_keepalive() { .and_then(|activation| activation.popup_id()) .expect("popup Fetch owner id"); let (ordinary, keepalive) = vm - .with_default_context_scope_and_checkpoint_for_test(|scope, host_ptr| { - let previous_popup = - crate::native_bridge::enter_active_lightweight_popup_scope(scope, popup_id); + .with_popup_context_scope_and_checkpoint_for_test(popup_id, |scope, host_ptr| { let host = unsafe { &mut *host_ptr }; let registered = ( register_pending_window_fetch_for_test( @@ -2547,7 +2539,6 @@ fn popup_replacement_aborts_fetch_and_detaches_keepalive() { PendingWindowFetchTestStage::Pending, ), ); - crate::native_bridge::restore_active_lightweight_popup_scope(scope, previous_popup); Ok(registered) }) .expect("popup Fetches should register"); 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 405a9aadc83..a4ed22e05ce 100644 --- a/moli-renderer-v8/src/script_vm/tests/extracted/workers.rs +++ b/moli-renderer-v8/src/script_vm/tests/extracted/workers.rs @@ -286,9 +286,7 @@ async fn popup_replacement_retires_local_window_owned_dedicated_worker() { .current_lightweight_popup_local_window_id(popup_id) .expect("initial popup LocalWindow owner"); - vm.with_default_context_scope_and_checkpoint_for_test(|scope, host_ptr| { - let previous_popup = - crate::native_bridge::enter_active_lightweight_popup_scope(scope, popup_id); + vm.with_popup_context_scope_and_checkpoint_for_test(popup_id, |scope, host_ptr| { let host = unsafe { &mut *host_ptr }; let owner = host .current_runtime_window_execution_context_binding(scope) @@ -312,7 +310,6 @@ async fn popup_replacement_retires_local_window_owned_dedicated_worker() { outside_settings_load, owner, ); - crate::native_bridge::restore_active_lightweight_popup_scope(scope, previous_popup); Ok(()) }) .expect("popup Worker should register"); 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 4ff82c3e310..0ad2b838ee0 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,19 @@ use super::*; +#[test] +fn popup_window_owns_its_script_global_and_intrinsic_prototypes() { + let mut vm = new_storage_html_test_vm("https://popup-realm.test/"); + vm.eval(include_str!( + "../../../tests/fixtures/popup-window-realm.js" + )) + .unwrap(); + assert_eq!( + vm.eval("JSON.stringify(__nodeReplacementResults.failures)") + .unwrap(), + "[]" + ); +} + #[tokio::test] async fn initial_popup_aliases_its_creators_document_domain_in_both_directions() { let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap(); @@ -102,19 +116,52 @@ async fn popup_window_promise_reactions_keep_their_origin_without_granting_it_to }).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( + let root = scope.get_current_context().global(scope); + let reports = root + .get( + scope, + crate::util::v8str(scope, "retainedPopupReaction").into(), + ) + .unwrap(); + let host_ptr = crate::util::context_host_ptr_from_global_bridge(scope).unwrap(); + let context = unsafe { &mut *host_ptr }.ensure_popup_default_context(scope, popup_id)?; + let retained_probe = { + let scope = &mut v8::ContextScope::new(scope, context); + let popup = context.global(scope); + popup.set( + scope, + crate::util::v8str(scope, "retainedPopupReaction").into(), + reports, + ); + popup.set( + scope, + crate::util::v8str(scope, "popup").into(), + popup.into(), + ); + // Capture the actual old realm before the opener's queued navigation. + run_body( + scope, + r#"((reports, target) => { + Promise.resolve().then(() => { + try { reports.push(target.document.URL); } + catch (error) { reports.push(error.name); } + }); + })(retainedPopupReaction, popup);"#, + ); + let source = crate::util::v8_string( + scope, + "((target) => () => { try { return target.document.URL; } catch (error) { return error.name; } })(popup)", + ) + .unwrap(); + let script = v8::Script::compile(scope, source, None).unwrap(); + let probe = crate::script_execution::execute_compiled_script(scope, script).unwrap(); + v8::Global::new(scope, probe) + }; + root.set( scope, - r#"Promise.resolve().then(() => { - try { retainedPopupReaction.push(popup.document.URL); } - catch (error) { retainedPopupReaction.push(error.name); } - });"#, + crate::util::v8str(scope, "retainedPopupProbe").into(), + v8::Local::new(scope, &retained_probe), ); - owner.restore(scope, previous); run_body( scope, r#" @@ -125,9 +172,9 @@ async fn popup_window_promise_reactions_keep_their_origin_without_granting_it_to }) .unwrap(); assert_eq!( - vm.eval("JSON.stringify([retainedPopupReaction, newWindowReaction, popupNavigationError])") + vm.eval("JSON.stringify([retainedPopupReaction, retainedPopupProbe(), newWindowReaction, popupNavigationError])") .unwrap(), - r#"[["SecurityError"],["about:blank"],null]"# + r#"[[],"SecurityError",["about:blank"],null]"# ); assert_eq!(server.finish_targets().await.len(), 1); } diff --git a/moli-renderer-v8/src/window_host.rs b/moli-renderer-v8/src/window_host.rs index 3a677e9853d..c35f8ec88f9 100644 --- a/moli-renderer-v8/src/window_host.rs +++ b/moli-renderer-v8/src/window_host.rs @@ -896,11 +896,8 @@ pub(crate) fn window_post_message_callback<'s>( rv.set_undefined(); return; } - // Blink captures the incumbent DOMWindow at API acceptance. Lightweight - // popups still share the top-level V8 context, so their active execution - // scope is the one necessary override; the ambient source marker is only - // a fallback for legacy execution paths that do not expose an incumbent - // context. + // Capture the incumbent Window at acceptance, including related Pages. + // Ambient dispatch markers are only a fallback for legacy execution paths. let related_source = incumbent_related_page_message_source(scope, host_ptr); let source_identity = related_source .as_ref() @@ -2130,6 +2127,9 @@ fn window_message_endpoint_from_receiver<'s>( scope: &mut v8::PinScope<'s, '_>, object: v8::Local<'s, v8::Object>, ) -> Option { + if let Some(popup_id) = crate::native_bridge::lightweight_popup_id_from_window(scope, object) { + return Some(PendingWindowMessageEndpoint::LightweightPopup(popup_id)); + } let global = scope.get_current_context().global(scope); if object.strict_equals(global.into()) { return Some( @@ -2149,10 +2149,6 @@ fn window_message_endpoint_from_receiver<'s>( )); } - if let Some(popup_id) = crate::native_bridge::lightweight_popup_id_from_window(scope, object) { - return Some(PendingWindowMessageEndpoint::LightweightPopup(popup_id)); - } - if let Some(popup_id) = crate::native_bridge::cross_origin_lightweight_popup_id(scope, object) { return Some(PendingWindowMessageEndpoint::LightweightPopup(popup_id)); } @@ -2244,24 +2240,19 @@ fn incumbent_window_message_source_identity( WindowExecutionContextOwner, RuntimeObservableContextToken, )> { - let incumbent_context = scope.get_incumbent_context()?; - let incumbent_global = incumbent_context.global(scope); - let endpoint = if let Some(popup_id) = - crate::native_bridge::lightweight_popup_id_from_window(scope, incumbent_global) - { - PendingWindowMessageEndpoint::LightweightPopup(popup_id) - } else { - object_child_window_handle(scope, incumbent_global) - .map(PendingWindowMessageEndpoint::ChildWindow) - .unwrap_or(PendingWindowMessageEndpoint::TopWindow) + let context = scope.get_incumbent_context()?; + let identity = host.window_execution_context_identity_for_access_check(context)?; + if !host.window_execution_context_identity_is_current(identity) { + return None; + } + let endpoint = match identity.dispatch_scope() { + OwnerDispatchScope::Top => PendingWindowMessageEndpoint::TopWindow, + OwnerDispatchScope::Child(handle) => PendingWindowMessageEndpoint::ChildWindow(handle), + OwnerDispatchScope::LightweightPopup(id) => { + PendingWindowMessageEndpoint::LightweightPopup(id) + } }; - let incumbent_scope = &mut v8::ContextScope::new(scope, incumbent_context); - let identity = host.current_runtime_window_execution_context_identity(incumbent_scope)?; - (identity.dispatch_scope() == endpoint.dispatch_scope()).then_some(( - endpoint, - identity.owner(), - identity.realm_token(), - )) + Some((endpoint, identity.owner(), identity.realm_token())) } #[cfg(test)] diff --git a/moli-renderer-v8/tests/fixtures/popup-window-realm.js b/moli-renderer-v8/tests/fixtures/popup-window-realm.js new file mode 100644 index 00000000000..98c33b3572a --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/popup-window-realm.js @@ -0,0 +1,33 @@ +(() => { + const rows = []; + const popup = open(); + function check(name, expected, run) { + let actual; + try { actual = run(); } catch (error) { actual = {name: error.name, message: error.message}; } + rows.push({name, expected, actual, pass: JSON.stringify(actual) === JSON.stringify(expected)}); + } + globalThis.openerOnlySentinel = 73; + Object.prototype.openerPrototypeSentinel = 79; + try { + popup.document.open(); + popup.document.write('