> Markdown version of [Content Security Policy](https://vaadin.com/docs/next/flow/security/protections/content-security-policy). Section index: [llms.txt](https://vaadin.com/docs/next/flow/llms.txt)

# Content Security Policy

A [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) is a browser standard that helps to mitigate certain types of attacks, such as Cross-Site Scripting (XSS) and data injection. With a Content Security Policy, the application defines rules for how scripts and other resources can be loaded and run in the browser. This page describes the settings that Vaadin Flow needs, and how to use a strict, nonce-based policy.

## <a id="required-settings"></a>Required Settings

Vaadin Flow needs the settings `script-src 'unsafe-inline' 'unsafe-eval'` and `style-src 'unsafe-inline'`. The bootstrap page starts the Flow client engine — the part of the framework that runs in the browser — with an inline script. The engine then runs the JavaScript expressions that the server sends, such as those of `executeJs()` and of event data expressions, by constructing functions from them, which is what `unsafe-eval` permits.

## <a id="vaadin-strict-csp"></a>Vaadin & Strict Content Security Policy

Vaadin Flow isn’t generally compatible with strict Content Security Policy rules. This is due to how the client-server communication has been built. For example, dynamic JavaScript functions and `eval` calls are used in Vaadin. These aren’t compatible with strict Content Security Policy rules.

However, with some effort, a nonce-based strict Content Security Policy can be used with Vaadin Flow applications. Nonce is a random identifier which is generated by the server for each HTTP request. It needs to be included in the response headers. Once this is done, only script tags containing this nonce value are loaded by the browser — while dynamic functions and calling `eval` are not allowed.

A strict Content Security Policy implemented this way is only available when the Vaadin application is running in production mode.

## <a id="creating-random-nonce"></a>Creating Random Nonce

The application generates a new nonce for each request of the bootstrap page in an [`IndexHtmlRequestListener`](https://vaadin.com/docs/next/flow/advanced/modifying-the-bootstrap-page.md#IndexHtmlRequestListener-interface). The listener sends the nonce in the `Content-Security-Policy` header, and adds it to the scripts and module preload links of the page. The `csp-nonce` meta tag provides the nonce to the module preload links that the page adds later, when it loads more of the application. The following example registers the listener in a Spring application:

```java
@Bean
VaadinServiceInitListener contentSecurityPolicyNonceInjector() {
    return event -> event.addIndexHtmlRequestListener(response -> {
        if (!response.getVaadinRequest().getService()
                .getDeploymentConfiguration().isProductionMode()) {
            return; // A strict Content Security Policy works only in production mode
        }
        String nonce = UUID.randomUUID().toString();

        // Make the browser require the nonce for all scripts
        response.getVaadinResponse().setHeader("Content-Security-Policy",
                "script-src 'nonce-" + nonce + "'");

        // Add the nonce to the scripts and module preloads of the page
        Document document = response.getDocument();
        document.select("script, link[rel=modulepreload]")
                .attr("nonce", nonce);
        document.head().appendElement("meta")
                .attr("property", "csp-nonce").attr("nonce", nonce);
    });
}
```

<!-- vale Vale.Spelling = NO -->

## <a id="function-execution-eval-calls"></a>Function Execution & Eval Calls

<!-- vale Vale.Spelling = YES -->

The nonce alone doesn’t cover the JavaScript that the server sends as strings. The Flow client engine runs it by constructing functions with the `Function` constructor, which a strict policy blocks. An application that uses a strict Content Security Policy must therefore override the `Function` constructor and `eval()` with versions that return pre-defined functions instead. Put the overrides into a JavaScript file, such as `src/main/frontend/content-security-policy.js`, and load it with `@JsModule("./content-security-policy.js")` on the main layout of the application:

```javascript
// Override the Function constructor with a version that uses pre-defined functions
const originalFunction = window.Function;
window.Function = function(...args) {
  const key = args.join(",");

  if (functions.has(key)) {
    return functions.get(key);
  }

  // Log the code to add to the functions map
  const code = args[args.length - 1];
  console.warn(`functions.set(${JSON.stringify(key)},\n  function(${args.slice(0, -1).join(',')}) {${code}\n});`);

  // Fall back to the original constructor.
  // This fails under a strict Content Security Policy, but this way the browser reports an error.
  return originalFunction.apply(null, args);
};

// Override eval() with a version that uses pre-defined functions
const originalEval = window.eval;
window.eval = function(script) {
  const originalArg = script;
  // Removes parentheses used by Vaadin Charts
  if (script.length > 1 && script.startsWith("(") && script.endsWith(")")) {
    script = script.substring(1, script.length - 1);
  }
  if (evalCalls.has(script)) {
    return evalCalls.get(script);
  }

  // Log the code to add to the evalCalls map
  if (script.startsWith("function")) {
    console.warn(`evalCalls.set(${JSON.stringify(script)},\n  ${script}\n);`);
  } else {
    console.warn(`evalCalls.set(${JSON.stringify(script)},\n  function() {return ${script}\n});`);
  }

  // Fall back to the original eval().
  // This fails under a strict Content Security Policy, but this way the browser reports an error.
  return originalEval(originalArg);
};
```

Loading a route whose JavaScript is in a lazily loaded chunk doesn’t need an entry: the chunk loader is a function declared in the bundle, so nothing is compiled from a string when the chunk loads.

The `functions` and `evalCalls` maps map the code that the server sends to pre-defined functions. Which entries an application needs depends on the components and features that it uses, and on the Vaadin version. To collect them, run the application in production mode without the `Content-Security-Policy` header, and use every view and feature. For every function that’s missing from the maps, the overrides log a line to the browser console that you can copy into the file. Collect the entries again after upgrading Vaadin.

The following snippet shows a few entries. A real application has many more:

```javascript
const functions = new Map();
functions.set("event,element,return (event.shiftKey)",
  function(event,element) {return (event.shiftKey)});
functions.set("$0,if ($0) window.Vaadin.Flow.gridConnector.initLazy($0)",
  function($0) {if ($0) window.Vaadin.Flow.gridConnector.initLazy($0)});

const evalCalls = new Map();
evalCalls.set("'The value for <b>' + this.x + '</b> is <b>' + this.y + '</b>'",
  function() {return 'The value for <b>' + this.x + '</b> is <b>' + this.y + '</b>'});
```

## <a id="built-in-strict-csp"></a>Built-in Strict Content Security Policy

The `contentSecurityPolicy` configuration parameter is a separate mechanism, with which Vaadin sends a strict, nonce-based policy itself, without `'unsafe-inline'` and `'unsafe-eval'` in `script-src`. (V25.4 pre-release) See [Configuration Properties](https://vaadin.com/docs/next/flow/configuration/properties.md) for how to set the parameter.

The `strict` mode is a preview. An application runs under the policy when everything it uses works without `eval`. See [Preview Limitations](#preview-limitations) for the APIs that don’t. For an application that such a limitation affects, use the approach described in [Creating Random Nonce](#creating-random-nonce) and [Function Execution & Eval Calls](#function-execution-eval-calls) to run under a strict policy.

Set the parameter to `warn` to log every call in the application that wouldn’t work under such a policy. Each log entry is a `ContentSecurityPolicyViolationException`, whose stack trace leads to the code that made the call.

Set the parameter to `strict` to have Vaadin send the policy. Vaadin sends it only in production mode. In development mode, no `Content-Security-Policy` header is sent and no nonce is added to the page, because the development server and the development tools need `eval`. An API that sends JavaScript to the browser as a string, such as `executeJs()` with a string expression, throws a `ContentSecurityPolicyViolationException` in both production and development mode. However, the browser doesn’t block anything the policy wouldn’t allow, such as a request to an external API or an image from another origin, until the application runs as a production build. Test a production build of the application under the policy before you rely on it.

In production mode, Vaadin generates a new nonce for every index HTML response. It puts the nonce on every `<script>` element and script preload link of the page. This includes the ones added by an `IndexHtmlRequestListener` or an `@Inline` annotation. Vaadin then sends a header such as:

```
Content-Security-Policy: default-src 'self'; script-src 'nonce-...' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self' data:; worker-src 'self'; object-src 'none'; base-uri 'self'
```

To allow a resource that the default policy doesn’t, such as an external API the application calls, add an `IndexHtmlRequestListener` and add sources to the `ContentSecurityPolicy` of the response:

```java
@Bean
VaadinServiceInitListener contentSecurityPolicySources() {
    return event -> event.addIndexHtmlRequestListener(response -> {
        ContentSecurityPolicy policy = response.getContentSecurityPolicy();
        if (policy != null) { // null unless contentSecurityPolicy is strict
            policy.addSources("connect-src", "https://api.example.com");
        }
    });
}
```

The `data:` source in `connect-src` lets an `SvgIcon` load an icon from a `data:image/svg+xml` URL, because the browser fetches the source of the icon. It allows the page to read inline data, but not to run it as code. If a security scanner of the application reports it, and the application doesn’t use `data:` URLs for icons, remove it by setting the directive again in the listener. Call it before any `addSources()` call for `connect-src`, such as the one in the listener above, because `setDirective()` replaces all the sources of the directive:

```java
ContentSecurityPolicy policy = response.getContentSecurityPolicy();
if (policy != null) {
    policy.setDirective("connect-src", "'self'"); // removes data:
}
```

Leave `script-src` unchanged: it holds the nonce and `'strict-dynamic'`, so replacing it blocks every script on the page, and host sources added to it are ignored by the browser. To load a script from another origin instead, add a `<script>` element to the document, which gets the nonce automatically.

Setting the `Content-Security-Policy` header another way, such as from a servlet filter that runs before Vaadin or the listener in [Creating Random Nonce](#creating-random-nonce), isn’t compatible with this: in production mode, the request fails if the header is already set when the page is written, so that the page is never sent without Vaadin’s own policy. A policy configured in Spring Security doesn’t fail the request. See [Spring Security](#spring-security) for how the two policies work together.

### <a id="preview-limitations"></a>Preview Limitations

The `strict` mode has the following limitations:

- A chart option that takes a JavaScript function as a string, such as `Tooltip.setFormatter()`, throws a `ContentSecurityPolicyViolationException`. Use a format string or a `ChartFunction` instead, as described in [Chart Functions Under a Strict Content Security Policy](https://vaadin.com/docs/next/components/charts/configuration.md#charts.configuration.csp).

- An add-on that calls a string-based JavaScript API throws the same exception. Run the application with `warn` first to see which of its add-ons are affected.

- The policy keeps `'unsafe-inline'` in `style-src`, because UI components add styles to the page while the application runs.

### <a id="spring-security"></a>Spring Security

Spring Security can send a `Content-Security-Policy` header of its own, which an application configures with `contentSecurityPolicy()` in the security filter chain. In the `strict` mode, the bootstrap page carries only the policy of Vaadin. The directives configured in Spring Security aren’t merged into it, and nothing is logged about that.

Add the directives that the bootstrap page needs to the `ContentSecurityPolicy` of the response instead:

```java
@Bean
VaadinServiceInitListener contentSecurityPolicyDirectives() {
    return event -> event.addIndexHtmlRequestListener(response -> {
        ContentSecurityPolicy policy = response.getContentSecurityPolicy();
        if (policy != null) { // null unless contentSecurityPolicy is strict
            policy.setDirective("frame-ancestors", "'none'");
        }
    });
}
```

The other responses of the application keep the policy configured in Spring Security. These are the files of the frontend bundle, downloads, and the responses that Spring Security writes itself, such as an access denied response.

`B5E8EEC6-0F7E-49C5-8121-0906827BE4A5`
