diff --git a/files/en-us/web/api/trusted_types_api/index.md b/files/en-us/web/api/trusted_types_api/index.md index b81cb4594d74338..d66e47ddfb1d871 100644 --- a/files/en-us/web/api/trusted_types_api/index.md +++ b/files/en-us/web/api/trusted_types_api/index.md @@ -8,30 +8,128 @@ spec-urls: https://w3c.github.io/trusted-types/dist/spec/ {{DefaultAPISidebar("Trusted Types API")}}{{AvailableInWorkers}} -The **Trusted Types API** gives web developers a way to lock down the insecure parts of the {{domxref("Document Object Model","DOM API", "", "nocode")}} to prevent client-side {{Glossary("Cross-site scripting")}} (XSS) attacks. +The **Trusted Types API** gives web developers a way to ensure that input has been passed through a [sanitization](/en-US/docs/Web/Security/Attacks/XSS#sanitization) function before being passed to an API that might execute that input. This can help to protect against client-side [cross-site scripting (XSS)](/en-US/docs/Web/Security/Attacks/XSS) attacks. -## Concepts and Usage +## Concepts and usage -Client-side, or DOM-based, XSS attacks happen when data controlled by a user (such as that input into a form field) reaches a function that can execute that data. These functions are known as _injection sinks_. DOM-based XSS attacks happen when a user is able to write arbitrary JavaScript code and have it executed by one of these functions. +Client-side, or DOM-based, XSS attacks happen when data crafted by an attacker is passed to a browser API that executes that data as code. These APIs are known as _injection sinks_. -The Trusted Types API locks down risky injection sinks, requiring you to process the data before passing it to one of these functions. If you use a string, then the browser will throw a {{jsxref("TypeError")}} and prevent the use of the function. +Examples of injection sinks include: -Trusted Types works alongside [Content-Security Policy](/en-US/docs/Web/HTTP/CSP) with the {{CSP("trusted-types")}} and {{CSP("require-trusted-types-for")}} directives. - -### Injection Sinks - -The Trusted Types API locks down injection sinks that can act as a vector for DOM-XSS attacks. An injection sink is any Web API function that should only be called with trusted, validated or sanitized input. Examples of injection sinks include: - -- Functions that insert HTML into the document such as {{domxref("Element.innerHTML")}}, {{domxref("Element.outerHTML")}}, or {{domxref("Document.write()")}}. +- Functions that insert HTML into the document such as {{domxref("Element.innerHTML")}}. - Functions that create a new same-origin {{domxref("Document")}} with caller-controlled markup such as {{domxref("DOMParser.parseFromString()")}}. - Functions that execute code such as {{jsxref("Global_Objects/eval", "eval()")}}. - Setters for {{domxref("Element")}} attributes that accept a URL of code to load or execute. -Trusted Types will force you to process the data before passing it to any injection sink rather than use a string. This ensures that the data is trustworthy. +One of the main defenses against DOM-based XSS attacks is to [sanitize](/en-US/docs/Web/Security/Attacks/XSS#sanitization) data before passing it to an injection sink. The Trusted Types API enables a developer to centralize the sanitization code and to ensure that any data passed to an injection sink has been passed through the sanitization code. + +The API has two main parts: + +- A JavaScript API enables a developer to sanitize data before passing it to an injection sink. +- Two [CSP](/en-US/docs/Web/HTTP/CSP) directives enforce and control the usage of the JavaScript API. + +### The Trusted Types JavaScript API + +In the Trusted Types API: + +- The {{domxref("Window.trustedTypes", "trustedTypes")}} global property is used to create {{domxref("TrustedTypePolicy")}} objects. +- A {{domxref("TrustedTypePolicy")}} object is used to create trusted type objects: it will do this by passing the data through a sanitization function. +- Trusted type objects represent data that has been sanitized, and can therefore be safely passed to an injection sink. There are three sorts of trusted type, corresponding to different sort of injection sink: + - {{domxref("TrustedHTML")}} is for passing to a sink that will render the data as HTML. + - {{domxref("TrustedScript")}} is for passing to a sink that will execute the data as JavaScript. + - {{domxref("TrustedScriptURL")}} is for passing to a sink that will parse the data as a URL. + +With this API, instead of passing a string to an injection sink like `innerHTML`, you use a `TrustedTypePolicy` to create a `TrustedHTML` object from the string, then pass that into the sink, and can be sure that the string has been passed through a sanitization function. + +Note that the Trusted Types API does _not_ itself include a sanitization function: you supply your own function when you define the `TrustedTypePolicy` that you will use. + +For example, this code creates a `TrustedTypePolicy` that can create `TrustedHTML` objects by sanitizing the input strings with the [DOMPurify](https://github.com/cure53/DOMPurify) library: + +```js +const policy = trustedTypes.createPolicy("my-policy", { + createHTML: (input) => DOMPurify.sanitize(input), +}); +``` + +Next, you can use this `policy` object to create a `TrustedHTML` object, and pass that object into the injection sink: + +```js +const userInput = "I might be XSS"; +const element = document.querySelector("#container"); + +const trustedHTML = policy.createHTML(userInput); +element.innerHTML = trustedHTML; +``` + +### Using a CSP to enforce trusted types + +The API described above enables you to sanitize data, but it doesn't ensure that your code never passes input directly to an injection sink: that is, it doesn't stop you passing a string into `innerHTML`. + +In order to enforce that a trusted type must always be passed, you include the {{CSP("require-trusted-types-for")}} directive in your [CSP](/en-US/docs/Web/HTTP/CSP). +With this directive set, passing strings into injection sinks will result in a `TypeError` exception: + +```js example-bad +const userInput = "I might be XSS"; +const element = document.querySelector("#container"); + +element.innerHTML = userInput; // Throws a TypeError +``` -### Trusted Type Policies +Additionally, the {{CSP("trusted-types")}} CSP directive can be used to control which policies your code is allowed to create. When you create a policy using {{domxref("TrustedTypePolicyFactory/createPolicy", "trustedTypes.createPolicy()")}}, you pass a name for the policy. The `trusted-types` CSP directive lists acceptable policy names, so `createPolicy()` will throw an exception if it is passed a name which was not listed in `trusted-types`. This prevents some code in your web application from creating a policy that you were not expecting. + +### Cross-browser support for trusted types + +The Trusted Types API is not yet available in all modern browsers, but it is usable everywhere today thanks to [compatibility aids created by the W3C](https://github.com/w3c/trusted-types/tree/main?tab=readme-ov-file#polyfill). + +- The [_full_ polyfill](https://github.com/w3c/trusted-types/blob/main/src/polyfill/full.js) defines the JavaScript API, attempts to infer the CSP from the current document, and enforces the use of trusted types based on the inferred CSP. +- The [_API only_ polyfill](https://github.com/w3c/trusted-types/blob/main/src/polyfill/api_only.js) defines only the JavaScript API, and does not include the ability to enforce the use of trusted types using a CSP. + +As well as these two polyfills, the W3C provides what it calls a _tinyfill_, which we'll explain in more detail below. + +Note that as long as you have tested your code on a supporting browser with CSP enforcement enabled, then you don't need to use the _full polyfill_ above on other browsers — you can get the same benefits using the _API only polyfill_ or the _tinyfill_. + +This is because the enforcement forces you to refactor your code to ensure that all data is passed through the Trusted Types API (and therefore has been through a sanitization function) before being passed to an injection sink. +If you then run the refactored code in a different browser without enforcement, it will still go through the same code paths, and give you the same protection. + +#### Trusted Types tinyfill + +In this section we'll look at how the trusted types tinyfill can protect a website, even though it doesn't add support for trusted types at all. + +The trusted types tinyfill is just this: + +```js +if (typeof trustedTypes == "undefined") + trustedTypes = { createPolicy: (n, rules) => rules }; +``` + +It provides an implementation of `trustedTypes.createPolicy()` which just returns the [`policyOptions`](/en-US/docs/Web/API/TrustedTypePolicyFactory/createPolicy#policyoptions) object it was passed. The `policyOptions` object defines sanitization functions for data, and these functions are expected to return strings. + +With this tinyfill in place, suppose we create a policy: + +```js +const policy = trustedTypes.createPolicy("my-policy", { + createHTML: (input) => DOMPurify.sanitize(input), +}); +``` + +In browsers that support trusted types, this will return a `TrustedTypePolicy` which will create a `TrustedHTML` object when we call `policy.createHTML()`. The `TrustedHTML` object can then be passed to an injection sink, and we can enforce that the sink received a trusted type, rather than a string. + +In browsers that don't support trusted types, this code will return an object with a `createHTML()` function that sanitizes its input and returns it as a string. The sanitized string can then be passed to an injection sink. + +```js +const userInput = "I might be XSS"; +const element = document.querySelector("#container"); + +const trustedHTML = policy.createHTML(userInput); +// In supporting browsers, trustedHTML is a TrustedHTML object. +// In non-supporting browsers, trustedHTML is a string. + +element.innerHTML = trustedHTML; +// In supporting browsers, this will throw if trustedHTML +// is not a TrustedHTML object. +``` -A policy is a factory for Trusted Types. Web developers can specify a set of policies used for the creation of typed objects which form the trusted codebase for valid Trusted Type objects. +Either way, the injection sink gets sanitized data, and because we could enforce the use of the policy in the supporting browser, we know that this code path goes through the sanitization function in the non-supporting browser, too. ## Interfaces diff --git a/files/en-us/web/api/trustedhtml/index.md b/files/en-us/web/api/trustedhtml/index.md index cd6cf14f6aa32ce..57915c3ba12f0e3 100644 --- a/files/en-us/web/api/trustedhtml/index.md +++ b/files/en-us/web/api/trustedhtml/index.md @@ -7,7 +7,7 @@ browser-compat: api.TrustedHTML {{APIRef("Trusted Types API")}}{{AvailableInWorkers}} -The **`TrustedHTML`** interface of the {{domxref("Trusted Types API", "", "", "nocode")}} represents a string that a developer can insert into an [injection sink](/en-US/docs/Web/API/Trusted_Types_API#injection_sinks) that will render it as HTML. These objects are created via {{domxref("TrustedTypePolicy.createHTML()")}} and therefore have no constructor. +The **`TrustedHTML`** interface of the {{domxref("Trusted Types API", "", "", "nocode")}} represents a string that a developer can insert into an [injection sink](/en-US/docs/Web/API/Trusted_Types_API#concepts_and_usage) that will render it as HTML. These objects are created via {{domxref("TrustedTypePolicy.createHTML()")}} and therefore have no constructor. The value of a `TrustedHTML` object is set when the object is created and cannot be changed by JavaScript as there is no setter exposed. diff --git a/files/en-us/web/api/trustedscript/index.md b/files/en-us/web/api/trustedscript/index.md index aa347c85fcc5506..019a1b6199bb96c 100644 --- a/files/en-us/web/api/trustedscript/index.md +++ b/files/en-us/web/api/trustedscript/index.md @@ -7,7 +7,7 @@ browser-compat: api.TrustedScript {{APIRef("Trusted Types API")}}{{AvailableInWorkers}} -The **`TrustedScript`** interface of the {{domxref("Trusted Types API", "", "", "nocode")}} represents a string with an uncompiled script body that a developer can insert into an [injection sink](/en-US/docs/Web/API/Trusted_Types_API#injection_sinks) that might execute the script. These objects are created via {{domxref("TrustedTypePolicy.createScript","TrustedTypePolicy.createScript()")}} and therefore have no constructor. +The **`TrustedScript`** interface of the {{domxref("Trusted Types API", "", "", "nocode")}} represents a string with an uncompiled script body that a developer can insert into an [injection sink](/en-US/docs/Web/API/Trusted_Types_API#concepts_and_usage) that might execute the script. These objects are created via {{domxref("TrustedTypePolicy.createScript","TrustedTypePolicy.createScript()")}} and therefore have no constructor. The value of a **TrustedScript** object is set when the object is created and cannot be changed by JavaScript as there is no setter exposed. diff --git a/files/en-us/web/api/trustedscript/tostring/index.md b/files/en-us/web/api/trustedscript/tostring/index.md index 1da6cd48b420679..6362aceb73f451f 100644 --- a/files/en-us/web/api/trustedscript/tostring/index.md +++ b/files/en-us/web/api/trustedscript/tostring/index.md @@ -8,7 +8,7 @@ browser-compat: api.TrustedScript.toString {{APIRef("Trusted Types API")}}{{AvailableInWorkers}} -The **`toString()`** method of the {{domxref("TrustedScript")}} interface returns a string which may safely inserted into an [injection sink](/en-US/docs/Web/API/Trusted_Types_API#injection_sinks). +The **`toString()`** method of the {{domxref("TrustedScript")}} interface returns a string which may be safely inserted into an [injection sink](/en-US/docs/Web/API/Trusted_Types_API#concepts_and_usage). ## Syntax diff --git a/files/en-us/web/api/trustedscripturl/index.md b/files/en-us/web/api/trustedscripturl/index.md index d22ec4629e05c97..6d321edda8c7f16 100644 --- a/files/en-us/web/api/trustedscripturl/index.md +++ b/files/en-us/web/api/trustedscripturl/index.md @@ -7,7 +7,7 @@ browser-compat: api.TrustedScriptURL {{APIRef("Trusted Types API")}}{{AvailableInWorkers}} -The **`TrustedScriptURL`** interface of the {{domxref("Trusted Types API", "", "", "nocode")}} represents a string that a developer can insert into an [injection sink](/en-US/docs/Web/API/Trusted_Types_API#injection_sinks) that will parse it as a URL of an external script. These objects are created via {{domxref("TrustedTypePolicy.createScriptURL","TrustedTypePolicy.createScriptURL()")}} and therefore have no constructor. +The **`TrustedScriptURL`** interface of the {{domxref("Trusted Types API", "", "", "nocode")}} represents a string that a developer can insert into an [injection sink](/en-US/docs/Web/API/Trusted_Types_API#concepts_and_usage) that will parse it as a URL of an external script. These objects are created via {{domxref("TrustedTypePolicy.createScriptURL","TrustedTypePolicy.createScriptURL()")}} and therefore have no constructor. The value of a `TrustedScriptURL` object is set when the object is created and cannot be changed by JavaScript as there is no setter exposed. diff --git a/files/en-us/web/api/trustedscripturl/tostring/index.md b/files/en-us/web/api/trustedscripturl/tostring/index.md index c8ba90514d9cf9d..c6b2ecd1b02c49a 100644 --- a/files/en-us/web/api/trustedscripturl/tostring/index.md +++ b/files/en-us/web/api/trustedscripturl/tostring/index.md @@ -8,7 +8,7 @@ browser-compat: api.TrustedScriptURL.toString {{APIRef("Trusted Types API")}}{{AvailableInWorkers}} -The **`toString()`** method of the {{domxref("TrustedScriptURL")}} interface returns a string which may safely inserted into an [injection sink](/en-US/docs/Web/API/Trusted_Types_API#injection_sinks). +The **`toString()`** method of the {{domxref("TrustedScriptURL")}} interface returns a string which may safely inserted into an [injection sink](/en-US/docs/Web/API/Trusted_Types_API#concepts_and_usage). ## Syntax