fix(window): follow child target-name visibility

Select the first direct child with each target name before checking its
original origin against the receiving Window. Share this lookup between
same-origin and cross-origin named access, including live name changes and
navigation, without applying document.domain relaxation.

Allow named children to shadow non-exposed properties and the then fallback,
while keeping cross-origin IDL properties first. Use canonical array-index
parsing so names such as 01 and 4294967295 remain available by name.

Cover property descriptors, duplicate names, origin changes, renaming,
removal, and indexed WindowProxy identities. The named-access WPT now passes
all three subtests. An older frameElement WPT assumes that cross-origin
name-only lookup succeeds, contrary to this requirement; direct and indexed
frameElement security checks remain covered separately.
This commit is contained in:
ldm0
2026-11-24 14:31:52 +08:00
parent de155e6622
commit eebd5fa20c
9 changed files with 220 additions and 9 deletions
+11 -2
View File
@@ -5424,7 +5424,16 @@ async fn cross_origin_window_proxy_exposes_named_child_frames() -> Result<()> {
const named = win.nestedNamed;\
const indexed = win[0];\
const descriptor = Object.getOwnPropertyDescriptor(win, 'nestedNamed');\
const documentDescriptor = Object.getOwnPropertyDescriptor(win, 'document');\
const probe = operation => {\
try { return operation(); }\
catch (error) { return `${error && error.name}:${error instanceof DOMException}`; }\
};\
const documentDescriptor = probe(() => {\
const d = Object.getOwnPropertyDescriptor(win, 'document');\
return {enumerable:d.enumerable, configurable:d.configurable, writable:d.writable,\
getterType:typeof d.get, setterType:typeof d.set, valueType:typeof d.value,\
matchesIndexed:d.value === win[1]};\
});\
const focusDescriptor = Object.getOwnPropertyDescriptor(win, 'focus');\
let documentAccess;\
try {\
@@ -5475,7 +5484,7 @@ async fn cross_origin_window_proxy_exposes_named_child_frames() -> Result<()> {
assert_eq!(
before,
Some(
r#"{"hasNamed":true,"ownNamed":true,"hasDocumentCollision":true,"hasFocusCollision":true,"sameAsIndexed":true,"documentDescriptor":{"enumerable":false,"configurable":true,"getterType":"undefined","setterType":"undefined","valueType":"object"},"focusDescriptor":{"enumerable":false,"configurable":true,"writable":false,"valueType":"function"},"documentAccess":"read","focusType":"function","namedSelf":true,"namedWindow":true,"namedFrames":true,"namedParent":true,"namedTop":true,"namedLength":0,"descriptor":{"enumerable":false,"configurable":true,"writable":false,"valueType":"object"}}"#
r#"{"hasNamed":true,"ownNamed":true,"hasDocumentCollision":true,"hasFocusCollision":true,"sameAsIndexed":true,"documentDescriptor":{"enumerable":false,"configurable":true,"writable":false,"getterType":"undefined","setterType":"undefined","valueType":"object","matchesIndexed":true},"focusDescriptor":{"enumerable":false,"configurable":true,"writable":false,"valueType":"function"},"documentAccess":"read","focusType":"function","namedSelf":true,"namedWindow":true,"namedFrames":true,"namedParent":true,"namedTop":true,"namedLength":0,"descriptor":{"enumerable":false,"configurable":true,"writable":false,"valueType":"object"}}"#
.to_owned(),
),
"{}",
@@ -1674,21 +1674,19 @@ fn install_cross_origin_window_named_slots<'s>(
fn is_cross_origin_named_child_slot_name(name: &str) -> bool {
!name.is_empty()
&& name.parse::<u32>().is_err()
&& !CROSS_ORIGIN_DENIED_WINDOW_PROPERTIES.contains(&name)
&& crate::native_bridge::collections::array_index_property_name(name).is_none()
&& !CROSS_ORIGIN_WINDOW_NOOP_METHODS.contains(&name)
&& !matches!(
name,
"window"
| "self"
| "globalThis"
| "top"
| "parent"
| "frames"
| "location"
| "closed"
| "opener"
| "then"
| "postMessage"
)
}
@@ -1,5 +1,6 @@
use super::*;
use crate::dom::native::Node;
use crate::native_bridge::context_host::OwnerDispatchScope;
use std::collections::HashSet;
impl PageScriptHost {
@@ -262,7 +263,7 @@ impl PageScriptHost {
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| {
let first = handles.into_iter().find(|handle| {
self.dom_host()
.node(*handle)
.is_some_and(|node| node.flags().in_document_tree())
@@ -270,7 +271,14 @@ impl PageScriptHost {
.child_browsing_contexts
.get(handle)
.is_some_and(|entry| entry.matches_browsing_context_name(key))
})
})?;
// The target-name property set selects the first child for each name
// before filtering by origin. A cross-origin first match must not
// expose a later same-origin duplicate, and document.domain does not
// relax this same-origin check.
let parent_scope = parent.map_or(OwnerDispatchScope::Top, OwnerDispatchScope::Child);
self.window_scopes_have_same_origin(parent_scope, OwnerDispatchScope::Child(first))
.then_some(first)
}
fn child_browsing_context_handle_by_name_in_document_order_from_document(
@@ -0,0 +1,68 @@
use super::*;
#[tokio::test(flavor = "current_thread")]
async fn cross_origin_window_names_follow_target_names_and_origin_filtering() {
let host = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/cross-origin-window-names-host.html"
));
let child = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/cross-origin-window-names-child.html"
));
let script = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/cross-origin-window-names.js"
));
let server = StaticHttpServer::spawn_with_bodies(vec![
host.to_owned(),
child.to_owned(),
child.to_owned(),
child.to_owned(),
])
.await;
let loader = static_http_loader([
server.resolve_entry("www.example.test"),
server.resolve_entry("remote.example.test"),
]);
let parent_url = server.url_for_host("www.example.test", "/page.html");
let host_url = server.url_for_host("remote.example.test", "/host.html");
let child_url = server.url_for_host("www.example.test", "/child.html");
let mut vm = new_storage_page_task_executor_test_vm_with_loader(parent_url.as_str(), &loader);
vm.exec(
&format!(
r#"
if (!document.documentElement) document.appendChild(document.createElement('html'));
if (!document.body) document.documentElement.appendChild(document.createElement('body'));
globalThis.__windowNamesResult = null;
({script})({{hostURL: {host_url:?}, crossURL: {child_url:?}}}).then(
result => {{ __windowNamesResult = result; }},
error => {{ __windowNamesResult = {{error: String(error)}}; }}
);
"#,
host_url = host_url.as_str(),
child_url = child_url.as_str(),
),
None,
)
.unwrap();
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(__windowNamesResult !== null)",
"true",
"Window named property probe should finish",
)
.await;
let result: serde_json::Value = serde_json::from_str(
&vm.eval("JSON.stringify(__windowNamesResult)")
.expect("Window named property observations"),
)
.unwrap();
assert_eq!(result["checks"], 97, "{result}");
assert_eq!(result["failures"], serde_json::json!([]), "{result}");
assert_eq!(
server.finish_targets().await,
vec!["/host.html", "/child.html", "/child.html", "/child.html"]
);
}
@@ -2311,6 +2311,7 @@ mod credential_signals;
mod audio_param_native_receivers;
mod cross_origin_window_indexes;
mod cross_origin_window_names;
mod css_keyframes_mutations;
mod css_keyframes_receivers;
mod device_events;
@@ -45,7 +45,8 @@ async function probeCrossOriginWindowIndexes({sameURL, crossURL, hostURL, nested
preventExtensions:'SecurityError', samePrototype:'SecurityError', differentPrototype:'SecurityError',
borrowMessage:true, keys:Array.from({length:count}, (_,i) => String(i)),
ownIndex:true, parentIdentity:true,
descriptor:['object',false,true,true], named:true, namedDescriptor:['object',false,false,true],
descriptor:['object',false,true,true], named:navigated ? 'SecurityError' : true,
namedDescriptor:navigated ? 'SecurityError' : ['object',false,false,true],
has:true, missing:'SecurityError', missingHas:'SecurityError', missingDescriptor:'SecurityError',
nonIndex:'SecurityError', document:'SecurityError', deniedDescriptor:'SecurityError', missingNamedDescriptor:'SecurityError',
set:'SecurityError', define:'SecurityError', delete:'SecurityError', focus:'ok', cachedIdentity:true,
@@ -0,0 +1,3 @@
<!doctype html><body>named destination<script>
window.name = decodeURIComponent(location.hash.slice(1));
</script>
@@ -0,0 +1,45 @@
<!doctype html><body><script>
const names = ['document', 'open', 'globalThis', 'then', 'constructor', '__proto__',
'01', '4294967295', 'close', 'postMessage', 'frames', 'length', '0', 'duplicate', 'duplicate'];
const children = [];
async function navigate(frame, url) {
const loaded = new Promise(resolve => frame.onload = resolve);
frame.src = url;
frame.removeAttribute('srcdoc');
await loaded;
}
addEventListener('message', async event => {
if (event.data?.kind !== 'named-window-action') return;
const {action, crossURL} = event.data;
try {
if (action === 'init') {
for (const name of names) {
const frame = document.createElement('iframe');
frame.name = name;
const loaded = new Promise(resolve => frame.onload = resolve);
frame.srcdoc = '<p>named child</p>';
document.body.append(frame);
children.push(frame);
await loaded;
}
} else if (action === 'rename') {
children[0].contentWindow.name = 'renamed';
} else if (action === 'restore') {
children[0].contentWindow.name = 'document';
} else if (action === 'cross-duplicate') {
await navigate(children[13], crossURL + '#duplicate');
} else if (action === 'remove-duplicate') {
children[13].remove();
} else if (action === 'cross-document') {
await navigate(children[0], crossURL + '#document');
} else if (action === 'cross-then') {
await navigate(children[3], crossURL + '#then');
}
event.source.postMessage({kind:'named-window-result', action,
duplicateType: typeof globalThis.duplicate,
duplicateIsSecond: globalThis.duplicate === children[14].contentWindow}, '*');
} catch (error) {
event.source.postMessage({kind:'named-window-result', action, error:String(error)}, '*');
}
});
</script>
@@ -0,0 +1,78 @@
async function probeCrossOriginWindowNames({hostURL, crossURL}) {
const failures = [];
let checks = 0;
const equal = (actual, expected, label) => {
checks++;
if (JSON.stringify(actual) !== JSON.stringify(expected)) failures.push({label, actual, expected});
};
const observe = callback => {
try { return callback(); } catch (error) { return error.name; }
};
const host = document.createElement('iframe');
const loaded = new Promise(resolve => host.onload = resolve);
host.src = hostURL;
document.body.append(host);
await loaded;
const win = host.contentWindow;
const ask = action => new Promise((resolve, reject) => {
const listener = event => {
if (event.source !== win || event.data?.kind !== 'named-window-result' || event.data.action !== action) return;
removeEventListener('message', listener);
if (event.data.error) reject(new Error(event.data.error)); else resolve(event.data);
};
addEventListener('message', listener);
win.postMessage({kind:'named-window-action', action, crossURL}, '*');
});
const checkName = (name, value, phase, denied = false) => {
const prefix = phase + ' ' + name;
equal(observe(() => win[name] === value), denied ? 'SecurityError' : true, prefix + ' get');
equal(observe(() => {
const d = Object.getOwnPropertyDescriptor(win, name);
return [d.value === value, d.writable, d.enumerable, d.configurable];
}), denied ? 'SecurityError' : [true, false, false, true], prefix + ' descriptor');
equal(observe(() => name in win), denied ? 'SecurityError' : true, prefix + ' has');
equal(observe(() => Object.hasOwn(win, name)), denied ? 'SecurityError' : true, prefix + ' hasOwn');
};
await ask('init');
const children = Array.from({length:15}, (_, i) => win[i]);
const names = ['document', 'open', 'globalThis', 'then', 'constructor', '__proto__', '01', '4294967295'];
names.forEach((name, i) => checkName(name, children[i], 'initial'));
checkName('duplicate', children[13], 'initial');
for (const name of ['close', 'postMessage']) equal(typeof win[name], 'function', name + ' keeps the IDL method');
equal(win.frames === win, true, 'frames keeps the IDL getter');
equal(win.length, 15, 'length keeps the IDL getter');
equal(win['0'] === children[0] && win['0'] !== children[12], true, 'canonical array index takes precedence');
for (const name of ['document', 'then']) {
equal(observe(() => Reflect.set(win, name, null)), 'SecurityError', name + ' set');
equal(observe(() => Reflect.defineProperty(win, name, {value:null})), 'SecurityError', name + ' define');
equal(observe(() => Reflect.deleteProperty(win, name)), 'SecurityError', name + ' delete');
}
equal(Reflect.ownKeys(win).filter(key => names.includes(key) && key !== 'then'), [], 'named children stay out of own keys');
equal(observe(() => children[0].document), 'SecurityError', 'named access does not expose the child Document');
await ask('rename');
checkName('document', undefined, 'renamed', true);
checkName('renamed', children[0], 'renamed');
await ask('restore');
checkName('document', children[0], 'restored');
checkName('renamed', undefined, 'restored', true);
const crossDuplicate = await ask('cross-duplicate');
checkName('duplicate', undefined, 'cross-origin first duplicate', true);
equal(crossDuplicate.duplicateType, 'undefined', 'same-origin caller also filters the first duplicate');
equal(win[13] === children[13], true, 'cross-origin first duplicate remains indexed');
equal(win[14] === children[14], true, 'second duplicate remains indexed');
const removed = await ask('remove-duplicate');
checkName('duplicate', children[14], 'first duplicate removed');
equal(removed.duplicateIsSecond, true, 'same-origin caller sees the next duplicate after removal');
await ask('cross-document');
checkName('document', undefined, 'cross-origin document child', true);
equal(win[0] === children[0], true, 'navigation preserves the indexed WindowProxy');
equal(children[0].document.body.textContent.startsWith('named destination'), true, 'indexed child is checked against the caller origin');
await ask('cross-then');
checkName('then', undefined, 'cross-origin then child uses the fallback');
host.remove();
checkName('duplicate', undefined, 'removed host', true);
checkName('then', undefined, 'removed host fallback');
equal(win.closed, true, 'removed host closed');
equal(win.length, 0, 'removed host length');
return {checks, failures};
}