Skip to content

Enabling Content Security Policy #9488

Open

Description

@totally-not-ai

Description

A csp mode setting — off (default, today's behaviour), warn (reports what would break), strict (Vaadin serves a nonce-based policy and eval-requiring APIs throw).

Tier

Free

License

Apache 2.0

Motivation

Background

A strict Content Security Policy (script-src 'nonce-…', no unsafe-inline, no unsafe-eval) is a standing requirement in banking, public sector, and anywhere a security audit gates deployment. Vaadin sends server-initiated JavaScript to the browser as strings that are compiled with new Function — exactly what unsafe-eval forbids.

Since 24.5 a nonce-based policy is possible: the application adds an IndexHtmlRequestListener that generates the nonce and puts it on the script tags, overrides window.Function and window.eval, and hand-maintains a map from every JavaScript string Vaadin, its components and its add-ons might send to a pre-defined function. That is the documented approach today.

Problem

  • The workaround is not maintainable. The map has to be rebuilt whenever Flow, a component or an add-on changes a snippet, and entries are discovered by watching console warnings at runtime. The reference application for it already breaks on server-side navigation (csp.js file throws client-side error with backend navigation flow-crm-tutorial#314).
  • The framework itself is not CSP-clean. Five places in the client engine compile strings into functions: executeJs expressions, server-sent JS functions (Support executeJs decomposition through passing an JS function to executeJs flow#24373), DOM event data expressions, DOM event filters, and on-demand chunk loading. Flow has ~100 executeJs call sites and the components ~60, so an application that writes no JavaScript of its own still cannot run strictly.
  • Nothing tells you where you stand. Finding violations means enabling the policy in a browser and reading console errors that name generated JavaScript, not the Java code that caused it. There is no incremental path from "works" to "strict".
  • The same string concatenation is an XSS risk. Building snippets by concatenating values into JavaScript is the failure mode declared JavaScript removes.

Solution

One setting that makes the state explicit:

  • off (default) — exactly today's behaviour. No application sees a change.
  • warn — the application runs unchanged, but every API call that would not work under a strict policy is logged, with the Java call site.
  • strict — Vaadin generates the nonce and sends the header itself, and the APIs that cannot work throw instead of failing silently in the browser.

Plus the mechanism that makes strict reachable: JavaScript declared as constants in Java, collected into the bundle by the build, invoked by naming the interface and method rather than by sending a script (vaadin/flow#10759).

@JsInvoker
public interface ScrollJs extends Serializable {
    @JsExpression("this.scrollTo({ top: $0, behavior: 'smooth' })")
    void scrollTo(int top);
}

container.getElement().getJsInvoker(ScrollJs.class).scrollTo(320);

Notes

warn is what makes the migration tractable — it turns "somewhere in this application something uses eval" into a list. It is also the reason the mode is one setting with three values rather than a boolean: the middle state is where applications and add-ons will spend their time.

Update 25 Nov 2026: some names in this text changed during the work. The setting is now contentSecurityPolicy and @JsInvoker is @JsDefinition. The text is kept as written; see the comments for the current names and decisions.

Staging: off and warn together with the declared-JavaScript mechanism and Flow's own migration in 25.4. strict is announced as supported only once the core components are migrated and the violation test is green.

Requirements

Nice-to-haves

Risks, limitations and breaking changes

Risks

  • The migration surface is the whole framework plus the component set (~170 call sites). A partially migrated strict looks like a broken framework rather than an unfinished migration — which is why warn and the violation test are requirements, not follow-ups.
  • warn only sees calls that actually execute, so a code path no one exercises stays unreported. It lowers the cost of migration; it does not prove completeness.
  • Add-ons and hand-written application JavaScript are outside Vaadin's control, so strict stays out of reach for some applications until those migrate.

Limitations

  • In strict mode the header is sent in production mode only.
  • Charts passes string-defined JavaScript functions to the client (_fn_formatter, _fn_positioner, …) where they are evaluated, and the Spreadsheet client calls eval during its GWT bootstrap. Neither is usable in strict mode until reworked; both are tracked separately from this PRD.
  • Update 25 Nov 2026: the Charts and Spreadsheet integration tests now run in strict mode. A chart function declared as a ChartFunction works; a function set as a string still does not. A ChartFunction is not applied in server-side export with SVGGenerator, and ChartAIController does not keep it (ChartAIController state should keep ChartFunction values flow-components#10803).
  • Added 25 Nov 2026: add-on fallbacks match fixed JavaScript strings only. An add-on that builds its JavaScript by concatenating values has to be fixed in the add-on.

Breaking changes

  • None by default: off is today's behaviour.
  • In strict mode, executeJs and string-based event filters and event data throw. This is the point of the mode, and it is opt-in.
  • From feat: run declared JavaScript without compiling it in the browser flow#25749: Focusable.focus()/blur() no longer schedule a script string, so code or tests that read the scheduled JavaScript must read the invoker call instead; and every application's bundle is rebuilt once.

Out of scope

  • Trusted Types, and CSP directives unrelated to script execution beyond the application hook.
  • A policy for the development server and dev tools.
  • Migrating third-party add-ons.
  • Hash-based policies and subresource integrity as an alternative to nonces.

Materials

Metrics

  • A new application using the standard components can set strict and run with zero CSP violations, without writing any JavaScript or an IndexHtmlRequestListener.
  • Enabling warn on an existing application produces the complete list of what blocks strict, each entry pointing at a Java call site.
  • The documentation article is the setting plus a migration guide — no overriding of Function or eval.

Pre-implementation checklist

  • Estimated (estimate entered into Estimate custom field)
  • Product Manager sign-off
  • Engineering Manager sign-off

Pre-release checklist

  • Documented (link to documentation provided in sub-issue or comment)
  • UX/DX tests conducted and blockers addressed
  • Approved for release by Product Manager

Security review

Security audit conducted

Activity

  1. totally-not-ai commented on Sep 19, 2026

    @totally-not-ai
    ContributorAuthor

    One requirement above — "the platform component test also runs in strict mode and fails on any CSP violation" — covers the components but says nothing about how Flow's own suite guards the migration. Proposal for that, to be tuned before sub-issues are created.

    Running every Flow test in strict mode is not the right target:

    • Part of the suite tests the APIs strict forbids. Element.executeJs, DomListenerRegistration.setFilter(String) and string-based event data stay supported public API in off mode, and there are integration tests whose purpose is to exercise them. In strict they throw by design, so those must keep running in off.
    • Most integration tests run in development mode, where the header is not sent because the dev server and dev tools need unsafe-eval. Running them in strict would only exercise the Java-side rejection, not the violation the browser reports — which is the failure being guarded against. That signal only exists in production-mode suites.
    • Duplicating the whole integration-test matrix is the most expensive way to obtain it.

    Three layers instead, cheapest first:

    1. A static rule in the unit layer asserting that Flow's own production code contains no remaining calls to the eval-requiring APIs (an ArchUnit-style rule over the compiled classes), plus a client-engine unit test asserting the invoker path never reaches new Function. Seconds per push, no browser, and this is what stops a newly added executeJs from silently undoing the migration.
    2. The existing development-mode suites run in warn, failing the build on an unexpected warning, with an allowlist for the tests that use those APIs on purpose. Near-complete coverage of the API-level problem at almost no CI cost, and warn is the mode that can be enabled globally where strict cannot.
    3. One dedicated strict-CSP integration-test module in production mode covering the framework's own client paths — navigation, push, chunk loading, event filters and event data, overlays, focus — failing on anything a securitypolicyviolation listener reports; plus a strict variant of one broad existing suite, reusing the same test sources under a second pom, the way test-themes/pom-production.xml and test-router-custom-context-encoded-prod already do.
  2. changed the title [-]Content Security Policy support: off, warn and strict modes[/-] [+]Enabling Content Security Policy[/+] on Sep 19, 2026
  3. Legioth commented on Sep 24, 2026

    @Legioth
    Member

    One additional "feature request": Add support for an application-wide "fallback definition" class that can carry @JsExpression annotations for add-on invocations that are passed as a string. These expressions get included in the bundle and the runtime checks any executeJs(string) invocation against that list to avoid warning or raising errors due to those specific cases.

  4. mshabarov commented on Oct 8, 2026

    @mshabarov
    Contributor

    Some side cases that we may want to take into account. These we observed in 24.5 when we shipped CSP workarounds:

    1. LitRenderer (Grid, ComboBox, etc.). LitRenderer.of("...") templates arrive from Java as strings, and the client compiles them with Function. See flow-components#6518. A template written in Java can't be declared ahead of time, so it needs its own solution.
    2. Hilla / React views. Hilla adds scripts without a nonce (RouteUnifyingIndexHtmlRequestListener).
    3. strict-dynamic in the policy. Chunks load through dynamic import(), and a nonce alone doesn't cover that. The PRD only says "nonce-based", so it should state the default policy explicitly.
    4. Moving off the 24.5 recipe. Some apps already set their own nonce and header and override Function.
    5. Embedded web components (exporter). The host page owns the CSP header there, not Vaadin. This needs at least a note in the docs.

    Risks

    1. Bundle hash. Any declared JS outside flow-server (WebPush, AuthenticationContext) changes the whole file's hash and forces a bundle rebuild. The suggested fix is to compare individual functions instead of the whole file.
    2. Polymer templates and AbstractNodeStateProvider. They need a context object as this, which page-level declared JS doesn't have. This needs a design decision. Though Vaadin Polymer templates are deprecated, so could be just a limitation.

    Minor

    • Rich Text Editor (Quill) broke under the Function override, so it's worth checking separately in strict.
    • Component icons used to be data: URIs (platform#583). The default policy shouldn't break them.
  5. mshabarov commented on Oct 26, 2026

    @mshabarov
    Contributor

    Strict CSP: plan to beta

    Goal for beta: all API in place and frozen. A Flow demo app runs in production mode with csp=strict and zero CSP violations.

    Timeline, honestly: 3 weeks only if API decisions are made in the first 2 days and nothing needs a second round. Realistic estimate: 3–4 weeks. If 3 weeks is not enough, the items under "If we fall behind" move out first.

    What changes, and where

    flow

    • flow-client:
      • event data and filters are read by property path, without new Function;
      • JsSnippet execution;
      • calling functions from a @JsModule.
    • flow-server:
      • new wire format for event data;
      • nonce and CSP header, nonce on every script (index.html, push, web component bootstrap), hook for app directives;
      • warn mode logging the call site; string-based APIs throw in strict;
      • Flow's remaining JS moved to declared JS (navigation, shortcuts, resize, click filters, trigger API);
      • JsSnippet and @JsParams, @JsInvoker on @JsModule, typed return values, this.method() without @JsExpression;
      • class with declared strings for add-on executeJs;
      • breaking changes (MPR constants).
    • Build (flow-build-tools / plugins): collect JsSnippets, modules and add-on declared strings into the bundle.
    • vaadin-spring: the csp property.
    • flow-tests: production-mode strict integration test module.

    flow-components

    • executeJs → @JsInvoker in Grid, ComboBox, Dialog, Notification, Upload, DatePicker, Checkbox, Tabs, MenuBar and their connectors (~37 calls).
    • LitRenderer columns are not part of the MVP.

    platform

    • ComponentsIT in strict in CI, non-blocking for now.

    docs

    • Short article: the csp setting, @JsInvoker, JsSnippet, what is not supported yet.

    Demo app: new repository.

    Plan

    Week 1

    • Days 1–2: fix the signatures of the whole API:
      • hook;
      • strict behaviour;
      • event data format;
      • JsSnippet;
      • @JsModule;
      • add-on strings;
      • typed return;
      • this.method().
    • Days 2–5:
      • event data and filters;
      • nonce, header and hook;
      • warn/strict;
      • JsSnippet;
      • simple JS calls in Flow;
      • components: Dialog, Notification, Checkbox, Tabs, MenuBar, DatePicker.

    Week 2

    • Finish:
      • event data, nonce, strict/warn, JsSnippet;
      • shortcuts, click filters.
    • New API:
      • @JsModule;
      • add-on strings;
      • typed return, this.method().
    • Components: Grid, ComboBox, Upload.
    • strict integration test module, platform run.
    • End of week: API frozen.

    Week 3

    • Demo app, shown to 1–2 customers.
    • Fix what tests, the demo and customers find.
    • Documentation.
    • Beta. strict marked as "preview".

    Week 4 (buffer, realistic case)

    • Finish what slipped from week 2: most likely JsSnippet, @JsModule and Grid.
    • API changes from customer feedback.

    After beta

    • On-demand chunk loading without eval.
    • LitRenderer in Grid and ComboBox via JsSnippet.
    • Connectors as @JsModule.
    • Remaining components: Grid Pro, RTE, Map, Charts, Spreadsheet.
    • Nonce in Hilla.
    • Static check and warn in dev-mode tests. Platform test made blocking.
    • Full migration guide.
    • style-src without 'unsafe-inline', splitting declared JS per chunk.

    If we fall behind

    1. Move typed return and this.method() to the next minor. They only add API and break nothing.
    2. Show the demo without Upload and ComboBox.
    3. Move beta by a week, but keep the customer demo before beta.

    Risks

    • Signatures not agreed in 2 days. The whole plan shifts.
    • JsSnippet turns out harder than it looks (client, build, click filters). It is the largest piece: +3–5 days.
    • Components need a fresh Flow snapshot. Build delays eat days.
    • Customers ask for API changes. Those land in weeks 3–4.
  6. mcollovati commented on Oct 26, 2026

    @mcollovati
    Contributor

    Note on names: @JsInvoker and getJsInvoker(...) in the description are names from the review of vaadin/flow#25749. They were renamed before the merge, so they were never released. The names in Flow are:

    • @JsInvoker → @JsDefinition (com.vaadin.flow.js.JsDefinition), together with @JsExpression
    • element.getJsInvoker(X.class) → element.executeJs(X.class)
    • page.getJsInvoker(X.class) → page.executeJs(X.class)

    The example in the description is now:

    @JsDefinition
    public interface ScrollJs extends Serializable {
        @JsExpression("this.scrollTo({ top: $0, behavior: 'smooth' })")
        void scrollTo(int top);
    }
    
    container.getElement().executeJs(ScrollJs.class).scrollTo(320);

    The Flow issues vaadin/flow#25810, vaadin/flow#25811, vaadin/flow#25812, vaadin/flow#25814, vaadin/flow#25837 and the epic vaadin/flow#26155 now use the new names.

  7. moved this to December 2026 (25.4) in Roadmapon Oct 29, 2026
  8. heruan commented on Nov 25, 2026

    @heruan
    Member

    Status and decisions, 25 Nov 2026

    The description is kept as written. I only added dated notes to it. This comment records what changed since the plan above.

    Decisions

    Open requirements

    Questions

    1. Is Allow @JsDefinition to target a @JsModule flow#25814 still a requirement for this PRD, or a follow-up?
    2. Is "document header overrides" enough for Spring Security, so that the requirement can be closed?
    3. Who writes the migration guide?
    4. Is Collect @JsDefinition types with the bundle scanner when optimizeBundle is on flow#27022 (only reachable definitions in the bundle) a goal for the 25.4 RC?
  9. heruan commented on Dec 2, 2026

    @heruan
    Member

    Status, 2 Dec 2026

    This replaces the open points of the status of 25 Nov.

    Done since then

    Open

    Question

    • Are the component connectors already moved to modules, so that the components requirement can be closed?
  10. mcollovati commented on Dec 2, 2026

    @mcollovati
    Contributor

    For components there's a draft PR that needs a review from the DS team to make sure changes in frontend files are not breaking anything.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions