Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(renderer): protect Document access and retained realm identity

ldm0fcadef16be05
diff --git a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page/auxiliary_page_retirement.rs b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page/auxiliary_page_retirement.rs
index 45823e190..ce3a8bbeb 100644
--- a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page/auxiliary_page_retirement.rs
+++ b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page/auxiliary_page_retirement.rs
@@ -16,6 +16,70 @@ async fn wait_for_value(page: &mut TestCdpSocket, expression: &str, expected: se
.unwrap_or_else(|_| panic!("{expression} did not become {expected}; last value was {actual}"));
}
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn popup_document_access_keeps_retained_functions_and_checks_borrowed_receivers() {
+ let (fixture_addr, _fixture) = spawn_dedicated_fixture_server(
+ Router::new().fallback(get(|uri: axum::http::Uri| async move {
+ axum::response::Html(format!("<h1>{}</h1>", uri.path()))
+ })),
+ "popup-document-access",
+ );
+ let base = format!("http://{fixture_addr}");
+ let cross = format!("http://localhost:{}", fixture_addr.port());
+ let (addr, server) = spawn_test_protocol_server().await;
+ let (mut browser, _) =
+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))
+ .await
+ .unwrap();
+ let opener_id = create_dynamic_target(&mut browser, 1).await;
+ let mut opener = connect_dynamic_page(addr, &opener_id).await;
+ send_cdp_command(&mut opener, 1, "Page.enable", None, json!({})).await;
+ navigate_dynamic_page_and_wait_for_load(&mut opener, 2, &format!("{base}/opener")).await;
+ for destination in [&base, &cross] {
+ let (child_id, mut child) = open_auxiliary(addr, &mut opener, "").await;
+ navigate_dynamic_page_and_wait_for_load(&mut child, 2, &format!("{base}/one")).await;
+ evaluate_window_name_probe(
+ &mut opener,
+ 3,
+ "window.oldDocument=p.document;window.readOldDocument=p.Function('return document');window.readOldBody=p.Function('return document.body.textContent');window.savedDocumentGetter=p.Object.getOwnPropertyDescriptor(p,'document').get;true",
+ )
+ .await;
+ navigate_dynamic_page_and_wait_for_load(&mut child, 3, &format!("{destination}/two")).await;
+ assert_eq!(
+ evaluate_window_name_probe(
+ &mut opener,
+ 4,
+ "[readOldDocument()===oldDocument,readOldBody(),oldDocument.body.textContent]",
+ )
+ .await,
+ json!([true, "/one", "/one"])
+ );
+ assert_eq!(
+ evaluate_window_name_probe(
+ &mut opener,
+ 5,
+ "[Object.getOwnPropertyDescriptor(window,'document').get,savedDocumentGetter,Object.getOwnPropertyDescriptor(__moliNativeBridge.window,'document').get].map(getter=>{try{return getter.call(p).body.textContent}catch(e){return e.name}})",
+ )
+ .await,
+ if destination == &base {
+ json!(["/two", "/two", "/two"])
+ } else {
+ json!(["SecurityError", "SecurityError", "SecurityError"])
+ }
+ );
+ assert_eq!(
+ evaluate_window_name_probe(&mut child, 4, "document.body.textContent").await,
+ "/two"
+ );
+ evaluate_window_name_probe(&mut child, 5, "window.close();true").await;
+ wait_for_target_list(addr, "closed popup removed", |targets| {
+ !targets.iter().any(|target| target["id"] == child_id)
+ })
+ .await;
+ }
+ abort_test_cdp_server(server).await;
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn initial_popup_commit_keeps_window_timers_and_service_worker_completion() {
let release = Arc::new(tokio::sync::Notify::new());
diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs
index 4b15b4579..0d5e163d5 100644
--- a/moli-renderer-v8/src/context_bootstrap.rs
+++ b/moli-renderer-v8/src/context_bootstrap.rs
@@ -1020,6 +1020,7 @@ pub(crate) fn live_ranges_detached_text_split<'s>(
pub(crate) use self::window_accessors::{
bind_current_child_window_document, current_window_style_viewport,
+ retain_window_document_in_retired_realm,
};
pub(crate) use session_history::{
diff --git a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
index 0f2525e47..be2733e39 100644
--- a/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
+++ b/moli-renderer-v8/src/context_bootstrap/runtime_state.rs
@@ -16,7 +16,9 @@ use super::{
web_storage::{
install_storage_runtime_state, window_local_storage_getter, window_session_storage_getter,
},
- window_accessors::{window_document_getter, window_length_getter},
+ window_accessors::{
+ WINDOW_DOCUMENT_SLOT, window_document_getter_template, window_length_getter,
+ },
window_runtime::{build_legacy_storage_info_object, window_noop_callback},
window_template::install_window_named_properties_object,
};
@@ -1532,8 +1534,11 @@ fn define_legacy_unforgeable_document_property<'s>(
scope: &mut v8::PinScope<'s, '_>,
object: v8::Local<'s, v8::Object>,
) -> Result<()> {
- let getter = v8::Function::builder(window_document_getter)
- .build(scope)
+ let cache_property = crate::util::private_key(scope, WINDOW_DOCUMENT_SLOT)
+ .ok_or_else(|| anyhow!("failed to allocate Window.document cache key"))?;
+ let getter_template = window_document_getter_template(scope, Some(cache_property));
+ let getter = getter_template
+ .get_function(scope)
.ok_or_else(|| anyhow!("failed to build document getter"))?;
getter.set_name(v8str(scope, "get document"));
define_get_set_property(
diff --git a/moli-renderer-v8/src/context_bootstrap/window_accessors.rs b/moli-renderer-v8/src/context_bootstrap/window_accessors.rs
index f8337caeb..e8da9beca 100644
--- a/moli-renderer-v8/src/context_bootstrap/window_accessors.rs
+++ b/moli-renderer-v8/src/context_bootstrap/window_accessors.rs
@@ -24,8 +24,10 @@ pub(super) use child_context::{
};
pub(crate) use cross_origin_cache::cached_cross_origin_window_surface;
pub(super) use cross_origin_cache::initialize_cross_origin_window_cache;
-pub(crate) use document::bind_current_child_window_document;
-pub(super) use document::window_document_getter;
+pub(super) use document::{WINDOW_DOCUMENT_SLOT, window_document_getter_template};
+pub(crate) use document::{
+ bind_current_child_window_document, retain_window_document_in_retired_realm,
+};
pub(super) use helpers::window_child_context_handle;
pub(crate) use helpers::{current_window_style_viewport, window_host_ptr};
pub(super) use interceptors::{
diff --git a/moli-renderer-v8/src/context_bootstrap/window_accessors/document.rs b/moli-renderer-v8/src/context_bootstrap/window_accessors/document.rs
index ebc001a37..b3ebca9ef 100644
--- a/moli-renderer-v8/src/context_bootstrap/window_accessors/document.rs
+++ b/moli-renderer-v8/src/context_bootstrap/window_accessors/document.rs
@@ -5,7 +5,50 @@ use crate::{
util::{get_private_object, set_private_value},
};
-const WINDOW_DOCUMENT_SLOT: &str = "__moliWindowAssociatedDocument";
+pub(in crate::context_bootstrap) const WINDOW_DOCUMENT_SLOT: &str =
+ "__moliWindowAssociatedDocument";
+
+pub(in crate::context_bootstrap) fn window_document_getter_template<'s>(
+ scope: &mut v8::PinScope<'s, '_, ()>,
+ cache_property: Option<v8::Local<'s, v8::Private>>,
+) -> v8::Local<'s, v8::FunctionTemplate> {
+ let template = match cache_property {
+ Some(cache_property) => {
+ v8::FunctionTemplate::new_with_cache(scope, window_document_getter, cache_property)
+ }
+ None => v8::FunctionTemplate::new(scope, window_document_getter),
+ };
+ template.remove_prototype();
+ // V8 checks the receiver against the actual access Context before
+ // invoking the callback, including when the getter is borrowed.
+ template.set_accept_any_receiver(false);
+ template
+}
+
+pub(crate) fn retain_window_document_in_retired_realm(
+ scope: &mut v8::PinScope<'_, '_>,
+) -> Option<()> {
+ let context = scope.get_current_context();
+ let host_ptr = crate::util::context_host_ptr_from_context_slot(context)?;
+ let _ = WindowEnvironmentSettings::bind_current_main_document_for_retirement(scope, unsafe {
+ &*host_ptr
+ });
+ let window = context.global(scope);
+ if get_private_object(scope, window, WINDOW_DOCUMENT_SLOT).is_some() {
+ return Some(());
+ }
+ let handle = WindowEnvironmentSettings::for_current_realm(scope)
+ .map(|settings| settings.document_handle())
+ .unwrap_or_else(|| unsafe { &*host_ptr }.document_handle());
+ let document = unsafe { &mut *host_ptr }
+ .native_bridge_mut()
+ .wrap_handle(scope, host_ptr, handle)?;
+ // Fix the outgoing global's Document before its WindowProxy is reused.
+ // V8 resolves a cached accessor on this global, so a saved JS function
+ // keeps reading its own Document after navigation.
+ set_private_value(scope, window, WINDOW_DOCUMENT_SLOT, document.into());
+ Some(())
+}
pub(crate) fn bind_current_child_window_document<'s>(
scope: &mut v8::PinScope<'s, '_>,
@@ -30,27 +73,25 @@ pub(in crate::context_bootstrap) fn window_document_getter<'s>(
let Some(receiver) = window_receiver(scope, &args) else {
return;
};
- if !crate::native_bridge::caller_can_access_window(scope, receiver) {
- crate::native_bridge::throw_cross_origin_location_security_error(scope);
- return;
- }
- let Some(host_ptr) = window_host_ptr(scope, receiver) else {
+ let Some(context) = receiver.get_creation_context(scope) else {
rv.set_null();
return;
};
- let Some(context) = receiver.get_creation_context(scope) else {
+ let Some(host_ptr) = crate::util::context_host_ptr_from_context_slot(context)
+ .or_else(|| window_host_ptr(scope, receiver))
+ else {
rv.set_null();
return;
};
// A borrowed getter runs in its function's realm. Resolve both settings
// and wrappers in the receiver's realm, including a retained old Window.
let scope = &mut v8::ContextScope::new(scope, context);
+ let window = context.global(scope);
+ if let Some(document) = get_private_object(scope, window, WINDOW_DOCUMENT_SLOT) {
+ rv.set(document.into());
+ return;
+ }
let handle = if let Some(settings) = WindowEnvironmentSettings::for_current_realm(scope) {
- let window = context.global(scope);
- if let Some(document) = get_private_object(scope, window, WINDOW_DOCUMENT_SLOT) {
- rv.set(document.into());
- return;
- }
settings.document_handle()
} else if let Some(handle) = window_child_context_handle(scope, receiver) {
// During bootstrap the Document wrapper can precede settings binding.
diff --git a/moli-renderer-v8/src/context_bootstrap/window_template.rs b/moli-renderer-v8/src/context_bootstrap/window_template.rs
index 336536aba..bcbbcdf6d 100644
--- a/moli-renderer-v8/src/context_bootstrap/window_template.rs
+++ b/moli-renderer-v8/src/context_bootstrap/window_template.rs
@@ -195,9 +195,6 @@ struct WindowIdentityAccessorsDeclaration {
#[webapi(accessor_property, getter = window_frame_element_getter)]
frame_element: (),
- #[webapi(accessor_property, getter = window_document_getter)]
- document: (),
-
#[webapi(
accessor_property,
dont_delete,
@@ -347,6 +344,15 @@ pub(crate) fn install_window_own_template_bindings<'s>(
// metadata. Installing on this aggregate template also gives accessor
// functions the actual WindowProxy as `this`.
WindowIdentityAccessorsDeclaration::initialize_prototype_template(scope, window_template);
+ // Synthetic Window wrappers need the same protected getter as globals.
+ // Their Document is resolved by the callback rather than a global cache.
+ let document_getter = window_document_getter_template(scope, None);
+ window_template.set_accessor_property(
+ v8str(scope, "document").into(),
+ Some(document_getter),
+ None,
+ v8::PropertyAttribute::NONE,
+ );
WindowEarlyTemplateMethodsDeclaration::initialize_prototype_template(scope, window_template);
WindowObsoleteTemplateMethodsDeclaration::initialize_prototype_template(scope, window_template);
network_host::install_window_network_bindings(scope, window_template);
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs
index 5553016b4..5936c115c 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime.rs
@@ -8,8 +8,7 @@ mod window;
pub(super) use crate::context_bootstrap::WINDOW_EVENT_HANDLER_PROPERTIES;
pub(in crate::native_bridge::context_host) use window::ChildWindowProxyRecords;
pub(crate) use window::{
- caller_can_access_window, cross_origin_lightweight_popup_id,
- install_child_window_proxy_access_check_handlers, is_cross_origin_location_proxy,
- is_cross_origin_top_window_proxy, throw_cross_origin_location_security_error,
- throw_cross_origin_type_error,
+ cross_origin_lightweight_popup_id, install_child_window_proxy_access_check_handlers,
+ is_cross_origin_location_proxy, is_cross_origin_top_window_proxy,
+ throw_cross_origin_location_security_error, throw_cross_origin_type_error,
};
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window.rs
index 0409ead87..ea72cde17 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
@@ -623,7 +623,7 @@ fn contexts_can_script_access<'s>(
let Some((accessing_host_ptr, accessing_identity)) = (|| {
let host_ptr = crate::util::context_host_ptr_from_context_slot(accessing_context)?;
let identity = unsafe { &*host_ptr }
- .window_execution_context_identity_for_access_check(accessing_context)?;
+ .window_execution_context_identity_for_access_check(accessing_context);
Some((host_ptr, identity))
})() else {
return false;
@@ -636,15 +636,28 @@ fn contexts_can_script_access<'s>(
})() else {
return false;
};
+ let host = unsafe { &*accessing_host_ptr };
+ let Some(accessing_identity) = accessing_identity
+ .filter(|identity| host.window_execution_context_identity_is_current(*identity))
+ else {
+ return accessing_context
+ .get_slot::<super::super::WindowEnvironmentSettings>()
+ .is_some_and(|settings| {
+ settings.can_access_current_window(
+ host,
+ unsafe { &*accessed_host_ptr },
+ accessed_identity,
+ )
+ });
+ };
if accessing_host_ptr != accessed_host_ptr {
return false;
}
- let host = unsafe { &*accessing_host_ptr };
host.window_execution_context_can_access(accessing_identity, accessed_identity)
}
-pub(crate) fn caller_can_access_window<'s>(
+fn caller_can_access_window<'s>(
scope: &mut v8::PinScope<'s, '_>,
window: v8::Local<'s, v8::Object>,
) -> bool {
diff --git a/moli-renderer-v8/src/native_bridge/context_host/document_domain.rs b/moli-renderer-v8/src/native_bridge/context_host/document_domain.rs
index 5e90ed799..f0db959a2 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/document_domain.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/document_domain.rs
@@ -174,6 +174,18 @@ impl JsContextHost {
.and_then(|origin| url_host_domain(&origin))
}
+ pub(in crate::native_bridge::context_host) fn child_document_domain_owner_document(
+ &self,
+ handle: DomHandle,
+ ) -> Option<DomHandle> {
+ match self.child_browsing_context_security_origin_owner(handle)? {
+ ChildSecurityOriginOwner::Main => Some(self.document_handle()),
+ ChildSecurityOriginOwner::Child(owner) => {
+ self.child_browsing_context_document_handle(owner)
+ }
+ }
+ }
+
fn child_browsing_context_security_origin_owner(
&self,
handle: DomHandle,
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 97fec62e5..cbe35a0ec 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs
@@ -178,7 +178,7 @@ use child_documents::{ChildDocumentParserStore, PendingChildDocumentNavigation};
use child_events::ChildWindowEventListenerEntry;
use child_frame_runtime::ChildWindowProxyRecords;
pub(crate) use child_frame_runtime::{
- caller_can_access_window, cross_origin_lightweight_popup_id, is_cross_origin_location_proxy,
+ cross_origin_lightweight_popup_id, is_cross_origin_location_proxy,
is_cross_origin_top_window_proxy, throw_cross_origin_location_security_error,
throw_cross_origin_type_error,
};
diff --git a/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/settings.rs b/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/settings.rs
index ba58abba8..ba2280913 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/settings.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/window_execution_context/settings.rs
@@ -1,5 +1,6 @@
use super::super::JsContextHost;
use super::super::OwnerDispatchScope;
+use super::super::window_security_tokens::WindowAccessOrigin;
use super::WindowExecutionContextIdentity;
use crate::document_runtime::DomHandle;
use moli_url::WebOrigin;
@@ -17,6 +18,8 @@ use url::Url;
pub(crate) struct WindowEnvironmentSettings {
document: DomHandle,
origin: WebOrigin,
+ access_origin: WindowAccessOrigin,
+ domain_owner_document: DomHandle,
execution_identity: WindowExecutionContextIdentity,
}
@@ -37,10 +40,16 @@ impl WindowEnvironmentSettings {
let document = host.child_browsing_context_document_handle(child_handle)?;
let owner = host.frame_owner_current_child_snapshot(child_handle)?;
let origin = WebOrigin::from_serialized(&owner.settings.origin);
+ let access_origin = host.child_window_access_origin(child_handle)?;
+ let domain_owner_document = host
+ .child_document_domain_owner_document(child_handle)
+ .unwrap_or(document);
let context = scope.get_current_context();
let _previous = context.set_slot(Rc::new(Self {
document,
origin,
+ access_origin,
+ domain_owner_document,
execution_identity,
}));
Some(())
@@ -50,6 +59,75 @@ impl WindowEnvironmentSettings {
scope.get_current_context().get_slot::<Self>()
}
+ pub(crate) fn bind_current_main_document_for_retirement(
+ scope: &mut v8::PinScope<'_, '_>,
+ host: &JsContextHost,
+ ) -> Option<()> {
+ let context = scope.get_current_context();
+ let execution_identity =
+ host.window_execution_context_identity_for_access_check(context)?;
+ if execution_identity.dispatch_scope() != OwnerDispatchScope::Top
+ || !host.window_execution_context_identity_is_current(execution_identity)
+ {
+ return None;
+ }
+ let access_origin = host.main_window_access_origin()?;
+ let _previous = context.set_slot(Rc::new(Self {
+ document: host.document_handle(),
+ origin: WebOrigin::from_serialized(&host.main_document_security_origin()),
+ access_origin,
+ domain_owner_document: host.document_handle(),
+ execution_identity,
+ }));
+ Some(())
+ }
+
+ /// Pure DOM access still uses the outgoing Document's origin after its
+ /// task registry entry is retired. This grants no execution authority.
+ pub(in crate::native_bridge::context_host) fn can_access_current_window(
+ &self,
+ host: &JsContextHost,
+ target_host: &JsContextHost,
+ target: WindowExecutionContextIdentity,
+ ) -> bool {
+ if !target_host.window_execution_context_identity_is_current(target) {
+ return false;
+ }
+ if self.execution_identity.grants_universal_access() {
+ return true;
+ }
+ // Retiring a resource loader must not turn an inherited origin into
+ // the origin of its about:blank URL. Keep that origin, while observing
+ // domain changes on the exact Document that owns the shared origin.
+ let mut origin = self.access_origin.clone();
+ if let WindowAccessOrigin::Tuple {
+ document_domain, ..
+ } = &mut origin
+ {
+ if self.domain_owner_document == host.document_handle() {
+ *document_domain = host.document_domain_override.clone();
+ } else if let Some(handle) =
+ host.child_browsing_context_handle_for_stored_document(self.domain_owner_document)
+ {
+ *document_domain = host.child_browsing_context_document_domain_override(handle);
+ }
+ }
+ let Some(target_origin) =
+ target_host.window_access_origin_for_dispatch_scope(target.dispatch_scope())
+ else {
+ return false;
+ };
+ // Opaque owner IDs are scoped to a host, whereas tuple origins can be
+ // compared across Pages sharing the browser's V8 isolate.
+ if !std::ptr::eq(host, target_host)
+ && (matches!(origin, WindowAccessOrigin::Opaque { .. })
+ || matches!(target_origin, WindowAccessOrigin::Opaque { .. }))
+ {
+ return false;
+ }
+ origin.can_access(&target_origin)
+ }
+
pub(crate) fn document_handle(&self) -> DomHandle {
self.document
}
diff --git a/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs b/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs
index 6c5024819..ed88d682c 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
@@ -251,7 +251,9 @@ impl JsContextHost {
}
}
- fn main_window_access_origin(&self) -> Option<WindowAccessOrigin> {
+ pub(in crate::native_bridge::context_host) fn main_window_access_origin(
+ &self,
+ ) -> Option<WindowAccessOrigin> {
let serialized_origin = self.main_document_security_origin();
if self.document_sandbox_policy().forces_opaque_origin || serialized_origin == "null" {
return Some(WindowAccessOrigin::opaque(
diff --git a/moli-renderer-v8/src/native_bridge/identity.rs b/moli-renderer-v8/src/native_bridge/identity.rs
index cc2b5643d..24adaa79a 100644
--- a/moli-renderer-v8/src/native_bridge/identity.rs
+++ b/moli-renderer-v8/src/native_bridge/identity.rs
@@ -553,6 +553,7 @@ pub(crate) fn clear_context_wrapper_cache_for_teardown(
include_shared_default_world: bool,
) {
let context = scope.get_current_context();
+ let _ = crate::context_bootstrap::retain_window_document_in_retired_realm(scope);
crate::util::detach_document_page_context(context);
if let Some(host) = crate::util::context_host_ptr_from_context_slot(context) {
unsafe { &mut *host }
diff --git a/moli-renderer-v8/src/native_bridge/mod.rs b/moli-renderer-v8/src/native_bridge/mod.rs
index 314856edd..7e677c128 100644
--- a/moli-renderer-v8/src/native_bridge/mod.rs
+++ b/moli-renderer-v8/src/native_bridge/mod.rs
@@ -8,7 +8,7 @@ mod context_host;
mod current_input;
pub(crate) use context_host::{
JsContextHost, JsContextHostPageTaskCapabilities, PendingScrollObservableEffects,
- PostParseAutofocusAdmission, ServiceWorkerWindowOwner, caller_can_access_window,
+ PostParseAutofocusAdmission, ServiceWorkerWindowOwner,
};
pub(crate) use current_input::{
CurrentInputEvent, CurrentInputEventScope, InputNavigationPolicy, navigation_policy_from_event,
diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rs
index ac1b1af28..83cfc6c54 100644
--- a/moli-renderer-v8/src/script_vm.rs
+++ b/moli-renderer-v8/src/script_vm.rs
@@ -69,7 +69,12 @@ impl MainWindowProxyNavigationCommit {
.with_renderer_document_isolate_mut(|isolate| {
let scope = pin!(v8::HandleScope::new(isolate));
let scope = &mut scope.init();
- v8::Local::new(scope, &self.context).detach_global();
+ let context = v8::Local::new(scope, &self.context);
+ let scope = &mut v8::ContextScope::new(scope, context);
+ // Preserve the outgoing global's cached Document while the
+ // WindowProxy still forwards private properties to it.
+ crate::context_bootstrap::retain_window_document_in_retired_realm(scope);
+ context.detach_global();
});
tracing::debug!(
page_id = self.page_id,
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted/window_and_frame_surfaces.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted/window_and_frame_surfaces.rs
index 507cd2b32..6c8d4bcfa 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted/window_and_frame_surfaces.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface/extracted/window_and_frame_surfaces.rs
@@ -1,5 +1,56 @@
use super::*;
+#[test]
+fn document_getter_checks_the_actual_access_context_and_preserves_function_realms() {
+ let mut vm = new_storage_html_test_vm("https://document-access-context.test/");
+ vm.exec("globalThis.readOwnDocument = () => document;", None)
+ .unwrap();
+ vm.with_default_context_scope(|scope, _| {
+ let own_context = scope.get_current_context();
+ let window = own_context.global(scope);
+ let document_key = crate::util::v8str(scope, "document");
+ let descriptor = window
+ .get_own_property_descriptor(scope, document_key.into())
+ .unwrap();
+ let descriptor = v8::Local::<v8::Object>::try_from(descriptor).unwrap();
+ let getter = descriptor
+ .get(scope, crate::util::v8str(scope, "get").into())
+ .unwrap();
+ let document = window.get(scope, document_key.into()).unwrap();
+ let read_own = window
+ .get(scope, crate::util::v8str(scope, "readOwnDocument").into())
+ .unwrap();
+ let caller = v8::Context::new(scope, Default::default());
+ let scope = &mut v8::ContextScope::new(scope, caller);
+ let backup = std::pin::pin!(v8::BackupIncumbentScope::new(caller));
+ let _backup = backup.init();
+ let global = caller.global(scope);
+ for (name, value) in [
+ ("nativeGetter", getter),
+ ("receiver", window.into()),
+ ("savedDocument", document),
+ ("readOwnDocument", read_own),
+ ] {
+ assert_eq!(
+ global.set(scope, crate::util::v8str(scope, name).into(), value),
+ Some(true)
+ );
+ }
+ let source = crate::util::v8str(
+ scope,
+ r#"JSON.stringify([
+ nativeGetter.call(receiver) === savedDocument,
+ readOwnDocument() === savedDocument
+ ])"#,
+ );
+ let script = v8::Script::compile(scope, source, None).unwrap();
+ let value = crate::script_execution::execute_compiled_script(scope, script).unwrap();
+ assert_eq!(value.to_rust_string_lossy(scope), r#"[true,true]"#);
+ Ok(())
+ })
+ .unwrap();
+}
+
#[test]
fn retired_window_named_and_indexed_access_cannot_follow_a_reinserted_iframe() {
for cleanup_before_reinsertion in [false, true] {
diff --git a/vendor/v8-152.2.0/src/context_ext.cc b/vendor/v8-152.2.0/src/context_ext.cc
index abd9df573..f3380bcd7 100644
--- a/vendor/v8-152.2.0/src/context_ext.cc
+++ b/vendor/v8-152.2.0/src/context_ext.cc
@@ -3,6 +3,7 @@
#include "support.h"
#include "v8-context.h"
#include "v8-isolate.h"
+#include "v8-template.h"
using namespace support;
@@ -12,6 +13,18 @@ static_assert(sizeof(v8::Context::BackupIncumbentScope) ==
extern "C" {
+const v8::FunctionTemplate* v8__FunctionTemplate__NewWithCache(
+ v8::Isolate* isolate, v8::FunctionCallback callback,
+ const v8::Private& cache_property) {
+ return local_to_ptr(v8::FunctionTemplate::NewWithCache(
+ isolate, callback, ptr_to_local(&cache_property)));
+}
+
+void v8__FunctionTemplate__SetAcceptAnyReceiver(
+ const v8::FunctionTemplate& self, bool value) {
+ ptr_to_local(&self)->SetAcceptAnyReceiver(value);
+}
+
void v8__Context__BackupIncumbentScope__CONSTRUCT(
uninit_t<v8::Context::BackupIncumbentScope>* buf,
const v8::Context& context) {
diff --git a/vendor/v8-152.2.0/src/template.rs b/vendor/v8-152.2.0/src/template.rs
index bb1c94f63..9991f1658 100644
--- a/vendor/v8-152.2.0/src/template.rs
+++ b/vendor/v8-152.2.0/src/template.rs
@@ -17,6 +17,7 @@ use crate::NamedQueryCallback;
use crate::NamedSetterCallback;
use crate::NamedSetterCallbackForAccessor;
use crate::Object;
+use crate::Private;
use crate::PropertyAttribute;
use crate::PropertyEnumeratorCallback;
use crate::PropertyHandlerFlags;
@@ -39,6 +40,11 @@ use std::convert::TryFrom;
use std::ptr::null;
unsafe extern "C" {
+ fn v8__FunctionTemplate__NewWithCache(
+ isolate: *mut RealIsolate,
+ callback: FunctionCallback,
+ cache_property: *const Private,
+ ) -> *const FunctionTemplate;
fn v8__Template__Set(
this: *const Template,
key: *const Name,
@@ -103,6 +109,10 @@ unsafe extern "C" {
);
fn v8__FunctionTemplate__ReadOnlyPrototype(this: *const FunctionTemplate);
fn v8__FunctionTemplate__RemovePrototype(this: *const FunctionTemplate);
+ fn v8__FunctionTemplate__SetAcceptAnyReceiver(
+ this: *const FunctionTemplate,
+ value: bool,
+ );
fn v8__FunctionTemplate__HasInstance(
this: *const FunctionTemplate,
value: *const Value,
@@ -892,6 +902,34 @@ impl Signature {
}
impl FunctionTemplate {
+ /// Creates a getter template backed by a private property. Property reads
+ /// use the holder's cached value; explicit calls invoke the callback.
+ #[inline(always)]
+ pub fn new_with_cache<'s>(
+ scope: &PinScope<'s, '_, ()>,
+ callback: impl MapFnTo<FunctionCallback>,
+ cache_property: Local<'s, Private>,
+ ) -> Local<'s, FunctionTemplate> {
+ unsafe {
+ scope.cast_local(|sd| {
+ v8__FunctionTemplate__NewWithCache(
+ sd.get_isolate_ptr(),
+ callback.map_fn_to(),
+ &*cache_property,
+ )
+ })
+ }
+ .unwrap()
+ }
+
+ /// Controls whether calls skip the receiver's access check. V8 defaults to
+ /// accepting any receiver; set this to false before instantiating a function
+ /// whose receiver must be accessible from the actual calling context.
+ #[inline(always)]
+ pub fn set_accept_any_receiver(&self, value: bool) {
+ unsafe { v8__FunctionTemplate__SetAcceptAnyReceiver(self, value) };
+ }
+
/// Returns true if `value` was created from this function template or from
/// a function template that inherits from it.
#[inline(always)]