Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(window): authorize frame documents against their actual parent
ldm06241410533ea
diff --git a/moli-renderer-v8/src/context_bootstrap/window_accessors/child_context.rs b/moli-renderer-v8/src/context_bootstrap/window_accessors/child_context.rsindex ca9f30eee..149da4478 100644--- a/moli-renderer-v8/src/context_bootstrap/window_accessors/child_context.rs+++ b/moli-renderer-v8/src/context_bootstrap/window_accessors/child_context.rs@@ -1,5 +1,6 @@use super::helpers::{- window_child_context_handle, window_hidden_value, window_host_ptr, window_receiver,+ window_child_context_handle, window_current_dispatch_scope, window_hidden_value,+ window_host_ptr, window_receiver,};use super::*;@@ -24,18 +25,24 @@ pub(in crate::context_bootstrap) fn window_frame_element_getter<'s>(let Some(receiver) = window_receiver(scope, &args) else {return;};- if let Some(value) = window_hidden_value(scope, receiver, WINDOW_FRAME_ELEMENT_SLOT) {- rv.set(value);- return;- }- let Some(handle) = window_child_context_handle(scope, receiver) else {+ let Some(host_ptr) = window_host_ptr(scope, receiver) else {rv.set_null();return;};- let Some(host_ptr) = window_host_ptr(scope, receiver) else {+ let Some(handle) = window_current_dispatch_scope(scope, receiver, unsafe { &*host_ptr })+ .and_then(|owner| owner.child_window())+ .filter(|handle| unsafe { &*host_ptr }.frame_owner_can_access_content_document(*handle))+ else {rv.set_null();return;};+ // A cached embedding element is a capability to its entire owner Document.+ // Recheck same origin-domain before returning it, including after domain+ // mutation or retirement of the receiver's original Realm.+ if let Some(value) = window_hidden_value(scope, receiver, WINDOW_FRAME_ELEMENT_SLOT) {+ rv.set(value);+ return;+ }match unsafe { &mut *host_ptr }.native_bridge_mut().wrap_handle(scope, host_ptr, handle)diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rsindex 872a2d97e..db551794d 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/document.rs@@ -32,6 +32,27 @@ struct ChildDocumentStreamMethodsDeclaration<'scope> {}impl JsContextHost {+ pub(crate) fn frame_owner_content_document_wrapper<'s>(+ &mut self,+ scope: &mut v8::PinScope<'s, '_>,+ handle: DomHandle,+ ) -> Option<v8::Local<'s, v8::Object>> {+ self.refresh_child_browsing_context(scope, handle);+ if !self.frame_owner_can_access_content_document(handle) {+ return None;+ }+ // Materialize the authorized target directly. Public Window getters+ // would check the native callback's realm instead of the node Document.+ self.ensure_prebootstrapped_child_default_context(scope, handle)+ .ok()?;+ if let Some(window) = self.existing_child_browsing_context_window_wrapper(scope, handle) {+ self.set_cached_detached_iframe_content_window(scope, handle, window);+ }+ let document = self.child_browsing_context_document_wrapper(scope, handle)?;+ self.set_cached_detached_iframe_content_document(scope, handle, document);+ Some(document)+ }+fn child_browsing_context_has_uncommitted_navigation_seed(&self, handle: DomHandle) -> bool {let Some(entry) = self.child_browsing_contexts.get(&handle) else {return false;@@ -128,12 +149,10 @@ impl JsContextHost {window,!self.child_browsing_context_has_uncommitted_navigation_seed(handle),);- crate::native_bridge::helpers::set_object_slot(- scope,- window,- "document",- document.into(),- );+ // bind_current_child_window_document publishes through the+ // private slot used by the unforgeable Window.document getter.+ // Redefining that public property can run a different realm's+ // access check and must not replace the native accessor.}ready_work.extend(self.sync_child_browsing_context_subtree_into_ready_work(scope, document_handle),diff --git a/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rs b/moli-renderer-v8/src/native_bridge/context_host/window_security_tokens.rsindex afea0531e..a3bf59e72 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@@ -184,6 +184,29 @@ impl JsContextHost {top.can_access(&child)}+ pub(crate) fn frame_owner_can_access_content_document(&self, handle: DomHandle) -> bool {+ let Some(document) = self.dom_host().owner_document_handle(handle) else {+ return false;+ };+ let owner_scope = if document == self.document_handle() {+ OwnerDispatchScope::Top+ } else if let Some(parent) =+ self.child_browsing_context_handle_for_stored_document(document)+ {+ OwnerDispatchScope::Child(parent)+ } else if let Some(popup) = self.lightweight_popup_id_for_document_handle(document) {+ OwnerDispatchScope::LightweightPopup(popup)+ } else {+ return false;+ };+ // HTML's content document algorithm compares the container's node+ // Document with the active child Document, using same origin-domain.+ // Neither the top-level Window nor the callback's realm is its owner.+ self.window_access_origin_for_dispatch_scope(owner_scope)+ .zip(self.child_window_access_origin(handle))+ .is_some_and(|(owner, child)| owner.can_access(&child))+ }+pub(in crate::native_bridge::context_host) fn child_window_can_access_lightweight_popup(&self,handle: DomHandle,diff --git a/moli-renderer-v8/src/native_bridge/element/resource_elements.rs b/moli-renderer-v8/src/native_bridge/element/resource_elements.rsindex 113f21649..0299d9c52 100644--- a/moli-renderer-v8/src/native_bridge/element/resource_elements.rs+++ b/moli-renderer-v8/src/native_bridge/element/resource_elements.rs@@ -1357,24 +1357,7 @@ fn frame_owner_content_document<'s>(None};}- let runtime = unsafe { &mut *runtime_ptr };- runtime.refresh_child_browsing_context(scope, handle);- if !runtime.child_browsing_context_is_same_origin_with_top(handle) {- return None;- }- if let Some(window) = runtime.child_browsing_context_window_wrapper(scope, handle) {- runtime.set_cached_detached_iframe_content_window(scope, handle, window);- if let Some(document) = window- .get(scope, v8str(scope, "document").into())- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())- {- runtime.set_cached_detached_iframe_content_document(scope, handle, document);- return Some(document);- }- }- let document = runtime.child_browsing_context_document_wrapper(scope, handle)?;- runtime.set_cached_detached_iframe_content_document(scope, handle, document);- Some(document)+ unsafe { &mut *runtime_ptr }.frame_owner_content_document_wrapper(scope, handle)}pub(super) fn frame_owner_content_window_getter_function<'s>(diff --git a/moli-renderer-v8/src/script_vm/tests/frame_owner_origin_access.rs b/moli-renderer-v8/src/script_vm/tests/frame_owner_origin_access.rsnew file mode 100644index 000000000..6a8c1a389--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/frame_owner_origin_access.rs@@ -0,0 +1,194 @@+use super::*;++pub(super) fn child_context_for_element(vm: &mut ScriptVm, element_id: &str) -> i64 {+ vm.live_child_default_runtime_realm_inventory()+ .into_iter()+ .find(|realm| {+ vm.child_frame_realm_store+ .get(&realm.context_id)+ .is_some_and(|record| {+ vm._context_host+ .borrow()+ .dom_host()+ .get_attribute(record.child_handle, "id")+ .as_deref()+ == Some(element_id)+ })+ })+ .expect("the committed child should have a default realm")+ .context_id+}++#[tokio::test(flavor = "current_thread")]+async fn frame_owner_content_document_uses_its_node_document_origin() {+ const ROOT: &str = "root.frame-owner.test";+ const PARENT: &str = "parent.frame-owner.test";+ const FOREIGN: &str = "foreign.frame-owner.test";+ let server = StaticHttpServer::spawn_with_responder(+ 6,+ "Content-Type: text/html; charset=utf-8\r\n",+ |_, request| {+ let nested = if request.target == "/parent" {+ let (_, port) = request.host.as_deref().unwrap().split_once(':').unwrap();+ format!(+ r#"<iframe id="root-origin" src="http://{ROOT}:{port}/root-child"></iframe>+ <iframe id="parent-origin" src="/parent-child"></iframe>+ <iframe id="foreign-origin" src="http://{FOREIGN}:{port}/foreign-child"></iframe>"#+ )+ } else {+ String::new()+ };+ format!(+ "<!doctype html><body>{nested}<p>private document</p>\+ <script>top.postMessage(location.pathname, '*')</script>"+ )+ },+ )+ .await;+ let loader = static_http_loader([+ server.resolve_entry(ROOT),+ server.resolve_entry(PARENT),+ server.resolve_entry(FOREIGN),+ ]);+ let mut vm = new_storage_page_task_executor_test_vm_with_loader(+ server.url_for_host(ROOT, "/root").as_str(),+ &loader,+ );+ let parent_url = server.url_for_host(PARENT, "/parent");+ vm.eval(&format!(+ r#"+ globalThis.loaded = new Set();+ addEventListener('message', event => loaded.add(event.data));+ const root = document.documentElement || document.appendChild(document.createElement('html'));+ const body = document.body || root.appendChild(document.createElement('body'));+ body.appendChild(Object.assign(document.createElement('iframe'), {{id: 'parent-frame', src: {parent_url:?}}}));+ "#,+ parent_url = parent_url.as_str(),+ ))+ .unwrap();+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(['/parent', '/root-child', '/parent-child', '/foreign-child'].every(path => loaded.has(path)))",+ "true",+ "three-origin nested frame documents should commit and execute",+ )+ .await;+ let parent = child_context_for_element(&mut vm, "parent-frame");+ assert_eq!(+ vm.eval_in_child_default_context(parent, "frameElement === null")+ .unwrap(),+ "true",+ "a cross-origin child must not obtain its embedding Document through frameElement"+ );+ for (id, visible) in [+ ("root-origin", false),+ ("parent-origin", true),+ ("foreign-origin", false),+ ] {+ let child = child_context_for_element(&mut vm, id);+ assert_eq!(+ vm.eval_in_child_default_context(child, "String(frameElement !== null)")+ .unwrap(),+ visible.to_string(),+ "frameElement must compare the child with its actual parent: {id}"+ );+ }+ let result = vm.eval_in_child_default_context(parent, r#"+ const probe = callback => {+ try { return callback(); }+ catch (error) { return error.name; }+ };+ const getter = Object.getOwnPropertyDescriptor(window, 'document').get;+ JSON.stringify(['root-origin', 'parent-origin', 'foreign-origin'].map(id => {+ const frame = document.getElementById(id);+ return {+ document: probe(() => frame.contentDocument === null ? null : frame.contentDocument.querySelector('p').textContent),+ windowDocument: probe(() => frame.contentWindow.document === frame.contentDocument),+ borrowedGetter: probe(() => getter.call(frame.contentWindow) === frame.contentDocument),+ svgDocument: frame.getSVGDocument()+ };+ }))+ "#).unwrap();+ assert_eq!(+ serde_json::from_str::<serde_json::Value>(&result).unwrap(),+ serde_json::json!([+ { "document": null, "windowDocument": "SecurityError", "borrowedGetter": "SecurityError", "svgDocument": null },+ { "document": "private document", "windowDocument": true, "borrowedGetter": true, "svgDocument": null },+ { "document": null, "windowDocument": "SecurityError", "borrowedGetter": "SecurityError", "svgDocument": null }+ ])+ );+ vm.eval_in_child_default_context(+ parent,+ "globalThis.retainedChild = document.getElementById('parent-origin').contentWindow",+ )+ .unwrap();+ for (host, path, visible) in [+ (ROOT, "/root-navigation", false),+ (PARENT, "/parent-navigation", true),+ ] {+ let url = server.url_for_host(host, path);+ vm.eval_in_child_default_context(+ parent,+ &format!(+ "document.getElementById('parent-origin').src = {:?}",+ url.as_str()+ ),+ )+ .unwrap();+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ &format!("String(loaded.has({path:?}))"),+ "true",+ "contentDocument access should follow the committed child origin",+ )+ .await;+ assert_eq!(+ vm.eval_in_child_default_context(+ parent,+ "JSON.stringify([document.getElementById('parent-origin').contentDocument !== null, document.getElementById('parent-origin').contentWindow === retainedChild])",+ )+ .unwrap(),+ format!("[{visible},true]")+ );+ }++ // contentDocument uses same origin-domain, unlike the stricter origin+ // tuple comparison for Window named child properties.+ vm.eval_in_child_default_context(parent, "document.domain = document.domain")+ .unwrap();+ assert_eq!(+ vm.eval_in_child_default_context(+ parent,+ "document.getElementById('parent-origin').contentDocument === null",+ )+ .unwrap(),+ "true",+ "one-sided document.domain assignment must revoke access"+ );+ let child = child_context_for_element(&mut vm, "parent-origin");+ assert_eq!(+ vm.eval_in_child_default_context(child, "frameElement === null")+ .unwrap(),+ "true",+ "the cached embedding element must be hidden after one-sided domain mutation"+ );+ vm.eval_in_child_default_context(child, "document.domain = document.domain")+ .unwrap();+ assert_eq!(+ vm.eval_in_child_default_context(child, "frameElement.ownerDocument === parent.document")+ .unwrap(),+ "true"+ );+ assert_eq!(+ vm.eval_in_child_default_context(+ parent,+ "document.getElementById('parent-origin').contentDocument === retainedChild.document",+ )+ .unwrap(),+ "true",+ "matching document.domain assignments must restore access"+ );+ assert_eq!(server.finish().await.len(), 6);+}diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rsindex b699a8e90..ce935b8a1 100644--- a/moli-renderer-v8/src/script_vm/tests/mod.rs+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs@@ -2185,6 +2185,7 @@ mod audio_event_interfaces;mod audio_value_owner_interface_exposure_interfaces;mod cross_origin_named_children;mod declarative_receivers;+mod frame_owner_origin_access;mod hyperlink_null_url_protocol;mod import_meta;mod indexed_db;