fix(window): enforce frameElement origin checks

This commit is contained in:
ldm0
2026-11-02 06:02:22 +08:00
parent d0220b1171
commit ddd3d125ca
6 changed files with 280 additions and 4 deletions
@@ -1,4 +1,5 @@
use super::helpers::{
same_origin_window_receiver,
window_child_context_handle, window_current_dispatch_scope, window_hidden_value,
window_host_ptr, window_receiver,
};
@@ -22,7 +23,7 @@ pub(in crate::context_bootstrap) fn window_frame_element_getter<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
let Some(receiver) = window_receiver(scope, &args) else {
let Some(receiver) = same_origin_window_receiver(scope, &args) else {
return;
};
let Some(host_ptr) = window_host_ptr(scope, receiver) else {
@@ -36,13 +37,27 @@ pub(in crate::context_bootstrap) fn window_frame_element_getter<'s>(
rv.set_null();
return;
};
// A cached embedding element is a capability to its entire owner Document.
// Recheck same origin-domain before returning it, including after domain
// mutation or retirement of the receiver's original Realm.
let Some(owner_context) =
crate::native_bridge::node_owner_document_relevant_context(scope, host_ptr, handle)
else {
rv.set_null();
return;
};
// The container belongs to the parent Document. Authorizing this Window
// does not grant access to that Document, including for sandboxed children
// and one-sided document.domain changes. Use the getter's current realm.
if !crate::native_bridge::window_contexts_allow_access(
scope.get_current_context(),
owner_context,
) {
rv.set_null();
return;
}
if let Some(value) = window_hidden_value(scope, receiver, WINDOW_FRAME_ELEMENT_SLOT) {
rv.set(value);
return;
}
let scope = &mut v8::ContextScope::new(scope, owner_context);
match unsafe { &mut *host_ptr }
.native_bridge_mut()
.wrap_handle(scope, host_ptr, handle)
@@ -147,6 +147,34 @@ pub(super) fn window_receiver<'s>(
None
}
pub(super) fn same_origin_window_receiver<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: &v8::FunctionCallbackArguments<'s>,
) -> Option<v8::Local<'s, v8::Object>> {
let receiver = args.this();
// An extracted getter bypasses WindowProxy's property access check. Check
// the native global before looking up receiver slots, which can themselves
// trigger V8's cross-origin fallback in a different realm.
if let Some(context) = receiver.get_creation_context(scope)
&& receiver.strict_equals(context.global(scope).into())
&& context_host_ptr_from_context_slot(context).is_some()
{
if crate::native_bridge::window_contexts_allow_access(scope.get_current_context(), context)
{
return Some(receiver);
}
} else if !crate::native_bridge::is_cross_origin_top_window_proxy(scope, receiver) {
return window_receiver(scope, args);
}
crate::native_bridge::throw_dom_exception(
scope,
"SecurityError",
18,
"Blocked access to a cross-origin Window.",
);
None
}
pub(crate) fn current_window_style_viewport(
scope: &mut v8::PinScope<'_, '_>,
host: &crate::native_bridge::JsContextHost,
@@ -0,0 +1,124 @@
use super::*;
#[tokio::test(flavor = "current_thread")]
async fn frame_element_checks_receiver_and_container_origins_in_the_getter_realm() {
let child = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/frame-element-security-child.html"
));
let server = StaticHttpServer::spawn_with_bodies(vec![child.to_owned(); 6]).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 same_url = server.url_for_host("www.example.test", "/child.html");
let cross_url = server.url_for_host("remote.example.test", "/child.html");
let mut vm = new_storage_page_task_executor_test_vm_with_loader(parent_url.as_str(), &loader);
let script = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/frame-element-security.js"
));
vm.exec(
&format!(
r#"
if (!document.documentElement) document.appendChild(document.createElement('html'));
if (!document.body) document.documentElement.appendChild(document.createElement('body'));
globalThis.__frameElementResult = null;
({script})({{sameURL: {same_url:?}, crossURL: {cross_url:?}}}).then(
result => {{ __frameElementResult = result; }},
error => {{ __frameElementResult = {{error: String(error)}}; }}
);
"#,
same_url = same_url.as_str(),
cross_url = cross_url.as_str(),
),
None,
)
.expect("frameElement origin probe should start");
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(__frameElementResult !== null)",
"true",
"frameElement origin probe should finish",
)
.await;
let result: serde_json::Value = serde_json::from_str(
&vm.eval("JSON.stringify(__frameElementResult)")
.expect("frameElement observations"),
)
.unwrap();
assert_eq!(result["checks"], 28, "{result}");
assert_eq!(result["failures"], serde_json::json!([]), "{result}");
assert_eq!(server.finish_targets().await, vec!["/child.html"; 6]);
}
#[tokio::test(flavor = "current_thread")]
async fn frame_element_uses_the_isolated_world_access_policy() {
for cross_origin in [false, true] {
let server = StaticHttpServer::spawn_with_bodies(vec![
"<!doctype html><body>isolated frameElement</body>".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 child_url = server.url_for_host(
if cross_origin {
"remote.example.test"
} else {
"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#"
globalThis.loaded = false;
const frame = document.createElement('iframe');
frame.onload = () => {{ loaded = true; }};
frame.src = {child_url:?};
(document.body || document.documentElement || document).appendChild(frame);
"#,
child_url = child_url.as_str(),
),
None,
)
.unwrap();
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(loaded)",
"true",
"child should load before creating isolated worlds",
)
.await;
let frame_id = vm
.live_child_default_runtime_realm_inventory()
.into_iter()
.next()
.and_then(|realm| realm.frame_id)
.expect("child frame id");
for universal in [false, true] {
let context_id = vm
.create_isolated_world_for_frame(
&frame_id,
if universal { "universal" } else { "enforced" },
universal,
)
.expect("child isolated world");
assert_eq!(
vm.eval_in_isolated_context(context_id, "String(frameElement === null)")
.expect("isolated frameElement"),
(cross_origin && !universal).to_string(),
"cross_origin={cross_origin}, universal={universal}"
);
}
assert_eq!(server.finish_targets().await, vec!["/child.html"]);
}
}
@@ -2284,6 +2284,7 @@ mod event_receivers;
mod fetch_integrity;
mod fetch_referrer;
mod fetch_request_guard;
mod frame_element_security;
mod geometry_matrix_constructor_union;
mod geometry_point_conversion_order;
mod geometry_point_transform;
@@ -0,0 +1,26 @@
<!doctype html><body><script>
onmessage = async event => {
if (event.data !== 'frame-element-security') return;
const get = Object.getOwnPropertyDescriptor(window, 'frameElement').get;
const probe = callback => {
try {
const value = callback();
return value === null ? 'null' : value.tagName;
} catch (error) {
return error.name + ':' + (error instanceof DOMException);
}
};
const nested = document.createElement('iframe');
const loaded = new Promise(resolve => nested.onload = resolve);
nested.src = location.href;
document.body.appendChild(nested);
await loaded;
event.source.postMessage({
own: probe(() => frameElement),
borrowed: probe(() => get.call(window)),
parent: probe(() => get.call(parent)),
nested: probe(() => nested.contentWindow.frameElement),
nestedBorrowed: probe(() => get.call(nested.contentWindow))
}, '*');
};
</script>
@@ -0,0 +1,82 @@
async ({sameURL, 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 throws = (callback, Constructor, name, label) => {
try { callback(); equal('returned', name, label); }
catch (error) { equal([error.name, error instanceof Constructor], [name, true], label); }
};
const get = Object.getOwnPropertyDescriptor(window, 'frameElement').get;
equal(get.call(window), null, 'top frameElement');
const frames = [];
const create = async (url, sandbox) => {
const frame = document.createElement('iframe');
if (sandbox) frame.sandbox = 'allow-scripts';
const loaded = new Promise(resolve => frame.onload = resolve);
frame.src = url;
document.body.appendChild(frame);
frames.push(frame);
await loaded;
return frame;
};
let same;
for (const mode of ['same', 'cross', 'sandbox']) {
const frame = await create(mode === 'cross' ? crossURL : sameURL, mode === 'sandbox');
const child = frame.contentWindow;
if (mode === 'same') {
same = frame;
equal(child.frameElement === frame, true, 'same-origin direct identity');
equal(get.call(child) === frame, true, 'same-origin borrowed identity');
} else {
throws(() => child.frameElement, DOMException, 'SecurityError', mode + ' direct');
throws(() => get.call(child), DOMException, 'SecurityError', mode + ' borrowed');
}
const response = new Promise(resolve => {
const listener = event => {
if (event.source !== child) return;
removeEventListener('message', listener);
resolve(event.data);
};
addEventListener('message', listener);
});
child.postMessage('frame-element-security', '*');
equal(await response, mode === 'same'
? {own:'IFRAME', borrowed:'IFRAME', parent:'null', nested:'IFRAME', nestedBorrowed:'IFRAME'}
: {own:'null', borrowed:'null', parent:'SecurityError:true', nested:mode === 'cross' ? 'IFRAME' : 'SecurityError:true', nestedBorrowed:mode === 'cross' ? 'IFRAME' : 'SecurityError:true'}, mode + ' child observations');
if (mode !== 'same') {
frame.remove();
throws(() => get.call(child), DOMException, 'SecurityError', mode + ' removed borrowed');
}
}
const child = same.contentWindow;
const childGet = Object.getOwnPropertyDescriptor(child, 'frameElement').get;
const childRead = child.Function('return frameElement');
const childDOMException = child.DOMException;
let traps = 0;
const revoked = Proxy.revocable(child, {}); revoked.revoke();
for (const invalid of [{}, Object.create(child), new Proxy(child, {
get() { traps++; throw new Error('author trap'); },
getPrototypeOf() { traps++; throw new Error('author trap'); }
}), revoked.proxy]) throws(() => get.call(invalid), TypeError, 'TypeError', 'invalid Window receiver');
equal(traps, 0, 'brand check does not run author traps');
child.document.domain = child.document.domain;
throws(() => child.frameElement, DOMException, 'SecurityError', 'one-sided domain direct');
throws(() => get.call(child), DOMException, 'SecurityError', 'one-sided domain parent getter');
equal(childGet.call(child), null, 'cached child getter uses its realm origin');
equal(childRead(), null, 'child execution cannot expose cross-origin container');
throws(() => childGet.call(window), childDOMException, 'SecurityError', 'child getter error realm');
document.domain = document.domain;
equal(child.frameElement === same, true, 'relaxed domain direct identity');
equal(get.call(child) === same, true, 'relaxed domain parent getter');
equal(childGet.call(child) === same, true, 'relaxed domain child getter');
same.remove();
equal(get.call(child), null, 'removed same-origin receiver');
equal(childGet.call(child), null, 'removed cached child getter');
equal(childRead(), null, 'removed child execution');
for (const frame of frames) frame.remove();
return {checks, failures};
}