Migrate to a Strict Content Security Policy
- Find the Calls with the Warn Mode
- Replace String JavaScript
- Handle Add-Ons
- Allow External Resources
- Switch to the Strict Mode
- Make Add-Ons Compatible
|
Note
|
Preview Feature
The strict Content Security Policy mode is a preview feature. This means that it is not yet ready for production usage and may have limitations or bugs. We encourage you to try it out and provide feedback to help us improve it. |
A strict Content Security Policy lets the browser run only the scripts that the server marked with a nonce, and blocks JavaScript that’s compiled from a string. Vaadin sends such a policy itself when the contentSecurityPolicy configuration parameter is strict. See Built-in Strict Content Security Policy for the policy it sends.
Code that sends JavaScript to the browser as a string, such as executeJs("…"), doesn’t work under the policy. This guide shows how to find that code with the warn mode, and what to replace it with. Follow these steps for an application:
-
Find the calls with the
warnmode. -
Replace string JavaScript in your own code.
-
Handle add-ons that send string JavaScript.
-
Allow external resources that the default policy blocks.
-
Switch to the strict mode, and test a production build.
If you maintain an add-on, see Make Add-Ons Compatible.
Find the Calls with the Warn Mode
The warn mode leaves the application unchanged, but logs every call that wouldn’t work under a strict policy. Set the parameter in application.properties:
Source code
properties
vaadin.contentSecurityPolicy=warnWithout Spring Boot, set contentSecurityPolicy as described in Configuration Properties.
The warn mode works in development mode, too. Start the application, and use every view and feature, so that each call runs at least once. Each call is logged as a warning with a ContentSecurityPolicyViolationException, whose stack trace starts at the API that sent the string, and usually leads to the code that called it. The call can be in your own code, in a Vaadin UI component, or in an add-on.
Some APIs send their string only when the response is written, so the stack trace has only framework frames. The first frame then tells you which API it is. Search your code for its calls:
-
LitRenderer.setElementRenderer: aLitRenderer.of(String)template -
StringFunctionReporterin the Charts package: a chart option set with a string, such asTooltip.setFormatter(String) -
ShortcutRegistration:Shortcuts.setShortcutListenOnElement(String, Component). The message calls it aJsFunction.of()call, and the method name it suggests doesn’t fit. Use the replacement in the table below instead.
Some string-based APIs, such as addEventData(String) and setShortcutListenOnElement(String, Component), are deprecated, so the deprecation warnings of the compiler are a second list of calls to change. Not every such call is logged. For example, addEventData(String) with a plain property path, such as event.target.value, works under the policy and isn’t logged, but you should still replace it.
For executeJs(), JsFunction.of(), and the string overloads of listener filters and event data, the message also contains a declaration that replaces the string, and how to use it. Paste it, then edit it: the method is named after the code that made the call, its parameters are Object arg0, Object arg1, and so on, and it returns PendingJavaScriptResult. Give the method a name that says what it does, and give the parameters and the return value their real types.
A call site is logged once for each string that it sends, and at most ten times. A call site that sends five or more different strings probably builds them from changing values. The message then says so. See Pass Changing Values as Parameters.
A call site that has sent fewer strings isn’t flagged, even if it builds them from changing values. Before you use a logged string as it is, check it for values that change, such as ids, counters, coordinates, or user data. Use each view more than once, or restart the application and use the view again, and check that the warning doesn’t come back.
The warn mode doesn’t send the policy, so the browser doesn’t block anything yet. JavaScript that the browser compiles on its own, such as a call to eval() in a frontend file, and resources from other origins don’t show up in the log. You find them in the last step, when you test under the policy.
Replace String JavaScript
Replace each logged call in your own code with the API that runs JavaScript from the frontend bundle. You declare the JavaScript in a Java interface annotated with @JsDefinition, and the build puts it into the bundle. The browser runs it from there, without compiling anything.
| String-based API | Replacement |
|---|---|
| A method of a |
| A |
| A method that returns |
|
|
|
|
|
|
|
|
|
|
Chart options that take a function as a string, such as | A format string, or a declared |
|
|
| A method of a |
An inline event handler attribute, such as | A server-side listener, or |
The warn mode doesn’t log inline event handlers, because the browser runs them without a Vaadin API. Search your code for setAttribute("on and for on attributes in HTML strings.
The following APIs work under a strict policy without changes:
-
callJsFunction(), unless an argument is aJsFunctionbuilt withJsFunction.of() -
The
filterof@DomEventand the values of@EventData, which the build puts into the bundle -
The built-in renderers of Grid and other UI components, such as
LocalDateRendererandComponentRenderer, unless a subclass overridesgetTemplateExpression()
A production build that optimizes the bundle, which is the default, only includes the @DomEvent classes and the @JsDefinition interfaces that it reaches from the routes of the application. If you use one of them only through reflection, name it in @Uses on a class that the build reaches.
Replace a Call to executeJs
For example, the following code scrolls an element to a position with a string expression:
Source code
Java
getElement().executeJs("this.scrollTop = $0", position);Declare the expression as a method of an interface instead, and call the method:
Source code
Java
@JsDefinition
public interface ScrollJs extends JsInvokers {
@JsExpression("this.scrollTop = $0")
void scrollTo(int position);
}Source code
Java
getElement().executeJs(ScrollJs.class).scrollTo(position);The build generates a function into the bundle for each method of the interface.
For a call that returns a value, declare PendingJavaScriptResult as the return type of the method, and read the value as before:
Source code
Java
@JsDefinition
public interface BrowserJs extends JsInvokers {
@JsExpression("return navigator.language")
PendingJavaScriptResult language();
}Source code
Java
UI.getCurrent().getPage().executeJs(BrowserJs.class).language()
.then(String.class, language -> setLocale(language));A method can also return JavaScriptResult with the type of the value. See Return Values.
A method that only calls a JavaScript function of the element needs no expression. Without @JsExpression, the method calls the function of the element that has the same name, with the arguments of the call. For example, void showPopover(); runs this.showPopover(). This works only through Element.executeJs(Class), because a call through the page doesn’t run on an element.
Pass Changing Values as Parameters
The build can only put JavaScript into the bundle that you know when you build the application. JavaScript that’s assembled from values at runtime has to take those values as parameters instead:
Source code
Java
// Can't be declared: a different string for each color
getElement().executeJs("this.style.color = '" + color + "'");
// Declared once, with the color as a parameter
@JsDefinition
public interface ColorJs extends JsInvokers {
@JsExpression("this.style.color = $0")
void setColor(String color);
}If the varying part is itself code, such as one of several functions, declare one method for each of them.
Call Functions of Frontend Modules
Code often reaches a function of a frontend module through a global variable that the module sets, for example a connector:
Source code
Java
getElement().executeJs("window.Vaadin.myChart.init(this, $0)", options);First, change the module to export its functions. A connector that sets a global object, such as window.Vaadin.myChart = { init, update }, exports nothing, so the declarations below would build, but fail in the browser with an error such as this.init is not a function. Turn each function of the global object into a named export:
Source code
JavaScript
// Before
window.Vaadin.myChart = {
init(element, options) { /* ... */ this.update(element, options); },
update(element, options) { /* ... */ }
};
// After
export function init(element, options) { /* ... */ update(element, options); }
export function update(element, options) { /* ... */ }A function of the old object that called another one through this now calls it directly, as init() calls update() above.
Then declare the call with @JsDefinitionImport. It imports what the module exports, the same way as a JavaScript import statement:
Source code
Java
@JsDefinition
@JsDefinitionImport(from = "./my-chart.js", exports = "init")
public interface MyChartJs extends JsInvokers {
@JsExpression("init(this, $0)")
void init(JsonNode options);
}Source code
Java
getElement().executeJs(MyChartJs.class).init(options);The module is loaded by the first call that needs it. The call waits for the module, so its JavaScript runs after the calls that follow it in the same round trip. When later calls depend on it, such as calls to a connector that the first call sets up, declare the functions in an interface that extends JsModuleInvokers instead. Its modules are loaded with the views that use it, or at startup in development mode, so its calls usually run in order. A call made before any view that uses the interface has been shown still waits for the module. In the JavaScript, the module is this, and a method without @JsExpression calls the function of the module with the same name:
Source code
Java
@JsDefinition
@JsDefinitionImport(from = "./my-chart.js")
public interface MyChartConnector extends JsModuleInvokers {
// Runs this.init($0, $1), where this is the module
void init(Element chart, JsonNode options);
}Source code
Java
addAttachListener(event -> event.getUI().getPage()
.executeModuleJs(MyChartConnector.class)
.init(getElement(), options));An Element argument arrives as null when the element isn’t attached when Vaadin sends the call. That’s why the example makes the call when the component is attached.
The module doesn’t need a @JsModule any more, so you can remove it. Keep it only if the module has to run code at startup, before the first call.
A path starting with ./ is resolved like the path of a @JsModule. The build fails when it can’t find the file. See Importing Module Exports for the details.
Declare Lit Renderer Templates
A LitRenderer created from a string template sends the template to the browser as a string, for example:
Source code
Java
grid.addColumn(LitRenderer.<Person> of(
"<span @click=${select}>${item.name}</span>")
.withProperty("name", Person::getName)
.withFunction("select", this::select));Declare the template as a method that returns CompiledLitTemplate in a JsSnippets interface. The expression is the body of a function that returns the template. The function gets html, the tag of a Lit template, and the values that the template renders, such as item and index. The functions added with withFunction() are members of functions, as in ${functions.select}:
Source code
Java
@JsDefinition
public interface PersonTemplates extends JsSnippets {
@JsExpression("return html`<span @click=${functions.select}>${item.name}</span>`;")
CompiledLitTemplate name();
}Source code
Java
private static final PersonTemplates TEMPLATES = JsSnippets.of(PersonTemplates.class);
grid.addColumn(LitRenderer.<Person> of(TEMPLATES.name())
.withProperty("name", Person::getName)
.withFunction("select", this::select));When you move a template, change each function in it, but leave the properties as they are:
Source code
JavaScript
// Before, in LitRenderer.of(String)
<span @click=${select}>${item.name}</span>
// After, in the declared template
<span @click=${functions.select}>${item.name}</span>A template that still uses ${select} renders nothing, and the browser console reports that select isn’t defined.
Handle Add-Ons
When the stack trace of a logged call leads into an add-on, check first whether a newer version of the add-on supports a strict Content Security Policy:
-
Read the release notes, documentation, and issue tracker of the add-on. Support for a strict policy can also be merged before it’s released.
-
Upgrade the add-on, and repeat the
warnrun. Also test the add-on in a production build under the policy, as in Switch to the Strict Mode, because thewarnmode doesn’t log what only the browser blocks.
An add-on that logs no warnings isn’t known to be safe yet, for the same reason. Some add-ons compile JavaScript only in the browser, and you only find that in the production test.
If it doesn’t, you can often declare the strings that the add-on sends in your application, in an interface annotated with @JsStringFallback. When the add-on sends a string that matches a declaration exactly, Vaadin runs the declared JavaScript from the bundle instead. The logged message contains the declaration to paste for most such calls. See Declaring Fallbacks for Add-on JavaScript Strings for the APIs that look for a fallback, and how to declare one.
For example, an add-on sends this string, which the application can’t change:
Source code
Java
// In the add-on
getElement().executeJs("return this.scrollTop");The application declares the same string in an interface of its own. The method is never called. The build puts its JavaScript into the bundle, and Vaadin runs it when the add-on sends the matching string:
Source code
Java
@JsDefinition
@JsStringFallback
public interface AddonFallbacks extends JsInvokers {
@JsExpression("return this.scrollTop")
PendingJavaScriptResult scrollTop();
}A fallback doesn’t help in the following cases, which only the maintainers of the add-on can fix:
-
The add-on builds the string from changing values, so that it’s different each time. Check the logged string for ids, counters, or other values that change, as described in Find the Calls with the Warn Mode. A fallback for such a string never matches again, even though the message offers one.
-
The add-on sends the string through an API that doesn’t look for a fallback, such as a
LitRenderertemplate or a chart option. -
The frontend files of the add-on call
eval()ornew Function(), or set inline event handler attributes, such asonclick. Thewarnmode doesn’t log these, because they don’t go through a Vaadin API. The browser blocks them under the policy.
Report these cases to the maintainers of the add-on, with the logged message or the error in the browser console. The section Make Add-Ons Compatible describes what they need to change.
An error in the browser console doesn’t name the add-on. It points to a minified file of the bundle, such as VAADIN/build/vaadin-theme-<hash>.js, because the build puts the frontend files of add-ons there. Find the add-on from the view and the component that fail. Development mode doesn’t show the error, because Vaadin doesn’t send the policy there.
Under the strict mode, a string that isn’t covered throws an exception where the add-on sends it. If that’s in the constructor of a view, the whole view fails to open, not only the component of the add-on.
Until the add-on is fixed, the application can’t use the strict mode. It can still run under a strict policy with the manual approach: it sends the policy itself as in Creating Random Nonce, and overrides the Function constructor and eval() as in the section after it. The overrides map every string that the browser would compile to a function collected in advance. This includes LitRenderer templates, chart options, and calls to eval() in frontend files. Like a fallback, they can’t map strings built from changing values, and they don’t cover inline event handler attributes.
Allow External Resources
The policy that Vaadin sends allows resources only from the origin of the application, plus images, fonts, and fetches of data: URLs. The browser blocks anything else, for example:
-
Images, fonts, or stylesheets from a content delivery network
-
Requests to an API on another origin, from the browser
-
An
IFramethat shows a page from another origin
Add the sources that the application needs in an IndexHtmlRequestListener, as described in Built-in Strict Content Security Policy. Keep script-src unchanged. To load a script from another origin, add a <script> element to the page, which gets the nonce automatically.
The default policy has no frame-src, media-src, or manifest-src directive, so the browser uses default-src 'self' for them. Adding a source to such a directive creates it with only that source, so add 'self' too, if the page needs it:
Source code
Java
policy.addSources("frame-src", "'self'", "https://www.openstreetmap.org");Directives of your own, such as frame-ancestors or upgrade-insecure-requests, go into the same listener.
Vaadin has to be the only code that sets the Content-Security-Policy header of the page, unless the policy comes from Spring Security. Remove any other code that sets it, such as a servlet filter, or a listener that adds a nonce to the page itself, and move its directives into the listener. In production mode, the request fails if the header is already set when Vaadin writes the page. Vaadin adds its policy only in the strict mode, so remove the other code in the same change that switches to strict. Otherwise, a build that’s deployed in between sends no policy at all.
If the application configures a policy in Spring Security, Vaadin puts the nonce of Spring Security on the scripts of the page, and sends no policy of its own. The directives stay in the Spring Security configuration, and the policy there has to allow what Vaadin needs, such as 'nonce-{nonce}' in script-src. The listener then gets no policy to change, so add the sources and directives of this section in the Spring Security configuration instead. VaadinSecurityConfigurer.contentSecurityPolicy() starts from the policy that Vaadin needs:
Source code
Java
http.with(vaadin(), vaadin -> vaadin.contentSecurityPolicy(policy -> policy
.addSources("img-src", "https://cdn.example.com")
.setDirective("frame-ancestors", "'self'")));See <<{articles}/flow/security/protections/content-security-policy#spring-security,Spring Security>>.
The strict mode replaces the manual nonce and the manual overrides of the Function constructor and eval(). If your application uses them, remove its nonce listener and the script with the overrides when you switch.
Switch to the Strict Mode
When the log stays free of warnings, switch to the strict mode:
Source code
properties
vaadin.contentSecurityPolicy=strictIn this mode, every call to a string-based API throws a ContentSecurityPolicyViolationException, in both development and production mode. A call that you missed fails visibly instead of being logged.
Vaadin sends the policy only in production mode, because the development server and the development tools need eval(). Create a production build and run it. Then use every view and feature of the application with the developer tools of the browser open. The browser logs every script, style, or resource that the policy blocks as an error in the console. Fix each of them by adding a source, or by changing the code that needs it.
The browser logs a block in a web worker in the console of the worker, such as a worker that loads from another origin and needs a worker-src source. The developer tools show it, but a test that collects the console messages of the page only sees that the worker failed to load.
Keep the strict mode in the tests that run against a production build, so that a new string-based call fails a test.
Make Add-Ons Compatible
An add-on works under a strict policy when it sends no JavaScript as a string, and its frontend files compile no JavaScript from strings.
For the Java code, replace every string-based API as listed in Replace String JavaScript. Declare the @JsDefinition interfaces in the add-on JAR. The build of the application puts their JavaScript into the bundle when it reaches the classes of the add-on that use them. Never build JavaScript from changing values: pass them as parameters, as described in Pass Changing Values as Parameters.
Some add-on APIs take JavaScript from the application as a string, such as a formatter or a callback. Have them take a JsFunction instead, which the application declares in a JsSnippets interface of its own. A declared function works across JARs. An add-on can also declare its own type that extends JsSnippet, so that its API accepts only functions of that kind. The ChartFunction of Charts is an example. Keep the old string API, deprecated, and have it build the function with JsFunction.of(), so that the warn mode logs the applications that still call it.
Connectors and other frontend modules that the Java code calls through a global variable can stay plain modules. Call their functions as described in Call Functions of Frontend Modules. Put the modules in the frontend folder of the JAR, like the files of a @JsModule. A module that the build can’t find stops the build of every application that uses the add-on.
For the frontend files, avoid the code that the browser blocks under the policy:
-
eval(),new Function(), andsetTimeout()orsetInterval()with a string -
Inline event handler attributes, such as
onclick, also when set from Java withsetAttribute() -
javascript:URLs -
<script>elements without the nonce, created from HTML strings -
Third-party libraries that do any of these
Inline styles aren’t affected, because the policy allows 'unsafe-inline' in style-src.
To test the add-on, run the browser tests of its test application against a production build, with contentSecurityPolicy set to strict. Only a production build is sent the policy, so only there does the browser block what the frontend files compile, such as new Function() in a connector. The strict mode in development mode is a quicker check for the Java code: the string-based calls throw there, too.
The declared JavaScript APIs need the Vaadin version that introduced the strict mode. Say in the description of the add-on which of its versions support a strict policy.
7B0D3C5E-2F4A-4E8B-9C61-5A8E2D7F14B3