Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expand trusted types guidance #37917

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
126 changes: 112 additions & 14 deletions files/en-us/web/api/trusted_types_api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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")}}.
Comment on lines -25 to +19
Copy link
Collaborator

@hamishwillee hamishwillee Feb 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This "Concepts and usage" section is now linked from all of the various trusted type interfaces as "injection syncs". For instance, in trusted HTML it says

The TrustedHTML interface of the Trusted Types API represents a string that a developer can insert into an injection sink that will render it as HTML.

But in TrustedHtml there is no listing of what interfaces this might be used with - and if you navigate here, just this single example of Element.innerHTML.

This is perhaps intentional - you don't want to have a list that can't be maintained as exhaustive? I think in this case it would be useful to either list the problematic interfaces in TrustedHtml and friends, or here have a larger subset of what they are used for. You can still say "such as" even for an incomplete list. FWIW I think page is good, and would have it in the interfaces as per https://github.com/mdn/content/pull/37917/files#r1938643809

FYI I'm looking at documenting Document.write() and Document.writeln() and when I was looking at this page, knowing this was an affected case of HTML insertion was useful.

Copy link
Collaborator Author

@wbamberg wbamberg Feb 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've made two changes here from what was there before:

  • removed the "injection sinks" heading
  • removed a couple of the examples, specifically outerHTML and document.write().

So pretty minor change. I haven't changed it from an exhaustive to a non-exhaustive list, it was never exhaustive. I don't want the "injection sinks" heading there, or a very long list, because I think it breaks the flow of the document.

But I do agree that it is a bit weird having the "injection sinks" link in pages like https://developer.mozilla.org/en-US/docs/Web/API/TrustedScript/toString go to "concepts and usage". To address that I might suggest having an "Injection sinks" H3 heading at the end of "concepts and usage", which looks quite a bit like the existing one at https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API#injection_sinks.

Separately, yes it would be good to have an exhaustive list! But I can't find one in the specification. Also I think that's out of the intended scope of this PR.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think even a non-exhaustive list would be useful. But appreciate you have a clear understanding of what you want to achieve.

No worse that what was here before so OK as an edit.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do think BTW that in pages like https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML we should talk about trusted types. It's unclear to me how someone can really use this API effectively without knowing exactly which APIs are governed by it. But again I don't want to do this now, because it turns into "rewrite everything".

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I plan to do that as part of #37518 - discovered it had not been done yesterday.

Copy link
Collaborator

@hamishwillee hamishwillee Feb 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note, at this point, covering the APIs in that PR (write, writeln from Document, the setInterval/Time, Element.innerHTML, ShadowRoot.innerHTML.
There are others that may also be affected, such as outerHTML, but I'm constraining myself in order to meet a specific FF release now overdue (i.e. what I have tested works in FF).

- 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;
```

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is one other thing it would be good to mention here, and that is default policy, which I would pull out of the createPolicy docs.

At least for the Document.write() method, the spec says that IFF CSP is enforced then any strings passed to injection sink (or at least write()) will be offered to the default policy, and only if that default policy doesn't exist is there a TypeError. The idea is that you log this default policy, and eventually end up with everything migrated.

IF you don't do it, then I'll have a go after this merges.

### 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

Expand Down
2 changes: 1 addition & 1 deletion files/en-us/web/api/trustedhtml/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion files/en-us/web/api/trustedscript/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion files/en-us/web/api/trustedscript/tostring/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion files/en-us/web/api/trustedscripturl/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion files/en-us/web/api/trustedscripturl/tostring/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down