Content Security Policy
- Required Settings
- Vaadin & Strict Content Security Policy
- Creating Random Nonce
- Function Execution & Eval Calls
- Built-in Strict Content Security Policy
A Content Security Policy 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.
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.
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.
Creating Random Nonce
The application generates a new nonce for each request of the bootstrap page in an IndexHtmlRequestListener. 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:
Source code
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);
});
}Function Execution & Eval Calls
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:
Source code
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:
Source code
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>'});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. See Configuration Properties 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 for the APIs that don’t. For an application that such a limitation affects, use the approach described in Creating Random Nonce and 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, Vaadin sends no Content-Security-Policy header. It adds no nonce to the page either, unless Spring Security sends a policy. See Spring Security. 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:
Source code
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:
Source code
Java
@Bean
VaadinServiceInitListener contentSecurityPolicySources() {
return event -> event.addIndexHtmlRequestListener(response -> {
ContentSecurityPolicy policy = response.getContentSecurityPolicy();
// null unless contentSecurityPolicy is strict and Vaadin sends the policy
if (policy != null) {
policy.addSources("connect-src", "https://api.example.com");
}
});
}The Map component is an example of this: it loads map images from the map service, so the origin of the service has to be added to img-src.
When Spring Security sends the policy, the listener has no policy to change. Change the policy as described in Spring Security instead.
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:
Source code
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, isn’t compatible with this. In production mode, the request fails if the header is already set when the page is written. This way, the page is never sent without Vaadin’s own policy. A policy configured in Spring Security is the exception: Vaadin then uses the nonce of that policy and sends no policy of its own. See Spring Security.
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 aContentSecurityPolicyViolationException. Use a format string or aChartFunctioninstead, as described in Chart Functions Under a Strict Content Security Policy. -
An add-on that calls a string-based JavaScript API throws the same exception. For the APIs listed in Declaring Fallbacks for Add-on JavaScript Strings, the application can declare the string as a fallback instead. Run the application with
warnfirst to see which of its add-ons are affected. -
The policy keeps
'unsafe-inline'instyle-src, because UI components add styles to the page while the application runs.
Declaring Fallbacks for Add-on JavaScript Strings
An add-on that sends JavaScript to the browser as a string, through an API such as executeJs(), throws the same exception as application code that does — but the add-on can only be fixed by its maintainers. Declare the exact strings it sends in a @JsDefinition interface marked @JsStringFallback, and a string that matches runs the declared JavaScript from the bundle instead of being refused.
For example, an add-on component sends these strings:
Source code
Java
// In the add-on, which the application can't change
getElement().executeJs("return this.scrollTop") 1
.then(Double.class, this::restoreScroll);
getElement().addJsInitializer("this.title = $0", title); 2
getElement().addEventListener("keydown", event -> close())
.setFilter("event.key === 'Escape'") 3
.addEventData("event.target.value.trim()"); 3-
A string run with
executeJs()orPage.executeJs(). -
A function body, as passed to
JsFunction.of(). The string overloads ofaddJsInitializer()andPage.addDynamicImport()build such a function. -
A listener filter or event data string.
The application declares the same strings as fallbacks:
Source code
Java
@JsDefinition
@JsStringFallback(
filters = "event.key === 'Escape'", 3
eventData = "event.target.value.trim()") 3
public interface AddonFallbacks extends JsInvokers {
@JsExpression("return this.scrollTop") 1
PendingJavaScriptResult scrollTop();
}
@JsDefinition
@JsStringFallback
public interface AddonFunctionFallbacks extends JsSnippets {
@JsExpression("this.title = $0") 2
JsFunction setTitle(Object title);
}-
A string for
executeJs()is the@JsExpressionof a method in an interface that extendsJsInvokers, with as many parameters as the call passes. It’s declared the same way as any other JavaScript in Java. -
A function body is the
@JsExpressionof a method that returnsJsFunction, with as many parameters as the function has captured values. It goes into an interface that extendsJsSnippets(see Declaring Snippets), since one interface can’t extend both. When the add-on then callswithArguments()on the function, declare the same names on the method with@JsFunctionParameterNames. -
A filter or event data string goes into the
filtersoreventDataof the annotation, rather than into a method. A property path, such asevent.target.value, isn’t compiled by the browser, so it needs no fallback, and the build fails if one is listed.
The method names only need to be unique within the interface. The application never calls these methods: the build puts their JavaScript into the bundle, and Flow uses it when the add-on sends a matching string.
The exception or log message for a refused string already contains the declaration to paste, with a note to add @JsStringFallback when the call is in an add-on. Copy it into an interface, add the annotation, and the next build puts the function into the bundle.
Fallbacks have the following limitations:
-
Only the APIs in the example and its callouts look for a fallback. A string sent another way, such as a chart option or a
LitRenderertemplate, has no fallback. -
A declaration matches one exact string, including whitespace. An add-on release that changes the string is refused again until the fallback is updated for the new text.
-
A string built from a value that changes can’t be matched, since the bundle only holds strings that are known when the application is built. For example, an add-on that joins a color into the JavaScript sends a different string for each color:
Source code
Java
// A different string for each color: no fallback can match it getElement().executeJs("this.style.color = '" + color + "'"); // One string, with the color as a parameter: a fallback can match it getElement().executeJs("this.style.color = $0", color);Only the add-on’s maintainers can change the first form into the second.
-
The JavaScript in the bundle runs in JavaScript strict mode, while a string that the browser compiles doesn’t. A string that only works outside strict mode, such as one that assigns to a variable it never declares, fails the same way when it runs as a fallback.
-
JavaScript that the browser refuses on its own, such as an inline
onclickattribute or a call toevalin the add-on’s frontend files, isn’t covered, since Flow never runs it.
Spring Security
An application that uses Spring Security can configure the policy there. Spring Security then creates a nonce for each request and sends the policy. Vaadin puts that nonce on the scripts of the bootstrap page and sends no policy of its own.
Use this together with the strict value of the contentSecurityPolicy parameter. With off or warn, the bootstrap page loads, but the browser blocks the JavaScript that the server sends as strings, such as the expression of executeJs().
Configure the policy with contentSecurityPolicy() of VaadinSecurityConfigurer:
Source code
Java
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.with(vaadin(), vaadin -> vaadin.contentSecurityPolicy());
return http.build();
}Spring Security then sends the same policy that Vaadin sends in the strict mode. It sends the policy with every response of the security filter chain, not only with the bootstrap page. Other pages of the application can use the nonce for their own scripts. Spring Security stores it as a request attribute named _csp, or the name set with nonceAttributeName() in the second function described below.
To change the policy, pass a function that receives the ContentSecurityPolicy:
Source code
Java
http.with(vaadin(), vaadin -> vaadin.contentSecurityPolicy(policy -> policy
.addSources("connect-src", "https://api.example.com")
.setDirective("frame-ancestors", "'none'")));An IndexHtmlRequestListener can’t change the policy in this case, because IndexHtmlResponse.getContentSecurityPolicy() returns null when Vaadin doesn’t send the policy.
A second function sets the other options that Spring Security has for the policy, such as the requests that it’s sent for:
Source code
Java
http.with(vaadin(), vaadin -> vaadin.contentSecurityPolicy(policy -> {
}, config -> config.requestMatchers("/app/**")));The request matcher must cover the routes of the application. A bootstrap page outside it is sent without a policy.
Calling contentSecurityPolicy() on VaadinSecurityConfigurer replaces a policy that the same filter chain configures with HttpSecurity.headers(). If the application has disabled the headers of Spring Security for the filter chain, only the Content-Security-Policy header is added.
Spring Security sends the policy in development mode too, and Vaadin puts the nonce on the scripts there as well. This differs from an application without Spring Security, where no policy is sent in development mode.
The application, the development tools and Copilot work with the policy in development mode. The browser blocks three things that they do, and reports each one in its console:
-
With the Vite development server, the page doesn’t reload by itself when its first script fails to load, for example while Vite is still starting. Reload the page by hand.
-
The Vaadin components don’t collect usage statistics.
-
The picture of the Vaadin account isn’t shown in the development tools, because it’s loaded from
vaadin.com.
Policy Written in Spring Security
An application can also write the policy itself with HttpSecurity.headers(). Vaadin uses the nonce of any policy that the filter chain configures there. The policy must allow the nonce in script-src, with the {nonce} placeholder that Spring Security replaces with the nonce of the request. It must also have all the directives of the following example, which is the policy that Vaadin sends in the strict mode. The application can add sources and directives to it:
Source code
Java
http.headers(headers -> headers.contentSecurityPolicy(policy -> policy
.policyDirectives("default-src 'self'; "
+ "script-src 'nonce-{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'")));
http.with(vaadin(), vaadin -> {
});When the Page Isn’t Protected
Spring Security decides what’s sent and for which requests, and Vaadin adds nothing to it. The page is sent as the security filter chain is configured, also when that leaves the bootstrap page without a strict policy. Nothing is logged in these cases:
| Policy in Spring Security | What the browser enforces on the bootstrap page |
|---|---|
A report-only policy, set with | Nothing. The browser only reports violations. |
A policy with a request matcher that doesn’t match the request | Nothing. The page is sent without a policy. |
A policy that doesn’t restrict scripts, such as | That policy. Scripts aren’t restricted. |
A policy with | That policy. Inline scripts aren’t restricted. |
A policy that restricts scripts without the nonce, such as | That policy. The inline scripts of the page are blocked. The browser console reports each one. |
An application that already has a policy in Spring Security keeps it unchanged when the contentSecurityPolicy parameter is set to strict. Check that the policy has the {nonce} placeholder in script-src, and neither 'unsafe-inline' nor 'unsafe-eval' there.
A filter chain without a policy isn’t affected: Vaadin sends its own policy for the bootstrap pages that it serves. An application can have the policy of Vaadin on the Vaadin pages and another policy elsewhere. Use two filter chains for that, and configure a policy only in the one that doesn’t serve Vaadin pages. See Multiple Filter Chains for how to set them up.
B5E8EEC6-0F7E-49C5-8121-0906827BE4A5