Truly independent web browser
LibWeb: Implement TrustedHTMLParserOptions and its policy steps in Rust
Shannon Booth87d30018f62c
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/sanitizer.rs b/Libraries/LibWeb/Bindings/Rust/src/html/sanitizer.rsindex 4c8e7a3a9cf..ee17e692efd 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/sanitizer.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/sanitizer.rs@@ -5,8 +5,6 @@*/use core::cell::RefCell;-use core::ffi::c_void;-use std::sync::Arc;use ak::Utf16String;use libjs_rust::api::{Trace, Utf16View, Vm};@@ -20,7 +18,7 @@ use super::sanitizer_configuration::{remove_unsafe_from_sanitizer_config, sanitizer_configuration_is_valid, sanitizer_configuration_to_bindings,sanitizer_list_contains, sanitizer_list_remove,};-use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi};+use crate::bindings::interface::{Ref, Wrappable, allocate};use crate::bindings::{CallContext, WebIdlResult};#[derive(Clone, Copy, PartialEq, Eq)]@@ -95,6 +93,20 @@ pub(crate) enum SanitizerConfigOrSanitizerPresets {SanitizerPresets(SanitizerPresets),}+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum SanitizerOrSanitizerConfigOrSanitizerPresets {+ Sanitizer(Ref<Sanitizer>),+ SanitizerConfig(#[gc(untraced)] SanitizerConfig),+ SanitizerPresets(#[gc(untraced)] SanitizerPresets),+}++// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#sethtmlunsafeoptions+pub(crate) struct SetHTMLUnsafeOptions {+ pub(crate) sanitizer: Option<SanitizerOrSanitizerConfigOrSanitizerPresets>,+ pub(crate) run_scripts: bool,+}+// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#sanitizer#[derive(Trace)]#[gc(crate = libjs_rust)]@@ -788,15 +800,3 @@ impl Sanitizer {))}}--/// Copies the Sanitizer’s configuration.-///-/// # Safety-///-/// `sanitizer` must be a live Sanitizer cell.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn web_rust_sanitizer_configuration(sanitizer: *mut c_void) -> *mut c_void {- // SAFETY: The caller passes a live Sanitizer.- let sanitizer = unsafe { cell_from_abi::<Sanitizer>(sanitizer) };- Arc::into_raw(Arc::new(sanitizer.configuration())).cast_mut().cast()-}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/sanitizer_configuration.rs b/Libraries/LibWeb/Bindings/Rust/src/html/sanitizer_configuration.rsindex 7032e7d005c..838be9d410a 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/sanitizer_configuration.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/sanitizer_configuration.rs@@ -16,8 +16,9 @@ use super::sanitizer::{SanitizerElementNamespace, SanitizerElementNamespaceWithAttributes, SanitizerPI, SanitizerPresets,SanitizerProcessingInstruction,};-use crate::bindings::interface::{Ref, cell_from_abi, cell_into_abi};+use crate::bindings::interface::{Ref, cell_from_abi};use crate::bindings::{Exception, WebIdlResult};+use crate::trusted_types::trusted_html_parser_options::TrustedHTMLParserOptions;const HTML: &str = "http://www.w3.org/1999/xhtml";const SVG: &str = "http://www.w3.org/2000/svg";@@ -1407,19 +1408,13 @@ pub(crate) fn built_in_safe_default_configuration() -> &'static SanitizerConfigu})}-#[derive(libjs_rust::api::Trace)]-#[gc(crate = libjs_rust)]-pub(crate) enum SanitizerInput {- Sanitizer(Ref<Sanitizer>),- Config(#[gc(untraced)] SanitizerConfig),- Preset(#[gc(untraced)] SanitizerPresets),-}+pub(crate) type SanitizerInput = sanitizer::SanitizerOrSanitizerConfigOrSanitizerPresets;#[derive(libjs_rust::api::Trace)]#[gc(crate = libjs_rust)]pub(crate) enum SanitizerOptions {Dictionary(Option<SanitizerInput>),- Trusted(#[gc(untraced)] Option<Arc<SanitizerConfiguration>>),+ Trusted(Ref<TrustedHTMLParserOptions>),}// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#get-a-sanitizer-config-from-options@@ -1438,8 +1433,8 @@ pub(crate) fn get_a_sanitizer_config_from_options<'a>(let mut sanitizer_input = ConfigurationInput::Empty;let set_sanitizer_input = |sanitizer: &'a SanitizerInput| {match sanitizer {- SanitizerInput::Config(config) => ConfigurationInput::Dictionary(config),- SanitizerInput::Preset(preset) => {+ SanitizerInput::SanitizerConfig(config) => ConfigurationInput::Dictionary(config),+ SanitizerInput::SanitizerPresets(preset) => {// 1. Assert: sanitizerInput is "default".assert!(*preset == SanitizerPresets::Default);@@ -1451,18 +1446,18 @@ pub(crate) fn get_a_sanitizer_config_from_options<'a>(};// 2. If options is a TrustedHTMLParserOptions:- if let SanitizerOptions::Trusted(configuration) = options {+ if let SanitizerOptions::Trusted(trusted_options) = options {// 1. If options's sanitizer configuration is null:- if configuration.is_none() {+ let Some(configuration) = trusted_options.sanitizer_configuration() else {// 1. Assert: safe is false.assert!(!safe);// 2. Return null.return Ok(None);- }+ };// 2. Set sanitizerInput to options's sanitizer configuration.- sanitizer_input = ConfigurationInput::Configuration(configuration.as_ref().unwrap());+ sanitizer_input = ConfigurationInput::Configuration(configuration);}// 3. Otherwise, if options["sanitizer"] exists, then set sanitizerInput to options["sanitizer"].@@ -1535,7 +1530,7 @@ pub(crate) fn get_a_sanitizer_from_sanitizer_input(// 3. Let configuration be null.let configuration = match sanitizer_input {// 4. If sanitizerInput is a SanitizerPresets:- SanitizerInput::Preset(preset) => {+ SanitizerInput::SanitizerPresets(preset) => {// 1. Assert: sanitizerInput is "default".assert!(*preset == SanitizerPresets::Default);@@ -1549,7 +1544,7 @@ pub(crate) fn get_a_sanitizer_from_sanitizer_input(// 6. Otherwise, if sanitizerInput is a SanitizerConfig:// 1. Set configuration to sanitizerInput.- SanitizerInput::Config(config) => canonicalize_sanitizer_config(config),+ SanitizerInput::SanitizerConfig(config) => canonicalize_sanitizer_config(config),};// 7. Assert: configuration is not null.@@ -1561,7 +1556,7 @@ pub(crate) fn get_a_sanitizer_from_sanitizer_input(Ok(Sanitizer::create_with_configuration(vm, canonical_configuration))}-// NB: SanitizerInputKind in SanitizerConfiguration.cpp matches this.+// NB: SanitizerInputKind in SanitizerConfiguration.h matches this.#[derive(Clone, Copy)]#[repr(u8)]#[allow(dead_code, reason = "C++ constructs the variants")]@@ -1728,12 +1723,12 @@ impl ConfigInputAbi<'_> {}}-unsafe fn input_from_abi(kind: SanitizerInputKind, input: *const c_void) -> SanitizerInput {+pub(crate) unsafe fn input_from_abi(kind: SanitizerInputKind, input: *const c_void) -> SanitizerInput {match kind {- SanitizerInputKind::DefaultPreset => SanitizerInput::Preset(SanitizerPresets::Default),+ SanitizerInputKind::DefaultPreset => SanitizerInput::SanitizerPresets(SanitizerPresets::Default),// SAFETY: C++ passes a live view whose buffers and strings outlive this conversion.SanitizerInputKind::Config => {- SanitizerInput::Config(unsafe { (&*input.cast::<ConfigInputAbi<'_>>()).config() })+ SanitizerInput::SanitizerConfig(unsafe { (&*input.cast::<ConfigInputAbi<'_>>()).config() })}// SAFETY: C++ passes a live Sanitizer cell.SanitizerInputKind::Sanitizer => SanitizerInput::Sanitizer(unsafe { cell_from_abi(input.cast_mut()) }),@@ -1771,7 +1766,7 @@ pub unsafe extern "C" fn web_rust_sanitizer_configuration_release(configuration:////// # Safety///-/// `input` must be the live configuration view, Sanitizer cell, or snapshot identified by `kind`.+/// `input` must be the live configuration view, Sanitizer cell, or TrustedHTMLParserOptions cell identified by `kind`.#[unsafe(no_mangle)]pub unsafe extern "C" fn web_rust_get_a_sanitizer_config_from_options(kind: SanitizerInputKind,@@ -1780,19 +1775,8 @@ pub unsafe extern "C" fn web_rust_get_a_sanitizer_config_from_options(out_configuration: &mut *const SanitizerConfiguration,) -> SanitizerConfigurationStatus {let options = match kind {- SanitizerInputKind::TrustedOptions => {- let snapshot = if input.is_null() {- None- } else {- let pointer = input.cast::<SanitizerConfiguration>();- // SAFETY: C++ holds a live Arc snapshot. This acquires a reference for the options.- unsafe {- Arc::increment_strong_count(pointer);- Some(Arc::from_raw(pointer))- }- };- SanitizerOptions::Trusted(snapshot)- }+ // SAFETY: C++ passes a live TrustedHTMLParserOptions cell.+ SanitizerInputKind::TrustedOptions => SanitizerOptions::Trusted(unsafe { cell_from_abi(input.cast_mut()) }),SanitizerInputKind::None => SanitizerOptions::Dictionary(None),// SAFETY: The caller lends the indicated input until this function returns._ => SanitizerOptions::Dictionary(Some(unsafe { input_from_abi(kind, input) })),@@ -1807,25 +1791,6 @@ pub unsafe extern "C" fn web_rust_get_a_sanitizer_config_from_options(}}-/// Obtains a Sanitizer from converted input.-///-/// # Safety-///-/// `input` must be the live configuration view or Sanitizer cell identified by `kind`.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn web_rust_get_a_sanitizer_from_sanitizer_input(- vm: &libjs_rust::api::Vm,- kind: SanitizerInputKind,- input: *const c_void,-) -> *mut c_void {- // SAFETY: The caller lends the indicated input until this function returns.- let input = unsafe { input_from_abi(kind, input) };- match get_a_sanitizer_from_sanitizer_input(vm, &input) {- Ok(sanitizer) => cell_into_abi(sanitizer),- Err(_) => core::ptr::null_mut(),- }-}-#[repr(C)]pub(crate) struct StringViewAbi<'a> {latin1: ak::Span<'a, u8>,diff --git a/Libraries/LibWeb/Bindings/Rust/src/trusted_types/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/trusted_types/mod.rsindex c23a9929092..9f406cc854d 100644--- a/Libraries/LibWeb/Bindings/Rust/src/trusted_types/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/trusted_types/mod.rs@@ -8,6 +8,7 @@pub(crate) mod require_trusted_types_for_directive;pub(crate) mod trusted_html;+pub(crate) mod trusted_html_parser_options;pub(crate) mod trusted_script;pub(crate) mod trusted_script_url;pub(crate) mod trusted_type_policy;diff --git a/Libraries/LibWeb/Bindings/Rust/src/trusted_types/trusted_html_parser_options.rs b/Libraries/LibWeb/Bindings/Rust/src/trusted_types/trusted_html_parser_options.rsnew file mode 100644index 00000000000..55a6ba0ae13--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/trusted_types/trusted_html_parser_options.rs@@ -0,0 +1,67 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! TrustedHTMLParserOptions, https://w3c.github.io/trusted-types/dist/spec/#trusted-html-parser-options++use core::ffi::c_void;++use libjs_rust::api::{Gc, Realm, Trace, Vm};++use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi};+use crate::html::sanitizer_configuration::SanitizerConfiguration;++/// https://w3c.github.io/trusted-types/dist/spec/#trusted-html-parser-options+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct TrustedHTMLParserOptions {+ realm: Gc<Realm>,+ // TrustedHTMLParserOptions objects have an associated boolean runScripts and an associated SanitizerConfig-or-null+ // sanitizer configuration. These values are set when the object is created, and will never change during its+ // lifetime.+ #[gc(untraced)]+ sanitizer_configuration: Option<SanitizerConfiguration>,+ run_scripts: bool,+}++impl Wrappable for TrustedHTMLParserOptions {+ fn relevant_realm(&self) -> Option<Gc<Realm>> {+ Some(self.realm)+ }+}++impl TrustedHTMLParserOptions {+ pub(crate) fn create(+ vm: &Vm,+ realm: Gc<Realm>,+ sanitizer_configuration: Option<SanitizerConfiguration>,+ run_scripts: bool,+ ) -> Ref<Self> {+ allocate(vm, |_| Self {+ realm,+ sanitizer_configuration,+ run_scripts,+ })+ }++ pub(crate) fn sanitizer_configuration(&self) -> Option<&SanitizerConfiguration> {+ self.sanitizer_configuration.as_ref()+ }++ pub(crate) fn run_scripts(&self) -> bool {+ self.run_scripts+ }+}++/// The runScripts of the TrustedHTMLParserOptions.+///+/// # Safety+///+/// `cell` must be the live cell of a TrustedHTMLParserOptions.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_trusted_types_trusted_html_parser_options_run_scripts(cell: *mut c_void) -> bool {+ // SAFETY: The caller passes a live cell.+ unsafe { cell_from_abi::<TrustedHTMLParserOptions>(cell) }.run_scripts()+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/trusted_types/trusted_type_policy.rs b/Libraries/LibWeb/Bindings/Rust/src/trusted_types/trusted_type_policy.rsindex 0438514a452..1c1747cbbcf 100644--- a/Libraries/LibWeb/Bindings/Rust/src/trusted_types/trusted_type_policy.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/trusted_types/trusted_type_policy.rs@@ -12,35 +12,31 @@ use core::ptr::NonNull;use ak::Utf16String;use libjs_rust::api::{- Gc, MarkedVec, Object, PrimitiveString, RawNativeFunctionResult, Realm, Trace, Utf16View, Value, Vm,- utf16_formatted,+ Gc, MarkedVec, Object, PrimitiveString, PropertyKey, Realm, Trace, Utf16View, Value, Vm, utf16_formatted,};use crate::bindings::callback::CallbackFunction;-use crate::bindings::conversions::{CppDictionary, CppInterface, to_dom_string, to_usv_string};-use crate::bindings::interface::{Ref, Wrappable, cell_from_abi, cell_into_abi};+#[cfg(web_idl_bindings)]+use crate::bindings::conversions::FromJs;+use crate::bindings::conversions::{to_dom_string, to_usv_string};+use crate::bindings::interface::{Ref, Wrappable, cell_from_abi, cell_into_abi, create_dictionary_object, wrap};use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::html::sanitizer::SetHTMLUnsafeOptions;+use crate::html::sanitizer_configuration::{+ SanitizerConfiguration, SanitizerInput, SanitizerInputKind, get_a_sanitizer_from_sanitizer_input, input_from_abi,+};use crate::html::window_or_worker_global_scope::trusted_types;use crate::trusted_types::require_trusted_types_for_directive::{does_sink_require_trusted_types, should_sink_type_mismatch_violation_be_blocked_by_content_security_policy,};use crate::trusted_types::trusted_html::TrustedHTML;+use crate::trusted_types::trusted_html_parser_options::TrustedHTMLParserOptions;use crate::trusted_types::trusted_script::TrustedScript;use crate::trusted_types::trusted_script_url::TrustedScriptURL;use crate::trusted_types::trusted_type_policy_factory::{HTML_NAMESPACE, SVG_NAMESPACE, get_trusted_type_data_for_attribute,};-unsafe extern "C" {- /// https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicy-createparseroptions- fn web_trusted_types_create_parser_options(- global: *mut c_void,- create_parser_options: *mut c_void,- options: *mut c_void,- arguments: ak::Span<'_, Value>,- ) -> RawNativeFunctionResult;-}-/// https://w3c.github.io/trusted-types/dist/spec/#trusted-type-policy-optionspub(crate) struct TrustedTypePolicyOptions {pub(crate) create_html: Option<CallbackFunction>,@@ -237,27 +233,56 @@ impl TrustedTypePolicy {// https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicy-createparseroptionspub(crate) fn create_parser_options(&self,- _: &mut CallContext,- options: CppDictionary,+ cx: &mut CallContext,+ options: SetHTMLUnsafeOptions,arguments: MarkedVec<'_, Value>,- ) -> WebIdlResult<CppInterface> {- let global = self.realm.global_object();- let callback = self- .create_parser_options- .as_ref()- .map_or(core::ptr::null_mut(), CallbackFunction::as_ptr);- // SAFETY: The global object, the callback, the options and the arguments are live for the call.- let wrapper = unsafe {- web_trusted_types_create_parser_options(- global.as_ptr().cast(),- callback,- options.as_ptr(),- ak::Span::new(&arguments.values()),- )- }- .into_completion()?;- // SAFETY: LibWeb returns the wrapper of a TrustedHTMLParserOptions.- Ok(unsafe { CppInterface::from_wrapper(wrapper.as_object()) })+ ) -> WebIdlResult<Ref<TrustedHTMLParserOptions>> {+ let vm = cx.vm();++ // Returns the result of executing the create a trusted type algorithm, with the following arguments:+ // policy: this value+ // trustedTypeName: "TrustedHTMLParserOptions"+ // value: options+ // arguments: arguments+ // https://w3c.github.io/trusted-types/dist/spec/#create-a-trusted-type-algorithm+ // 1. Let policyValue be the result of executing get trusted type policy value with the same arguments as this+ // algorithm and additionally true as throwIfMissing.+ // 2. If the algorithm threw an error, rethrow the error and abort the following steps.+ let policy_value = to_optional_set_html_unsafe_options(+ vm,+ get_parser_options_policy_value(+ vm,+ self.realm,+ self.create_parser_options.as_ref(),+ &options,+ &arguments.values(),+ true,+ )?,+ )?;++ // 3. If trustedTypeName is "TrustedHTMLParserOptions":+ // 1. If policyValue is null, throw a TypeError.+ // NOTE: Returning null from a named policy's createParserOptions callback throws a TypeError here, whereas+ // returning null or undefined from createHTML, createScript, or createScriptURL yields the empty string.+ let Some(policy_value) = policy_value else {+ return Err(Exception::type_error("createParserOptions returned null"));+ };++ // 2. Let sanitizerConfig be the result of getting a sanitizer configuration from policy's relevant realm and+ // policyValue.+ let sanitizer_config = get_a_sanitizer_config_copy_from_dictionary(vm, &policy_value)?;++ // 3. Let runScripts be policyValue["runScripts"] with default false.+ let run_scripts = policy_value.run_scripts;++ // 4. Return a new instance of TrustedHTMLParserOptions in policy's relevant realm with its sanitizer configuration+ // set to sanitizerConfig, and its runScripts set to runScripts.+ Ok(TrustedHTMLParserOptions::create(+ vm,+ self.realm,+ sanitizer_config,+ run_scripts,+ ))}// https://w3c.github.io/trusted-types/dist/spec/#create-a-trusted-type-algorithm@@ -331,6 +356,268 @@ impl TrustedTypePolicy {}}+// https://w3c.github.io/trusted-types/dist/spec/#create-a-parser-options-callback-argument+fn create_a_parser_options_callback_argument(+ vm: &Vm,+ realm: Gc<Realm>,+ dictionary: &SetHTMLUnsafeOptions,+) -> WebIdlResult<Value> {+ // 1. Let runScriptsInput be dictionary["runScripts"], with default false.+ let run_scripts_input = dictionary.run_scripts;++ // 2. Let argument be the ordered map «[ "runScripts" → runScriptsInput ]».+ let cx = CallContext::new(vm, realm);+ let argument = create_dictionary_object(&cx);+ argument.create_data_property(+ vm,+ &PropertyKey::from_utf8("runScripts"),+ Value::from_bool(run_scripts_input),+ None,+ None,+ )?;++ // 3. Let sanitizerInput be the result of getting a sanitizer from realm and dictionary.+ // https://w3c.github.io/trusted-types/dist/spec/#get-a-sanitizer-from-dictionary+ // 1. Let sanitizerInput be dictionary["sanitizer"], defaulting to null.+ // 2. If sanitizerInput is null, return null.+ // 4. If sanitizerInput is not null, set argument["sanitizer"] to sanitizerInput.+ if let Some(sanitizer_input) = &dictionary.sanitizer {+ let sanitizer = get_a_sanitizer_from_sanitizer_input(vm, sanitizer_input)?;+ argument.create_data_property(+ vm,+ &PropertyKey::from_utf8("sanitizer"),+ Value::from_object(wrap(&cx, sanitizer)),+ None,+ None,+ )?;+ }++ // 5. Return argument.+ Ok(Value::from_object(argument))+}++// NB: Converts the return value of a CreateParserOptionsCallback, whose return type is SetHTMLUnsafeOptions?, to an+// IDL value.+fn to_optional_set_html_unsafe_options(vm: &Vm, value: Value) -> WebIdlResult<Option<SetHTMLUnsafeOptions>> {+ if value.is_nullish() {+ return Ok(None);+ }+ #[cfg(web_idl_bindings)]+ return Ok(Some(SetHTMLUnsafeOptions::from_js(vm, value)?));+ #[cfg(not(web_idl_bindings))]+ {+ let _ = vm;+ unreachable!("converting to SetHTMLUnsafeOptions requires the generated bindings")+ }+}++// https://w3c.github.io/trusted-types/dist/spec/#get-a-sanitizer-config-copy-from-dictionary+fn get_a_sanitizer_config_copy_from_dictionary(+ vm: &Vm,+ dictionary: &SetHTMLUnsafeOptions,+) -> WebIdlResult<Option<SanitizerConfiguration>> {+ // 1. Let sanitizer be the result of getting a sanitizer from realm and dictionary.+ // 2. If sanitizer is null, return null.+ let Some(sanitizer_input) = &dictionary.sanitizer else {+ return Ok(None);+ };+ let sanitizer = get_a_sanitizer_from_sanitizer_input(vm, sanitizer_input)?;++ // 3. Return sanitizer's configuration.+ Ok(Some(sanitizer.configuration()))+}++// https://w3c.github.io/trusted-types/dist/spec/#get-trusted-type-policy-value+// NB: The steps for the "TrustedHTMLParserOptions" type name.+fn get_parser_options_policy_value(+ vm: &Vm,+ realm: Gc<Realm>,+ function: Option<&CallbackFunction>,+ value: &SetHTMLUnsafeOptions,+ arguments: &[Value],+ throw_if_missing: bool,+) -> WebIdlResult<Value> {+ // 1. Let functionName be a function name for the given trustedTypeName, based on the following table:+ // 2. Let function be policy's options[functionName].+ // NB: The caller passes function.++ // 3. If function is null, then:+ let Some(function) = function else {+ // 1. If throwIfMissing throw a TypeError.+ if throw_if_missing {+ return Err(Exception::type_error(+ "Trying to create a trusted type without a callback",+ ));+ }++ // 2. Else return null.+ return Ok(Value::NULL);+ };++ // 4. If trustedTypeName is "TrustedHTMLParserOptions":+ // 1. Set value to the result of creating a parser options callback argument given policy's relevant realm and+ // value.+ let argument = create_a_parser_options_callback_argument(vm, realm, value)?;++ // 5. Let args be « value ».+ let args = MarkedVec::new(vm);+ args.push(argument);++ // 6. Append each item in arguments to args.+ args.extend_from_slice(arguments);++ // 7. Let policyValue be the result of invoking function with args and "rethrow".+ // 8. Return policyValue.+ Ok(function.invoke(None, &args.values())?)+}++// NB: A SetHTMLUnsafeOptions or ParseHTMLUnsafeOptions options needs vetting if options["runScripts"] exists and is+// true, or if options["sanitizer"] exists and is not an empty SanitizerConfig.+// https://w3c.github.io/trusted-types/dist/spec/#parser-options-need-vetting+fn needs_vetting(options: &SetHTMLUnsafeOptions) -> bool {+ if options.run_scripts {+ return true;+ }+ let Some(sanitizer) = &options.sanitizer else {+ return false;+ };+ // NOTE: An empty SanitizerConfig does not change the parsed markup.+ let SanitizerInput::SanitizerConfig(config) = sanitizer else {+ return true;+ };+ config.elements.is_some()+ || config.remove_elements.is_some()+ || config.replace_with_children_elements.is_some()+ || config.processing_instructions.is_some()+ || config.remove_processing_instructions.is_some()+ || config.attributes.is_some()+ || config.remove_attributes.is_some()+ || config.comments.is_some()+ || config.data_attributes.is_some()+ || config.javascript_ur_ls.is_some()+}++// https://w3c.github.io/trusted-types/dist/spec/#get-trusted-type-compliant-parser-options+// NB: Returns None when the algorithm returns input, which the caller holds.+pub(crate) fn get_trusted_type_compliant_parser_options(+ vm: &Vm,+ global: Gc<Object>,+ input: &SetHTMLUnsafeOptions,+ throw_if_missing: bool,+ sink: &Utf16String,+ options_from_author: bool,+) -> WebIdlResult<Option<Ref<TrustedHTMLParserOptions>>> {+ // 1. If input is an instance of TrustedHTMLParserOptions, return input.+ // NB: The caller returns such an input itself.++ // 2. Let requireTrustedTypes be the result of executing Does sink type require trusted types? algorithm, passing+ // global, "script", and true.+ let script = Utf16String::from_utf8(SCRIPT_SINK_GROUP);+ let require_trusted_types = does_sink_require_trusted_types(global, &script, true);++ // 3. If requireTrustedTypes is false, return input.+ if !require_trusted_types {+ return Ok(None);+ }++ // 4. Let requirePolicy be throwIfMissing.+ let mut require_policy = throw_if_missing;++ // 5. If optionsFromAuthor is true and input needs vetting, set requirePolicy to true.+ if options_from_author && needs_vetting(input) {+ require_policy = true;+ }++ let reject_unless_allowed = || -> WebIdlResult<Option<Ref<TrustedHTMLParserOptions>>> {+ // 1. Let disposition be the result of executing should sink type mismatch violation be blocked by content+ // security policy? algorithm, passing global, sink, "script", and the empty string as source.+ let blocked = should_sink_type_mismatch_violation_be_blocked_by_content_security_policy(+ global,+ sink,+ &script,+ &Utf16String::default(),+ );++ // 2. If disposition is "Allowed", return input.+ if !blocked {+ return Ok(None);+ }++ // 3. Throw a TypeError.+ Err(Exception::TypeError(utf16_formatted(+ "Sink {} requires parser options vetted by a Trusted Types policy",+ &[sink],+ )))+ };++ // 6. Let defaultPolicy be the value of global's trusted type policy factory's default policy.+ // 7. If defaultPolicy is null:+ let Some(default_policy) = trusted_types(global).default_policy_value() else {+ // 1. If requirePolicy is true:+ if require_policy {+ return reject_unless_allowed();+ }++ // 2. Return input.+ return Ok(None);+ };++ // 8. Let function be defaultPolicy's options["createParserOptions"].+ let function = default_policy.create_parser_options_callback();++ // 9. If function is null:+ if function.is_none() {+ // 1. If requirePolicy is true:+ if require_policy {+ return reject_unless_allowed();+ }++ // 2. Return input.+ return Ok(None);+ }++ // 10. Let argument be the result of creating a parser options callback argument given global's relevant realm and+ // input.+ // 11. Let policyValue be the result of invoking function with « argument, "TrustedHTMLParserOptions", sink » and+ // "rethrow".+ // 12. If the algorithm threw an error, rethrow the error and abort the following steps.+ let realm = global.shape().realm();+ let arguments = [+ Value::from_string(PrimitiveString::create(+ vm,+ Utf16String::from_ascii(b"TrustedHTMLParserOptions"),+ )),+ Value::from_string(PrimitiveString::create(vm, sink.clone())),+ ];+ let policy_value = to_optional_set_html_unsafe_options(+ vm,+ get_parser_options_policy_value(vm, realm, function, input, &arguments, true)?,+ )?;++ // 13. If policyValue is null or undefined:+ let Some(policy_value) = policy_value else {+ // NOTE: This step assures that the default policy rejection will be reported, but ignored in a report-only+ // mode.+ return reject_unless_allowed();+ };++ // 14. Let runScripts be policyValue["runScripts"], with default false.+ // NOTE: When invoked as a default policy, the createParserOptions callback determines the final script execution+ // behavior, overriding the caller's requested runScripts option.+ let run_scripts = policy_value.run_scripts;++ // 15. Return a new TrustedHTMLParserOptions in global's relevant realm whose sanitizer configuration is set to the+ // result of getting a sanitizer configuration from global's relevant realm and policyValue, and whose+ // runScripts is set to runScripts.+ let sanitizer_config = get_a_sanitizer_config_copy_from_dictionary(vm, &policy_value)?;+ Ok(Some(TrustedHTMLParserOptions::create(+ vm,+ realm,+ sanitizer_config,+ run_scripts,+ )))+}+// https://w3c.github.io/trusted-types/dist/spec/#process-value-with-a-default-policy-algorithmpub(crate) fn process_value_with_a_default_policy(vm: &Vm,@@ -716,17 +1003,74 @@ pub unsafe extern "C" fn web_rust_trusted_types_process_value_with_a_default_pol}}-/// The policy's options["createParserOptions"], or null.+/// The parser options that C++ lends: the runScripts and the sanitizer input of a SetHTMLUnsafeOptions or+/// ParseHTMLUnsafeOptions dictionary.+#[repr(C)]+pub(crate) struct ParserOptionsInputAbi {+ run_scripts: bool,+ sanitizer_kind: SanitizerInputKind,+ sanitizer: *const c_void,+}++// NB: CompliantParserOptionsResult in TrustedTypePolicy.cpp matches this.+#[repr(u8)]+pub(crate) enum CompliantParserOptionsResultAbi {+ Input,+ TrustedHTMLParserOptions,+ Thrown,+ TypeError,+}++/// https://w3c.github.io/trusted-types/dist/spec/#get-trusted-type-compliant-parser-options////// # Safety///-/// `policy` must be the live cell of a TrustedTypePolicy.+/// `vm` must be the live VM and `global` a live global object. `input` and what it points to must be live for the call,+/// `sink` a raw string that C++ hands over, and `options`, `message` and `exception` writable.#[unsafe(no_mangle)]-pub unsafe extern "C" fn web_rust_trusted_types_trusted_type_policy_create_parser_options(- policy: *mut c_void,-) -> *mut c_void {- // SAFETY: The caller passes a live cell.- unsafe { cell_from_abi::<TrustedTypePolicy>(policy) }- .create_parser_options_callback()- .map_or(core::ptr::null_mut(), CallbackFunction::as_ptr)+pub unsafe extern "C" fn web_rust_trusted_types_get_trusted_type_compliant_parser_options(+ vm: *mut c_void,+ global: *mut c_void,+ input: &ParserOptionsInputAbi,+ throw_if_missing: bool,+ sink: usize,+ options_from_author: bool,+ options: &mut *mut c_void,+ message: &mut usize,+ exception: &mut u64,+) -> CompliantParserOptionsResultAbi {+ // SAFETY: The caller passes the live VM, a live global object and a sink string it hands over.+ let (vm, global, sink) = unsafe {+ (+ &*vm.cast::<Vm>(),+ Gc::from_non_null(NonNull::new(global.cast::<Object>()).expect("C++ passes a global object")),+ Utf16String::from_raw_owned(sink),+ )+ };+ let sanitizer = match input.sanitizer_kind {+ SanitizerInputKind::None => None,+ // SAFETY: C++ lends the sanitizer input of the kind for the call.+ kind => Some(unsafe { input_from_abi(kind, input.sanitizer) }),+ };+ // NB: A ParseHTMLUnsafeOptions has no runScripts member, which these algorithms read with default false.+ let input = SetHTMLUnsafeOptions {+ sanitizer,+ run_scripts: input.run_scripts,+ };+ match get_trusted_type_compliant_parser_options(vm, global, &input, throw_if_missing, &sink, options_from_author) {+ Ok(None) => CompliantParserOptionsResultAbi::Input,+ Ok(Some(trusted_options)) => {+ *options = cell_into_abi(trusted_options);+ CompliantParserOptionsResultAbi::TrustedHTMLParserOptions+ }+ Err(Exception::Thrown(throw)) => {+ *exception = throw.value().to_raw();+ CompliantParserOptionsResultAbi::Thrown+ }+ Err(Exception::TypeError(type_error)) => {+ *message = type_error.into_raw();+ CompliantParserOptionsResultAbi::TypeError+ }+ Err(_) => unreachable!("the Trusted Types algorithms throw only TypeErrors"),+ }}diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 484185c6df6..3cc455ca18e 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -564,7 +564,6 @@ set(SOURCESHTML/RadioNodeList.cppHTML/RemoteNavigable.cppHTML/RemoteWindow.cpp- HTML/Sanitizer.cppHTML/SanitizerConfiguration.cppHTML/Scripting/Agent.cppHTML/Scripting/ClassicScript.cppdiff --git a/Libraries/LibWeb/HTML/Sanitizer.cpp b/Libraries/LibWeb/HTML/Sanitizer.cppdeleted file mode 100644index cc0010ec0d4..00000000000--- a/Libraries/LibWeb/HTML/Sanitizer.cpp+++ /dev/null@@ -1,18 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibWeb/HTML/Sanitizer.h>--namespace Web::HTML {--extern "C" void const* web_rust_sanitizer_configuration(Sanitizer const*);--SanitizerConfiguration Sanitizer::configuration() const-{- return SanitizerConfiguration { web_rust_sanitizer_configuration(this) };-}--}diff --git a/Libraries/LibWeb/HTML/Sanitizer.h b/Libraries/LibWeb/HTML/Sanitizer.hindex 969ff2173fe..1cc2bda8638 100644--- a/Libraries/LibWeb/HTML/Sanitizer.h+++ b/Libraries/LibWeb/HTML/Sanitizer.h@@ -15,9 +15,6 @@ namespace Web::HTML {class WEB_API Sanitizer final : public Bindings::RustInterfaceCell {WEB_RUST_INTERFACE(Sanitizer, sanitizer)--public:- SanitizerConfiguration configuration() const;};}diff --git a/Libraries/LibWeb/HTML/Sanitizer.idl b/Libraries/LibWeb/HTML/Sanitizer.idlindex 818b7efa960..63f8f146321 100644--- a/Libraries/LibWeb/HTML/Sanitizer.idl+++ b/Libraries/LibWeb/HTML/Sanitizer.idl@@ -7,7 +7,6 @@ dictionary SetHTMLOptions {};// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#sethtmlunsafeoptions-[ImplementedIn=Cpp]dictionary SetHTMLUnsafeOptions {(Sanitizer or SanitizerConfig or SanitizerPresets) sanitizer;boolean runScripts = false;diff --git a/Libraries/LibWeb/HTML/SanitizerConfiguration.cpp b/Libraries/LibWeb/HTML/SanitizerConfiguration.cppindex aee87116b28..e7a2035c354 100644--- a/Libraries/LibWeb/HTML/SanitizerConfiguration.cpp+++ b/Libraries/LibWeb/HTML/SanitizerConfiguration.cpp@@ -20,14 +20,6 @@namespace Web::HTML {// NB: These match the enums of the same names in sanitizer_configuration.rs.-enum class SanitizerInputKind : u8 {- None,- DefaultPreset,- Config,- Sanitizer,- TrustedOptions,-};-enum class SanitizerConfigurationStatus : u8 {Null,Configuration,@@ -80,7 +72,6 @@ extern "C" {void web_rust_sanitizer_configuration_retain(void const*);void web_rust_sanitizer_configuration_release(void const*);SanitizerConfigurationStatus web_rust_get_a_sanitizer_config_from_options(SanitizerInputKind, void const* input, bool safe, void const** out_configuration);-Sanitizer* web_rust_get_a_sanitizer_from_sanitizer_input(JSVM*, SanitizerInputKind, void const* input);bool web_rust_sanitizer_config_allows_comments(void const*);bool web_rust_sanitizer_config_allows_processing_instruction_target(void const*, SanitizerStringView);SanitizerAction web_rust_sanitizer_action_for_element_name(void const*, FlatPtr name, FlatPtr namespace_);@@ -219,10 +210,9 @@ static auto with_sanitizer_input(SanitizerInput const& input, Function function)});}-// NB: The Rust implementation throws this error itself when script calls the Sanitizer constructor.-static WebIDL::SimpleException invalid_configuration_error()+void lend_sanitizer_input(SanitizerInput const& input, Function<void(SanitizerInputKind, void const*)> const& function){- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Sanitizer configuration is not valid"_utf16 };+ with_sanitizer_input(input, [&](SanitizerInputKind kind, void const* data) { function(kind, data); });}WebIDL::ExceptionOr<Optional<SanitizerConfiguration>> get_a_sanitizer_config_from_options(SanitizerOptions const& options, SanitizerSafety safety)@@ -235,14 +225,13 @@ WebIDL::ExceptionOr<Optional<SanitizerConfiguration>> get_a_sanitizer_config_frocase SanitizerConfigurationStatus::Configuration:return Optional<SanitizerConfiguration> { SanitizerConfiguration { configuration } };case SanitizerConfigurationStatus::Invalid:- return invalid_configuration_error();+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Sanitizer configuration is not valid"_utf16 };}VERIFY_NOT_REACHED();};return options.visit([&](GC::Ref<TrustedTypes::TrustedHTMLParserOptions> trusted_options) {- auto const& configuration = trusted_options->sanitizer_configuration();- return get_configuration(SanitizerInputKind::TrustedOptions, configuration.has_value() ? configuration->rust_configuration() : nullptr);+ return get_configuration(SanitizerInputKind::TrustedOptions, trusted_options.ptr());},[&](Bindings::SetHTMLOptions const* dictionary) {return with_sanitizer_input(dictionary->sanitizer, get_configuration);@@ -254,16 +243,6 @@ WebIDL::ExceptionOr<Optional<SanitizerConfiguration>> get_a_sanitizer_config_fro});}-WebIDL::ExceptionOr<GC::Ref<Sanitizer>> get_a_sanitizer_from_sanitizer_input(SanitizerInput const& input)-{- return with_sanitizer_input(input, [](SanitizerInputKind kind, void const* data) -> WebIDL::ExceptionOr<GC::Ref<Sanitizer>> {- auto* sanitizer = web_rust_get_a_sanitizer_from_sanitizer_input(JS::HostABI::vm_to_abi(JS::VM::the()), kind, data);- if (!sanitizer)- return invalid_configuration_error();- return GC::Ref { *sanitizer };- });-}-static SanitizerStringView to_string_view(Utf16View value){if (value.has_latin1_storage())diff --git a/Libraries/LibWeb/HTML/SanitizerConfiguration.h b/Libraries/LibWeb/HTML/SanitizerConfiguration.hindex 267be2525f1..1180627b036 100644--- a/Libraries/LibWeb/HTML/SanitizerConfiguration.h+++ b/Libraries/LibWeb/HTML/SanitizerConfiguration.h@@ -54,6 +54,15 @@ WEB_API bool sanitizer_config_allows_processing_instruction_target(Utf16View conWEB_API SanitizerAction sanitizer_action_for_element_name(Utf16FlyString const& local_name, Optional<Utf16FlyString> const& namespace_, SanitizerConfiguration const&);WEB_API bool sanitizer_config_allows_attribute(Utf16FlyString const& local_name, Optional<Utf16FlyString> const& namespace_, Utf16View const& value, Utf16FlyString const& element_local_name, Optional<Utf16FlyString> const& element_namespace, SanitizerConfiguration const&);+// NB: SanitizerInputKind in sanitizer_configuration.rs matches this.+enum class SanitizerInputKind : u8 {+ None,+ DefaultPreset,+ Config,+ Sanitizer,+ TrustedOptions,+};+enum class SanitizerSafety : u8 {Unsafe,Safe,@@ -64,6 +73,8 @@ using SanitizerOptions = Variant<Bindings::SetHTMLOptions const*, Bindings::SetHWEB_API WebIDL::ExceptionOr<Optional<SanitizerConfiguration>> get_a_sanitizer_config_from_options(SanitizerOptions const&, SanitizerSafety);using SanitizerInput = Variant<GC::Ref<Sanitizer>, Bindings::SanitizerConfig, Bindings::SanitizerPresets>;-WebIDL::ExceptionOr<GC::Ref<Sanitizer>> get_a_sanitizer_from_sanitizer_input(SanitizerInput const&);++// NB: Lends the Rust implementation a view of the input for the duration of the call.+void lend_sanitizer_input(SanitizerInput const&, Function<void(SanitizerInputKind, void const*)> const&);}diff --git a/Libraries/LibWeb/TrustedTypes/TrustedHTMLParserOptions.cpp b/Libraries/LibWeb/TrustedTypes/TrustedHTMLParserOptions.cppindex 07c1fea08d9..08c2f997241 100644--- a/Libraries/LibWeb/TrustedTypes/TrustedHTMLParserOptions.cpp+++ b/Libraries/LibWeb/TrustedTypes/TrustedHTMLParserOptions.cpp@@ -4,24 +4,18 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGC/Heap.h>#include <LibWeb/TrustedTypes/TrustedHTMLParserOptions.h>namespace Web::TrustedTypes {-GC_DEFINE_ALLOCATOR(TrustedHTMLParserOptions);--GC::Ref<TrustedHTMLParserOptions> TrustedHTMLParserOptions::create(Optional<HTML::SanitizerConfiguration> sanitizer_configuration, bool run_scripts)-{- return GC::Heap::the().allocate<TrustedHTMLParserOptions>(move(sanitizer_configuration), run_scripts);+extern "C" {+// Defined in Bindings/Rust/src/trusted_types/trusted_html_parser_options.rs.+bool web_rust_trusted_types_trusted_html_parser_options_run_scripts(TrustedHTMLParserOptions*);}-TrustedHTMLParserOptions::TrustedHTMLParserOptions(Optional<HTML::SanitizerConfiguration> sanitizer_configuration, bool run_scripts)- : m_sanitizer_configuration(move(sanitizer_configuration))- , m_run_scripts(run_scripts)+bool TrustedHTMLParserOptions::run_scripts() const{+ return web_rust_trusted_types_trusted_html_parser_options_run_scripts(const_cast<TrustedHTMLParserOptions*>(this));}-TrustedHTMLParserOptions::~TrustedHTMLParserOptions() = default;-}diff --git a/Libraries/LibWeb/TrustedTypes/TrustedHTMLParserOptions.h b/Libraries/LibWeb/TrustedTypes/TrustedHTMLParserOptions.hindex d86191f26d5..42385243799 100644--- a/Libraries/LibWeb/TrustedTypes/TrustedHTMLParserOptions.h+++ b/Libraries/LibWeb/TrustedTypes/TrustedHTMLParserOptions.h@@ -6,33 +6,16 @@#pragma once-#include <AK/Optional.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/HTML/SanitizerConfiguration.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/Bindings/TrustedHTMLParserOptions.h>namespace Web::TrustedTypes {-// https://w3c.github.io/trusted-types/dist/spec/#trusted-html-parser-options-class TrustedHTMLParserOptions final : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(TrustedHTMLParserOptions, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(TrustedHTMLParserOptions);+class TrustedHTMLParserOptions final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(TrustedHTMLParserOptions, trusted_html_parser_options)public:- static GC::Ref<TrustedHTMLParserOptions> create(Optional<HTML::SanitizerConfiguration>, bool run_scripts);-- virtual ~TrustedHTMLParserOptions() override;-- bool run_scripts() const { return m_run_scripts; }- Optional<HTML::SanitizerConfiguration> const& sanitizer_configuration() const { return m_sanitizer_configuration; }--private:- TrustedHTMLParserOptions(Optional<HTML::SanitizerConfiguration>, bool run_scripts);-- // TrustedHTMLParserOptions objects have an associated boolean runScripts and an associated SanitizerConfig-or-null- // sanitizer configuration. These values are set when the object is created, and will never change during its- // lifetime.- Optional<HTML::SanitizerConfiguration> const m_sanitizer_configuration;- bool const m_run_scripts { false };+ bool run_scripts() const;};}diff --git a/Libraries/LibWeb/TrustedTypes/TrustedHTMLParserOptions.idl b/Libraries/LibWeb/TrustedTypes/TrustedHTMLParserOptions.idlindex 0edcbfd2866..b6e64c92a88 100644--- a/Libraries/LibWeb/TrustedTypes/TrustedHTMLParserOptions.idl+++ b/Libraries/LibWeb/TrustedTypes/TrustedHTMLParserOptions.idl@@ -1,4 +1,4 @@// https://w3c.github.io/trusted-types/dist/spec/#trusted-html-parser-options-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface TrustedHTMLParserOptions {};diff --git a/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.cpp b/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.cppindex 655f91c9ea7..74fc22cb7f5 100644--- a/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.cpp+++ b/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.cpp@@ -9,41 +9,40 @@#include <LibGC/Ptr.h>#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/Value.h>-#include <LibWeb/Bindings/CppDictionary.h>#include <LibWeb/Bindings/Sanitizer.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/DOM/Document.h>-#include <LibWeb/HTML/Sanitizer.h>+#include <LibWeb/HTML/SanitizerConfiguration.h>#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>#include <LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h>#include <LibWeb/TrustedTypes/TrustedHTML.h>#include <LibWeb/TrustedTypes/TrustedHTMLParserOptions.h>#include <LibWeb/TrustedTypes/TrustedScript.h>#include <LibWeb/TrustedTypes/TrustedScriptURL.h>-#include <LibWeb/TrustedTypes/TrustedTypePolicyFactory.h>-#include <LibWeb/WebIDL/AbstractOperations.h>-#include <LibWeb/WebIDL/CallbackType.h>#include <LibWeb/WebIDL/ExceptionOr.h>-#include <LibWeb/WebIDL/ExceptionOrUtils.h>namespace Web::TrustedTypes {+// NB: CompliantParserOptionsResultAbi in trusted_type_policy.rs matches this.+enum class CompliantParserOptionsResult : u8 {+ Input,+ TrustedHTMLParserOptions,+ Thrown,+ TypeError,+};++// NB: ParserOptionsInputAbi in trusted_type_policy.rs matches this.+struct ParserOptionsInput {+ bool run_scripts { false };+ HTML::SanitizerInputKind sanitizer_kind { HTML::SanitizerInputKind::None };+ void const* sanitizer { nullptr };+};+extern "C" {// Defined in Bindings/Rust/src/trusted_types/trusted_type_policy.rs.-WebIDL::CallbackType* web_rust_trusted_types_trusted_type_policy_create_parser_options(TrustedTypePolicy*);+CompliantParserOptionsResult web_rust_trusted_types_get_trusted_type_compliant_parser_options(JSVM*, JSObject* global, ParserOptionsInput const*, bool throw_if_missing, FlatPtr sink, bool options_from_author, TrustedHTMLParserOptions** options, FlatPtr* message, JSValue* exception);u8 web_rust_trusted_types_get_trusted_type_compliant_string(JSVM*, u8 expected_type, JSObject* global, u8 input_kind, void* input_cell, FlatPtr input_string, FlatPtr sink, FlatPtr sink_group, FlatPtr* string, JSValue* exception);u8 web_rust_trusted_types_get_trusted_types_compliant_attribute_value(JSVM*, FlatPtr attribute_name, bool has_attribute_ns, FlatPtr attribute_ns, FlatPtr element_local_name, bool has_element_namespace, FlatPtr element_namespace, JSObject* global, u8 input_kind, void* input_cell, FlatPtr input_string, FlatPtr* string, JSValue* exception);bool web_rust_trusted_types_process_value_with_a_default_policy(JSVM*, u8 trusted_type_name, JSObject* global, u8 input_kind, void* input_cell, FlatPtr input_string, FlatPtr sink, void** result, JSValue* exception);--// Called by Bindings/Rust/src/trusted_types/trusted_type_policy.rs.-JSCompletion web_trusted_types_create_parser_options(JSObject* global, WebIDL::CallbackType* create_parser_options, Bindings::CppDictionary<Bindings::SetHTMLUnsafeOptions>* options, ReadonlySpan<JSValue> arguments);-}--GC::Ptr<WebIDL::CallbackType> TrustedTypePolicy::create_parser_options_callback() const-{- return web_rust_trusted_types_trusted_type_policy_create_parser_options(const_cast<TrustedTypePolicy*>(this));}static TrustedScript* trusted_script_from_value(JS::Value value)@@ -72,263 +71,43 @@ bool trusted_script_values_match(ReadonlySpan<JS::Value> values, ReadonlySpan<Streturn true;}-static JS::Completion invoke_trusted_type_policy_callback(WebIDL::CallbackType& callback, GC::RootVector<JS::Value> const& arguments)-{- return WebIDL::invoke_callback(callback, {}, WebIDL::ExceptionBehavior::Rethrow, arguments);-}--// https://w3c.github.io/trusted-types/dist/spec/#create-a-parser-options-callback-argument-template<typename Options>-static WebIDL::ExceptionOr<JS::Value> create_a_parser_options_callback_argument(JS::Object& global, Options const& dictionary)-{- // 1. Let runScriptsInput be dictionary["runScripts"], with default false.- bool run_scripts_input = false;- if constexpr (requires { dictionary.run_scripts; })- run_scripts_input = dictionary.run_scripts;-- // 2. Let argument be the ordered map «[ "runScripts" → runScriptsInput ]».- auto& realm = HTML::relevant_realm(global);- auto argument = JS::Object::create(realm, realm.intrinsics().object_prototype());- MUST(argument->create_data_property("runScripts"_utf16_fly_string, JS::Value(run_scripts_input)));-- // 3. Let sanitizerInput be the result of getting a sanitizer from realm and dictionary.- // https://w3c.github.io/trusted-types/dist/spec/#get-a-sanitizer-from-dictionary- // 1. Let sanitizerInput be dictionary["sanitizer"], defaulting to null.- // 2. If sanitizerInput is null, return null.- // 4. If sanitizerInput is not null, set argument["sanitizer"] to sanitizerInput.- if (dictionary.sanitizer.has_value()) {- auto sanitizer = TRY(HTML::get_a_sanitizer_from_sanitizer_input(*dictionary.sanitizer));- auto wrapper = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, sanitizer);- MUST(argument->create_data_property("sanitizer"_utf16_fly_string, wrapper));- }-- // 5. Return argument.- return argument;-}--// NB: Converts the return value of a CreateParserOptionsCallback, whose return type is SetHTMLUnsafeOptions?, to an-// IDL value.-static WebIDL::ExceptionOr<Optional<Bindings::SetHTMLUnsafeOptions>> to_optional_set_html_unsafe_options(JS::VM& vm, JS::Value value)-{- if (value.is_nullish())- return Optional<Bindings::SetHTMLUnsafeOptions> {};- return Optional<Bindings::SetHTMLUnsafeOptions> { TRY(Bindings::convert_to_idl_value_for_set_html_unsafe_options(vm, value)) };-}--// https://w3c.github.io/trusted-types/dist/spec/#get-a-sanitizer-config-copy-from-dictionary-static WebIDL::ExceptionOr<Optional<HTML::SanitizerConfiguration>> get_a_sanitizer_config_copy_from_dictionary(Bindings::SetHTMLUnsafeOptions const& dictionary)-{- // 1. Let sanitizer be the result of getting a sanitizer from realm and dictionary.- // 2. If sanitizer is null, return null.- if (!dictionary.sanitizer.has_value())- return Optional<HTML::SanitizerConfiguration> {};- auto sanitizer = TRY(HTML::get_a_sanitizer_from_sanitizer_input(*dictionary.sanitizer));-- // 3. Return sanitizer's configuration.- return Optional<HTML::SanitizerConfiguration> { sanitizer->configuration() };-}--// https://w3c.github.io/trusted-types/dist/spec/#get-trusted-type-policy-value-// NB: The steps for the "TrustedHTMLParserOptions" type name.-template<typename Options>-static WebIDL::ExceptionOr<JS::Value> get_parser_options_policy_value(JS::Object& global, GC::Ptr<WebIDL::CallbackType> function, Options const& value, GC::RootVector<JS::Value> const& arguments, ThrowIfCallbackMissing throw_if_missing)-{- // 1. Let functionName be a function name for the given trustedTypeName, based on the following table:- // 2. Let function be policy's options[functionName].- // NB: The caller passes function.-- // 3. If function is null, then:- if (!function) {- // 1. If throwIfMissing throw a TypeError.- if (throw_if_missing == ThrowIfCallbackMissing::Yes)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Trying to create a trusted type without a callback"_utf16 };-- // 2. Else return null.- return JS::js_null();- }-- // 4. If trustedTypeName is "TrustedHTMLParserOptions":- // 1. Set value to the result of creating a parser options callback argument given policy's relevant realm and- // value.- auto argument = TRY(create_a_parser_options_callback_argument(global, value));-- // 5. Let args be « value ».- GC::RootVector<JS::Value> args;- args.append(argument);-- // 6. Append each item in arguments to args.- args.extend(arguments);-- // 7. Let policyValue be the result of invoking function with args and "rethrow".- // 8. Return policyValue.- return TRY(invoke_trusted_type_policy_callback(*function, args));-}--// https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicy-createparseroptions-static WebIDL::ExceptionOr<GC::Ref<TrustedHTMLParserOptions>> create_parser_options(JS::Object& global, GC::Ptr<WebIDL::CallbackType> create_parser_options_callback, Bindings::SetHTMLUnsafeOptions const& options, GC::RootVector<JS::Value> const& arguments)-{- // Returns the result of executing the create a trusted type algorithm, with the following arguments:- // policy: this value- // trustedTypeName: "TrustedHTMLParserOptions"- // value: options- // arguments: arguments- // https://w3c.github.io/trusted-types/dist/spec/#create-a-trusted-type-algorithm- // 1. Let policyValue be the result of executing get trusted type policy value with the same arguments as this- // algorithm and additionally true as throwIfMissing.- // 2. If the algorithm threw an error, rethrow the error and abort the following steps.- auto policy_value = TRY(to_optional_set_html_unsafe_options(global.vm(), TRY(get_parser_options_policy_value(global, create_parser_options_callback, options, arguments, ThrowIfCallbackMissing::Yes))));-- // 3. If trustedTypeName is "TrustedHTMLParserOptions":- // 1. If policyValue is null, throw a TypeError.- // NOTE: Returning null from a named policy's createParserOptions callback throws a TypeError here, whereas- // returning null or undefined from createHTML, createScript, or createScriptURL yields the empty string.- if (!policy_value.has_value())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "createParserOptions returned null"_utf16 };-- // 2. Let sanitizerConfig be the result of getting a sanitizer configuration from policy's relevant realm and- // policyValue.- auto sanitizer_config = TRY(get_a_sanitizer_config_copy_from_dictionary(*policy_value));-- // 3. Let runScripts be policyValue["runScripts"] with default false.- auto run_scripts = policy_value->run_scripts;-- // 4. Return a new instance of TrustedHTMLParserOptions in policy's relevant realm with its sanitizer configuration- // set to sanitizerConfig, and its runScripts set to runScripts.- return TrustedHTMLParserOptions::create(move(sanitizer_config), run_scripts);-}--JSCompletion web_trusted_types_create_parser_options(JSObject* global, WebIDL::CallbackType* create_parser_options_callback, Bindings::CppDictionary<Bindings::SetHTMLUnsafeOptions>* options, ReadonlySpan<JSValue> arguments)-{- auto& global_object = *JS::HostABI::object_from_abi(global);- GC::RootVector<JS::Value> argument_values;- for (auto argument : arguments)- argument_values.append(JS::HostABI::value_from_abi(argument));- auto result = create_parser_options(global_object, create_parser_options_callback, options->dictionary(), argument_values);- if (result.is_exception()) {- auto& vm = global_object.vm();- return JS::HostABI::throw_completion_to_abi(WebIDL::exception_to_throw_completion(vm, *vm.current_realm(), result.exception()).value());- }- auto& realm = HTML::relevant_realm(global_object);- auto wrapper = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, result.release_value());- return JS::HostABI::normal_completion_to_abi(JS::HostABI::value_to_abi(wrapper));-}--// NB: A SetHTMLUnsafeOptions or ParseHTMLUnsafeOptions options needs vetting if options["runScripts"] exists and is-// true, or if options["sanitizer"] exists and is not an empty SanitizerConfig.-// https://w3c.github.io/trusted-types/dist/spec/#parser-options-need-vetting-template<typename Options>-static bool needs_vetting(Options const& options)-{- if constexpr (requires { options.run_scripts; }) {- if (options.run_scripts)- return true;- }- if (!options.sanitizer.has_value())- return false;- // NOTE: An empty SanitizerConfig does not change the parsed markup.- auto const* config = options.sanitizer->template get_pointer<Bindings::SanitizerConfig>();- if (!config)- return true;- return config->elements.has_value() || config->remove_elements.has_value() || config->replace_with_children_elements.has_value()- || config->processing_instructions.has_value() || config->remove_processing_instructions.has_value()- || config->attributes.has_value() || config->remove_attributes.has_value() || config->comments.has_value()- || config->data_attributes.has_value() || config->javascript_ur_ls.has_value();-}--// https://w3c.github.io/trusted-types/dist/spec/#get-trusted-type-compliant-parser-optionstemplate<typename Options>WebIDL::ExceptionOr<CompliantParserOptions<Options>> get_trusted_type_compliant_parser_options(JS::Object& global, CompliantParserOptions<Options> const& input, ThrowIfCallbackMissing throw_if_missing, InjectionSink sink, OptionsFromAuthor options_from_author){- // 1. If input is an instance of TrustedHTMLParserOptions, return input.- if (input.template has<GC::Ref<TrustedHTMLParserOptions>>())- return input;- auto const& options = input.template get<Options>();-- // 2. Let requireTrustedTypes be the result of executing Does sink type require trusted types? algorithm, passing- // global, "script", and true.- auto require_trusted_types = does_sink_require_trusted_types(global, Script.view(), IncludeReportOnlyPolicies::Yes);-- // 3. If requireTrustedTypes is false, return input.- if (!require_trusted_types)+ // NB: Steps 1 to 3, so that pages that don't require Trusted Types never call into Rust.+ if (input.template has<GC::Ref<TrustedHTMLParserOptions>>() || !does_sink_require_trusted_types(global, Script.view(), IncludeReportOnlyPolicies::Yes))return input;+ auto const& dictionary = input.template get<Options>();- // 4. Let requirePolicy be throwIfMissing.- bool require_policy = throw_if_missing == ThrowIfCallbackMissing::Yes;-- // 5. If optionsFromAuthor is true and input needs vetting, set requirePolicy to true.- if (options_from_author == OptionsFromAuthor::Yes && needs_vetting(options))- require_policy = true;-- auto reject_unless_allowed = [&]() -> WebIDL::ExceptionOr<CompliantParserOptions<Options>> {- // 1. Let disposition be the result of executing should sink type mismatch violation be blocked by content- // security policy? algorithm, passing global, sink, "script", and the empty string as source.- auto disposition = should_sink_type_mismatch_violation_be_blocked_by_content_security_policy(global, to_string(sink), Script.view(), {});-- // 2. If disposition is "Allowed", return input.- if (disposition == ContentSecurityPolicy::Directives::Directive::Result::Allowed)- return input;-- // 3. Throw a TypeError.- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Sink {} requires parser options vetted by a Trusted Types policy", to_string(sink)) };+ TrustedHTMLParserOptions* options = nullptr;+ FlatPtr message = 0;+ JSValue exception {};+ auto result = CompliantParserOptionsResult::Input;+ auto get_compliant_parser_options = [&](ParserOptionsInput const& input_abi) {+ result = web_rust_trusted_types_get_trusted_type_compliant_parser_options(JS::HostABI::vm_to_abi(global.vm()), JS::HostABI::object_to_abi(&global), &input_abi, throw_if_missing == ThrowIfCallbackMissing::Yes, to_string(sink).into_raw(), options_from_author == OptionsFromAuthor::Yes, &options, &message, &exception);};-- // 6. Let defaultPolicy be the value of global's trusted type policy factory's default policy.- auto* global_scope = HTML::window_or_worker_global_scope_from_global_object(global);- VERIFY(global_scope);- auto default_policy = global_scope->trusted_types()->default_policy();-- // 7. If defaultPolicy is null:- if (!default_policy) {- // 1. If requirePolicy is true:- if (require_policy)- return reject_unless_allowed();-- // 2. Return input.- return input;+ bool run_scripts = false;+ if constexpr (requires { dictionary.run_scripts; })+ run_scripts = dictionary.run_scripts;+ if (dictionary.sanitizer.has_value()) {+ HTML::lend_sanitizer_input(*dictionary.sanitizer, [&](HTML::SanitizerInputKind kind, void const* sanitizer) {+ get_compliant_parser_options({ .run_scripts = run_scripts, .sanitizer_kind = kind, .sanitizer = sanitizer });+ });+ } else {+ get_compliant_parser_options({ .run_scripts = run_scripts });}- // 8. Let function be defaultPolicy's options["createParserOptions"].- auto function = default_policy->create_parser_options_callback();-- // 9. If function is null:- if (!function) {- // 1. If requirePolicy is true:- if (require_policy)- return reject_unless_allowed();-- // 2. Return input.+ switch (result) {+ case CompliantParserOptionsResult::Input:return input;+ case CompliantParserOptionsResult::TrustedHTMLParserOptions:+ return CompliantParserOptions<Options> { GC::Ref { *options } };+ case CompliantParserOptionsResult::Thrown:+ return JS::throw_completion(JS::HostABI::value_from_abi(exception));+ case CompliantParserOptionsResult::TypeError:+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::adopt_raw(message) };}-- // 10. Let argument be the result of creating a parser options callback argument given global's relevant realm and- // input.- // 11. Let policyValue be the result of invoking function with « argument, "TrustedHTMLParserOptions", sink » and- // "rethrow".- // 12. If the algorithm threw an error, rethrow the error and abort the following steps.- auto& realm = HTML::relevant_realm(global);- auto& vm = realm.vm();- GC::RootVector<JS::Value> arguments;- arguments.append(JS::PrimitiveString::create(vm, "TrustedHTMLParserOptions"_utf16));- arguments.append(JS::PrimitiveString::create(vm, to_string(sink)));- auto policy_value = TRY(to_optional_set_html_unsafe_options(vm, TRY(get_parser_options_policy_value(global, function, options, arguments, ThrowIfCallbackMissing::Yes))));-- // 13. If policyValue is null or undefined:- if (!policy_value.has_value()) {- // NOTE: This step assures that the default policy rejection will be reported, but ignored in a report-only- // mode.- return reject_unless_allowed();- }-- // 14. Let runScripts be policyValue["runScripts"], with default false.- // NOTE: When invoked as a default policy, the createParserOptions callback determines the final script execution- // behavior, overriding the caller's requested runScripts option.- auto run_scripts = policy_value->run_scripts;-- // 15. Return a new TrustedHTMLParserOptions in global's relevant realm whose sanitizer configuration is set to the- // result of getting a sanitizer configuration from global's relevant realm and policyValue, and whose- // runScripts is set to runScripts.- auto sanitizer_config = TRY(get_a_sanitizer_config_copy_from_dictionary(*policy_value));- return CompliantParserOptions<Options> { TrustedHTMLParserOptions::create(move(sanitizer_config), run_scripts) };+ VERIFY_NOT_REACHED();}// https://w3c.github.io/trusted-types/dist/spec/#get-trusted-type-compliant-inputdiff --git a/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.h b/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.hindex c23d4dacc40..628f12f77c5 100644--- a/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.h+++ b/Libraries/LibWeb/TrustedTypes/TrustedTypePolicy.h@@ -47,9 +47,6 @@ enum class ThrowIfCallbackMissing {class TrustedTypePolicy final : public Bindings::RustInterfaceCell {WEB_RUST_INTERFACE(TrustedTypePolicy, trusted_type_policy)--public:- GC::Ptr<WebIDL::CallbackType> create_parser_options_callback() const;};WebIDL::ExceptionOr<Optional<TrustedType>> process_value_with_a_default_policy(TrustedTypeName, JS::Object&, Variant<GC::Ref<TrustedHTML>, GC::Ref<TrustedScript>, GC::Ref<TrustedScriptURL>, Utf16String>, InjectionSink);