Skip to content

fix: keep Vaadin dev mode code within a strict Content Security Policy - #27629

Open
totally-not-ai[bot] wants to merge 6 commits into
mainfrom
fix/dev-mode-strict-csp
Open

totally-not-ai[bot] wants to merge 6 commits into
mainfrom
fix/dev-mode-strict-csp

Conversation

@totally-not-ai

@totally-not-ai totally-not-ai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #27627

behavior deviation · flow-server (Vite config) · apps that send a strict Content Security Policy in development mode, enforced or report-only

Background — dev mode comment. @vaadin/vaadin-usage-statistics keeps its code inside a /*! vaadin-dev-mode:start … vaadin-dev-mode:end **/ comment, so a production minifier drops it. In development mode, @vaadin/vaadin-development-mode-detector takes the code out of the comment at runtime and runs it with new Function.

In development mode, two pieces of Vaadin's own code broke a strict policy: the usage statistics needed 'unsafe-eval', and the Vite entry point vite-devmode.ts had an inline onerror handler. With an enforced policy, statistics were not sent and the page no longer reloaded when the entry point failed to load, for example after a server restart. With report-only, every page load reported two violations that were not the application's.

Risks:

  • ⚠️ Behaviour change, dev mode only: the usage statistics code is now plain code in the dev bundle and in Vite dev mode, still run only when the detector says development mode. Production builds are unchanged, the comment is still dropped there.
  • ⚠️ The entry point is now loaded by an inline script with a dynamic import(), so it starts loading while the page is parsed instead of as a deferred module script. The page also reloads if the module throws while it runs, not only when it fails to load.
  • ✅ No API change, no change in production mode.

Context. The Vite plugin already transformed the usage statistics module, but only to keep the comment through minification. A nonce covers inline <script> elements, which Flow nonces like every other script, but not inline event handlers.

  • Changed the vaadin:preserve-usage-stats plugin into vaadin:uncomment-usage-stats, which removes the comment markers around the usage statistics code and keeps the sourcemap.
  • Replaced <script type="module" src="/generated/vite-devmode.ts" onerror="…"> with an inline script that imports it and reloads the page on failure. Vite resolves the import URL against its base as it does for src, so context paths keep working.
  • Changed DevBundleSourceMapsIT, which asserted the old comment rewrite: it now runs the stub and checks that its code ran.
  • Added a check to the Vite dev mode BasicsIT that the entry point loads and that no script has an inline event handler.

Working on behalf of @mcollovati

In development mode, the usage statistics code was kept in a comment
and run with new Function, which needs 'unsafe-eval'. The Vite build
plugin now takes it out of the comment, so it runs as plain code, still
only in development mode.

The Vite dev mode entry point had an onerror attribute to reload the
page when it fails to load. A nonce does not cover inline event
handlers, so an inline script that imports the entry point and reloads
on failure replaces it.

The existing dev bundle IT asserted the old comment rewrite, so it now
checks that the code is outside the comment.

Fixes #27627
The usage statistics IT now runs the stub and checks its effect, and
the Vite dev mode IT checks that the entry point loaded with status 200,
which also fails when the URL in the import is wrong.
@totally-not-ai

totally-not-ai Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Type of change

  • Bugfix

How to test

  1. Open the Vite dev mode app in flow-tests/test-frontend/vite-basics (view flow-tests/test-frontend/vite-basics/src/main/java/com/vaadin/viteapp/views/empty/MainView.java).
  2. Look at the <head> of the page.
  3. The vite-devmode.ts entry point is loaded by an inline <script> with import(…), and no script has an onerror attribute.

Test summary

  • The Vite dev mode IT checks that the entry point loads with status 200 and that no script of the page has an inline event handler. It fails on the old code.
  • The dev bundle IT runs the usage statistics stand-in and checks that its code ran, which fails when the code stays in its comment.
  • Manually, the Vite dev mode app was loaded with Vaadin's strict script-src policy as report-only and nonces on every script. No violation was reported, and the usage statistics code ran. A test inline handler on the same page was reported, so the check works.
  • Not covered by an automated test: the reload when the entry point fails to load, and a full dev mode run under an enforced policy. The existing CSP test modules run in production mode only.
Other options considered
  • Fixing the usage statistics in @vaadin/vaadin-development-mode-detector instead. That needs a release of the web components packages, and Flow already transforms this module.
  • An inline module script instead of a classic one. Vite turns inline module scripts into html-proxy modules served by the dev server, which is the server that may not be reachable when the fallback is needed.

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the changes — left 1 comment.

Finding
⚠️ Greedy match breaks a module that carries more than one dev-mode comment


const DEV_MODE_START_REGEXP = /\/\*[\*!]\s+vaadin-dev-mode:start/;
const DEV_MODE_CODE_REGEXP = /\/\*[\*!]\s+vaadin-dev-mode:start([\s\S]*)vaadin-dev-mode:end\s+\*\*\//i;
const DEV_MODE_CODE_REGEXP = /\/\*[\*!]\s+vaadin-dev-mode:start([\s\S]*)vaadin-dev-mode:end\s+\*\*\//di;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Greedy match breaks a module that carries more than one dev-mode comment

([\s\S]*) is greedy, so with two dev-mode comments in the same module the match spans from the first start to the last end. Only the outermost markers are then removed and the inner vaadin-dev-mode:end **/ … /*! vaadin-dev-mode:start pair is left as bare tokens, so the module no longer parses.

The previous code only rewrote the first opening marker, so it left such a module valid. A plausible trigger is a dep-optimizer chunk whose id matches vaadin-usage-statistics and which also carries the detector's own dev-mode comment. A lazy quantifier would restore the old tolerance.

vite.generated.ts:524 · correctness

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed. The match is now lazy and global, so each dev-mode comment of the module is uncommented on its own and a module with more than one stays valid code. The stand-in module of the dev bundle IT now has two such comments, and the IT checks that the code of both runs.

A greedy match spanned from the first comment to the last one of a
module with more than one, and left the markers between them as code.

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the changes — left 1 comment.

Finding
🧪 The new dev-bundle test calls a global that the page it opens never defines

+ "of its dev mode comments",
Boolean.TRUE, executeScript(
"""
window.vaadinUsageStatisticsStub();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧪 The new dev-bundle test calls a global that the page it opens never defines

DevBundleSourceMapsIT opens LitView, but vaadin-usage-statistics-stub.js is a @JsModule of DevBundleJsModuleView. Neither route is eager (FrontendDependencies.defaultIsRouteEager only makes "" and login eager), so the stub lives in a lazy chunk that is imported only when DevBundleJsModuleView attaches. On the LitView page window.vaadinUsageStatisticsStub is undefined and executeScript throws rather than asserting anything.

The old assertion read the built chunks from disk, which is why it did not need the module loaded. Either move the stub's @JsModule to LitView, or open DevBundleJsModuleView in this case.

DevBundleSourceMapsIT.java:91 · tests

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No change needed here. In this module's dev bundle, the stub is not in a lazy chunk. The generated generated-flow-imports.js imports Frontend/vaadin-usage-statistics-stub.js directly, next to Frontend/views/lit-view.ts. So it runs on every page, including LitView, and window.vaadinUsageStatisticsStub is defined there. The test passes against the built bundle. If the global ever went missing, executeScript would throw and the test would fail. It could not pass without checking anything.

@sonarqubecloud

sonarqubecloud Bot commented Dec 2, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Test Results

 1 662 files  ±0   1 753 suites  ±0   1h 40m 23s ⏱️ - 4m 48s
14 127 tests +1  14 055 ✅ +1  72 💤 ±0  0 ❌ ±0 
14 563 runs  +1  14 491 ✅ +1  72 💤 ±0  0 ❌ ±0 

Results for commit 7d94438. ± Comparison against base commit 9f07595.

@mcollovati
mcollovati marked this pull request as ready for review December 2, 2026 16:15
mcollovati added a commit to mcollovati/skeleton-starter-flow-spring that referenced this pull request Dec 2, 2026
With the PR (7d94438cbb, merged locally with #27612), the usage
statistics no longer need eval and vite-devmode.ts is loaded without an
inline onerror handler: the only report in development mode is the
image of the app, the statistics run under an enforced policy and the
page reloads when vite-devmode.ts fails to load. CspDevModeIT prints
whether the statistics ran and tests the reload with Vite.
@mcollovati

Copy link
Copy Markdown
Contributor

Tested 7d94438 with the reproducer of #27471 (repro/csp-spring-security-nonce at 97e5736, section "Vaadin's own code in development mode" of the README). I merged #27612 (40a11e2) locally, so that warn sends its report-only policy in development mode, and compared with 07aa51f (#27612 without this PR). Headless Chromium.

Both fixes work. In development mode, the only report left is the cross-origin image that the reproducer loads on purpose:

Development mode Policy Without this PR With this PR
Dev bundle built by the app report-only (warn) eval reported nothing from Vaadin
Dev bundle built by the app enforced (Spring Security configurer) eval blocked, usage statistics do not run nothing from Vaadin, usage statistics run
Vite report-only (warn) inline handler and eval reported nothing from Vaadin
Vite enforced both blocked, usage statistics do not run, and the page does not reload when vite-devmode.ts fails to load nothing from Vaadin, usage statistics run, the page reloads
  • To check that the usage statistics code still runs, and not only that the report is gone, the test checks window.Vaadin.usageStatsChecker, which that code sets.
  • For the reload, the test makes the first request for vite-devmode.ts fail and counts the page requests. One note for anyone who tests this: the import fails while the first page is still loading, so that page never fires load. Counting load events shows no reload even when there is one.
  • The served page has <script nonce="...">import('/VAADIN/generated/vite-devmode.ts').catch(...)</script>, so Vite adds the base to the import() URL, as the PR says.
  • The detector's own vaadin-dev-mode comment in isMinified() is not changed and does not need to be: IndexHtmlRequestHandler sets window.Vaadin.developmentMode = true in development mode, so isMinified() never runs.

Two things to know, both outside this PR:

  1. The prebuilt vaadin-dev-bundle is built by the platform with the Vite config of its Flow version, so apps that use it keep the eval until it is built with this change. To test the dev bundle, I had to make the app build its own (a local @JsModule file that the prebuilt bundle does not have).
  2. A dev bundle that an app already built itself is not built again when only the Flow version changes. When I switched from this PR to 07aa51f, Flow said "A development mode bundle build is not needed" and reused target/dev-bundle, which was built with the other Vite config. So after an upgrade, such an app keeps the old code until something else makes Flow build the bundle again. Maybe a change of vite.generated.ts should count as a reason to build it again, but that is a separate issue.

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Nothing to flag — the changes look good.

@mcollovati mcollovati added the csp label Dec 2, 2026

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the changes — left 2 comments.

Finding
🧪 No test covers the /*! comment form that the real package ships
📝 The new comments justify the change with a minification that never happens

// takes the code below out of its comments, each one on its own. See
// DevBundleSourceMapsIT.
function maybeGatherAndSendStats() {
/** vaadin-dev-mode:start

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧪 No test covers the /*! comment form that the real package ships

The stub carries two /** comments. The deleted stub comment stated that the published @vaadin/vaadin-usage-statistics already ships the /*! form, and the deleted assertion was the only place that touched it. Narrowing [\*!] in the regex would now pass CI while the shipped module stays commented, so the new Function call this PR removes comes back unnoticed.

Making one of the two stub comments /*! covers both forms at no extra cost.

vaadin-usage-statistics-stub.js:6 · tests

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, done. The stub's second comment now uses the /*! form that the published package ships, so the IT covers both forms. If the regex stopped accepting either form, the IT would fail.

* Left in the comment, the code is run with `new Function` when the page
* loads, which a Content Security Policy without 'unsafe-eval' blocks. Out of
* it, the function runs as it is, still only in development mode. The code
* also survives minification of the dev bundle as plain code.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 The new comments justify the change with a minification that never happens

build.minify is productionMode and the plugin is only registered when !productionMode, so it never runs in a build that minifies. The dev bundle is built unminified. The same reasoning appears in the new DevBundleSourceMapsIT javadoc ("a minifier would drop it").

The CSP reason stands on its own; the minifier half is left over from what the plugin used to do.

vite.generated.ts:533 · documentation

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right: the plugin only runs in builds that do not minify. I removed the minification reason from the plugin's comment and from the DevBundleSourceMapsIT javadoc. Only the Content Security Policy reason is left.

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the changes — left 1 comment.

Finding
⚠️ Uncommenting moves the statistics code from sloppy-mode new Function into ES-module strict mode, and only a trivial stub proves it still works

}
return null;
const magicString = new MagicString(src);
for (const match of src.matchAll(DEV_MODE_CODE_REGEXP)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Uncommenting moves the statistics code from sloppy-mode new Function into ES-module strict mode, and only a trivial stub proves it still works

Until now the comment body was never parsed by the bundler; it reached the browser as comment text and was compiled by new Function, i.e. sloppy mode, global scope, this === globalThis. Inlined into the module it is strict-mode code in module scope with this === undefined, and it has to parse at build time. Strict-mode early errors (octal literals, with, duplicate parameters) now fail the build rather than one feature, and this or an undeclared assignment changes meaning.

What I could not confirm is whether the published @vaadin/vaadin-usage-statistics blob is affected — it is not in this checkout, and the only thing exercising the plugin here is vaadin-usage-statistics-stub.js, whose comment bodies are single assignments. So nothing in this repository would reveal it; it would surface first in platform CI. Worth running the real package through the plugin once before merging.

vite.generated.ts:548 · correctness

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No change needed. I checked the published @vaadin/vaadin-usage-statistics 2.1.3, the current version:

  • The comment body is a single (function () { 'use strict'; … }());. The code already runs in strict mode under new Function, so moving it into a module changes nothing there.
  • Every this is inside a constructor or a method, not at the top level of the comment body.
  • I ran the real module through this plugin's transform, and the output parses as an ES module (node --check on a .mjs file).
  • In the Vite dev mode app of flow-tests/test-frontend/vite-basics, which uses the real package, the transformed module ran: window.Vaadin.usageStatsChecker was set and the strict policy reported no violations. The test report earlier in this PR confirms the same with the dev bundle and Vite under an enforced policy.

If a future release of the package added code that is not valid in strict mode, the build would fail and show it, so it would not break silently.

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Development mode code of Vaadin violates the strict Content Security Policy

2 participants