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): restrict named child access to same-origin documents
ldm0468533ced256
diff --git a/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rs b/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rsindex 18034b2b9..6e21f9784 100644--- a/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rs+++ b/moli-renderer-v8/src/context_bootstrap/window_accessors/interceptors.rs@@ -195,8 +195,9 @@ fn window_named_access_value<'s>(// Browsing-context names win over document id/name exposure, matching the// Window named access ordering. Both paths are fast miss paths now: child// contexts return immediately when empty, and document name lookup is indexed.- if let Some(handle) =- unsafe { &*host_ptr }.child_browsing_context_named_child_handle(child_handle, &key_name)+ let named_child = host.child_browsing_context_named_object_handle(child_handle, &key_name);+ if let Some(handle) = named_child+ && host.child_browsing_context_child_is_same_origin(child_handle, handle)&& let Some(window) =unsafe { &mut *host_ptr }.child_browsing_context_window_wrapper(scope, handle){@@ -208,6 +209,13 @@ fn window_named_access_value<'s>(None => host.document_handle(),};let handles = window_named_item_handles(host.dom_host(), document, &key_name);+ if !handles.is_empty()+ && let Some(handle) = named_child+ && let Some(window) =+ unsafe { &mut *host_ptr }.child_browsing_context_window_wrapper(scope, handle)+ {+ return Some(window.into());+ }if moli_trace::window_message_trace_enabled() {tracing::info!(target: "moli_window_message_trace",diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/cross_origin_bindings.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/cross_origin_bindings.rsindex 1aaa49d17..3ccb6533a 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/cross_origin_bindings.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/cross_origin_bindings.rs@@ -125,10 +125,7 @@ impl<'s> WindowTarget<'s> {})}- fn children(&self, scope: &mut v8::PinScope<'s, '_>) -> Vec<DomHandle> {- if self.closed {- return Vec::new();- }+ fn sync_children(&self, scope: &mut v8::PinScope<'s, '_>) {let host = unsafe { &mut *self.host };let document = match self.child {Some(handle) => host.child_browsing_context_document_handle(handle),@@ -138,6 +135,14 @@ impl<'s> WindowTarget<'s> {if let Some(document) = document {host.sync_child_browsing_context_subtree(scope, document);}+ }++ fn children(&self, scope: &mut v8::PinScope<'s, '_>) -> Vec<DomHandle> {+ if self.closed {+ return Vec::new();+ }+ self.sync_children(scope);+ let host = unsafe { &*self.host };match self.child {Some(handle) => host.child_browsing_context_direct_host_handles(handle)@@ -162,10 +167,10 @@ impl<'s> WindowTarget<'s> {scope: &mut v8::PinScope<'s, '_>,name: &str,) -> Option<v8::Local<'s, v8::Object>> {- self.children(scope);- if self.closed {+ if self.closed || name.is_empty() {return None;}+ self.sync_children(scope);let host = unsafe { &mut *self.host };let handle = host.child_browsing_context_named_child_handle(self.child, name)?;host.child_browsing_context_window_proxy_for_top(scope, handle)diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/frame_tree.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/frame_tree.rsindex de48201de..9a999bae2 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/frame_tree.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/frame_tree.rs@@ -44,47 +44,29 @@ impl JsContextHost {}pub(crate) fn child_browsing_context_child_frame_named_indices(- &mut self,+ &self,handle: crate::document_runtime::DomHandle,) -> Vec<(usize, String)> {- if self- .child_browsing_context_document_handle(handle)- .is_some()- {- return self- .child_browsing_context_direct_host_handles(handle)- .into_iter()- .enumerate()- .filter_map(|(index, child_handle)| {- self.dom_host()- .get_attribute(child_handle, "name")- .filter(|name| !name.is_empty())- .map(|name| (index, name))- })- .collect();- }- self.child_browsing_context_snapshot_markup(handle)- .map(|snapshot| {- let parent_scope = self- .child_browsing_context_web_storage_scope(- handle,- &moli_url::origin_ascii_serialization(self.document_url()),- )- .unwrap_or_else(|| self.top_web_storage_scope());- self.detached_child_browsing_context_frame_tree_snapshot(- "",- &snapshot.url,- &snapshot.markup,- self.child_browsing_context_scripting_enabled(handle),- 0,- parent_scope,- )- .into_iter()- .enumerate()- .filter_map(|(index, snapshot)| snapshot.name.map(|name| (index, name)))- .collect()+ // Markup-only snapshots cannot supply this set: visibility depends on+ // each child's active Document origin, after first-name deduplication.+ let mut seen = std::collections::HashSet::new();+ self.child_browsing_context_direct_host_handles(handle)+ .into_iter()+ .enumerate()+ .filter_map(|(index, child_handle)| {+ let name = self+ .child_browsing_contexts+ .get(&child_handle)?+ .window_name();+ if name.is_empty()+ || !seen.insert(name.to_owned())+ || !self.child_browsing_context_child_is_same_origin(Some(handle), child_handle)+ {+ return None;+ }+ Some((index, name.to_owned()))})- .unwrap_or_default()+ .collect()}pub(crate) fn child_browsing_context_frame_tree_snapshot(diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/lookup.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/lookup.rsindex 11f24ae3a..5ece54a1d 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/lookup.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/lookup.rs@@ -98,7 +98,6 @@ impl JsContextHost {}}- #[cfg(test)]pub(crate) fn top_level_child_browsing_context_handles_in_document_order(&self,) -> Vec<DomHandle> {@@ -204,12 +203,43 @@ impl JsContextHost {parent: Option<DomHandle>,key: &str,) -> Option<DomHandle> {+ let handle = self.child_browsing_context_named_object_handle(parent, key)?;+ // Deduplicate before filtering by origin: a cross-origin first match+ // must not expose a later same-origin child with the same target name.+ self.child_browsing_context_child_is_same_origin(parent, handle)+ .then_some(handle)+ }++ pub(crate) fn child_browsing_context_child_is_same_origin(+ &self,+ parent: Option<DomHandle>,+ child: DomHandle,+ ) -> bool {+ let parent = match parent {+ Some(parent) => self.child_window_access_origin(parent),+ None => self.main_window_access_origin(),+ };+ parent+ .zip(self.child_window_access_origin(child))+ .is_some_and(|(parent, child)| parent.is_same_origin(&child))+ }++ // Named objects also include cross-origin children when a Document's+ // id/name exposure independently supplies the supported property name.+ pub(crate) fn child_browsing_context_named_object_handle(+ &self,+ parent: Option<DomHandle>,+ key: &str,+ ) -> Option<DomHandle> {+ if key.is_empty() || self.child_browsing_contexts.is_empty() {+ return None;+ }// Window named access only searches direct scoped children. A full// frame-tree search can rediscover the receiver (for example when a// nested frame is named `document`) and recursively materialize it.let handles = match parent {- Some(parent) => self.child_browsing_context_child_frame_handles(parent),- None => self.top_level_child_browsing_context_handles_in_frame_tree_order(),+ Some(parent) => self.child_browsing_context_direct_host_handles(parent),+ None => self.top_level_child_browsing_context_handles_in_document_order(),};handles.into_iter().find(|handle| {self.dom_host()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 f57634414..afea0531e 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@@ -403,6 +403,31 @@ pub(in crate::native_bridge::context_host) enum WindowAccessOrigin {}impl WindowAccessOrigin {+ /// Compare document origins without document.domain relaxation.+ pub(in crate::native_bridge::context_host) fn is_same_origin(&self, other: &Self) -> bool {+ match (self, other) {+ (+ Self::Tuple {+ serialized_origin: left,+ ..+ },+ Self::Tuple {+ serialized_origin: right,+ ..+ },+ ) => left == right,+ (+ Self::Opaque {+ identity: Some(left),+ },+ Self::Opaque {+ identity: Some(right),+ },+ ) => left == right,+ _ => false,+ }+ }+pub(in crate::native_bridge::context_host) fn opaque(identity: WindowExecutionContextOwner,) -> Self {@@ -534,6 +559,25 @@ mod tests {assert!(inherited.can_access(&WindowAccessOrigin::opaque(inherited_identity)));assert!(!inherited.can_access(&WindowAccessOrigin::opaque(distinct_identity)));assert!(!inherited.can_access(&WindowAccessOrigin::Opaque { identity: None }));+ assert!(inherited.is_same_origin(&WindowAccessOrigin::opaque(inherited_identity)));+ assert!(!inherited.is_same_origin(&WindowAccessOrigin::opaque(distinct_identity)));+ assert!(!inherited.is_same_origin(&WindowAccessOrigin::Opaque { identity: None }));+ }++ #[test]+ fn same_origin_compares_tuples_without_document_domain_relaxation() {+ let origin = |url: &str, domain: Option<&str>| {+ WindowAccessOrigin::from_serialized_origin(url.to_owned(), domain.map(str::to_owned))+ .unwrap()+ };+ let parent = origin("https://a.example.test:8443", Some("example.test"));+ let same = origin("https://a.example.test:8443", None);+ let relaxed = origin("https://b.example.test:9443", Some("example.test"));+ assert!(parent.is_same_origin(&same));+ assert!(parent.can_access(&relaxed));+ assert!(!parent.is_same_origin(&relaxed));+ assert!(!parent.is_same_origin(&origin("http://a.example.test:8443", None)));+ assert!(!parent.is_same_origin(&origin("https://a.example.test:9443", None)));}#[test]diff --git a/moli-renderer-v8/src/script_vm/tests/cross_origin_named_children.rs b/moli-renderer-v8/src/script_vm/tests/cross_origin_named_children.rsnew file mode 100644index 000000000..bdba3f7ba--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/cross_origin_named_children.rs@@ -0,0 +1,225 @@+use 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)+ })+ })+ .unwrap()+ .context_id+}++#[tokio::test(flavor = "current_thread")]+async fn cross_origin_named_children_use_the_parent_origin_and_first_document_tree_match() {+ const PARENT: &str = "parent.named-children.test";+ const OBSERVER: &str = "observer.named-children.test";+ const FOREIGN: &str = "foreign.named-children.test";+ let server = StaticHttpServer::spawn_with_responder(+ 6,+ "Content-Type: text/html; charset=utf-8\r\n",+ |_, _| {+ "<!doctype html><body><script>\+ const url = new URL(location.href);\+ window.name = url.searchParams.get('name');\+ top.postMessage(url.pathname, '*');\+ </script>"+ .to_owned()+ },+ )+ .await;+ let parent_url = server.url_for_host(PARENT, "/parent");+ let observer_url = server.url_for_host(OBSERVER, "/observer?name=observer");+ let foreign_url = server.url_for_host(FOREIGN, "/foreign?name=foreign");+ let observer_origin_url = server.url_for_host(OBSERVER, "/observer-origin?name=observerOrigin");+ let duplicate_url = server.url_for_host(FOREIGN, "/duplicate?name=duplicate");+ let loader = static_http_loader([+ server.resolve_entry(PARENT),+ server.resolve_entry(OBSERVER),+ server.resolve_entry(FOREIGN),+ ]);+ let mut vm = new_storage_page_task_executor_test_vm_with_loader(parent_url.as_str(), &loader);+ 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'));+ const definitions = [+ ['observer-frame', 'observer', {observer_url:?}],+ ['foreign-frame', 'foreign', {foreign_url:?}],+ ['observer-origin-frame', 'observerOrigin', {observer_origin_url:?}],+ ['allowed-frame', 'allowed', 'about:blank'],+ ['duplicate-first', 'duplicate', {duplicate_url:?}],+ ['duplicate-second', 'duplicate', 'about:blank']+ ];+ for (const [id, name, src] of definitions) {{+ const frame = document.createElement('iframe');+ Object.assign(frame, {{id, name, src}});+ body.appendChild(frame);+ }}+ "#,+ observer_url = observer_url.as_str(),+ foreign_url = foreign_url.as_str(),+ observer_origin_url = observer_origin_url.as_str(),+ duplicate_url = duplicate_url.as_str(),+ ))+ .unwrap();+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(['/observer', '/foreign', '/observer-origin', '/duplicate'].every(path => loaded.has(path)))",+ "true",+ "three-origin child documents should commit and execute",+ )+ .await;+ let observer = child_context_for_element(&mut vm, "observer-frame");+ let result = vm.eval_in_child_default_context(observer, r#"+ globalThis.retained = top[1];+ globalThis.allowedDuplicate = top[5];+ globalThis.probe = callback => {+ try {+ const value = callback();+ return value === undefined ? 'undefined' : typeof value === 'boolean' ? value : 'exposed';+ }+ catch (error) { return error.name; }+ };+ globalThis.namedAccess = name => [+ probe(() => top[name]),+ probe(() => Object.getOwnPropertyDescriptor(top, name)),+ probe(() => name in top)+ ];+ JSON.stringify({+ foreign: namedAccess('foreign'),+ observerOrigin: namedAccess('observerOrigin'),+ duplicate: namedAccess('duplicate'),+ allowed: top.allowed === top[3],+ descriptor: Object.getOwnPropertyDescriptor(top, 'allowed').value === top[3],+ indexed: top[1].parent === top && top[2].parent === top+ })+ "#).unwrap();+ assert_eq!(+ serde_json::from_str::<serde_json::Value>(&result).unwrap(),+ serde_json::json!({+ "foreign": ["SecurityError", "SecurityError", "SecurityError"],+ "observerOrigin": ["SecurityError", "SecurityError", "SecurityError"],+ "duplicate": ["SecurityError", "SecurityError", "SecurityError"],+ "allowed": true,+ "descriptor": true,+ "indexed": true+ })+ );+ assert_eq!(+ vm.eval("window.foreign === undefined && window.duplicate === undefined")+ .unwrap(),+ "true"+ );++ // The receiver may itself be a child Window. Its own child inherits that+ // Window's origin, which differs from the top-level caller's origin.+ vm.eval_in_child_default_context(+ observer,+ r#"+ const nested = document.createElement('iframe');+ nested.name = 'inherited';+ document.body.appendChild(nested);+ void nested.contentWindow;+ "#,+ )+ .unwrap();+ assert_eq!(+ vm.eval("document.getElementById('observer-frame').contentWindow.inherited === document.getElementById('observer-frame').contentWindow[0]").unwrap(),+ "true"+ );++ // Reordering must select the first name in the current document tree,+ // rather than preserving insertion order or skipping a cross-origin first.+ vm.eval("document.body.appendChild(document.getElementById('duplicate-first'))")+ .unwrap();+ assert_eq!(+ vm.eval_in_child_default_context(observer, "top.duplicate === allowedDuplicate")+ .unwrap(),+ "true"+ );+ vm.eval("document.getElementById('duplicate-second').remove()")+ .unwrap();+ assert_eq!(+ vm.eval_in_child_default_context(observer, "JSON.stringify(namedAccess('duplicate'))")+ .unwrap(),+ r#"["SecurityError","SecurityError","SecurityError"]"#+ );++ for (host, path, visible) in [+ (PARENT, "/parent-origin?name=foreign", true),+ (FOREIGN, "/foreign-again?name=foreign", false),+ ] {+ let url = server.url_for_host(host, path);+ vm.eval(&format!(+ "document.getElementById('foreign-frame').src = {:?};",+ url.as_str()+ ))+ .unwrap();+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ &format!("String(loaded.has({:?}))", url.path()),+ "true",+ "named visibility should follow the committed child origin",+ )+ .await;+ assert_eq!(+ vm.eval_in_child_default_context(observer, "top[1] === retained")+ .unwrap(),+ "true",+ "numeric WindowProxy identity survives origin changes"+ );+ assert_eq!(+ vm.eval_in_child_default_context(observer, "probe(() => top.foreign === retained)")+ .unwrap(),+ if visible { "true" } else { "SecurityError" }+ );+ }+ // Setting document.domain does not change the origin tuple used for this+ // property set, even when it changes ordinary script access checks.+ vm.eval("document.domain = document.domain").unwrap();+ assert_eq!(+ vm.eval_in_child_default_context(observer, "top.allowed.parent === top")+ .unwrap(),+ "true"+ );+ let foreign = child_context_for_element(&mut vm, "foreign-frame");+ vm.eval_in_child_default_context(foreign, "window.name = 'then'")+ .unwrap();+ assert_eq!(+ vm.eval_in_child_default_context(observer,+ "top.then === undefined && Object.getOwnPropertyDescriptor(top, 'then').value === undefined").unwrap(),+ "true",+ "an ineligible child must not shadow the cross-origin fallback"+ );+ // Same-origin named access can still expose a cross-origin named object+ // when an element id independently supplies the supported property name.+ vm.eval(+ "document.body.appendChild(Object.assign(document.createElement('div'), {id: 'then'}))",+ )+ .unwrap();+ assert_eq!(+ vm.eval("window.then === document.getElementById('foreign-frame').contentWindow")+ .unwrap(),+ "true"+ );+ assert_eq!(+ vm.eval_in_child_default_context(observer, "top.then === undefined")+ .unwrap(),+ "true"+ );+ 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 fd844a446..ccfc74af4 100644--- a/moli-renderer-v8/src/script_vm/tests/mod.rs+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs@@ -2182,6 +2182,7 @@ mod svg_transform_sync_consolidation;mod audio_event_interfaces;mod audio_value_owner_interface_exposure_interfaces;+mod cross_origin_named_children;mod declarative_receivers;mod hyperlink_null_url_protocol;mod import_meta;