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(navigation): guard fragment routing and stale facade targets (#1701)
Donough Liu536fa76aee97
diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rsindex 210198104..f0b3a26e5 100644--- a/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs@@ -1,5 +1,5 @@use super::super::location_runtime::{- is_same_document_fragment_navigation, location_href_slot, sync_location_object,+ location_href_slot, sync_location_object, urls_equal_ignoring_fragment,};use super::super::navigation_entry::{cache_current_history_state, history_entries, history_index, navigation_current_entry,@@ -169,9 +169,7 @@ pub(in crate::context_bootstrap) fn dispatch_history_entry_post_commit_events<'s.old_url.as_deref().and_then(|old_url| url::Url::parse(old_url).ok())- .is_some_and(|old_url| {- is_same_document_fragment_navigation(Some(&old_url), &applied.parsed_url)- });+ .is_some_and(|old_url| urls_equal_ignoring_fragment(&old_url, &applied.parsed_url));if let Some(child_handle) = child_handle&& !is_same_document_traversal{diff --git a/moli-renderer-v8/src/context_bootstrap/location_runtime.rs b/moli-renderer-v8/src/context_bootstrap/location_runtime.rsindex f56648123..c4a801dd6 100644--- a/moli-renderer-v8/src/context_bootstrap/location_runtime.rs+++ b/moli-renderer-v8/src/context_bootstrap/location_runtime.rs@@ -18,7 +18,7 @@ pub(super) use install::{};pub(super) use navigation::{is_same_document_fragment_navigation, resolve_location_navigation_target,- urls_refer_to_same_document,+ urls_equal_ignoring_fragment, urls_refer_to_same_document,};pub(super) use slots::{location_href_slot, sync_location_object};pub(crate) use surface::sync_global_location_runtime_state;diff --git a/moli-renderer-v8/src/context_bootstrap/location_runtime/navigation.rs b/moli-renderer-v8/src/context_bootstrap/location_runtime/navigation.rsindex 1d8fabe0a..f911f66e8 100644--- a/moli-renderer-v8/src/context_bootstrap/location_runtime/navigation.rs+++ b/moli-renderer-v8/src/context_bootstrap/location_runtime/navigation.rs@@ -45,9 +45,16 @@ pub(in crate::context_bootstrap) fn is_same_document_fragment_navigation(current: Option<&url::Url>,target: &url::Url,) -> bool {- let Some(current) = current else {- return false;- };+ // URL equality alone is not fragment navigation: assigning the current URL+ // without a fragment still navigates to a new Document. An empty # counts.+ target.fragment().is_some()+ && current.is_some_and(|current| urls_equal_ignoring_fragment(current, target))+}++pub(in crate::context_bootstrap) fn urls_equal_ignoring_fragment(+ current: &url::Url,+ target: &url::Url,+) -> bool {let mut current_without_fragment = current.clone();current_without_fragment.set_fragment(None);let mut target_without_fragment = target.clone();@@ -65,5 +72,5 @@ pub(in crate::context_bootstrap) fn urls_refer_to_same_document(let Ok(target) = url::Url::parse(target_href) else {return false;};- is_same_document_fragment_navigation(Some(¤t), &target)+ urls_equal_ignoring_fragment(¤t, &target)}diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_events.rs b/moli-renderer-v8/src/context_bootstrap/navigation_events.rsindex 1744e33f3..fb9aeaa12 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_events.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_events.rs@@ -1135,8 +1135,7 @@ fn dispatch_cross_document_navigation_navigate_event_for_window_with_type_form_d.as_ref().is_some_and(|next| is_same_document_fragment_navigation(current_url.as_ref(), next))};- let hash_change =- navigation_type != "reload" && should_dispatch_hash_change(¤t_href, href);+ let hash_change = same_document && should_dispatch_hash_change(¤t_href, href);let destination = create_navigation_destination(scope, href, same_document, -1, None);let signal = create_navigation_abort_signal(scope);let init = NavigateEventInitDeclaration {diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_seed.rs b/moli-renderer-v8/src/context_bootstrap/navigation_seed.rsindex e60d954bc..a12ebd4f4 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_seed.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_seed.rs@@ -1,4 +1,4 @@-use super::location_runtime::is_same_document_fragment_navigation;+use super::location_runtime::urls_equal_ignoring_fragment;use super::navigation_entry::{history_index, navigation_entry_public_token};use super::navigation_serialize::{apply_current_document_referrer_policy_to_entry_snapshots, serialize_history_entries,@@ -122,7 +122,7 @@ pub(super) fn history_entry_seed_for_traversal<'s>();let mut candidate = traversal_navigation_seed_candidate(entries, current_index, target_index)?;- if is_same_document_fragment_navigation(Some(&candidate.current_url), &candidate.target_url) {+ if urls_equal_ignoring_fragment(&candidate.current_url, &candidate.target_url) {return None;}diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_window.rs b/moli-renderer-v8/src/context_bootstrap/navigation_window.rsindex 2912f7cc7..0a95b3270 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_window.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_window.rs@@ -287,6 +287,6 @@ pub(super) fn should_dispatch_hash_change(old_url: &str, new_url: &str) -> boollet Ok(new) = url::Url::parse(new_url) else {return false;};- super::location_runtime::is_same_document_fragment_navigation(Some(&old), &new)+ super::location_runtime::urls_equal_ignoring_fragment(&old, &new)&& old.fragment() != new.fragment()}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.rsindex 00cc30adb..030e29287 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@@ -29,8 +29,10 @@ mod cross_origin_bindings;mod location;use cross_origin_bindings::*;-#[derive(Clone, Copy)]-struct ChildWindowProxyFacadeContextHandle(DomHandle);+// The same DOM handle can acquire a new browsing context after reinsertion.+// Keep the creating frame identity with the facade's navigation authority.+#[derive(Clone)]+struct ChildWindowProxyFacadeContextHandle(DomHandle, String);#[derive(Default)]pub(in crate::native_bridge::context_host) struct ChildWindowProxyRecords {@@ -997,6 +999,9 @@ impl JsContextHost {if self.top_window_can_access_child(handle) {return true;}+ let Some(frame_id) = self.frame_owner_frame_id_for_child_handle(handle) else {+ return false;+ };let Some(window_proxy) = self.child_window_proxy_records.live_window(scope, handle) else {return false;};@@ -1012,7 +1017,9 @@ impl JsContextHost {self as *mut Self,self.context_host_lifecycle_handle(),);- let previous = context.set_slot(Rc::new(ChildWindowProxyFacadeContextHandle(handle)));+ let previous = context.set_slot(Rc::new(ChildWindowProxyFacadeContextHandle(+ handle, frame_id.0,+ )));debug_assert!(previous.is_none());// Keep V8's unique default security token. A facade is not a real// LocalWindow realm, so no external context may bypass the access@@ -1111,6 +1118,7 @@ impl JsContextHost {return None;}+ let frame_id = self.frame_owner_frame_id_for_child_handle(handle)?;let (proxy, facade_context) = self.bridge.bindings.instantiate_window_proxy_shell(scope);let global = scope.get_current_context().global(scope);let top = self.child_browsing_context_root_window(scope, handle, global);@@ -1124,7 +1132,9 @@ impl JsContextHost {self as *mut Self,self.context_host_lifecycle_handle(),);- context.set_slot(Rc::new(ChildWindowProxyFacadeContextHandle(handle)));+ context.set_slot(Rc::new(ChildWindowProxyFacadeContextHandle(+ handle, frame_id.0,+ )));{let scope = &mut v8::ContextScope::new(scope, context);set_null_prototype(scope, proxy);@@ -2375,7 +2385,7 @@ fn cross_origin_location_navigate<'s>(};let host = unsafe { &mut *host_ptr };let target = host.resolve_child_browsing_context_url(handle, &raw);- if cross_origin_location_target_is_same_document(host, handle, &target)+ if cross_origin_location_target_is_fragment_navigation(host, handle, &target)&& let Some(window) = host.existing_child_browsing_context_window_wrapper(scope, handle)&& !dispatch_cross_document_navigation_navigate_event_for_window(scope,@@ -2392,19 +2402,21 @@ fn cross_origin_location_navigate<'s>(true}-fn cross_origin_location_target_is_same_document(+fn cross_origin_location_target_is_fragment_navigation(host: &JsContextHost,handle: DomHandle,target: &url::Url,) -> bool {- host.child_browsing_context_current_url(handle)- .is_some_and(|current| {- let mut current = current;- current.set_fragment(None);- let mut target = target.clone();- target.set_fragment(None);- current == target- })+ target.fragment().is_some()+ && host+ .child_browsing_context_current_url(handle)+ .is_some_and(|current| {+ let mut current = current;+ current.set_fragment(None);+ let mut target = target.clone();+ target.set_fragment(None);+ current == target+ })}fn cross_origin_location_replace_callback<'s>(diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/location.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/location.rsindex ac0bf08b8..8fca4cd11 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/location.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/window/location.rs@@ -129,17 +129,26 @@ fn navigate_cross_origin_child<'s>(let context = window.get_creation_context(scope)?;let host_ptr = crate::util::context_host_ptr_from_context_slot(context)?;let host = unsafe { &mut *host_ptr };- let handle = host- .window_execution_context_identity_for_access_check(context)- .filter(|identity| host.window_execution_context_identity_is_current(*identity))- .and_then(|identity| identity.dispatch_scope().child_window())- .or_else(|| {- context- .get_slot::<ChildWindowProxyFacadeContextHandle>()- .map(|handle| handle.0)- })?;+ let handle =+ if let Some(identity) = host.window_execution_context_identity_for_access_check(context) {+ let handle = identity.dispatch_scope().child_window()?;+ if !host.window_execution_context_identity_is_current(identity) {+ return Some(false);+ }+ handle+ } else {+ let facade = context.get_slot::<ChildWindowProxyFacadeContextHandle>()?;+ if !host.child_window_proxy_frame_is_current(facade.0, &facade.1) {+ // Deny the retired facade without falling back to the old Window's+ // Location route, which could otherwise retarget the reused handle.+ return Some(false);+ }+ facade.0+ };let target = url::Url::parse(raw).ok()?;- if cross_origin_location_target_is_same_document(host, handle, &target) {+ if kind != crate::context_bootstrap::LocationNavigationKind::Reload+ && cross_origin_location_target_is_fragment_navigation(host, handle, &target)+ {return None;}// A foreign initiator navigates the browsing context, without firing adiff --git a/moli-renderer-v8/src/script_vm/tests/cross_origin_navigation.rs b/moli-renderer-v8/src/script_vm/tests/cross_origin_navigation.rsindex ceaf58aa2..05c915a95 100644--- a/moli-renderer-v8/src/script_vm/tests/cross_origin_navigation.rs+++ b/moli-renderer-v8/src/script_vm/tests/cross_origin_navigation.rs@@ -147,3 +147,315 @@ root.appendChild(frame);}}}++#[tokio::test(flavor = "current_thread")]+async fn cross_origin_location_same_url_without_fragment_is_cross_document() {+ let server = StaticHttpServer::spawn_with_responder(+ 24,+ "Content-Type: text/html; charset=utf-8\r\n",+ |_, _| {+ r#"<!doctype html><script>+navigation.onnavigate = event => {+ top.postMessage('NAVIGATE:' + event.destination.sameDocument + ':' + event.hashChange, '*');+ if (location.search === '?cancel') event.preventDefault();+};+</script>"#+ .to_owned()+ },+ )+ .await;+ let loader = static_http_loader([+ server.resolve_entry("parent.same-url.test"),+ server.resolve_entry("child.same-url.test"),+ ]);+ let parent = server.url_for_host("parent.same-url.test", "/parent");+ for foreign in [true, false] {+ let host = if foreign {+ "child.same-url.test"+ } else {+ "parent.same-url.test"+ };+ let path = if foreign {+ "/child?cancel"+ } else {+ "/child?allow"+ };+ let target = server.url_for_host(host, path);+ for fragment in ["", "#old"] {+ for replace in [false, true] {+ let mut vm =+ new_storage_page_task_executor_test_vm_with_loader(parent.as_str(), &loader);+ let initial = format!("{target}{fragment}");+ vm.eval(&format!(+ r#"+globalThis.loads = 0;+globalThis.messages = [];+addEventListener('message', event => messages.push(event.data));+const root = document.documentElement || document.appendChild(document.createElement('html'));+const frame = document.createElement('iframe');+frame.onload = () => ++loads;+frame.src = {initial:?};+root.appendChild(frame);+"#+ ))+ .unwrap();+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(loads)",+ "1",+ "initial child load",+ )+ .await;+ let action = if replace {+ format!(+ "frame.contentWindow.location.replace({:?}); 'queued'",+ target.as_str()+ )+ } else {+ format!(+ "frame.contentWindow.location.href = {:?}; 'queued'",+ target.as_str()+ )+ };+ vm.eval(&action).unwrap();+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(loads)",+ "2",+ "a target without a fragment must load a new Document, including an unchanged URL",+ )+ .await;+ let expected = if foreign {+ "[]"+ } else {+ r#"["NAVIGATE:false:false"]"#+ };+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "JSON.stringify(messages)",+ expected,+ "navigate event must reflect initiator origin and cross-document routing",+ )+ .await;+ }+ }+ }+}++#[tokio::test(flavor = "current_thread")]+async fn cross_origin_location_fragments_preserve_the_document() {+ let server = StaticHttpServer::spawn_with_responder(+ 1,+ "Content-Type: text/html; charset=utf-8\r\n",+ |_, _| {+ r#"<!doctype html><script>+navigation.onnavigate = event => top.postMessage('NAVIGATE:' + event.destination.sameDocument + ':' + event.hashChange, '*');+onhashchange = () => top.postMessage('HASH', '*');+</script>"#+ .to_owned()+ },+ )+ .await;+ let loader = static_http_loader([+ server.resolve_entry("parent.fragment-route.test"),+ server.resolve_entry("child.fragment-route.test"),+ ]);+ let parent = server.url_for_host("parent.fragment-route.test", "/parent");+ let child = server.url_for_host("child.fragment-route.test", "/child");+ let mut vm = new_storage_page_task_executor_test_vm_with_loader(parent.as_str(), &loader);+ vm.eval(&format!(+ r#"+globalThis.loads = 0;+globalThis.messages = [];+addEventListener('message', event => messages.push(event.data));+const root = document.documentElement || document.appendChild(document.createElement('html'));+const frame = document.createElement('iframe');+frame.onload = () => ++loads;+frame.src = {child:?};+root.appendChild(frame);+"#,+ child = child.as_str()+ ))+ .unwrap();+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "String(loads)",+ "1",+ "initial foreign child load",+ )+ .await;+ for (fragment, expected) in [+ ("#", r#"["NAVIGATE:true:true","HASH"]"#),+ (+ "#section",+ r#"["NAVIGATE:true:true","HASH","NAVIGATE:true:true","HASH"]"#,+ ),+ ] {+ let target = format!("{child}{fragment}");+ vm.eval(&format!(+ "frame.contentWindow.location.href = {target:?}; 'queued'"+ ))+ .unwrap();+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "JSON.stringify(messages)",+ expected,+ "empty and nonempty fragments must retain the fragment navigation path",+ )+ .await;+ assert_eq!(vm.eval("String(loads)").unwrap(), "1");+ }+ // Returning to an entry without a fragment is still a same-document+ // history traversal, even though assigning that URL would navigate.+ vm.eval(+ "globalThis.retainedTopDocument = document; globalThis.topHashes = 0; \+ addEventListener('hashchange', () => ++topHashes); \+ history.pushState(null, '', '#parent');",+ )+ .unwrap();+ assert_eq!(+ vm.eval("JSON.stringify([location.hash, topHashes])")+ .unwrap(),+ r##"["#parent",0]"##+ );+ vm.eval("history.back(); 'queued'").unwrap();+ let expected = format!("[{:?},1]", parent.as_str());+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "JSON.stringify([location.href, topHashes])",+ &expected,+ "history may remove a fragment without replacing the Document",+ )+ .await;+ assert_eq!(+ vm.eval("String(document === retainedTopDocument)").unwrap(),+ "true"+ );+}++#[tokio::test(flavor = "current_thread")]+async fn cross_origin_facade_location_is_scoped_to_its_browsing_context() {+ let server = StaticHttpServer::spawn_with_responder(+ 6,+ "Content-Type: text/html; charset=utf-8\r\n",+ |_, _| r#"<!doctype html><script>onload = () => top.postMessage(location.pathname, '*');</script>"#.to_owned(),+ ).await;+ let loader = static_http_loader([+ server.resolve_entry("parent.facade-location.test"),+ server.resolve_entry("child.facade-location.test"),+ ]);+ let parent = server.url_for_host("parent.facade-location.test", "/parent");+ let child = server.url_for_host("child.facade-location.test", "/child");+ let target = server.url_for_host("child.facade-location.test", "/target");+ for reinsert in [false, true] {+ let mut vm = new_storage_page_task_executor_test_vm_with_loader(parent.as_str(), &loader);+ vm.eval(&format!(+ r#"+globalThis.loads = 0;+globalThis.messages = [];+addEventListener('message', event => messages.push(event.data));+const root = document.documentElement || document.appendChild(document.createElement('html'));+const frame = document.createElement('iframe');+frame.id = 'child';+frame.onload = () => ++loads;+frame.src = {child:?};+root.appendChild(frame);+"#,+ child = child.as_str()+ ))+ .unwrap();+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "JSON.stringify([loads, messages])",+ r#"[1,["/child"]]"#,+ "initial child and message delivery",+ )+ .await;+ vm.eval("messages.length = 0").unwrap();+ let handle = vm.document_runtime.get_element_by_id("child").unwrap();+ let context_id = vm+ .child_frame_realm_store+ .iter_by_execution_context_id()+ .find_map(|(id, context)| (context.child_handle == handle).then_some(id))+ .unwrap();+ // Use the production retirement path, pausing before a successor Realm+ // materializes, so the saved Location really belongs to a facade.+ vm.destroy_child_default_context(context_id);+ let context = &vm.page_default_runtime.context as *const v8::Global<v8::Context>;+ vm.with_context_scope_by_ptr(context, |scope, _| {+ let host_ptr = crate::util::context_host_ptr_from_global_bridge(scope).unwrap();+ let host = unsafe { &mut *host_ptr };+ let window = host+ .child_browsing_context_window_proxy_for_accessing_context(scope, handle)+ .unwrap();+ let facade = window.get_creation_context(scope).unwrap();+ assert!(+ host.window_execution_context_identity_for_access_check(facade)+ .is_none()+ );+ let location_value = window+ .get(scope, crate::util::v8str(scope, "location").into())+ .unwrap();+ let location = v8::Local::<v8::Object>::try_from(location_value).unwrap();+ assert_eq!(location.get_creation_context(scope), Some(facade));+ let global = scope.get_current_context().global(scope);+ global+ .set(+ scope,+ crate::util::v8str(scope, "oldFacadeWindow").into(),+ window.into(),+ )+ .unwrap();+ global+ .set(+ scope,+ crate::util::v8str(scope, "oldFacadeLocation").into(),+ location.into(),+ )+ .unwrap();+ let code = format!(+ r#"+if ({reinsert}) {{ frame.remove(); root.appendChild(frame); }}+try {{ oldFacadeLocation.href = {target:?}; }} catch (error) {{+ if (!{reinsert} || error.name !== 'SecurityError') throw error;+}}+!{reinsert} || oldFacadeWindow !== frame.contentWindow+"#,+ target = target.as_str()+ );+ let code = crate::util::v8_string(scope, &code).unwrap();+ let script = v8::Script::compile(scope, code, None).unwrap();+ assert!(+ crate::script_execution::execute_compiled_script(scope, script)+ .unwrap()+ .boolean_value(scope)+ );+ // A stale facade keeps its own WindowProxy, so the creating-Realm+ // equality check alone cannot protect the reinserted frame.+ assert_eq!(window.get_creation_context(scope), Some(facade));+ assert_eq!(location.get_creation_context(scope), Some(facade));+ Ok(())+ })+ .unwrap();+ let expected = if reinsert {+ r#"[2,["/child"]]"#+ } else {+ r#"[2,["/target"]]"#+ };+ advance_page_task_executor_until_eval_equals(+ &mut vm,+ &loader,+ "JSON.stringify([loads, messages])",+ expected,+ "a current facade may navigate, but a retired facade cannot target a reinserted iframe",+ )+ .await;+ }+}