Skip to main content

script/dom/trustedtypes/
trustedtypepolicyfactory.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4use std::cell::RefCell;
5
6use dom_struct::dom_struct;
7use html5ever::{LocalName, Namespace, QualName, local_name, ns};
8use js::context::JSContext;
9use js::conversions::ToJSValConvertible;
10use js::jsval::NullValue;
11use js::rust::HandleValue;
12use script_bindings::reflector::{Reflector, reflect_dom_object};
13
14use crate::conversions::Convert;
15use crate::dom::bindings::codegen::Bindings::TrustedTypePolicyFactoryBinding::{
16    TrustedTypePolicyFactoryMethods, TrustedTypePolicyOptions,
17};
18use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
19use crate::dom::bindings::codegen::Bindings::WorkerGlobalScopeBinding::WorkerGlobalScopeMethods;
20use crate::dom::bindings::codegen::UnionTypes::TrustedHTMLOrTrustedScriptOrTrustedScriptURLOrString as TrustedTypeOrString;
21use crate::dom::bindings::conversions::root_from_handlevalue;
22use crate::dom::bindings::error::{Error, Fallible};
23use crate::dom::bindings::inheritance::Castable;
24use crate::dom::bindings::reflector::DomGlobal;
25use crate::dom::bindings::root::{DomRoot, MutNullableDom};
26use crate::dom::bindings::str::DOMString;
27use crate::dom::csp::CspReporting;
28use crate::dom::eventtarget::EventTarget;
29use crate::dom::globalscope::GlobalScope;
30use crate::dom::trustedtypes::trustedhtml::TrustedHTML;
31use crate::dom::trustedtypes::trustedscript::TrustedScript;
32use crate::dom::trustedtypes::trustedscripturl::TrustedScriptURL;
33use crate::dom::trustedtypes::trustedtypepolicy::{TrustedType, TrustedTypePolicy};
34use crate::dom::types::WorkerGlobalScope;
35use crate::dom::window::Window;
36
37#[dom_struct]
38pub struct TrustedTypePolicyFactory {
39    reflector_: Reflector,
40
41    default_policy: MutNullableDom<TrustedTypePolicy>,
42    policy_names: RefCell<Vec<String>>,
43}
44
45pub(crate) static DEFAULT_SCRIPT_SINK_GROUP: &str = "'script'";
46
47// We currently always clone the result, so keep the `clone()` in the trait
48// for now to keep the caller side clean
49impl Convert<DOMString> for TrustedTypeOrString {
50    fn convert(self) -> DOMString {
51        match self {
52            TrustedTypeOrString::TrustedHTML(trusted_html) => trusted_html.data().clone().root(),
53            TrustedTypeOrString::TrustedScript(trusted_script) => {
54                trusted_script.data().clone().root()
55            },
56            TrustedTypeOrString::TrustedScriptURL(trusted_script_url) => {
57                trusted_script_url.data().clone().root()
58            },
59            TrustedTypeOrString::String(str_) => str_,
60        }
61    }
62}
63
64impl TrustedTypePolicyFactory {
65    fn new_inherited() -> Self {
66        Self {
67            reflector_: Reflector::new(),
68            default_policy: Default::default(),
69            policy_names: RefCell::new(vec![]),
70        }
71    }
72
73    pub(crate) fn new(cx: &mut JSContext, global: &GlobalScope) -> DomRoot<Self> {
74        reflect_dom_object(cx, Box::new(Self::new_inherited()), global)
75    }
76
77    /// <https://www.w3.org/TR/trusted-types/#create-trusted-type-policy-algorithm>
78    fn create_trusted_type_policy(
79        &self,
80        cx: &mut JSContext,
81        policy_name: String,
82        options: &TrustedTypePolicyOptions,
83        global: &GlobalScope,
84    ) -> Fallible<DomRoot<TrustedTypePolicy>> {
85        // Avoid double borrow on policy_names
86        {
87            // Step 1: Let allowedByCSP be the result of executing Should Trusted Type policy creation be blocked by
88            // Content Security Policy? algorithm with global, policyName and factory’s created policy names value.
89            let policy_names = self.policy_names.borrow();
90            let policy_names: Vec<&str> = policy_names.iter().map(String::as_ref).collect();
91            let allowed_by_csp = global.call_on_csp_list(|csp_list| {
92                csp_list.is_trusted_type_policy_creation_allowed(
93                    cx,
94                    global,
95                    &policy_name,
96                    &policy_names,
97                )
98            });
99
100            // Step 2: If allowedByCSP is "Blocked", throw a TypeError and abort further steps.
101            if !allowed_by_csp {
102                return Err(Error::Type(c"Not allowed by CSP".to_owned()));
103            }
104        }
105
106        // Step 3: If policyName is default and the factory’s default policy value is not null, throw a TypeError
107        // and abort further steps.
108        if policy_name == "default" && self.default_policy.get().is_some() {
109            return Err(Error::Type(
110                c"Already set default policy for factory".to_owned(),
111            ));
112        }
113
114        // Step 4: Let policy be a new TrustedTypePolicy object.
115        // Step 5: Set policy’s name property value to policyName.
116        // Step 6: Set policy’s options value to «[ "createHTML" ->
117        // options["createHTML", "createScript" -> options["createScript",
118        // "createScriptURL" -> options["createScriptURL" ]».
119        let policy = TrustedTypePolicy::new(cx, policy_name.clone(), options, global);
120        // Step 7: If the policyName is default, set the factory’s default policy value to policy.
121        if policy_name == "default" {
122            self.default_policy.set(Some(&policy))
123        }
124        // Step 8: Append policyName to factory’s created policy names.
125        self.policy_names.borrow_mut().push(policy_name);
126        // Step 9: Return policy.
127        Ok(policy)
128    }
129
130    /// <https://w3c.github.io/trusted-types/dist/spec/#abstract-opdef-get-trusted-type-data-for-attribute>
131    #[expect(clippy::if_same_then_else)]
132    fn get_trusted_type_data_for_attribute(
133        element_namespace: &Namespace,
134        element_name: &LocalName,
135        attribute: &str,
136        attribute_namespace: Option<&Namespace>,
137    ) -> Option<(TrustedType, String)> {
138        // Step 1: Let data be null.
139        //
140        // We return the if directly
141        // Step 2: If attributeNs is null, « HTML namespace, SVG namespace, MathML namespace » contains
142        // element’s namespace, and attribute is the name of an event handler content attribute:
143        if attribute_namespace.is_none() &&
144            matches!(*element_namespace, ns!(html) | ns!(svg) | ns!(mathml)) &&
145            EventTarget::is_content_event_handler(attribute)
146        {
147            // Step 2.1. Return (Element, null, attribute, TrustedScript, "Element " + attribute).
148            return Some((
149                TrustedType::TrustedScript,
150                "Element ".to_owned() + attribute,
151            ));
152        }
153        // Step 3: Find the row in the following table, where element is in the first column,
154        // attributeNs is in the second column, and attribute is in the third column.
155        // If a matching row is found, set data to that row.
156        // Step 4: Return data.
157        if *element_namespace == ns!(html) &&
158            *element_name == local_name!("iframe") &&
159            attribute_namespace.is_none() &&
160            attribute == "srcdoc"
161        {
162            Some((
163                TrustedType::TrustedHTML,
164                "HTMLIFrameElement srcdoc".to_owned(),
165            ))
166        } else if *element_namespace == ns!(html) &&
167            *element_name == local_name!("script") &&
168            attribute_namespace.is_none() &&
169            attribute == "src"
170        {
171            Some((
172                TrustedType::TrustedScriptURL,
173                "HTMLScriptElement src".to_owned(),
174            ))
175        } else if *element_namespace == ns!(svg) &&
176            *element_name == local_name!("script") &&
177            attribute_namespace.is_none() &&
178            attribute == "href"
179        {
180            Some((
181                TrustedType::TrustedScriptURL,
182                "SVGScriptElement href".to_owned(),
183            ))
184        } else if *element_namespace == ns!(svg) &&
185            *element_name == local_name!("script") &&
186            attribute_namespace == Some(&ns!(xlink)) &&
187            attribute == "href"
188        {
189            Some((
190                TrustedType::TrustedScriptURL,
191                "SVGScriptElement href".to_owned(),
192            ))
193        } else {
194            None
195        }
196    }
197
198    /// <https://w3c.github.io/trusted-types/dist/spec/#validate-attribute-mutation>
199    pub(crate) fn get_trusted_types_compliant_attribute_value(
200        cx: &mut JSContext,
201        element_namespace: &Namespace,
202        element_name: &LocalName,
203        attribute: &str,
204        attribute_namespace: Option<&Namespace>,
205        new_value: TrustedTypeOrString,
206        global: &GlobalScope,
207    ) -> Fallible<DOMString> {
208        // Step 1. If attributeNs is the empty string, set attributeNs to null.
209        let attribute_namespace = attribute_namespace.filter(|a| **a != ns!());
210        // Step 2. Set attributeData to the result of Get Trusted Type data for attribute algorithm,
211        // with the following arguments:
212        let Some(attribute_data) = Self::get_trusted_type_data_for_attribute(
213            element_namespace,
214            element_name,
215            attribute,
216            attribute_namespace,
217        ) else {
218            // Step 3. If attributeData is null, then:
219            // Step 3.1. If newValue is a string, return newValue.
220            // Step 3.2. Assert: newValue is TrustedHTML or TrustedScript or TrustedScriptURL.
221            // Step 3.3. Return value’s associated data.
222            return Ok(new_value.convert());
223        };
224        // Step 4. Let expectedType be the value of the fourth member of attributeData.
225        // Step 5. Let sink be the value of the fifth member of attributeData.
226        let (expected_type, sink) = attribute_data;
227        let new_value = if let TrustedTypeOrString::String(str_) = new_value {
228            str_
229        } else {
230            // If the type was already trusted, we should return immediately as
231            // all callers of `get_trusted_type_compliant_string` implement this
232            // check themselves. However, we should only do this if it matches
233            // the expected type.
234            if expected_type.matches_idl_trusted_type(&new_value) {
235                return Ok(new_value.convert());
236            }
237            new_value.convert()
238        };
239        // Step 6. Return the result of executing Get Trusted Type compliant string with the following arguments:
240        // If the algorithm threw an error, rethrow the error.
241        Self::get_trusted_type_compliant_string(
242            cx,
243            expected_type,
244            global,
245            new_value,
246            &sink,
247            DEFAULT_SCRIPT_SINK_GROUP,
248        )
249    }
250
251    /// <https://w3c.github.io/trusted-types/dist/spec/#process-value-with-a-default-policy-algorithm>
252    pub(crate) fn process_value_with_default_policy(
253        cx: &mut JSContext,
254        expected_type: TrustedType,
255        global: &GlobalScope,
256        input: DOMString,
257        sink: &str,
258    ) -> Fallible<Option<DOMString>> {
259        // Step 1: Let defaultPolicy be the value of global’s trusted type policy factory's default policy.
260        let global_policy_factory = global.trusted_types(cx);
261        let default_policy = match global_policy_factory.default_policy.get() {
262            None => return Ok(None),
263            Some(default_policy) => default_policy,
264        };
265        // Step 2: Let policyValue be the result of executing Get Trusted Type policy value,
266        // with the following arguments:
267        rooted!(&in(cx) let mut trusted_type_name_value = NullValue());
268        expected_type
269            .as_ref()
270            .to_jsval(cx, trusted_type_name_value.handle_mut());
271
272        rooted!(&in(cx) let mut sink_value = NullValue());
273        sink.to_jsval(cx, sink_value.handle_mut());
274
275        let arguments = vec![trusted_type_name_value.handle(), sink_value.handle()];
276        let policy_value = default_policy.get_trusted_type_policy_value(
277            cx,
278            expected_type,
279            input,
280            arguments,
281            false,
282        );
283        #[expect(clippy::question_mark, reason = "better match the spec")]
284        let data_string = match policy_value {
285            // Step 3: If the algorithm threw an error, rethrow the error and abort the following steps.
286            Err(error) => return Err(error),
287            Ok(policy_value) => match policy_value {
288                // Step 4: If policyValue is null or undefined, return policyValue.
289                None => return Ok(None),
290                // Step 5: Let dataString be the result of stringifying policyValue.
291                Some(policy_value) => policy_value,
292            },
293        };
294        Ok(Some(data_string))
295    }
296    /// Step 1 is implemented by the caller
297    /// <https://w3c.github.io/trusted-types/dist/spec/#get-trusted-type-compliant-string-algorithm>
298    pub(crate) fn get_trusted_type_compliant_string(
299        cx: &mut JSContext,
300        expected_type: TrustedType,
301        global: &GlobalScope,
302        input: DOMString,
303        sink: &str,
304        sink_group: &str,
305    ) -> Fallible<DOMString> {
306        // Step 2: Let requireTrustedTypes be the result of executing Does sink type require trusted types?
307        // algorithm, passing global, sinkGroup, and true.
308        let require_trusted_types = global.call_on_csp_list(|csp_list| {
309            csp_list.does_sink_type_require_trusted_types(sink_group, true)
310        });
311        // Step 3: If requireTrustedTypes is false, return stringified input and abort these steps.
312        if !require_trusted_types {
313            return Ok(input);
314        }
315        // Step 4: Let convertedInput be the result of executing Process value with a default policy
316        // with the same arguments as this algorithm.
317        let converted_input = TrustedTypePolicyFactory::process_value_with_default_policy(
318            cx,
319            expected_type,
320            global,
321            input.clone(),
322            sink,
323        );
324        // Step 5: If the algorithm threw an error, rethrow the error and abort the following steps.
325        match converted_input? {
326            // Step 6: If convertedInput is null or undefined, execute the following steps:
327            None => {
328                // Step 6.1: Let disposition be the result of executing Should sink type mismatch violation
329                // be blocked by Content Security Policy? algorithm, passing global,
330                // stringified input as source, sinkGroup and sink.
331                let is_blocked = global.call_on_csp_list(|csp_list| {
332                    csp_list.should_sink_type_mismatch_violation_be_blocked_by_csp(
333                        cx,
334                        global,
335                        sink,
336                        sink_group,
337                        &input.str(),
338                    )
339                });
340                // Step 6.2: If disposition is “Allowed”, return stringified input and abort further steps.
341                if !is_blocked {
342                    Ok(input)
343                } else {
344                    // Step 6.3: Throw a TypeError and abort further steps.
345                    Err(Error::Type(
346                        c"Cannot set value, expected trusted type".to_owned(),
347                    ))
348                }
349            },
350            // Step 8: Return stringified convertedInput.
351            Some(converted_input) => Ok(converted_input),
352        }
353        // Step 7: Assert: convertedInput is an instance of expectedType.
354        // TODO(https://github.com/w3c/trusted-types/issues/566): Implement when spec is resolved
355    }
356
357    /// <https://www.w3.org/TR/trusted-types/#dom-trustedtypepolicyfactory-isscript>
358    pub(crate) fn is_trusted_script(
359        cx: &mut JSContext,
360        value: HandleValue,
361    ) -> Result<DomRoot<TrustedScript>, ()> {
362        root_from_handlevalue::<TrustedScript>(cx, value)
363    }
364}
365
366impl TrustedTypePolicyFactoryMethods<crate::DomTypeHolder> for TrustedTypePolicyFactory {
367    /// <https://www.w3.org/TR/trusted-types/#dom-trustedtypepolicyfactory-createpolicy>
368    fn CreatePolicy(
369        &self,
370        cx: &mut JSContext,
371        policy_name: DOMString,
372        options: &TrustedTypePolicyOptions,
373    ) -> Fallible<DomRoot<TrustedTypePolicy>> {
374        self.create_trusted_type_policy(cx, String::from(policy_name), options, &self.global())
375    }
376    /// <https://www.w3.org/TR/trusted-types/#dom-trustedtypepolicyfactory-ishtml>
377    fn IsHTML(&self, cx: &mut JSContext, value: HandleValue) -> bool {
378        root_from_handlevalue::<TrustedHTML>(cx, value).is_ok()
379    }
380    /// <https://www.w3.org/TR/trusted-types/#dom-trustedtypepolicyfactory-isscript>
381    fn IsScript(&self, cx: &mut JSContext, value: HandleValue) -> bool {
382        TrustedTypePolicyFactory::is_trusted_script(cx, value).is_ok()
383    }
384    /// <https://www.w3.org/TR/trusted-types/#dom-trustedtypepolicyfactory-isscripturl>
385    fn IsScriptURL(&self, cx: &mut JSContext, value: HandleValue) -> bool {
386        root_from_handlevalue::<TrustedScriptURL>(cx, value).is_ok()
387    }
388    /// <https://www.w3.org/TR/trusted-types/#dom-trustedtypepolicyfactory-emptyhtml>
389    fn EmptyHTML(&self, cx: &mut JSContext) -> DomRoot<TrustedHTML> {
390        TrustedHTML::new(cx, DOMString::new(), &self.global())
391    }
392    /// <https://www.w3.org/TR/trusted-types/#dom-trustedtypepolicyfactory-emptyscript>
393    fn EmptyScript(&self, cx: &mut JSContext) -> DomRoot<TrustedScript> {
394        TrustedScript::new(cx, DOMString::new(), &self.global())
395    }
396    /// <https://www.w3.org/TR/trusted-types/#dom-trustedtypepolicyfactory-getattributetype>
397    fn GetAttributeType(
398        &self,
399        tag_name: DOMString,
400        attribute: DOMString,
401        element_namespace: Option<DOMString>,
402        attribute_namespace: Option<DOMString>,
403    ) -> Option<DOMString> {
404        // Step 1: Set localName to tagName in ASCII lowercase.
405        let local_name = tag_name.to_ascii_lowercase();
406        // Step 2: Set attribute to attribute in ASCII lowercase.
407        let attribute = attribute.to_ascii_lowercase();
408        // Step 3: If elementNs is null or an empty string, set elementNs to HTML namespace.
409        let element_namespace = match element_namespace {
410            Some(namespace) if !namespace.is_empty() => Namespace::from(namespace),
411            Some(_) | None => ns!(html),
412        };
413        // Step 4: If attrNs is an empty string, set attrNs to null.
414        let attribute_namespace = match attribute_namespace {
415            Some(namespace) if !namespace.is_empty() => Some(Namespace::from(namespace)),
416            Some(_) | None => None,
417        };
418        // Step 5: Let interface be the element interface for localName and elementNs.
419        // Step 6: Let expectedType be null.
420        // Step 7: Set attributeData to the result of Get Trusted Type data for attribute algorithm,
421        // with the following arguments: interface as element, attribute, attrNs
422        // Step 8: If attributeData is not null, then set expectedType to the interface’s name of
423        // the value of the fourth member of attributeData.
424        // Step 9: Return expectedType.
425        TrustedTypePolicyFactory::get_trusted_type_data_for_attribute(
426            &element_namespace,
427            &LocalName::from(local_name),
428            &attribute,
429            attribute_namespace.as_ref(),
430        )
431        .map(|tuple| DOMString::from(tuple.0.as_ref()))
432    }
433    /// <https://www.w3.org/TR/trusted-types/#dom-trustedtypepolicyfactory-getpropertytype>
434    #[expect(clippy::if_same_then_else)]
435    fn GetPropertyType(
436        &self,
437        tag_name: DOMString,
438        property: DOMString,
439        element_namespace: Option<DOMString>,
440    ) -> Option<DOMString> {
441        // Step 1: Set localName to tagName in ASCII lowercase.
442        let local_name = tag_name.to_ascii_lowercase();
443        // Step 2: If elementNs is null or an empty string, set elementNs to HTML namespace.
444        let element_namespace = match element_namespace {
445            Some(namespace) if !namespace.is_empty() => Namespace::from(namespace),
446            Some(_) | None => ns!(html),
447        };
448        // Step 3: Let interface be the element interface for localName and elementNs.
449        let interface = QualName::new(None, element_namespace, LocalName::from(local_name));
450        // Step 4: Let expectedType be null.
451        let mut expected_type = None;
452        // Step 5: Find the row in the following table, where the first column is "*" or interface’s name,
453        // and property is in the second column. If a matching row is found, set expectedType to
454        // the interface’s name of the value of the third column.
455        let property = property.str();
456        if interface.ns == ns!(html) &&
457            interface.local == local_name!("iframe") &&
458            property == "srcdoc"
459        {
460            expected_type = Some(DOMString::from_static("TrustedHTML"))
461        } else if interface.ns == ns!(html) &&
462            interface.local == local_name!("script") &&
463            property == "innerText"
464        {
465            expected_type = Some(DOMString::from_static("TrustedScript"))
466        } else if interface.ns == ns!(html) &&
467            interface.local == local_name!("script") &&
468            property == "src"
469        {
470            expected_type = Some(DOMString::from_static("TrustedScriptURL"))
471        } else if interface.ns == ns!(html) &&
472            interface.local == local_name!("script") &&
473            property == "text"
474        {
475            expected_type = Some(DOMString::from_static("TrustedScript"))
476        } else if interface.ns == ns!(html) &&
477            interface.local == local_name!("script") &&
478            property == "textContent"
479        {
480            expected_type = Some(DOMString::from_static("TrustedScript"))
481        } else if property == "innerHTML" {
482            expected_type = Some(DOMString::from_static("TrustedHTML"))
483        } else if property == "outerHTML" {
484            expected_type = Some(DOMString::from_static("TrustedHTML"))
485        }
486        // Step 6: Return expectedType.
487        expected_type
488    }
489    /// <https://www.w3.org/TR/trusted-types/#dom-trustedtypepolicyfactory-defaultpolicy>
490    fn GetDefaultPolicy(&self) -> Option<DomRoot<TrustedTypePolicy>> {
491        self.default_policy.get()
492    }
493}
494
495impl GlobalScope {
496    fn trusted_types(&self, cx: &mut JSContext) -> DomRoot<TrustedTypePolicyFactory> {
497        if let Some(window) = self.downcast::<Window>() {
498            return window.TrustedTypes(cx);
499        }
500        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
501            return worker.TrustedTypes(cx);
502        }
503        unreachable!();
504    }
505}