fix(window): resolve special open targets from the receiver

Use native parent/top relationships without consulting replaceable Window properties. Keep URL resolution and navigation authority tied to the entry Window, and preserve cross-origin WindowProxy projections.
This commit is contained in:
ldm0
2026-11-20 22:47:42 +08:00
parent 07cc74c6d7
commit c3fa4d290a
8 changed files with 345 additions and 48 deletions
+1 -1
View File
@@ -1244,7 +1244,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,
retain_window_document_in_retired_realm, window_parent_or_top,
};
pub(crate) use session_history::{
@@ -40,7 +40,8 @@ pub(super) use interceptors::{
window_named_property_query,
};
pub(crate) use surface::{
window_closed_getter, window_opener_getter, window_parent_getter, window_top_getter,
window_closed_getter, window_opener_getter, window_parent_getter, window_parent_or_top,
window_top_getter,
};
pub(super) use surface::{
window_custom_elements_getter, window_device_pixel_ratio_getter, window_frames_getter,
@@ -348,3 +348,17 @@ pub(crate) fn window_closed_getter<'s>(
rv.set(value);
}
}
/// Resolve native Window relationships without consulting replaceable author properties.
pub(crate) fn window_parent_or_top<'s>(
scope: &mut v8::PinScope<'s, '_>,
receiver: v8::Local<'s, v8::Object>,
top: bool,
) -> v8::Local<'s, v8::Value> {
let value = if top {
super::values::window_top_value(scope, receiver)
} else {
super::values::window_parent_value(scope, receiver)
};
value.unwrap_or_else(|| v8::null(scope).into())
}
@@ -239,12 +239,7 @@ pub(crate) fn window_open_callback<'s>(
}
};
if special_target == Some(SpecialBrowsingContextTarget::Current) {
navigate_window_open_self(
scope,
entered_window,
url.as_ref().map(Url::as_str),
&mut rv,
);
navigate_window_open_self(scope, args.this(), url.as_ref().map(Url::as_str), &mut rv);
return;
}
let parsed_features = WindowOpenFeatures::parse(&parsed.features);
@@ -306,6 +301,8 @@ pub(crate) fn window_open_callback<'s>(
scope,
host_ptr,
source,
receiver.dispatch_scope(),
args.this(),
target,
url.as_deref(),
) {
@@ -563,41 +563,12 @@ fn browsing_context_dispatch_scope_for_node(
.map(crate::native_bridge::OwnerDispatchScope::Child)
}
fn special_target_window_from_window<'s>(
scope: &mut v8::PinScope<'s, '_>,
source_window: v8::Local<'s, v8::Object>,
target: Option<SpecialBrowsingContextTarget>,
) -> Option<v8::Local<'s, v8::Object>> {
match target {
None | Some(SpecialBrowsingContextTarget::Current) => Some(source_window),
Some(SpecialBrowsingContextTarget::Top) => source_window
.get(scope, v8str(scope, "top").into())
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok()),
Some(SpecialBrowsingContextTarget::Parent) => source_window
.get(scope, v8str(scope, "parent").into())
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok()),
Some(SpecialBrowsingContextTarget::Blank) => None,
}
}
fn navigate_special_target_from_window<'s>(
scope: &mut v8::PinScope<'s, '_>,
source_window: v8::Local<'s, v8::Object>,
target: Option<SpecialBrowsingContextTarget>,
resolved_url: Option<&str>,
) -> Option<v8::Local<'s, v8::Object>> {
let target_window = special_target_window_from_window(scope, source_window, target)?;
let Some(resolved_url) = resolved_url else {
return Some(target_window);
};
let navigated = navigate_target_window_location(scope, target_window, resolved_url);
if navigated { Some(target_window) } else { None }
}
pub(crate) fn navigate_existing_browsing_context_target<'s>(
scope: &mut v8::PinScope<'s, '_>,
runtime_ptr: *mut PageScriptHost,
navigation_source: crate::native_bridge::OwnerDispatchScope,
receiver_scope: crate::native_bridge::OwnerDispatchScope,
receiver_window: v8::Local<'s, v8::Object>,
target: SpecialBrowsingContextTarget,
resolved_url: Option<&str>,
) -> Option<v8::Local<'s, v8::Object>> {
@@ -607,12 +578,11 @@ pub(crate) fn navigate_existing_browsing_context_target<'s>(
"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;
// Blink chooses targets from the receiver's frame tree, independently of
// the entry Window that supplies the URL base and navigation authority.
// Use native ancestry: the replaceable Window.parent property can be
// shadowed by author code and must not redirect this lookup.
let mut destination_scope = receiver_scope;
while target != SpecialBrowsingContextTarget::Current
&& let crate::native_bridge::OwnerDispatchScope::Child(handle) = destination_scope
{
@@ -629,9 +599,21 @@ pub(crate) fn navigate_existing_browsing_context_target<'s>(
{
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)
let target_window = if destination_scope == receiver_scope {
receiver_window
} else {
v8::Local::<v8::Object>::try_from(crate::context_bootstrap::window_parent_or_top(
scope,
receiver_window,
target == SpecialBrowsingContextTarget::Top,
))
.ok()?
};
let Some(resolved_url) = resolved_url else {
return Some(target_window);
};
let navigated = navigate_target_window_location(scope, target_window, resolved_url);
if navigated { Some(target_window) } else { None }
}
/// Resolve an existing target without reading script-visible WindowProxy properties.
@@ -126,6 +126,7 @@ mod window_onerror;
mod window_open_empty_url;
mod window_open_named_targets;
mod window_open_referrer;
mod window_open_special_targets;
mod worker_listener_invocation;
mod worker_options;
@@ -0,0 +1,228 @@
use super::*;
#[tokio::test]
async fn window_open_special_targets_use_native_receiver_ancestry() {
let loader = static_http_loader([]);
let mut vm = new_parsed_page_task_executor_test_vm(
"https://special-open.test/root/index",
"<!doctype html><body>root",
&loader,
);
vm.eval(include_str!(
"../../../../tests/fixtures/window-open-special-targets.js"
))
.unwrap();
vm.drain_ready_page_task_executor_turns_for_setup(&loader, 100)
.await
.unwrap();
assert_eq!(vm.take_pending_popup_activations().len(), 1);
assert_eq!(
vm.eval("JSON.stringify(specialTargetCase.run())").unwrap(),
r#"{"count":432,"parentReads":0,"failures":[]}"#,
);
assert!(vm.take_pending_location_navigation_with_seed().is_none());
assert!(vm.take_pending_popup_activations().is_empty());
vm.eval("specialTargetCase.close()").unwrap();
}
#[tokio::test]
async fn window_open_special_targets_navigate_receiver_with_entry_url() {
for target in ["_self", "_parent", "_top"] {
for root in ["main", "popup"] {
for callee in ["window", "deep"] {
let is_top_navigation = root == "main" && target == "_top";
let bodies = if is_top_navigation {
Vec::new()
} else {
vec!["<!doctype html><body>selected".into()]
};
let server = StaticHttpServer::spawn_with_bodies(bodies).await;
let origin = server.base_url().origin().ascii_serialization();
let loader = static_http_loader([]);
let mut vm = new_parsed_page_task_executor_test_vm(
&format!("{origin}/entry/index"),
"<!doctype html><body>entry",
&loader,
);
vm.eval(&format!(
r#"
const root = {root:?} === 'main' ? window : open('', 'navigation-root');
const frame = root.document.createElement('iframe'); root.document.body.append(frame);
const middle = frame.contentWindow;
const nested = middle.document.createElement('iframe'); middle.document.body.append(nested);
const deep = nested.contentWindow;
const base = deep.document.createElement('base');
base.href = '{origin}/receiver/'; deep.document.head.append(base);
const expected = {target:?} === '_self' ? deep : {target:?} === '_parent' ? middle : root;
const before = expected.document;
const methods = {{window: window.open, deep: deep.open}};
"#
))
.unwrap();
vm.drain_ready_page_task_executor_turns_for_setup(&loader, 100)
.await
.unwrap();
vm.take_pending_popup_activations();
assert_eq!(
vm.eval(&format!(
"String(methods[{callee:?}].call(deep, 'selected', {target:?}) === expected)"
))
.unwrap(),
"true",
"{root}, {callee}, {target}",
);
assert!(vm.take_pending_popup_activations().is_empty());
if is_top_navigation {
let navigation = vm.take_pending_location_navigation_with_seed().unwrap();
assert_eq!(navigation.url.as_str(), format!("{origin}/entry/selected"));
} else {
assert!(vm.take_pending_location_navigation_with_seed().is_none());
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(expected.document !== before && expected.document.body?.textContent === 'selected')",
"true",
&format!("{root}, {callee}, {target}"),
)
.await;
}
assert_eq!(
server.finish_targets().await,
if is_top_navigation {
Vec::new()
} else {
vec!["/entry/selected".to_owned()]
},
"{root}, {callee}, {target}",
);
}
}
}
}
#[test]
fn window_open_special_targets_do_not_revive_receiver_removed_during_conversion() {
let mut vm = new_storage_test_vm("https://special-open.test/root");
for target in ["_self", "_parent", "_top"] {
assert_eq!(
vm.eval(&format!(
r#"(() => {{
const frame = document.createElement('iframe');
(document.body || document.documentElement || document).append(frame);
const child = frame.contentWindow;
let conversions = 0;
const url = {{toString() {{ ++conversions; frame.remove(); return '/removed'; }}}};
const result = open.call(child, url, {target:?});
return JSON.stringify([result === null, conversions]);
}})()"#
))
.unwrap(),
"[true,1]",
"{target}",
);
assert!(vm.take_pending_location_navigation_with_seed().is_none());
assert!(vm.take_pending_popup_activations().is_empty());
}
}
#[tokio::test]
async fn window_open_special_targets_preserve_cross_origin_window_projections() {
let server = StaticHttpServer::spawn_with_bodies(vec![
r#"<!doctype html><body><script>
const failures = [];
for (const target of ['_self', '_parent', '_top']) {
const expected = target === '_self' ? window : parent;
const actual = open('', target);
if (actual !== expected) failures.push('wrong identity: ' + target);
if (expected === parent) {
try { actual.document; failures.push('exposed parent document'); }
catch (error) { if (error.name !== 'SecurityError') failures.push(error.name); }
}
}
parent.postMessage(failures, '*');
</script>"#
.to_owned(),
])
.await;
let origin = server.base_url().origin().ascii_serialization();
let loader = static_http_loader([]);
let mut vm = new_parsed_page_task_executor_test_vm(
&format!("{}/root", origin.replace("127.0.0.1", "localhost")),
"<!doctype html><body>root",
&loader,
);
vm.eval(&format!(
r#"
globalThis.selectionFailures = null;
onmessage = event => {{selectionFailures = event.data}};
const frame = document.createElement('iframe');
frame.sandbox = 'allow-scripts allow-same-origin allow-top-navigation';
frame.src = '{origin}/child';
document.body.append(frame);
"#
))
.unwrap();
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(selectionFailures !== null)",
"true",
"cross-origin target selection",
)
.await;
assert_eq!(vm.eval("JSON.stringify(selectionFailures)").unwrap(), "[]");
assert_eq!(server.finish_targets().await, vec!["/child"]);
assert!(vm.take_pending_location_navigation_with_seed().is_none());
assert!(vm.take_pending_popup_activations().is_empty());
}
#[tokio::test]
async fn window_open_special_targets_keep_entry_sandbox_authority() {
for allow_top in [false, true] {
for target in ["_parent", "_top"] {
let loader = static_http_loader([]);
let mut vm = new_parsed_page_task_executor_test_vm(
"https://special-open.test/root",
"<!doctype html><body>root",
&loader,
);
let sandbox = if allow_top {
"allow-scripts allow-same-origin allow-top-navigation"
} else {
"allow-scripts allow-same-origin"
};
vm.eval(&format!(
r#"
globalThis.selectionDone = false;
const frame = document.createElement('iframe'); frame.sandbox = {sandbox:?};
frame.srcdoc = `<script>
parent.emptyTargetSelected = parent.open.call(parent, '', '{target}') === parent;
try {{ parent.open.call(parent, 'https://special-open.test/selected', '{target}'); }}
catch (error) {{ if (error.name !== 'SecurityError') throw error; }}
parent.selectionDone = true;
<\/script>`;
document.body.append(frame);
"#
))
.unwrap();
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(selectionDone)",
"true",
"sandboxed entry borrowing top open",
)
.await;
assert_eq!(vm.eval("String(emptyTargetSelected)").unwrap(), "true");
let navigation = vm.take_pending_location_navigation_with_seed();
assert_eq!(navigation.is_some(), allow_top, "{target}");
if let Some(navigation) = navigation {
assert_eq!(
navigation.url.as_str(),
"https://special-open.test/selected"
);
}
assert!(vm.take_pending_popup_activations().is_empty());
}
}
}
@@ -0,0 +1,74 @@
globalThis.specialTargetCase = (() => {
const frame = document.createElement('iframe');
document.body.append(frame);
const middle = frame.contentWindow;
const nested = middle.document.createElement('iframe');
middle.document.body.append(nested);
const deep = nested.contentWindow;
const popup = open('', 'special-target-popup');
const popupFrame = popup.document.createElement('iframe');
popup.document.body.append(popupFrame);
const popupChild = popupFrame.contentWindow;
const windows = {root: window, middle, deep, popup, popupChild};
const targets = {
root: ['root', 'root', 'root'],
deep: ['deep', 'middle', 'root'],
popup: ['popup', 'popup', 'popup'],
popupChild: ['popupChild', 'popup', 'popup']
};
const names = ['_self', '_parent', '_top'];
const identify = value => Object.keys(windows).find(key => windows[key] === value) || String(value);
return {
ready() {
return Object.values(windows).every(w => w.document.readyState === 'complete');
},
run() {
const failures = [];
let count = 0, parentReads = 0;
for (const shadowParent of [false, true]) {
const descriptors = Object.values(windows).map(w => Object.getOwnPropertyDescriptor(w, 'parent'));
try {
if (shadowParent) {
for (const w of Object.values(windows)) {
Object.defineProperty(w, 'parent', {configurable: true, get() {
++parentReads;
throw new Error('Window.parent must not participate in target selection');
}});
}
}
for (const callee of ['root', 'deep', 'popup']) {
for (const [receiver, destinations] of Object.entries(targets)) {
for (let i = 0; i < names.length; ++i) {
for (const name of [names[i], names[i].toUpperCase()]) {
for (const features of ['', 'noopener', 'noreferrer']) {
const expected = windows[destinations[i]];
const before = [expected.document, expected.location.href,
expected.history.length, expected.opener];
const label = [callee, receiver, name, features, shadowParent].join('/');
++count;
try {
const actual = windows[callee].open.call(windows[receiver], '', name, features);
if (actual !== expected) failures.push(label + ': returned ' + identify(actual));
const after = [expected.document, expected.location.href,
expected.history.length, expected.opener];
if (!before.every((value, j) => value === after[j])) failures.push(label + ': navigated');
} catch (error) {
failures.push(label + ': ' + error);
}
}
}
}
}
}
} finally {
Object.values(windows).forEach((w, i) => Object.defineProperty(w, 'parent', descriptors[i]));
}
}
return {count, parentReads, failures};
},
close() {
popup.close();
frame.remove();
}
};
})();