From 05292bca7f5db2f4b71a582a6cea790804cb3f37 Mon Sep 17 00:00:00 2001 From: ldm0 Date: Fri, 25 Sep 2026 07:46:04 +0800 Subject: [PATCH] fix(navigation): validate child ancestor navigation permissions --- .../page/tests/same_document_history.rs | 1 + .../ancestor_navigation.js | 27 ++ .../ancestor_navigation.rs | 444 ++++++++++++++++++ moli-renderer-v8/Cargo.toml | 1 + moli-renderer-v8/src/context_bootstrap.rs | 1 - .../context_bootstrap/location_navigation.rs | 88 ++-- .../window_runtime/dialogs.rs | 36 +- .../context_host/child_documents/commit.rs | 1 + .../child_documents/initial_empty.rs | 1 + .../child_frame_runtime/window.rs | 6 + .../context_host/child_frames.rs | 3 + .../context_host/child_frames/registry.rs | 3 + .../child_frames/request_scope.rs | 30 -- .../src/native_bridge/context_host/mod.rs | 1 + .../context_host/navigation_permissions.rs | 163 +++++++ .../element/activation/targets.rs | 41 +- .../native_bridge/element/forms/submission.rs | 2 +- 17 files changed, 751 insertions(+), 98 deletions(-) create mode 100644 moli-protocol/src/domains/page/tests/same_document_history/ancestor_navigation.js create mode 100644 moli-protocol/src/domains/page/tests/same_document_history/ancestor_navigation.rs create mode 100644 moli-renderer-v8/src/native_bridge/context_host/navigation_permissions.rs diff --git a/moli-protocol/src/domains/page/tests/same_document_history.rs b/moli-protocol/src/domains/page/tests/same_document_history.rs index 1d336ae3245..0b674b5fcbb 100644 --- a/moli-protocol/src/domains/page/tests/same_document_history.rs +++ b/moli-protocol/src/domains/page/tests/same_document_history.rs @@ -1,5 +1,6 @@ use super::*; +mod ancestor_navigation; mod child_beforeunload; mod child_history_traversal; mod cross_origin_navigation; diff --git a/moli-protocol/src/domains/page/tests/same_document_history/ancestor_navigation.js b/moli-protocol/src/domains/page/tests/same_document_history/ancestor_navigation.js new file mode 100644 index 00000000000..442f4934344 --- /dev/null +++ b/moli-protocol/src/domains/page/tests/same_document_history/ancestor_navigation.js @@ -0,0 +1,27 @@ +function ancestorNavigationProbe(operation, targetName, destination) { + const target = targetName === '_top' || targetName === 'ancestor-top' ? top : parent; + let conversions = 0; + const value = {toString() { ++conversions; return destination; }}; + const result = {operation, targetName, before: [navigator.userActivation.isActive, navigator.userActivation.hasBeenActive]}; + try { + if (operation === 'location') target.location = value; + else if (operation === 'href') target.location.href = value; + else if (operation === 'replace') target.location.replace(value); + else if (operation === 'open') result.returnedTarget = open(destination, targetName) === target; + else if (operation === 'anchor') { + const a = document.body.appendChild(document.createElement('a')); + a.href = destination; a.target = targetName; a.click(); + } else if (operation === 'form' || operation === 'post') { + const form = document.body.appendChild(document.createElement('form')); + form.action = destination; form.target = targetName; + if (operation === 'post') form.method = 'POST'; + form.submit(); + } + result.outcome = 'returned'; + } catch (error) { + result.outcome = error.name; + result.localException = error instanceof DOMException; + } + result.conversions = conversions; + return result; +} diff --git a/moli-protocol/src/domains/page/tests/same_document_history/ancestor_navigation.rs b/moli-protocol/src/domains/page/tests/same_document_history/ancestor_navigation.rs new file mode 100644 index 00000000000..46e5c314f75 --- /dev/null +++ b/moli-protocol/src/domains/page/tests/same_document_history/ancestor_navigation.rs @@ -0,0 +1,444 @@ +use super::*; +use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, +}; + +const PROBE: &str = include_str!("ancestor_navigation.js"); +const PARENT: &str = r#""#; + +struct RemoteOrigin { + base_url: String, + server: tokio::task::JoinHandle<()>, +} + +impl Drop for RemoteOrigin { + fn drop(&mut self) { + self.server.abort(); + } +} + +impl RemoteOrigin { + async fn new(routes: axum::Router) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base_url = format!("http://{}/history.html", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { axum::serve(listener, routes).await.unwrap() }); + Self { base_url, server } + } +} + +fn routes(requests: Arc, request_received: Arc) -> axum::Router { + axum::Router::new() + .route( + "/ancestor-source", + axum::routing::get(|| async { + axum::response::Html(format!( + r#""# + )) + }), + ) + .route( + "/ancestor-parent", + axum::routing::get(|| async { axum::response::Html(PARENT) }), + ) + .route( + "/ancestor-destination", + axum::routing::any(move || { + requests.fetch_add(1, Ordering::SeqCst); + request_received.notify_one(); + async { axum::http::StatusCode::NO_CONTENT } + }), + ) +} + +#[derive(Debug, Default)] +struct Case { + nested: bool, + parent_cross_origin: bool, + source_same_origin: bool, + target_parent: bool, + related_destination: bool, + activation: &'static str, + sandbox: Option<&'static str>, + remove_sandbox: bool, + popup: bool, + named: bool, +} + +async fn check(operation: &str, case: Case, allowed: bool) { + tokio::task::LocalSet::new() + .run_until(check_in_local_set(operation, case, allowed)) + .await; +} + +async fn check_in_local_set(operation: &str, case: Case, allowed: bool) { + let requests = Arc::new(AtomicUsize::new(0)); + let request_received = Arc::new(tokio::sync::Notify::new()); + let other = RemoteOrigin::new(routes(requests.clone(), request_received.clone())).await; + let mut page = + SameDocumentPage::with_routes(routes(requests.clone(), request_received.clone())).await; + page.ctx.enable_background_navigation_scheduler_for_test(); + let source_base = if case.source_same_origin { + &page.base_url + } else { + &other.base_url + }; + let source_url = source_base.replace("/history.html", "/ancestor-source"); + let mut frame_url = url::Url::parse(&source_url).unwrap(); + if case.nested { + let parent_base = if case.parent_cross_origin { + &other.base_url + } else { + &page.base_url + }; + frame_url = + url::Url::parse(&parent_base.replace("/history.html", "/ancestor-parent")).unwrap(); + frame_url + .query_pairs_mut() + .append_pair("source", &source_url); + if let Some(sandbox) = case.sandbox { + frame_url.query_pairs_mut().append_pair("sandbox", sandbox); + } + } + page.evaluate(&format!( + r#"(async () => {{ + globalThis.ancestorContainer = {}; + ancestorContainer.beforeUnloadCount = 0; + ancestorContainer.addEventListener('beforeunload', () => ++ancestorContainer.beforeUnloadCount); + const frame = ancestorContainer.document.createElement('iframe'); + frame.id = 'source'; + frame.name = 'ancestor-parent'; + const sandbox = {}; + if (sandbox !== null) frame.setAttribute('sandbox', sandbox); + frame.src = {}; + const loaded = new Promise(resolve => frame.onload = resolve); + ancestorContainer.document.body.append(frame); + await loaded; + return true; + }})()"#, + if case.popup { "open('about:blank', 'ancestor-top')" } else { "window" }, + json!(if case.nested { None } else { case.sandbox }), + json!(frame_url.as_str()), + )).await; + page.command("Runtime.enable", json!({})).await; + let context = + page.ctx + .sent + .iter() + .rev() + .find(|event| { + event["method"] == "Runtime.executionContextCreated" + && event["params"]["context"]["name"] == source_url + && event["params"]["context"]["auxData"]["isDefault"] == true + }) + .unwrap_or_else(|| panic!("missing source realm: {}", json!(page.ctx.sent)))["params"] + ["context"]["id"] + .clone(); + if case.remove_sandbox { + page.evaluate( + "ancestorContainer.document.getElementById('source').removeAttribute('sandbox')", + ) + .await; + } + if case.activation == "parent" { + page.command( + "Runtime.evaluate", + json!({"expression": "navigator.userActivation.hasBeenActive", "userGesture": true}), + ) + .await; + } + if case.activation == "synthetic" { + page.command( + "Runtime.evaluate", + json!({ + "expression": "document.body.appendChild(document.createElement('button')).click()", + "contextId": context, + }), + ) + .await; + } + let destination_base = if case.related_destination { + &page.base_url + } else { + &other.base_url + }; + let destination = destination_base.replace("/history.html", "/ancestor-destination"); + let target = match (case.target_parent, case.named) { + (true, false) => "_parent", + (false, false) => "_top", + (true, true) => "ancestor-parent", + (false, true) => "ancestor-top", + }; + if case.activation == "source" { + page.command( + "Runtime.evaluate", + json!({ + "expression": "navigator.userActivation.hasBeenActive", + "contextId": context, + "userGesture": true, + }), + ) + .await; + } + let result = if case.popup { + // Exercise the child realm directly for virtual popup windows, whose + // message delivery is managed separately from the opener's page. + let response = page + .command( + "Runtime.evaluate", + json!({ + "expression": format!( + "ancestorNavigationProbe({operation:?}, {target:?}, {destination:?})" + ), + "contextId": context, + "returnByValue": true, + }), + ) + .await; + assert!(response["exceptionDetails"].is_null(), "{response}"); + response["result"]["value"].clone() + } else { + page.evaluate(&format!( + r#"new Promise(resolve => {{ + const receive = event => {{ + if (event.data.kind !== 'ancestor-result') return; + removeEventListener('message', receive); + resolve(event.data.value); + }}; + addEventListener('message', receive); + let source = ancestorContainer.document.getElementById('source').contentWindow; + if ({}) source = source[0]; + source.postMessage({{ + kind: 'ancestor-probe', operation: {operation:?}, + target: {target:?}, destination: {destination:?}, + }}, '*'); + }})"#, + case.nested + )) + .await + }; + let location = matches!(operation, "location" | "href" | "replace"); + assert_eq!( + result["outcome"], + if !allowed && location { + "SecurityError" + } else { + "returned" + }, + "{operation}/{case:?}: {result}" + ); + assert_eq!(result["conversions"], usize::from(location)); + if !allowed && location { + assert_eq!(result["localException"], true); + } + if operation == "open" { + assert_eq!(result["returnedTarget"], allowed); + } + assert_eq!(result["before"][1], case.activation == "source", "{result}"); + if allowed { + let description = format!("admitted ancestor navigation request: {operation}/{case:?}"); + // The HTTP server has its own wake source. A 204 response need not + // publish another CDP event after the request counter changes. + tokio::select! { + () = page.ctx.wait_until_scheduler_state( + &description, + |_| requests.load(Ordering::SeqCst) == 1, + ) => {}, + () = request_received.notified() => {}, + } + assert_eq!(requests.load(Ordering::SeqCst), 1, "{operation}/{case:?}"); + } else { + page.evaluate("new Promise(resolve => setTimeout(resolve, 50))") + .await; + assert_eq!(requests.load(Ordering::SeqCst), 0, "{operation}"); + assert_eq!( + page.evaluate("ancestorContainer.beforeUnloadCount").await, + 0 + ); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ancestor_navigation_rejects_cross_origin_sources_across_all_entry_points() { + for operation in [ + "location", "href", "replace", "open", "anchor", "form", "post", + ] { + check(operation, Case::default(), false).await; + check( + operation, + Case { + nested: true, + target_parent: true, + ..Case::default() + }, + false, + ) + .await; + check( + operation, + Case { + popup: true, + ..Case::default() + }, + false, + ) + .await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ancestor_navigation_rejects_named_ancestor_targets() { + for operation in ["open", "anchor", "form", "post"] { + check( + operation, + Case { + popup: true, + named: true, + ..Case::default() + }, + false, + ) + .await; + check( + operation, + Case { + nested: true, + target_parent: true, + named: true, + ..Case::default() + }, + false, + ) + .await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ancestor_navigation_preserves_accessible_ancestors_activation_and_related_destinations() { + for operation in ["href", "open", "anchor", "form", "post"] { + check( + operation, + Case { + activation: "source", + ..Case::default() + }, + true, + ) + .await; + check( + operation, + Case { + related_destination: true, + ..Case::default() + }, + true, + ) + .await; + check( + operation, + Case { + nested: true, + parent_cross_origin: true, + source_same_origin: true, + target_parent: true, + ..Case::default() + }, + true, + ) + .await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn ancestor_navigation_activation_belongs_to_the_source_and_only_unlocks_the_top() { + for activation in ["parent", "synthetic"] { + check( + "href", + Case { + activation, + ..Case::default() + }, + false, + ) + .await; + } + check( + "href", + Case { + nested: true, + target_parent: true, + activation: "source", + ..Case::default() + }, + false, + ) + .await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn ancestor_navigation_uses_committed_sandbox_flags_and_ancestor_delegation() { + for (sandbox, needs_activation) in [ + ("allow-scripts allow-same-origin", None), + ( + "allow-scripts allow-same-origin allow-top-navigation", + Some(false), + ), + ( + "allow-scripts allow-same-origin allow-top-navigation-by-user-activation", + Some(true), + ), + ] { + for activation in ["none", "source"] { + let allowed = + needs_activation.is_some_and(|required| !required || activation == "source"); + check( + "href", + Case { + sandbox: Some(sandbox), + activation, + ..Case::default() + }, + allowed, + ) + .await; + } + } + check( + "href", + Case { + sandbox: Some("allow-scripts allow-same-origin"), + remove_sandbox: true, + ..Case::default() + }, + false, + ) + .await; + check( + "href", + Case { + nested: true, + parent_cross_origin: true, + sandbox: Some("allow-scripts allow-same-origin allow-top-navigation"), + ..Case::default() + }, + false, + ) + .await; +} diff --git a/moli-renderer-v8/Cargo.toml b/moli-renderer-v8/Cargo.toml index 885ad7846e1..27381644ecb 100644 --- a/moli-renderer-v8/Cargo.toml +++ b/moli-renderer-v8/Cargo.toml @@ -81,6 +81,7 @@ moli-script = { path = "../moli-script" } moli-site = { path = "../moli-site" } moli-session-history = { path = "../moli-session-history" } moli-history = { path = "../moli-history" } +moli-site = { path = "../moli-site" } moli-stylesheet-blocking = { path = "../moli-stylesheet-blocking" } moli-sqlite = { path = "../moli-sqlite" } moli-web-storage = { path = "../moli-web-storage" } diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs index 8bbf96e3fd3..1400b453f95 100644 --- a/moli-renderer-v8/src/context_bootstrap.rs +++ b/moli-renderer-v8/src/context_bootstrap.rs @@ -214,7 +214,6 @@ pub(crate) use location_navigation::{ navigate_location_object_for_hyperlink, navigate_location_object_with_child_navigate_event, navigate_location_object_with_source_element, navigate_top_level_meta_refresh, navigate_top_level_same_document_from_browser, resolve_cross_window_location_target, - sandbox_blocks_ancestor_or_top_navigation_from_source, }; pub(crate) use navigation_cancellation::{ NavigationCancellationReason, inform_about_canceled_navigation_for_window, diff --git a/moli-renderer-v8/src/context_bootstrap/location_navigation.rs b/moli-renderer-v8/src/context_bootstrap/location_navigation.rs index 4ee3be054a8..8314ad8056d 100644 --- a/moli-renderer-v8/src/context_bootstrap/location_navigation.rs +++ b/moli-renderer-v8/src/context_bootstrap/location_navigation.rs @@ -37,8 +37,7 @@ use super::navigation_serialize::serialize_history_entries; use super::navigation_window::{ child_browsing_context_handle_for_runtime_owner, navigation_document_has_disabled_entries, navigation_document_is_active, navigation_unload_event_active, runtime_window_is_global, - runtime_window_owner, runtime_window_uses_top_level_history_model, window_history_for_holder, - window_location_for_holder, + runtime_window_owner, window_history_for_holder, window_location_for_holder, }; use super::*; use crate::native_bridge::NavigationHistoryEntrySeed; @@ -440,14 +439,6 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>( } } let exact_same_href = current_href == resolved.as_str(); - if !matches!(kind, LocationNavigationKind::Reload) - && exact_same_href - && source_element.is_none() - && raw_target_is_fragment_only - && !force_exact_same_document_navigation - { - return; - } let owner = runtime_window_owner(scope, location); let source_can_access_target = source_can_access_target.unwrap_or_else(|| { let Some(host_ptr) = context_host_ptr_for_navigation_owner(scope, owner) else { @@ -469,14 +460,22 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>( { return; } - if sandbox_blocks_ancestor_or_top_location_navigation(scope, owner) { + if blocks_ancestor_location_navigation(scope, owner, &resolved) { crate::context_bootstrap::throw_dom_exception_value( scope, - "Blocked a sandboxed frame from navigating an ancestor browsing context.", + "The source frame is not allowed to navigate this ancestor browsing context.", "SecurityError", ); return; } + if !matches!(kind, LocationNavigationKind::Reload) + && exact_same_href + && source_element.is_none() + && raw_target_is_fragment_only + && !force_exact_same_document_navigation + { + return; + } if matches!(kind, LocationNavigationKind::Reload) && matches!( navigation_reload_admission(scope, owner), @@ -1078,22 +1077,10 @@ fn capture_location_navigation_source<'s>( } } -fn sandbox_blocks_ancestor_or_top_location_navigation<'s>( +fn blocks_ancestor_location_navigation<'s>( scope: &mut v8::PinScope<'s, '_>, owner: v8::Local<'s, v8::Object>, -) -> bool { - let Some(source_handle) = - crate::context_bootstrap::current_child_browsing_context_handle_for_runtime_scope(scope) - else { - return false; - }; - sandbox_blocks_ancestor_or_top_navigation_from_source(scope, source_handle, owner) -} - -pub(crate) fn sandbox_blocks_ancestor_or_top_navigation_from_source<'s>( - scope: &mut v8::PinScope<'s, '_>, - source_handle: crate::document_runtime::DomHandle, - owner: v8::Local<'s, v8::Object>, + destination: &url::Url, ) -> bool { let Some(host_ptr) = context_host_ptr_for_navigation_owner(scope, owner) .or_else(|| context_host_ptr_from_global_bridge(scope)) @@ -1101,35 +1088,14 @@ pub(crate) fn sandbox_blocks_ancestor_or_top_navigation_from_source<'s>( return false; }; let host = unsafe { &*host_ptr }; - if host.child_browsing_context_allows_top_navigation(source_handle) { + let Some(target) = super::navigation_window::runtime_window_dispatch_scope(scope, owner) else { return false; - } - if let Some(popup_id) = crate::native_bridge::lightweight_popup_id_from_window(scope, owner) - && host.lightweight_popup_id_for_node_owner_document(source_handle) != Some(popup_id) - { - return false; - } - match child_browsing_context_handle_for_runtime_owner(scope, owner) { - Some(target_handle) => { - child_browsing_context_is_ancestor(host, target_handle, source_handle) - } - None => runtime_window_uses_top_level_history_model(scope, owner), - } -} - -fn child_browsing_context_is_ancestor( - host: &PageScriptHost, - ancestor: crate::document_runtime::DomHandle, - child: crate::document_runtime::DomHandle, -) -> bool { - let mut current = host.child_browsing_context_parent_handle(child); - while let Some(handle) = current { - if handle == ancestor { - return true; - } - current = host.child_browsing_context_parent_handle(handle); - } - false + }; + host.blocks_ancestor_navigation( + location_navigation_initiator_scope(scope, host), + target, + destination, + ) } fn window_for_child_cross_document_location_navigation<'s>( @@ -1377,13 +1343,19 @@ fn location_navigation_initiator_scope( scope: &mut v8::PinScope<'_, '_>, host: &PageScriptHost, ) -> crate::native_bridge::OwnerDispatchScope { + let incumbent = scope + .get_incumbent_context() + .and_then(|context| host.window_execution_context_identity_for_access_check(context)) + .map(|identity| identity.dispatch_scope()); + // Popup callbacks share the main realm, but a real child realm keeps its + // own source identity when it calls a popup ancestor's Location binding. + if let Some(source @ crate::native_bridge::OwnerDispatchScope::Child(_)) = incumbent { + return source; + } if let Some(popup_id) = crate::native_bridge::active_lightweight_popup_id(scope) { return crate::native_bridge::OwnerDispatchScope::LightweightPopup(popup_id); } - scope - .get_incumbent_context() - .and_then(|context| host.window_execution_context_identity_for_access_check(context)) - .map(|identity| identity.dispatch_scope()) + incumbent .or_else(|| { crate::context_bootstrap::current_child_browsing_context_handle_for_runtime_scope(scope) .map(crate::native_bridge::OwnerDispatchScope::Child) 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 45bccdd06be..b5389d102f6 100644 --- a/moli-renderer-v8/src/context_bootstrap/window_runtime/dialogs.rs +++ b/moli-renderer-v8/src/context_bootstrap/window_runtime/dialogs.rs @@ -292,14 +292,11 @@ pub(crate) fn window_open_callback<'s>( target @ (SpecialBrowsingContextTarget::Parent | SpecialBrowsingContextTarget::Top), ) = special_target { - let source_window = if window_receiver_child_handle(scope, args.this()).is_some() { - args.this() - } else { - entered_window - }; + let source = entered_window_dispatch_scope(scope, unsafe { &*host_ptr }); match navigate_existing_browsing_context_target( scope, - source_window, + host_ptr, + source, target, url.as_deref(), ) { @@ -312,6 +309,22 @@ pub(crate) fn window_open_callback<'s>( existing_named_child_window_for_window_open(scope, host_ptr, &parsed.target_name) && !suppress_opener { + let host = unsafe { &*host_ptr }; + let source = entered_window_dispatch_scope(scope, host); + if url + .as_deref() + .and_then(|url| Url::parse(url).ok()) + .is_some_and(|url| { + host.blocks_ancestor_navigation( + source, + OwnerDispatchScope::Child(target_handle), + &url, + ) + }) + { + rv.set(v8::null(scope).into()); + return; + } let opener_child_handle = window_open_receiver_child_handle(scope, entered_window); let opener_endpoint = opener_child_handle .map(PendingWindowMessageEndpoint::ChildWindow) @@ -334,6 +347,17 @@ pub(crate) fn window_open_callback<'s>( } } let host = unsafe { &mut *host_ptr }; + if let Some(popup_id) = host.named_lightweight_popup_id(&parsed.target_name) + && let Some(destination) = url.as_deref().and_then(|url| Url::parse(url).ok()) + && host.blocks_ancestor_navigation( + entered_window_dispatch_scope(scope, host), + OwnerDispatchScope::LightweightPopup(popup_id), + &destination, + ) + { + rv.set(v8::null(scope).into()); + return; + } // Only a newly selected browsing context defaults an omitted URL to // about:blank. Reusing a target must preserve its current document and any // navigation already in flight. diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs index f8e72ee726c..f4df7a02a88 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs @@ -397,6 +397,7 @@ impl PageScriptHost { replaced_document_handle, expected_current_document_handle, "adapter document handle must change in the same owner commit" ); + self.capture_child_top_navigation_permission(handle); if let Some(loader_id) = loader_id { self.child_browsing_contexts .get_mut(&handle) diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/initial_empty.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/initial_empty.rs index 5b29a4bc942..51abf02a733 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/initial_empty.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/initial_empty.rs @@ -169,6 +169,7 @@ impl PageScriptHost { ); self.populate_initial_empty_child_html_document(document_handle); + self.capture_child_top_navigation_permission(handle); self.dom_host_mut() .mark_subtree_connected_preserving_owner_document(document_handle); self.install_empty_child_classic_script_runner_for_current_document( 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 0bb035e4f59..86346d9c191 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 @@ -2473,6 +2473,12 @@ 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/child_frames.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs index 902d7e41a96..3759b1d6138 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames.rs @@ -74,6 +74,9 @@ pub(super) struct ChildBrowsingContextEntry { srcdoc_history: HashMap>, document_policy_container: ChildDocumentPolicyContainer, + // Captured at Document commit; changing sandbox or document.domain must + // not grant a descendant permission to navigate the top without activation. + pub(super) can_navigate_top_without_user_gesture: bool, document_internal_ancestor_origins: Vec, ancestor_origins_referrer_policy_snapshot: ChildAncestorOriginsReferrerPolicy, completed_frame_owner_resource_timing: Option, diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs index cffac8e99d1..d5439f23dbb 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/registry.rs @@ -593,6 +593,9 @@ impl PageScriptHost { .map(|entry| entry.srcdoc_history.clone()) .unwrap_or_default(), document_policy_container, + can_navigate_top_without_user_gesture: existing + .as_ref() + .is_some_and(|entry| entry.can_navigate_top_without_user_gesture), document_internal_ancestor_origins, ancestor_origins_referrer_policy_snapshot, completed_frame_owner_resource_timing: existing.as_ref().and_then( diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs index ef46c1b724b..2e411572543 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs @@ -924,36 +924,6 @@ impl PageScriptHost { (policy.sandboxes_document_domain && !policy.allows_popups_to_escape).then_some(policy) } - pub(crate) fn child_browsing_context_allows_top_navigation(&self, handle: DomHandle) -> bool { - self.child_browsing_contexts - .get(&handle) - .is_some_and(|entry| entry.document_sandbox_policy().allows_top_navigation) - } - - pub(crate) fn sandbox_blocks_ancestor_navigation( - &self, - source: OwnerDispatchScope, - target: OwnerDispatchScope, - ) -> bool { - let OwnerDispatchScope::Child(source_handle) = source else { - return false; - }; - if self.child_browsing_context_allows_top_navigation(source_handle) { - return false; - } - let mut ancestor = self.owner_dispatch_scope_for_node(source_handle); - while let Some(owner) = ancestor { - if owner == target { - return true; - } - ancestor = match owner { - OwnerDispatchScope::Child(handle) => self.owner_dispatch_scope_for_node(handle), - OwnerDispatchScope::Top | OwnerDispatchScope::LightweightPopup(_) => None, - }; - } - false - } - pub(crate) fn sandbox_allows_history_traversal( &self, source: OwnerDispatchScope, 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 ce27c9c2b17..6c867990381 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs @@ -142,6 +142,7 @@ pub(crate) use mouse_click::MouseReleaseFollowUp; #[cfg(feature = "devtools")] pub(crate) use mouse_click::common_flat_tree_ancestor; mod navigation; +mod navigation_permissions; mod navigator_overrides; mod opfs_tasks; mod permissions; diff --git a/moli-renderer-v8/src/native_bridge/context_host/navigation_permissions.rs b/moli-renderer-v8/src/native_bridge/context_host/navigation_permissions.rs new file mode 100644 index 00000000000..0e37d908da9 --- /dev/null +++ b/moli-renderer-v8/src/native_bridge/context_host/navigation_permissions.rs @@ -0,0 +1,163 @@ +use super::{OwnerDispatchScope, PageScriptHost, window_security_tokens::WindowAccessOrigin}; +use url::Url; + +impl PageScriptHost { + /// Admission for a child navigating one of its ancestors. Location, + /// hyperlinks and forms must check the source before entering the target + /// realm or publishing navigation work. + pub(crate) fn blocks_ancestor_navigation( + &self, + source: OwnerDispatchScope, + target: OwnerDispatchScope, + destination: &Url, + ) -> bool { + let OwnerDispatchScope::Child(source_handle) = source else { + return false; + }; + let mut ancestor = self.navigation_parent_scope(source); + while let Some(owner) = ancestor { + if owner == target { + break; + } + ancestor = self.navigation_parent_scope(owner); + } + if ancestor.is_none() { + return false; + } + let Some(entry) = self.child_browsing_contexts.get(&source_handle) else { + return true; + }; + let sandbox = entry.document_sandbox_policy(); + let target_is_top = !matches!(target, OwnerDispatchScope::Child(_)); + if destination.scheme() == "javascript" + && !self.window_scopes_have_same_origin_domain(source, target) + { + return true; + } + // Consult the active Document's flags, including inherited/CSP flags. + // Mutating the container's sandbox attribute does not change them. + if sandbox.restricts_navigation { + if !target_is_top { + return true; + } + return if sandbox.allows_top_navigation { + !entry.can_navigate_top_without_user_gesture + && !self.window_user_activation_state(source).1 + } else { + !(sandbox.allows_top_navigation_by_user_activation + && self.window_has_transient_user_activation(source)) + }; + } + let mut accessible_ancestor = Some(target); + while let Some(owner) = accessible_ancestor { + if self.window_scopes_have_same_origin_domain(source, owner) { + return false; + } + accessible_ancestor = self.navigation_parent_scope(owner); + } + // An unrelated intermediate ancestor cannot be navigated, even with + // activation. A top-level ancestor additionally permits sticky + // activation and destinations related to its existing origin/site. + !(target_is_top + && (self.window_user_activation_state(source).1 + || self.ancestor_navigation_destination_is_related(target, destination))) + } + + pub(super) fn capture_child_top_navigation_permission( + &mut self, + handle: crate::document_runtime::DomHandle, + ) { + let source = OwnerDispatchScope::Child(handle); + let Some(parent) = self.navigation_parent_scope(source) else { + return; + }; + let mut top = parent; + while let Some(ancestor) = self.navigation_parent_scope(top) { + top = ancestor; + } + let parent_allows = match parent { + OwnerDispatchScope::Child(parent) => self + .child_browsing_contexts + .get(&parent) + .is_some_and(|entry| entry.can_navigate_top_without_user_gesture), + OwnerDispatchScope::Top | OwnerDispatchScope::LightweightPopup(_) => true, + }; + // A cross-origin parent cannot delegate a permission it does not have. + // Unlike access checks, this committed grant ignores document.domain. + let allowed = self.window_scopes_have_same_origin(source, top) + || (parent_allows + && self + .dom_host() + .get_attribute(handle, "sandbox") + .is_some_and(|value| { + value + .split_ascii_whitespace() + .any(|token| token.eq_ignore_ascii_case("allow-top-navigation")) + })); + if let Some(entry) = self.child_browsing_contexts.get_mut(&handle) { + entry.can_navigate_top_without_user_gesture = allowed; + } + } + + fn navigation_parent_scope(&self, owner: OwnerDispatchScope) -> Option { + match owner { + OwnerDispatchScope::Child(handle) => self.owner_dispatch_scope_for_node(handle), + OwnerDispatchScope::Top | OwnerDispatchScope::LightweightPopup(_) => None, + } + } + + fn ancestor_navigation_destination_is_related( + &self, + target: OwnerDispatchScope, + destination: &Url, + ) -> bool { + let Some(origin) = self.window_access_origin_for_dispatch_scope(target) else { + return false; + }; + if WindowAccessOrigin::from_serialized_origin( + moli_url::origin_ascii_serialization(destination), + None, + ) + .is_some_and(|destination_origin| origin.can_access(&destination_origin)) + { + return true; + } + let WindowAccessOrigin::Tuple { + serialized_origin, + scheme, + document_domain, + } = origin + else { + return false; + }; + if scheme != destination.scheme() { + return false; + } + let target_host = document_domain.or_else(|| { + Url::parse(&serialized_origin) + .ok()? + .host_str() + .map(str::to_owned) + }); + target_host + .as_deref() + .and_then(navigation_registrable_domain) + .zip( + destination + .host_str() + .and_then(navigation_registrable_domain), + ) + .is_some_and(|(target, destination)| target == destination) + } +} + +fn navigation_registrable_domain(host: &str) -> Option<&str> { + let host = host.trim_start_matches('[').trim_end_matches(']'); + if host.parse::().is_ok() + || !host.contains('.') + || moli_site::host_is_public_suffix(host) + { + return None; + } + Some(moli_site::registrable_site_host(host)) +} 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 e6dae714184..a1ff895d11f 100644 --- a/moli-renderer-v8/src/native_bridge/element/activation/targets.rs +++ b/moli-renderer-v8/src/native_bridge/element/activation/targets.rs @@ -438,6 +438,15 @@ pub(in crate::native_bridge) fn choose_form_navigation_target( return Some(OwnerDispatchScope::Child(handle)); } } + if let Some(popup_id) = runtime.named_lightweight_popup_id(target_name) + && runtime.blocks_ancestor_navigation( + source, + OwnerDispatchScope::LightweightPopup(popup_id), + destination, + ) + { + return None; + } let relations = element_popup_relations(unsafe { &*runtime_ptr }, form, target_name); let mut creator = element_popup_creator(scope, runtime_ptr, form)?; creator.policy_container.document_referrer = if relations.suppress_referrer { @@ -587,7 +596,8 @@ fn navigate_special_target_from_window<'s>( pub(crate) fn navigate_existing_browsing_context_target<'s>( scope: &mut v8::PinScope<'s, '_>, - source_window: v8::Local<'s, v8::Object>, + runtime_ptr: *mut PageScriptHost, + navigation_source: crate::native_bridge::OwnerDispatchScope, target: SpecialBrowsingContextTarget, resolved_url: Option<&str>, ) -> Option> { @@ -596,6 +606,31 @@ pub(crate) fn navigate_existing_browsing_context_target<'s>( SpecialBrowsingContextTarget::Blank, "a new-context target cannot use existing-context navigation" ); + let runtime = unsafe { &*runtime_ptr }; + let dispatch_scope = runtime + .window_execution_context_identity_for_access_check(scope.get_current_context()) + .map(|identity| identity.dispatch_scope()) + .filter(|owner| matches!(owner, crate::native_bridge::OwnerDispatchScope::Child(_))) + .unwrap_or_else(|| runtime.entered_owner_dispatch_scope(scope)); + let mut destination_scope = dispatch_scope; + while target != SpecialBrowsingContextTarget::Current + && let crate::native_bridge::OwnerDispatchScope::Child(handle) = destination_scope + { + destination_scope = runtime.owner_dispatch_scope_for_node(handle)?; + if target == SpecialBrowsingContextTarget::Parent { + break; + } + } + if resolved_url + .and_then(|url| url::Url::parse(url).ok()) + .is_some_and(|url| { + runtime.blocks_ancestor_navigation(navigation_source, destination_scope, &url) + }) + { + return None; + } + let source_window = + browsing_context_window_for_dispatch_scope(scope, runtime_ptr, dispatch_scope)?; navigate_special_target_from_window(scope, source_window, Some(target), resolved_url) } @@ -671,7 +706,9 @@ pub(in crate::native_bridge) fn navigate_element_target_browsing_context( }); }; let runtime = unsafe { &mut *runtime_ptr }; - if runtime.sandbox_blocks_ancestor_navigation(source, target) { + if url::Url::parse(resolved_url) + .is_ok_and(|destination| runtime.blocks_ancestor_navigation(source, target, &destination)) + { return true; } let Some(document) = runtime.dom_host().owner_document_handle(source_handle) else { diff --git a/moli-renderer-v8/src/native_bridge/element/forms/submission.rs b/moli-renderer-v8/src/native_bridge/element/forms/submission.rs index 37295d3fd15..4cac870f09a 100644 --- a/moli-renderer-v8/src/native_bridge/element/forms/submission.rs +++ b/moli-renderer-v8/src/native_bridge/element/forms/submission.rs @@ -648,7 +648,7 @@ pub(in crate::native_bridge) fn submit_form_default_action( else { return false; }; - if runtime.sandbox_blocks_ancestor_navigation(source, destination) { + if runtime.blocks_ancestor_navigation(source, destination, request.url()) { return false; } let mutation = runtime.form_navigation_history_mutation_for_scope(