Skip to content

docs: add a guide for migrating to a strict CSP - #6789

Draft
totally-not-ai[bot] wants to merge 15 commits into
mainfrom
docs/strict-csp-migration-guide
Draft

totally-not-ai[bot] wants to merge 15 commits into
mainfrom
docs/strict-csp-migration-guide

Conversation

@totally-not-ai

@totally-not-ai totally-not-ai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds a how-to guide under Building Apps > Security for moving an application or an add-on to the strict, nonce-based Content Security Policy mode (contentSecurityPolicy=strict). It starts from the warn mode, which logs every call that wouldn't work under the policy, and walks through fixing them.

The Spring Security paragraph describes the behavior of vaadin/flow#27471 (also in 25.4); the reference section it links to is updated for that behavior in #6808 / #6821, so merge one of those together with this PR.

What changed

  • New page building-apps/security/strict-content-security-policy.adoc (marked as a preview, like the strict mode itself):
    • Find the calls with warn: what is logged, the stack traces that have only framework frames (Lit renderers, chart options, shortcut locators), compiler deprecation warnings as a second list, editing the suggested declarations, strings with changing ids that aren't flagged, the per-call-site limits, and what warn can't find (browser-side blocks).
    • A table that maps each string-based API (executeJs(String), JsFunction.of(), addJsInitializer(String), addDynamicImport(String), setFilter(String), addEventData(String), LitRenderer.of(String), chart string functions, setShortcutListenOnElement(String), executeJsWhenAttached(), inline on… handler attributes) to its replacement, with links to the reference. Notes on withArguments(), and on dynamic imports of server-served URLs that now fail the build.
    • What already works unchanged (callJsFunction(), @DomEvent filters, @EventData, built-in renderers), and the @Uses caveat for optimized production builds.
    • A JsInvokers method without @JsExpression, which calls the element function of the same name, and a call that returns a value.
    • Passing changing values as parameters, and declaring Lit renderer templates with CompiledLitTemplate.
    • Calling functions of frontend modules (such as connectors reached through a global variable) with @JsDefinitionImport, or with JsModuleInvokers and Page.executeModuleJs(Class) when later calls depend on the first one. Turning a global-object connector into named exports, and dropping its @JsModule.
    • A before/after of a Lit template, for ${fn} → ${functions.fn}.
    • Add-ons the application can't change: how to check for a ready version, why no warnings doesn't mean safe, @JsStringFallback, the cases only the maintainers can fix, finding the add-on behind a bundle error, and how an uncovered call fails under strict.
    • Allowing external resources (including directives the default policy lacks, such as frame-src, and the app's own directives), removing other Content-Security-Policy headers together with the switch to strict, the manual nonce/override approach, and Spring Security, where the policy and its sources stay in the Spring Security configuration.
    • Switching to strict and testing a production build with the browser console, including blocks that only a web worker's console shows.
    • A section for add-on maintainers: Java and frontend changes, keeping connectors as plain modules, APIs that take a JsFunction instead of a JavaScript string, and testing against a production build.
  • The Security guides overview links to the new page.

Test summary

  • Checked every statement against the Flow and Flow Components sources of the 25.4 branch, and the Spring Security behavior against feat: use Spring Security nonce for strict Content Security Policy flow#27471.
  • The guide was followed step by step on a test application with its own string JavaScript, an in-house add-on and three published add-ons; the findings from that run are addressed.
  • Vale (PR config) reports no errors or warnings on the changed pages.
  • Checked that all cross-reference anchors exist on main.

Follow-ups:

Working on behalf of Mikhail

vaadin-bot and others added 9 commits November 25, 2026 12:13
Document @JsStringFallback, which lets an application declare the
exact JavaScript strings an add-on sends so they run from the bundle
instead of being refused under the built-in strict Content Security
Policy. Updates the Content Security Policy page.

Documents vaadin/flow#27128 (`60ebba0e1cd03b876938f40b306bf74f1e48aad9`).
Show the add-on call next to the fallback that matches it, for
executeJs, JsFunction.of, listener filters and event data, and list
the limitations of fallbacks as bullets, with a code example for a
string that joins a value into the JavaScript.
Shows how applications find the calls that don't work under the
strict Content Security Policy mode with the warn mode, what to
replace each string-based JavaScript API with, how to handle add-ons
and external resources, and what add-on maintainers need to change.
@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Preview Deployment

This PR has been deployed for preview.

URL: https://docs-preview-pr-6789.fly.dev

Changed pages

Added content is highlighted in green; removed content is marked in red on each page.

Built from 53be17d

@mcollovati

Copy link
Copy Markdown
Contributor

@totally-not-ai update the content based on the latest changes in the Flow repository

@mcollovati mcollovati self-assigned this Dec 2, 2026
@totally-not-ai

totally-not-ai Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@mcollovati I updated the guide for the Flow changes merged into 25.4 since it was written:

  • Element method calls: a JsInvokers method without @JsExpression calls the element function of the same name. The guide says so after the executeJs example, and that it works only through Element.executeJs(Class).
  • Frontend modules: a new section, Call Functions of Frontend Modules, replaces executeJs("window.Vaadin.myChart.init(this, $0)")-style calls. It shows @JsDefinitionImport for a plain import, and JsModuleInvokers with Page.executeModuleJs(Class) for connectors that later calls depend on. It also says when module calls can still run late, that a detached Element argument arrives as null, and that a missing ./ module fails the build. A new row in the replacement table points to it.
  • Add-on maintainers: connectors can stay plain modules in the JAR's frontend folder, and a missing module stops the build of every application that uses the add-on.

The Spring Security header fix doesn't change what the guide says: the bootstrap page still carries only the policy Vaadin sends.

The new section links to Importing Module Exports, which is on main but not yet on the #6775 branch. A link to the JsModuleInvokers reference can follow once #6805 is merged. The PR description lists both.

@mcollovati

Copy link
Copy Markdown
Contributor

I followed the guide step by step on an application that was not ready for a strict policy, with one commit per step:
https://github.com/mcollovati/skeleton-starter-flow-spring/tree/repro/strict-csp-migration-guide

The test application:

  • Its own code: string executeJs, Page.executeJs with results, JsFunction.of, addJsInitializer(String), addDynamicImport(String), a string listener filter and event data, LitRenderer.of(String), a Charts formatter, a shortcut locator string, an inline onclick, a connector reached through a global variable, external resources, and a filter that sets its own CSP header.
  • An in-house add-on with a connector that uses new Function.
  • Three published add-ons: flow-viritin 3.9.1, maplibre 2.1.1 and vaadin-fullcalendar 8.0.0.

The guide was read at 83d29e54e0, with Vaadin 25.4-SNAPSHOT of 2026-12-02.

Result: 29 of 30 features work in a production build under strict. vaadin-fullcalendar 8.0.x compiles callbacks with Function() in the browser, and the maplibre marker sends a new UUID each time. Both are cases the guide says only the maintainers can fix.

The guide works. Most examples worked as written: executeJs, changing values, Lit templates, chart functions, @JsStringFallback and @DomEvent filters. Below are the gaps I found, most important first. Each one has a section in MIGRATION-NOTES.md with the details.

Important

  1. Call Functions of Frontend Modules: say that the module must export the functions (G6). The sentence "@JsDefinitionImport imports what the module exports" assumes a module that exports something. A typical connector only sets a global object (window.Acme.sparkline = { init, update }). If the reader follows the guide without changing the module, the build passes and the browser fails with this.init is not a function. Please add a step: turn the functions of the global object into named exports. Also say that functions of the old object that call each other through this should call each other directly.

  2. Replace String JavaScript, addDynamicImport row: a URL that the server serves no longer works (G9). addDynamicImport("return import('/js/report-extras.js')") (a file in META-INF/resources/js) worked as a string. The same expression in a JsSnippets method is now bundled, so the build fails: [UNRESOLVED_IMPORT] Could not resolve '/js/report-extras.js' in src/main/frontend/generated/vaadin-js-definitions.js. This affects only migrations, because the string form never went through the bundler. Suggested text: "If the old string imports a URL that the server serves, move the file to the frontend folder and import it with a Frontend/ path."

  3. Find the Calls / Handle Add-Ons: strings that contain ids (G12, G21). maplibre's marker string has a new UUID each time (component.markers['4a733491-…']). After using the view once, as the guide says, the message has no "changing values" note, because that needs five strings. The reader pastes a @JsStringFallback that never matches again. Under strict, the exception is thrown in the view constructor, so the whole view fails to open, not just the marker. Please add:

    • Check pasted strings for ids, counters, coordinates or user data. Use a view more than once, or restart and check that a warning doesn't come back, before trusting a fallback.
    • Under strict, an add-on call that is not covered makes the whole view (or action) fail.
  4. Find the Calls: some warnings don't lead to your code (G1, G2). The guide says the stack trace "leads to the code that called it". That isn't true for these APIs:

    Until these are fixed, a sentence would help: "A warning whose trace starts in LitRenderer.setElementRenderer, charts.StringFunctionReporter or ShortcutRegistration comes from a Lit renderer, a chart option or setShortcutListenOnElement. Search your code for these calls."

  5. Allow External Resources, Spring Security sentence is out of date (G23). "A policy that Spring Security sends doesn't fail the request, but isn't applied to the page either" is no longer true since feat: use Spring Security nonce for strict Content Security Policy flow#27471. When Spring Security configures the header, Vaadin uses it with its nonce. The directives stay in the Spring Security configuration, so there is nothing to move. "Vaadin has to be the only code that sets the header" also needs an exception for Spring Security.

  6. Allow External Resources: adding a directive that the default policy doesn't have (G17). The default policy has no frame-src, so frames fall back to default-src 'self'. addSources("frame-src", "https://www.openstreetmap.org") creates the directive with only that source, so the app's own IFrames are blocked (checked in Chromium). The guide mentions the IFrame case, but its only example is connect-src, which the default policy already has. Suggested text: "For a directive that the default policy doesn't have (frame-src, media-src, manifest-src), also add 'self' if the page needs it." Filed as ContentSecurityPolicy.addSources() on a directive that is not set drops the default-src fallback flow#27617; this may change in Flow.

  7. Replace String JavaScript: inline event handlers in your own code (G10). setAttribute("onclick", "…") in application code is not in the table, and warn mode doesn't log it. The reader finds it only in the browser console of the production build. Suggested table row: setAttribute("on…", …) → addJsInitializer(JsFunction) that adds the listener and returns the cleanup, like the Javadoc example of that method. Add a hint to search the code for setAttribute("on. The same applies to on… attributes inside Html or innerHTML strings.

  8. Handle Add-Ons / Switch: a browser-side block doesn't name the add-on (G20). The fullcalendar eval error points to VAADIN/build/vaadin-theme-<hash>.js, a minified chunk. The guide says to report it "with the error in the browser console", but the reader first has to find which add-on it is. A hint would help: the view and component that fail. Development mode doesn't show the error, because no policy is sent there.

Add-on maintainers

  1. Add-on APIs that take JavaScript from the application (G15). Some add-ons take code (a formatter, a callback) as a string, like Charts did. A JsFunction parameter that the application declares in its own JsSnippets works across JARs. Please mention it, with ChartFunction as the model, and say to keep the old string API deprecated so that warn finds its callers.
  2. Testing the add-on (G16). "Set contentSecurityPolicy to strict in its test application" reads as if development mode were enough. It doesn't catch new Function in the connector, because the policy is sent only in production mode. Make the production test the main point.

Smaller points

  • G3: addEventData(String) with a plain property path is not logged (and it works), so a reader who expects a warning finds nothing. The deprecation warnings of the compiler are a second list of calls to change. This applies to setShortcutListenOnElement(String, …) too.

  • G4: There's no example of a call that returns a value (Page.executeJs("return navigator.language")). Show the return type in the example and say how to read the result.

  • G5: "Ready to paste" declarations need editing. The method is named after the call site (productsViewNew), the parameters are Object arg0, and the return type is always PendingJavaScriptResult. Say to rename them and use real types.

  • G7: Say whether to keep the @JsModule of a connector that is now reached through JsModuleInvokers. Removing it works.

  • G8: In "Declare Lit Renderer Templates", a before → after of the template line would make ${select} → ${functions.select} stand out. With ${select}, the column renders nothing.

  • G11: The JsFunction.of() row could mention that withArguments("event") becomes @JsFunctionParameterNames("event").

  • G13: "Check whether a newer version supports a strict Content Security Policy" gives no way to check. Suggested order:

    1. The add-on's release notes, docs and issue tracker.
    2. Then upgrade and repeat the warn run, plus the production test for browser-side code.

    Example: vaadin-fullcalendar has merged strict CSP support on master (Make new strict CSP work with JsCallback stefanuebe/vaadin-fullcalendar#479), but the 8.0.1 release notes don't say so yet.

  • G14: An add-on with no warnings is not known to be safe. vaadin-fullcalendar logs nothing in warn mode.

  • G18: Say where a filter's own directives (frame-ancestors, upgrade-insecure-requests) go: the same IndexHtmlRequestListener.

  • G19: "Allow External Resources" says to remove the other header now, but getContentSecurityPolicy() is null until the mode is strict. A build deployed between the two steps sends no policy at all. Move the removal to "Switch to the Strict Mode", or say that both changes go out together.

  • G22: A block in a worker (maplibre's worker, worker-src) is logged only in the worker's console. A test that collects the page console sees only Worker failed to load.

Not tested: MenuItemBase.executeJsWhenAttached(), a JsInvokers method without @JsExpression, @JsDefinitionImport on a JsInvokers interface, @Uses, Spring Security, and the manual nonce approach.

@totally-not-ai

totally-not-ai Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

@mcollovati Thanks for running the guide end to end. All the points are addressed:

Important

  1. G6: Call Functions of Frontend Modules now starts by turning the global object into named exports. It has a before/after and says that functions calling each other through this now call each other directly.
  2. G9: the addDynamicImport row says that a URL the server serves now fails the build. Move the file to the frontend folder and import it with a Frontend/ path.
  3. G12, G21: Find the Calls says that a call site with fewer than five strings isn't flagged. Check pasted strings for ids, counters, coordinates or user data. Use each view more than once, or restart, and check that the warning doesn't come back. Handle Add-Ons repeats this for fallbacks. It also says that under strict an uncovered call throws where the add-on makes it, so a call in a view constructor stops the whole view from opening.
  4. G1, G2: a list maps the first frame of a framework-only trace to the API: LitRenderer.setElementRenderer, the Charts StringFunctionReporter and ShortcutRegistration. For the shortcut warning, it says to ignore the suggested method name. The text can be shortened once CSP warning for LitRenderer.of(String) does not say which renderer it is flow-components#10899 and CSP warning for setShortcutListenOnElement(String) has no application frame and suggests a method named uidlWriterEncodeChanges() flow#27614 are fixed.
  5. G23: the Spring Security text describes feat: use Spring Security nonce for strict Content Security Policy flow#27471. Vaadin uses the Spring Security nonce and sends no policy of its own, and the directives stay in the Spring Security configuration. The "only code that sets the header" rule now makes an exception for Spring Security. A short VaadinSecurityConfigurer.contentSecurityPolicy() example shows where sources and directives go in that case. The reference section it links to is updated for the new behavior in docs: describe strict Content Security Policy with Spring Security #6808 / docs: use Spring Security's nonce for strict Content Security Policy #6821.
  6. G17: frame-src, media-src and manifest-src fall back to default-src, so add 'self' too when the page needs it. There's an addSources() example. This may change with ContentSecurityPolicy.addSources() on a directive that is not set drops the default-src fallback flow#27617.
  7. G10: a new table row covers inline on… attributes from setAttribute(), Html or innerHTML. The replacement is a server-side listener, or an addJsInitializer(JsFunction) snippet that adds the listener and returns the cleanup. The guide also says warn doesn't log these, and to search for setAttribute("on.
  8. G20: Handle Add-Ons says a console error points to a minified bundle file, not to the add-on. Find the add-on from the view and component that fail. Development mode doesn't show the error.

Add-on maintainers
9. G15: add-on APIs that take JavaScript should take a JsFunction that the application declares, or a JsSnippet subtype like ChartFunction. Keep the string API, deprecated, and have it build a JsFunction.of() so that warn finds its callers.
10. G16: the main test is now the browser tests against a production build under strict. strict in development mode is described as a quicker check for the Java side only.

Smaller points

  • G3: addEventData(String) with a plain path isn't logged but should still be replaced. Compiler deprecation warnings are a second list of calls to change.
  • G4: a Page.executeJs example returns PendingJavaScriptResult and reads it with then(), with a link to Return Values.
  • G5: the guide says to rename the pasted method and give its parameters and return value real types.
  • G7: the @JsModule can be removed. Keep it only if the module must run code at startup.
  • G8: a before/after of the template line shows ${select} → ${functions.select}, and what happens if you miss it.
  • G11: the JsFunction.of() row maps withArguments() to @JsFunctionParameterNames.
  • G13, G14: checking for a ready add-on version is now two steps. First read the release notes, docs and issue tracker. Then upgrade, repeat the warn run and run the production test. An add-on with no warnings isn't known to be safe yet.
  • G18: your own directives (frame-ancestors, upgrade-insecure-requests) go into the same listener.
  • G19: remove the other header in the same change that switches to strict, so no build goes out without a policy.
  • G22: worker blocks show only in the worker's console, so a test that collects the page console sees only that the worker failed to load.

Base automatically changed from doc-bot/vaadin-flow/27128-7e118347c0cbc8f3 to main December 2, 2026 11:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants