fix(webidl): validate body and frameset Window handlers

This commit is contained in:
ldm0
2026-11-24 14:36:21 +08:00
parent 1be8f705c8
commit 06a90ff2fd
3 changed files with 180 additions and 0 deletions
@@ -0,0 +1,108 @@
(() => {
const rows = [];
function assert(value, message) { if (!value) throw new Error(message); }
function check(name, callback) {
try { callback(); rows.push({name, passed: true}); }
catch (error) { rows.push({name, passed: false, error: String(error)}); }
}
function throwsTypeError(w, callback, message) {
let error;
try { callback(); } catch (value) { error = value; }
assert(error instanceof w.TypeError, message + ': callee TypeError');
if (w !== window) assert(!(error instanceof TypeError), message + ': distinct realm');
}
const names = [
'onblur', 'onerror', 'onfocus', 'onload', 'onresize', 'onscroll',
'onafterprint', 'onbeforeprint', 'onbeforeunload', 'ongamepadconnected',
'ongamepaddisconnected', 'onhashchange', 'onlanguagechange', 'onmessage',
'onmessageerror', 'onoffline', 'ononline', 'onpagehide', 'onpagereveal',
'onpageshow', 'onpageswap', 'onpopstate', 'onrejectionhandled', 'onstorage',
'onunhandledrejection', 'onunload'
];
const frame = document.createElement('iframe');
document.body.appendChild(frame);
const popup = open();
assert(popup !== null, 'popup fixture');
try {
const realms = [window, frame.contentWindow, popup];
for (const [realmIndex, w] of realms.entries()) {
for (const tag of ['body', 'frameset']) {
const proto = (tag === 'body' ? w.HTMLBodyElement : w.HTMLFrameSetElement).prototype;
const otherTag = tag === 'body' ? 'frameset' : 'body';
const real = w.document.createElement(tag);
const detached = w.document.implementation.createHTMLDocument('').createElement(tag);
for (const name of names) {
const key = realmIndex + ':' + tag + ':' + name;
const descriptor = Object.getOwnPropertyDescriptor(proto, name);
check(key + ':descriptor', () => {
assert(descriptor && descriptor.enumerable && descriptor.configurable, 'own accessor');
assert(descriptor.get.length === 0 && descriptor.set.length === 1, 'accessor arity');
assert(descriptor.get.name === 'get ' + name && descriptor.set.name === 'set ' + name, 'accessor name');
throwsTypeError(window, () => Reflect.construct(descriptor.get, []), 'getter constructor');
throwsTypeError(window, () => Reflect.construct(descriptor.set, [null]), 'setter constructor');
});
check(key + ':invalid-receivers', () => {
let traps = 0;
const handler = { get() { traps++; throw new Error('get trap'); },
getPrototypeOf() { traps++; throw new Error('prototype trap'); },
has() { traps++; throw new Error('has trap'); } };
const revoked = Proxy.revocable(real, handler); revoked.revoke();
const invalid = [proto, {}, Object.create(proto), Object.create(real),
w.document.createElement(otherTag), w.document.createElement('div'),
w.document, w, null, undefined, 7, 'body', Symbol('body'),
new Proxy(real, handler), revoked.proxy];
const value = new Proxy(function() {}, handler);
const saved = w[name];
try {
for (const receiver of invalid) {
throwsTypeError(w, () => descriptor.get.call(receiver), 'getter receiver');
throwsTypeError(w, () => descriptor.set.call(receiver, value), 'setter receiver');
}
assert(traps === 0, 'validation executes no author traps');
assert(w[name] === saved, 'invalid setter keeps Window handler');
} finally { w[name] = saved; }
});
check(key + ':native-receivers', () => {
const saved = w[name];
const handler = function() {};
const originalPrototype = Object.getPrototypeOf(real);
try {
assert(descriptor.set.call(real, handler) === undefined, 'setter result');
assert(descriptor.get.call(real) === handler && w[name] === handler, 'native Window forwarding');
Object.setPrototypeOf(real, null);
descriptor.set.call(real, null);
assert(descriptor.get.call(real) === null && w[name] === null, 'native identity survives prototype change');
for (const other of realms) {
const cross = other.document.createElement(tag);
const otherSaved = other[name];
try {
descriptor.set.call(cross, handler);
assert(descriptor.get.call(cross) === handler && other[name] === handler, 'cross-realm receiver owner');
} finally { other[name] = otherSaved; }
}
descriptor.set.call(detached, handler);
assert(descriptor.get.call(detached) === null, 'windowless native receiver has no target');
assert(w[name] === null, 'windowless setter keeps live Window');
} finally {
Object.setPrototypeOf(real, originalPrototype);
w[name] = saved;
}
});
}
}
check(realmIndex + ':lenient-global-handlers', () => {
for (const name of ['onmouseenter', 'onmouseleave']) {
const descriptor = Object.getOwnPropertyDescriptor(w.HTMLElement.prototype, name);
assert(descriptor.get.call({}) === undefined, 'lenient getter');
assert(descriptor.set.call({}, function() {}) === undefined, 'lenient setter');
}
});
}
const failures = rows.filter(row => !row.passed);
globalThis.__nodeReplacementResults = {total: rows.length, passed: rows.length - failures.length, failures, rows};
return failures.length === 0;
} finally {
popup.close();
frame.remove();
}
})()
@@ -0,0 +1,71 @@
use super::*;
#[test]
fn body_and_frameset_window_handlers_validate_native_interface_receivers() {
let mut vm = new_storage_page_task_executor_test_vm("https://body-handler-brands.test/");
let result = vm
.eval(include_str!("body_window_handler_receivers.js"))
.unwrap();
assert_eq!(
vm.eval("JSON.stringify(__nodeReplacementResults.failures)")
.unwrap(),
"[]"
);
assert_eq!(result, "true");
}
#[test]
fn body_window_handlers_accept_registered_native_proxies_and_reject_author_wrappers() {
let mut vm = new_storage_page_task_executor_test_vm("https://body-handler-proxy.test/");
vm.eval("globalThis.nativeBody = document.createElement('body')")
.unwrap();
let context_ptr = &vm.page_default_context as *const _;
vm.with_context_scope_by_ptr_and_checkpoint_for_test(context_ptr, |scope, _| {
let global = scope.get_current_context().global(scope);
let body = global
.get(scope, crate::util::v8str(scope, "nativeBody").into())
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
.expect("native body fixture");
let handler = crate::util::new_null_prototype_object(scope);
let proxy = v8::Proxy::new(scope, body, handler).unwrap();
moli_webapi_declare::register_web_api_proxy(scope, proxy).unwrap();
assert!(crate::web_api_interfaces::HTMLBodyElement::is_instance(
scope,
proxy.into()
));
assert_eq!(
global.create_data_property(
scope,
crate::util::v8str(scope, "nativeBodyProxy").into(),
proxy.into()
),
Some(true)
);
Ok(())
})
.unwrap();
assert_eq!(
vm.eval(
r#"(() => {
const assert = (ok, message) => { if (!ok) throw Error(message); };
const descriptor = Object.getOwnPropertyDescriptor(HTMLBodyElement.prototype, 'onmessage');
const callback = () => {};
try {
descriptor.set.call(nativeBodyProxy, callback);
assert(descriptor.get.call(nativeBodyProxy) === callback && window.onmessage === callback, 'native Proxy forwards to Window');
let traps = 0;
const trap = () => { traps++; throw Error('author trap'); };
for (const receiver of [new Proxy(nativeBodyProxy, {get: trap, getPrototypeOf: trap}), Object.create(nativeBodyProxy)]) {
let error;
try { descriptor.set.call(receiver, null); } catch (value) { error = value; }
assert(error instanceof TypeError, 'author wrapper rejects');
}
assert(traps === 0 && window.onmessage === callback, 'receiver validation has no author side effects');
return true;
} finally { window.onmessage = null; }
})()"#
)
.unwrap(),
"true"
);
}
@@ -2288,6 +2288,7 @@ mod blob_response_headers;
mod body_completion;
mod body_completion_http;
mod body_mime;
mod body_window_handler_receivers;
mod browser_api;
mod cache_dictionary_inheritance;
mod cache_interfaces;