fix(location): preserve entry settings during proxy forwarding

This commit is contained in:
ldm0
2026-11-22 02:01:54 +08:00
parent 0ee2f5d9af
commit 096439ff17
4 changed files with 207 additions and 13 deletions
@@ -80,7 +80,6 @@ fn location_proxy_set<'s>(
let caller = scope
.get_incumbent_context()
.unwrap_or_else(|| scope.get_current_context());
let scope = &mut v8::ContextScope::new(scope, caller);
if target
.get_creation_context(scope)
.is_some_and(|owner| window_contexts_allow_access(caller, owner))
@@ -100,8 +99,15 @@ fn location_proxy_set<'s>(
let Ok(key) = v8::Local::<v8::Name>::try_from(args.get(1)) else {
return;
};
if let Some(value) =
set_cross_origin_location_property(scope, target, key, args.get(2), args.get(3))
let setter = {
let scope = &mut v8::ContextScope::new(scope, caller);
cross_origin_location_setter(scope, target, key)
};
// Only construct the cross-origin surface in the caller's realm. Entering
// that context during the call would replace the entry settings object
// used by URL parsing, including nested calls during value conversion.
if let Some(setter) = setter
&& let Some(value) = call_location_setter(scope, setter, args.get(3), args.get(2))
{
rv.set_bool(value);
}
@@ -127,16 +133,26 @@ pub(super) fn set_location_href<'s>(
{
return target.set_with_receiver(scope, key.into(), value, location);
}
set_cross_origin_location_property(scope, target, key.into(), value, location.into())
let setter = cross_origin_location_setter(scope, target, key.into())?;
call_location_setter(scope, setter, location.into(), value)
}
fn set_cross_origin_location_property<'s>(
fn call_location_setter<'s>(
scope: &mut v8::PinScope<'s, '_>,
setter: v8::Local<'s, v8::Function>,
receiver: v8::Local<'s, v8::Value>,
value: v8::Local<'s, v8::Value>,
) -> Option<bool> {
// Preserve Reflect.set's receiver. Interceptor callbacks only expose the
// holder, and must not substitute it for a forged or author Proxy receiver.
setter.call(scope, receiver, &[value]).map(|_| true)
}
fn cross_origin_location_setter<'s>(
scope: &mut v8::PinScope<'s, '_>,
target: v8::Local<'s, v8::Object>,
key: v8::Local<'s, v8::Name>,
value: v8::Local<'s, v8::Value>,
receiver: v8::Local<'s, v8::Value>,
) -> Option<bool> {
) -> Option<v8::Local<'s, v8::Function>> {
if key != v8str(scope, "href") {
crate::native_bridge::throw_cross_origin_location_security_error(scope);
return None;
@@ -145,12 +161,9 @@ fn set_cross_origin_location_property<'s>(
let descriptor = surface
.get_own_property_descriptor(scope, key)
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())?;
let setter = descriptor
descriptor
.get(scope, v8str(scope, "set").into())
.and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())?;
// Preserve Reflect.set's receiver. Interceptor callbacks only expose the
// holder, and must not substitute it for a forged or author Proxy receiver.
setter.call(scope, receiver, &[value]).map(|_| true)
.and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
}
fn location_proxy_set_prototype<'s>(
@@ -0,0 +1,50 @@
use super::*;
#[tokio::test]
async fn location_proxy_forwarding_preserves_entry_settings_and_caller_exceptions() {
let script = include_str!("../../../../tests/fixtures/location-entry-settings.js");
let child = format!("<!doctype html><body><script>({script})({{role:'child'}})</script>");
// One entry document, its incumbent and 26 navigation targets, each loaded
// before and after its Location operation.
let server = StaticHttpServer::spawn_with_bodies(vec![child; 54]).await;
let loader = static_http_loader([
server.resolve_entry("localhost"),
server.resolve_entry("127.0.0.1"),
]);
let source = server.url_for_host("localhost", "/top/page.html");
let entry = server.url_for_host("localhost", "/entry/page.html");
let mut vm = new_parsed_page_task_executor_test_vm(
source.as_str(),
"<!doctype html><body>source",
&loader,
);
vm.eval(&format!(
"globalThis.locationEntryResult = null; \
({script})({{entryURL:{entry:?}}}).then(\
result => locationEntryResult = result,\
error => locationEntryResult = {{error:String(error)}});",
entry = entry.as_str(),
))
.unwrap();
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(locationEntryResult !== null)",
"true",
"cross-realm Location entry settings",
)
.await;
let result: serde_json::Value =
serde_json::from_str(&vm.eval("JSON.stringify(locationEntryResult)").unwrap()).unwrap();
assert_eq!(result["checks"], 60, "{result}");
assert_eq!(result["failures"], serde_json::json!([]), "{result}");
let requests = server.finish_targets().await;
assert_eq!(requests.len(), 54);
assert_eq!(
requests
.iter()
.filter(|path| path.starts_with("/converted/"))
.count(),
26,
);
}
@@ -53,6 +53,7 @@ mod images;
mod input_event_init;
mod joint_history_child_pushes;
mod legacy_event_init;
mod location_entry_settings;
mod media;
mod media_devices;
mod media_player_init;
@@ -0,0 +1,130 @@
(function locationEntrySettings(config) {
const methods = {
same: ['href', 'reflect', 'descriptor', 'window', 'document', 'assign', 'replace', 'expando'],
cross: ['href', 'reflect', 'descriptor', 'window', 'replace']
};
const cases = Object.entries(methods).flatMap(([origin, kinds]) =>
['event', 'promise'].flatMap(mode => kinds.map(kind =>
({origin, mode, kind, label: `${origin}-${mode}-${kind}`}))));
if (config.role === 'child') {
if (location.pathname === '/entry/page.html') {
const base = document.createElement('base');
base.href = '/entry/base/';
document.head.append(base);
window.scheduleLocationCases = callback => Promise.resolve().then(() => callback());
const incumbent = document.createElement('iframe');
incumbent.id = 'incumbent';
incumbent.src = '/incumbent/page.html';
document.body.append(incumbent);
for (const item of cases) {
const frame = document.createElement('iframe');
frame.id = item.label;
const url = new URL('/relevant/empty.html', location);
if (item.origin === 'cross') url.hostname = '127.0.0.1';
frame.src = url.href;
document.body.append(frame);
}
window.onload = () => top.locationEntryLoaded(window);
} else if (location.pathname.endsWith('/target.html')) {
top.postMessage({
label: new URL(location).searchParams.get('case'),
href: location.href,
referrer: document.referrer
}, '*');
}
return;
}
return new Promise(resolve => {
const rows = new Map();
const failures = [];
let checks = 0;
const check = (condition, label) => {
checks++;
if (!condition) failures.push(label);
};
const frame = document.createElement('iframe');
const receive = event => {
if (!cases.some(item => item.label === event.data?.label)) return;
rows.set(event.data.label, event.data);
if (rows.size !== cases.length) return;
for (const [label, row] of rows) {
const expected = new URL(`/converted/${label}/target.html?case=${label}`, config.entryURL).href;
check(row.href === expected, `${label}: URL ${row.href}, expected ${expected}`);
check(row.referrer === new URL('/incumbent/page.html', config.entryURL).href,
`${label}: referrer ${row.referrer}`);
}
window.removeEventListener('message', receive);
delete window.locationEntryLoaded;
frame.remove();
resolve({checks, failures, rows: [...rows.values()]});
};
window.addEventListener('message', receive);
window.locationEntryLoaded = entry => {
const incumbent = entry.document.getElementById('incumbent').contentWindow;
const navigate = incumbent.Function('target', 'entry', 'kind', 'label', `
const input = {toString() {
entry.document.querySelector('base').href = '/converted/' + label + '/';
return 'target.html?case=' + label;
}};
switch (kind) {
case 'href': target.location.href = input; break;
case 'reflect': Reflect.set(target.location, 'href', input); break;
case 'descriptor': Object.getOwnPropertyDescriptor(target.location, 'href').set.call(target.location, input); break;
case 'window': target.location = input; break;
case 'document': target.document.location = input; break;
case 'assign': target.location.assign(input); break;
case 'replace': target.location.replace(input); break;
case 'expando':
Object.defineProperty(target.location, 'navigateFromSetter', {
set() { target.location.assign(input); }
});
target.location.navigateFromSetter = true;
break;
}
`);
const exceptions = incumbent.Function('target', 'ExpectedTypeError', 'sameOrigin', `
const results = [];
const location = target.location;
let conversions = 0;
const value = {toString() { conversions++; return 'target.html'; }};
if (sameOrigin) {
const revoked = Proxy.revocable(location, {});
revoked.revoke();
for (const receiver of [{}, new Proxy(location, {}), revoked.proxy]) {
try { Reflect.set(location, 'href', value, receiver); results.push(false); }
catch (error) { results.push(error instanceof ExpectedTypeError && conversions === 0); }
}
} else {
try { location.hash = value; results.push(false); }
catch (error) {
results.push(error instanceof DOMException && error.name === 'SecurityError' && conversions === 0);
}
}
const sentinel = {};
try { location.href = {toString() { throw sentinel; }}; results.push(false); }
catch (error) { results.push(error === sentinel); }
try { location.href = Symbol(); results.push(false); }
catch (error) { results.push(error instanceof ExpectedTypeError); }
return results;
`);
for (const origin of ['same', 'cross']) {
const target = entry.document.getElementById(`${origin}-event-href`).contentWindow;
const expectedTypeError = origin === 'same' ? target.TypeError : incumbent.TypeError;
exceptions(target, expectedTypeError, origin === 'same').forEach((result, index) =>
check(result, `${origin}: receiver/conversion exception ${index}`));
}
const run = mode => {
for (const item of cases.filter(item => item.mode === mode)) {
const target = entry.document.getElementById(item.label).contentWindow;
navigate(target, entry, item.kind, item.label);
}
};
run('event');
entry.scheduleLocationCases(() => run('promise'));
};
frame.src = config.entryURL;
document.body.append(frame);
});
})