fix(dom): derive attribute value conversion before name validation

This commit is contained in:
ldm0
2026-11-19 00:57:40 +08:00
parent 88bd5ee3e9
commit 1ac2005aeb
8 changed files with 303 additions and 41 deletions
@@ -35,6 +35,15 @@ pub(in crate::native_bridge::document) fn detached_attribute_name<'s>(
node: v8::Local<'s, v8::Object>,
name: &str,
) -> String {
if let Ok((runtime_ptr, handle)) =
crate::native_bridge::node_runtime_and_handle_from_object_or_detached(scope, node)
&& let Some(name) = unsafe { &*runtime_ptr }
.dom_host()
.dom()
.normalized_attribute_name(handle, name)
{
return name;
}
let name = name.to_owned();
let is_html_element_in_html_document =
detached_state_string(scope, node, "documentKind").as_deref() == Some("html")
@@ -253,14 +253,58 @@ detached_bridge_method_forwarder!(
detached_has_attribute_ns_method_callback,
"__detachedHasAttributeNS"
);
detached_bridge_method_forwarder!(
detached_set_attribute_method_callback,
"__detachedSetAttribute"
);
detached_bridge_method_forwarder!(
detached_set_attribute_ns_method_callback,
"__detachedSetAttributeNS"
);
pub(in crate::native_bridge) fn detached_set_attribute_method_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
let Some(parsed) =
webidl::parse_args::<crate::native_bridge::element::SetAttributeArgs>(scope, &args)
else {
return;
};
let Some(name) = v8_string(scope, &parsed.name) else {
return;
};
if let Some(value) = call_global_bridge_method(
scope,
"__detachedSetAttribute",
&[args.this().into(), name.into(), parsed.value],
) {
rv.set(value);
}
}
pub(in crate::native_bridge) fn detached_set_attribute_ns_method_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
let Some(parsed) =
webidl::parse_args::<crate::native_bridge::element::SetAttributeNsArgs>(scope, &args)
else {
return;
};
let namespace = match parsed.namespace {
Some(namespace) => {
let Some(namespace) = v8_string(scope, &namespace) else {
return;
};
namespace.into()
}
None => v8::null(scope).into(),
};
let Some(name) = v8_string(scope, &parsed.qualified_name) else {
return;
};
if let Some(value) = call_global_bridge_method(
scope,
"__detachedSetAttributeNS",
&[args.this().into(), namespace, name.into(), parsed.value],
) {
rv.set(value);
}
}
detached_bridge_method_forwarder!(
detached_remove_attribute_method_callback,
"__detachedRemoveAttribute"
@@ -98,6 +98,8 @@ mod styles;
mod toggle_event;
mod trusted_types;
pub(in crate::native_bridge) use attributes::{SetAttributeArgs, SetAttributeNsArgs};
pub(crate) use script_execution::{
inline_script_source_for_execution, prepare_inline_classic_frame_script_job_for_execution,
};
@@ -22,22 +22,46 @@ struct AttributeNamespaceNameArgs {
#[derive(crate::webidl::WebIdlArgs)]
#[webidl(prefix = "Element setAttribute")]
struct SetAttributeArgs<'s> {
pub(in crate::native_bridge) struct SetAttributeArgs<'s> {
#[webidl(required)]
name: String,
#[webidl(required, converter = "raw")]
value: v8::Local<'s, v8::Value>,
pub(in crate::native_bridge) name: String,
#[webidl(required, with = set_attribute_value)]
pub(in crate::native_bridge) value: v8::Local<'s, v8::Value>,
}
#[derive(crate::webidl::WebIdlArgs)]
#[webidl(prefix = "Element setAttributeNS")]
struct SetAttributeNsArgs<'s> {
pub(in crate::native_bridge) struct SetAttributeNsArgs<'s> {
#[webidl(required, nullable)]
namespace: Option<String>,
pub(in crate::native_bridge) namespace: Option<String>,
#[webidl(required)]
qualified_name: String,
#[webidl(required, converter = "raw")]
value: v8::Local<'s, v8::Value>,
pub(in crate::native_bridge) qualified_name: String,
#[webidl(required, with = set_attribute_ns_value)]
pub(in crate::native_bridge) value: v8::Local<'s, v8::Value>,
}
fn set_attribute_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: &v8::FunctionCallbackArguments<'s>,
index: i32,
) -> Result<v8::Local<'s, v8::Value>, crate::webidl::WebIdlError> {
super::trusted_types::convert_trusted_attribute_value(
scope,
args.get(index),
super::TrustedAttributeSetter::SetAttribute.conversion_context(),
)
}
fn set_attribute_ns_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: &v8::FunctionCallbackArguments<'s>,
index: i32,
) -> Result<v8::Local<'s, v8::Value>, crate::webidl::WebIdlError> {
super::trusted_types::convert_trusted_attribute_value(
scope,
args.get(index),
super::TrustedAttributeSetter::SetAttributeNs.conversion_context(),
)
}
#[derive(crate::webidl::WebIdlArgs)]
@@ -56,7 +56,7 @@ pub(in crate::native_bridge) fn node_set_attribute_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
let Some((runtime_ptr, handle)) = element_method_receiver(scope, &args, "setAttribute") else {
let Some((runtime_ptr, _)) = element_method_receiver(scope, &args, "setAttribute") else {
rv.set_undefined();
return;
};
@@ -72,11 +72,15 @@ pub(in crate::native_bridge) fn node_set_attribute_callback<'s>(
throw_invalid_attribute_name(scope);
return;
}
// Argument conversion can adopt the receiver before name normalization
// and the Trusted Types policy lookup observe its node document.
let Some((runtime_ptr, handle)) = element_method_receiver(scope, &args, "setAttribute") else {
return;
};
let normalized_name = unsafe { &*runtime_ptr }
.dom_host()
.node(handle)
.and_then(Node::as_element)
.map(|element| element.normalized_attribute_name(&parsed.name))
.dom()
.normalized_attribute_name(handle, &parsed.name)
.unwrap_or_else(|| parsed.name.clone());
let Some(units) = trusted_attribute_value_string16(
scope,
@@ -90,7 +94,7 @@ pub(in crate::native_bridge) fn node_set_attribute_callback<'s>(
return;
};
let value = String::from_utf16_lossy(&units);
// Value conversion can adopt the receiver into a different native tree.
// The default policy can also adopt the receiver into a different tree.
let Some((runtime_ptr, handle)) = element_method_receiver(scope, &args, "setAttribute") else {
return;
};
@@ -158,7 +162,7 @@ pub(in crate::native_bridge) fn node_set_attribute_ns_callback<'s>(
return;
};
let value = String::from_utf16_lossy(&units);
// Conversion may adopt the element into another native document.
// The default policy may adopt the element into another native document.
let Some((runtime_ptr, handle)) = element_method_receiver(scope, &args, "setAttributeNS")
else {
return;
@@ -21,7 +21,7 @@ impl TrustedAttributeSetter {
}
}
fn conversion_context(self) -> crate::webidl::Context {
pub(super) fn conversion_context(self) -> crate::webidl::Context {
match self {
Self::SetAttribute => crate::webidl::Context::argument("Element setAttribute", 2),
Self::SetAttributeNs => crate::webidl::Context::argument("Element setAttributeNS", 3),
@@ -257,6 +257,22 @@ pub(in crate::native_bridge::element) fn trusted_script_url_sink_string<'s>(
)
}
// Convert the Web IDL union without consulting the node document or its
// Trusted Types policy. DOM name validation happens after this conversion.
pub(super) fn convert_trusted_attribute_value<'s>(
scope: &mut v8::PinScope<'s, '_>,
value: v8::Local<'s, v8::Value>,
context: crate::webidl::Context,
) -> Result<v8::Local<'s, v8::Value>, crate::webidl::WebIdlError> {
if value.is_string() || crate::context_bootstrap::trusted_type_kind(scope, value).is_some() {
return Ok(value);
}
let units = crate::webidl::convert::<crate::webidl::DomString16>(scope, value, context)?.0;
crate::util::v8_string_from_utf16_units(scope, &units)
.map(Into::into)
.ok_or_else(|| crate::webidl::WebIdlError::pending_exception(context))
}
pub(in crate::native_bridge) fn trusted_attribute_value_string16<'s>(
scope: &mut v8::PinScope<'s, '_>,
runtime_and_handle: Option<(*mut PageScriptHost, DomHandle)>,
@@ -265,24 +281,13 @@ pub(in crate::native_bridge) fn trusted_attribute_value_string16<'s>(
value: v8::Local<'s, v8::Value>,
setter: TrustedAttributeSetter,
) -> Option<Vec<u16>> {
// Web IDL converts the union before the DOM algorithm observes the node
// document. A user-defined toString can adopt the element into another realm.
let input_kind = crate::context_bootstrap::trusted_type_kind(scope, value);
let value = if input_kind.is_some() || value.is_string() {
value
} else {
let value = match crate::webidl::convert::<crate::webidl::DomString16>(
scope,
value,
setter.conversion_context(),
) {
Ok(value) => value.0,
Err(error) => {
crate::webidl::throw_error(scope, &error);
return None;
}
};
crate::util::v8_string_from_utf16_units(scope, &value)?.into()
let value = match convert_trusted_attribute_value(scope, value, setter.conversion_context()) {
Ok(value) => value,
Err(error) => {
crate::webidl::throw_error(scope, &error);
return None;
}
};
let sink = runtime_and_handle.and_then(|(runtime_ptr, handle)| {
let element = unsafe { &*runtime_ptr }
@@ -0,0 +1,145 @@
(async () => {
const checks = [];
const check = (name, actual, expected) => {
checks.push({name, passed: JSON.stringify(actual) === JSON.stringify(expected), actual, expected});
};
const capture = (action, sentinel) => {
try { action(); return null; }
catch (error) { return error === sentinel ? 'sentinel' : error.name; }
};
const frame = document.createElement('iframe');
document.body.appendChild(frame);
const popup = globalThis.__attributeOrderIncludePopup === false ? null : open('');
const realms = [['main', window], ['iframe', frame.contentWindow]];
if (popup) realms.push(['popup', popup]);
try {
for (const [realmName, w] of realms) {
const docs = [
['live', w.document],
['html', w.document.implementation.createHTMLDocument('')],
['xml', w.document.implementation.createDocument(null, 'root')],
['parsed', new w.DOMParser().parseFromString('<root/>', 'application/xml')],
];
for (const [docName, doc] of docs) {
for (const [method, namespace, name, expectedError] of [
['setAttribute', null, 'x y', 'InvalidCharacterError'],
['setAttributeNS', 'urn:test', 'x y', 'InvalidCharacterError'],
['setAttributeNS', null, 'p:name', 'NamespaceError'],
['setAttributeNS', 'urn:test', 'xml:name', 'NamespaceError'],
]) {
for (const shape of ['plain', 'throw', 'symbol', 'primitive-throw']) {
const element = doc.createElement('div');
const records = new w.MutationObserver(() => {});
records.observe(element, {attributes: true});
const log = [];
const sentinel = {};
const value = shape === 'symbol' ? Symbol('value') :
shape === 'primitive-throw' ? {[Symbol.toPrimitive](hint) {log.push(hint); throw sentinel;}} :
{toString() {log.push('value'); if (shape === 'throw') throw sentinel; return 'ok';}};
const args = method === 'setAttribute' ? [name, value] : [namespace, name, value];
const error = capture(() => element[method](...args), sentinel);
const expectedLog = shape === 'symbol' ? [] : [shape === 'primitive-throw' ? 'string' : 'value'];
const expected = shape === 'symbol' ? 'TypeError' : shape.includes('throw') ? 'sentinel' : expectedError;
const label = `${realmName}/${docName}/${method}/${name}/${shape}`;
check(label + '/order', [log, error], [expectedLog, expected]);
check(label + '/mutation', [element.attributes.length, records.takeRecords().length], [0, 0]);
records.disconnect();
}
}
for (const method of ['setAttribute', 'setAttributeNS']) {
const element = doc.createElement('div');
const ordinalCount = method === 'setAttribute' ? 2 : 3;
for (let stop = -1; stop < ordinalCount; stop++) {
const log = [], sentinel = {};
const texts = method === 'setAttribute' ? ['data-order', 'value'] : ['urn:test', 'p:order', 'value'];
const args = texts.map((text, index) => ({toString() {log.push(index); if (index === stop) throw sentinel; return text;}}));
const error = capture(() => element[method](...args), sentinel);
const label = `${realmName}/${docName}/${method}/argument-${stop}`;
check(label, [log, error], [Array.from({length: stop < 0 ? ordinalCount : stop + 1}, (_, index) => index), stop < 0 ? null : 'sentinel']);
}
for (let count = 0; count < ordinalCount; count++) {
const log = [];
const args = Array.from({length: count}, () => ({toString() {log.push('unexpected'); return 'x y';}}));
check(`${realmName}/${docName}/${method}/arity-${count}`, [capture(() => element[method](...args)), log], ['TypeError', []]);
}
for (const text of ['', '\ud800', 'a\udc00z', '\ud83d\ude00', 'nul\u0000value']) {
let conversions = 0;
const value = {toString() {conversions++; return text;}};
if (method === 'setAttribute') element[method]('data-units', value);
else element[method]('urn:test', 'p:units', value);
const actual = method === 'setAttribute' ? element.getAttribute('data-units') : element.getAttributeNS('urn:test', 'units');
check(`${realmName}/${docName}/${method}/UTF16-${JSON.stringify(text)}`, [actual, conversions], [text, 1]);
}
const invalidReceivers = [{}, Object.create(element), new w.Proxy(element, {})];
const revoked = w.Proxy.revocable(element, {}); revoked.revoke(); invalidReceivers.push(revoked.proxy);
for (let index = 0; index < invalidReceivers.length; index++) {
const log = [];
const arg = {toString() {log.push('unexpected'); return 'value';}};
const args = method === 'setAttribute' ? [arg, arg] : [arg, arg, arg];
const error = capture(() => w.Element.prototype[method].call(invalidReceivers[index], ...args));
check(`${realmName}/${docName}/${method}/receiver-${index}`, [error, log], ['TypeError', []]);
}
}
}
for (const method of ['setAttribute', 'setAttributeNS']) {
for (const intoHtml of [false, true]) {
const html = w.document.implementation.createHTMLDocument('');
const xml = w.document.implementation.createDocument(null, 'root');
const source = intoHtml ? xml : html, target = intoHtml ? html : xml;
const element = source.createElementNS('http://www.w3.org/1999/xhtml', 'div');
let calls = 0;
const value = {toString() {calls++; target.adoptNode(element); return '\ud800value';}};
if (method === 'setAttribute') element[method]('DATA-CASE', value);
else element[method](null, 'DATA-CASE', value);
const name = method === 'setAttribute' && intoHtml ? 'data-case' : 'DATA-CASE';
check(`${realmName}/${method}/adopt-${intoHtml}`, [element.ownerDocument === target, element.getAttributeNames(), element.getAttributeNodeNS(null, name)?.value, calls], [true, [name], '\ud800value', 1]);
}
}
const policy = w.trustedTypes.createPolicy('attribute-order', {
createHTML: value => value,
createScript: value => value,
createScriptURL: value => value,
});
for (const method of ['setAttribute', 'setAttributeNS']) {
for (const kind of ['HTML', 'Script', 'ScriptURL']) {
const trusted = policy['create' + kind]('trusted-\ud800');
Object.defineProperty(trusted, 'toString', {value() {throw new Error('author toString must not run');}});
const element = w.document.createElement('div');
const args = method === 'setAttribute' ? ['data-trusted', trusted] : ['urn:test', 'p:trusted', trusted];
check(`${realmName}/${method}/native-Trusted${kind}`, capture(() => element[method](...args)), null);
const actual = method === 'setAttribute' ? element.getAttribute('data-trusted') : element.getAttributeNS('urn:test', 'trusted');
check(`${realmName}/${method}/native-Trusted${kind}/value`, actual, kind === 'ScriptURL' ? 'trusted-\ufffd' : 'trusted-\ud800');
}
}
}
const strict = document.createElement('iframe');
const loaded = new Promise(resolve => strict.addEventListener('load', resolve, {once: true}));
strict.srcdoc = `<!doctype html><meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script'; trusted-types *"><body>`;
document.body.appendChild(strict);
await loaded;
try {
const w = strict.contentWindow;
const policyLog = [];
w.trustedTypes.createPolicy('default', {createScript(value) {policyLog.push(value); return value;}});
for (const ns of [false, true]) {
const element = w.document.createElement('div');
let calls = 0;
const value = {toString() {calls++; return 'return false;';}};
policyLog.length = 0;
const invalid = capture(() => ns ? element.setAttributeNS(null, 'p:onclick', value) : element.setAttribute('on click', value));
check(`default-policy/${ns}/invalid`, [invalid, calls, policyLog], [ns ? 'NamespaceError' : 'InvalidCharacterError', 1, []]);
policyLog.length = 0; calls = 0;
const valid = capture(() => ns ? element.setAttributeNS(null, 'onclick', value) : element.setAttribute('onclick', value));
check(`default-policy/${ns}/valid`, [valid, calls, policyLog, element.getAttribute('onclick')], [null, 1, ['return false;'], 'return false;']);
}
} finally { strict.remove(); }
} catch (error) {
checks.push({name: 'uncaught', passed: false, actual: String(error), expected: 'no exception'});
} finally { frame.remove(); if (popup) popup.close(); }
globalThis.__uiEventResults = {complete: true, includePopup: Boolean(popup), total: checks.length, passed: checks.filter(row => row.passed).length, checks};
return checks.every(row => row.passed);
})()
@@ -305,6 +305,35 @@ fn mutation_observer_observe_accepts_registered_native_proxy_targets_and_receive
})()"#).unwrap(), "true");
}
#[tokio::test(flavor = "current_thread")]
async fn attribute_argument_conversion_precedes_dom_validation_and_policy_lookup() {
let loader = static_http_loader(std::iter::empty::<String>());
let mut vm = new_page_task_executor_test_vm_with_loader(
"https://attribute-argument-order.test/",
&loader,
);
// Actual popup Pages are covered by the same fixture over CDP.
vm.exec("globalThis.__attributeOrderIncludePopup = false;", None)
.unwrap();
vm.exec(include_str!("attribute_argument_order.js"), None)
.unwrap();
advance_page_task_executor_until_eval_equals(
&mut vm,
&loader,
"String(globalThis.__uiEventResults?.complete === true)",
"true",
"attribute argument conversion order",
)
.await;
assert_eq!(
vm.eval("JSON.stringify(__uiEventResults.checks.filter(row => !row.passed))")
.unwrap(),
"[]",
);
assert_eq!(vm.eval("__uiEventResults.includePopup").unwrap(), "false");
assert_eq!(vm.eval("__uiEventResults.total").unwrap(), "532");
}
#[tokio::test(flavor = "current_thread")]
async fn attribute_mutation_and_custom_element_reaction_snapshots_preserve_utf16() {
let loader = static_http_loader(std::iter::empty::<String>());