1use 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
47impl 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 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 {
87 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 if !allowed_by_csp {
102 return Err(Error::Type(c"Not allowed by CSP".to_owned()));
103 }
104 }
105
106 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 let policy = TrustedTypePolicy::new(cx, policy_name.clone(), options, global);
120 if policy_name == "default" {
122 self.default_policy.set(Some(&policy))
123 }
124 self.policy_names.borrow_mut().push(policy_name);
126 Ok(policy)
128 }
129
130 #[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 if attribute_namespace.is_none() &&
144 matches!(*element_namespace, ns!(html) | ns!(svg) | ns!(mathml)) &&
145 EventTarget::is_content_event_handler(attribute)
146 {
147 return Some((
149 TrustedType::TrustedScript,
150 "Element ".to_owned() + attribute,
151 ));
152 }
153 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 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 let attribute_namespace = attribute_namespace.filter(|a| **a != ns!());
210 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 return Ok(new_value.convert());
223 };
224 let (expected_type, sink) = attribute_data;
227 let new_value = if let TrustedTypeOrString::String(str_) = new_value {
228 str_
229 } else {
230 if expected_type.matches_idl_trusted_type(&new_value) {
235 return Ok(new_value.convert());
236 }
237 new_value.convert()
238 };
239 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 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 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 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 Err(error) => return Err(error),
287 Ok(policy_value) => match policy_value {
288 None => return Ok(None),
290 Some(policy_value) => policy_value,
292 },
293 };
294 Ok(Some(data_string))
295 }
296 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 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 if !require_trusted_types {
313 return Ok(input);
314 }
315 let converted_input = TrustedTypePolicyFactory::process_value_with_default_policy(
318 cx,
319 expected_type,
320 global,
321 input.clone(),
322 sink,
323 );
324 match converted_input? {
326 None => {
328 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 if !is_blocked {
342 Ok(input)
343 } else {
344 Err(Error::Type(
346 c"Cannot set value, expected trusted type".to_owned(),
347 ))
348 }
349 },
350 Some(converted_input) => Ok(converted_input),
352 }
353 }
356
357 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 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 fn IsHTML(&self, cx: &mut JSContext, value: HandleValue) -> bool {
378 root_from_handlevalue::<TrustedHTML>(cx, value).is_ok()
379 }
380 fn IsScript(&self, cx: &mut JSContext, value: HandleValue) -> bool {
382 TrustedTypePolicyFactory::is_trusted_script(cx, value).is_ok()
383 }
384 fn IsScriptURL(&self, cx: &mut JSContext, value: HandleValue) -> bool {
386 root_from_handlevalue::<TrustedScriptURL>(cx, value).is_ok()
387 }
388 fn EmptyHTML(&self, cx: &mut JSContext) -> DomRoot<TrustedHTML> {
390 TrustedHTML::new(cx, DOMString::new(), &self.global())
391 }
392 fn EmptyScript(&self, cx: &mut JSContext) -> DomRoot<TrustedScript> {
394 TrustedScript::new(cx, DOMString::new(), &self.global())
395 }
396 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 let local_name = tag_name.to_ascii_lowercase();
406 let attribute = attribute.to_ascii_lowercase();
408 let element_namespace = match element_namespace {
410 Some(namespace) if !namespace.is_empty() => Namespace::from(namespace),
411 Some(_) | None => ns!(html),
412 };
413 let attribute_namespace = match attribute_namespace {
415 Some(namespace) if !namespace.is_empty() => Some(Namespace::from(namespace)),
416 Some(_) | None => None,
417 };
418 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 #[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 let local_name = tag_name.to_ascii_lowercase();
443 let element_namespace = match element_namespace {
445 Some(namespace) if !namespace.is_empty() => Namespace::from(namespace),
446 Some(_) | None => ns!(html),
447 };
448 let interface = QualName::new(None, element_namespace, LocalName::from(local_name));
450 let mut expected_type = None;
452 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 expected_type
488 }
489 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}