Repository navigation
fix: keep Vaadin dev mode code within a strict Content Security Policy - #27629
totally-not-ai[bot] wants to merge 9 commits into
Conversation
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.
Type of change
How to test
Test summary
Other options considered
|
vaadin-review-bot
left a comment
There was a problem hiding this comment.
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; |
There was a problem hiding this 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
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
🧪 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
There was a problem hiding this comment.
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.
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.
|
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 Both fixes work. In development mode, the only report left is the cross-origin image that the reproducer loads on purpose:
Two things to know, both outside this PR:
|
vaadin-review-bot
left a comment
There was a problem hiding this comment.
✅ Nothing to flag — the changes look good.
vaadin-review-bot
left a comment
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
🧪 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.
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
📝 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
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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)) { |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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 undernew Function, so moving it into a module changes nothing there. - Every
thisis 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 --checkon a.mjsfile). - In the Vite dev mode app of
flow-tests/test-frontend/vite-basics, which uses the real package, the transformed module ran:window.Vaadin.usageStatsCheckerwas 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.
vaadin-review-bot
left a comment
There was a problem hiding this comment.
Reviewed the changes — left 1 comment.
| Finding | |
|---|---|
| 🧪 | The uncommenting is only tested in the dev-bundle build, never with the Vite dev server |
| Assert.assertNotEquals( | ||
| "No chunk of the dev bundle has the usage statistics comment", | ||
| 0, rewritten); | ||
| public void usageStatisticsCodeRunsAsPlainFunction() { |
There was a problem hiding this comment.
🧪 The uncommenting is only tested in the dev-bundle build, never with the Vite dev server
This IT runs against vite build output (devMode is false there), so the plugin is only ever exercised in build mode, on a local stub. No test module in the repo depends on @vaadin/vaadin-usage-statistics, so nothing runs the real package through the plugin either.
The serve path is where it matters most and where the conditions differ: in dev the module is reached only because it sits in optimizeDeps.exclude, so it is served raw rather than pre-bundled by esbuild. Dropping it from that list, or any id-matching regression specific to serve mode, would silently stop the uncommenting while this IT stays green.
DevBundleSourceMapsIT.java:85 · tests
There was a problem hiding this comment.
Agreed, added. The vite-basics app now depends on the published @vaadin/vaadin-usage-statistics 2.1.3. It imports the package by its bare name, so the dev server serves it as an excluded dependency, the same path real apps use. The new BasicsIT.usageStatisticsRunWithoutFunctionConstructor replaces Function with a stub that records any call, runs the usage statistics, and checks two things: new Function was not called, and window.Vaadin.usageStatsChecker was set. The test fails on the code before this PR. If the module was pre-bundled or the plugin stopped matching it in serve mode, the test would also fail.
The dev bundle IT only covers a stand-in module in a build. This runs the published package as the dev server serves it, and checks that it no longer goes through new Function.
vaadin-review-bot
left a comment
There was a problem hiding this comment.
Reviewed the changes — left 1 comment.
| Finding | |
|---|---|
| The dynamic import in the new inline script is not base-prefixed, so the dev-mode entry point is requested from the wrong URL |
| scripts.push({ | ||
| tag: 'script', | ||
| attrs: { type: 'module', src: `/generated/vite-devmode.ts`, onerror: "document.location.reload()" }, | ||
| children: "import('/generated/vite-devmode.ts').catch(() => document.location.reload());", |
There was a problem hiding this comment.
Vite's dev HTML transform rewrites root-relative src/href attributes (that is how the old tag became /VAADIN/generated/vite-devmode.ts, which the new IT asserts), but it leaves the body of a classic inline script untouched — only type="module" inline scripts go through addInlineModule and import analysis.
So the browser resolves /generated/vite-devmode.ts against the origin, bypassing the --base (<contextPath>/VAADIN) that ViteHandler passes to Vite. The request never reaches the dev server, the promise rejects, and .catch reloads the page — on every load.
The inline comment's claim that "Vite resolves the URL of the import as it does a src" is the same mistake. Adding attrs: { type: 'module' } makes Vite process the inline script and rewrite the specifier, and Flow still nonces it since it stays a <script> element.
vite.generated.ts:764 · correctness
There was a problem hiding this comment.
This one does not hold for the Vite version Flow uses (8.4.0), so I left the code as is.
- Vite's dev HTML hook also handles classic inline scripts. For a
<script>withoutsrcand withouttype="module", it runsextractImportExpressionFromClassicScriptover the body and rewrites eachimport('…')URL with the sameprocessNodeUrlthat it uses forsrc. - The served page shows this: it contains
<script>import('/VAADIN/generated/vite-devmode.ts').catch(() => document.location.reload());</script>, with the base added. BasicsIT.devModeEntryPointLoadedWithoutInlineEventHandlerchecks that/VAADIN/generated/vite-devmode.tswas fetched with status 200. With an unprefixed URL it would fail, and the page would reload in a loop. The test report earlier in this PR saw the same served markup and no extra reloads.- Making it
type="module"would turn the inline script into anhtml-proxymodule served by the Vite dev server. That is the server that may not be reachable when the fallback is needed, so the reload would not happen in exactly that case.
|



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-statisticskeeps 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-detectortakes the code out of the comment at runtime and runs it withnew 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 pointvite-devmode.tshad an inlineonerrorhandler. 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:
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.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.vaadin:preserve-usage-statsplugin intovaadin:uncomment-usage-stats, which removes the comment markers around the usage statistics code and keeps the sourcemap.<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 forsrc, so context paths keep working.DevBundleSourceMapsIT, which asserted the old comment rewrite: it now runs the stub and checks that its code ran.BasicsITthat the entry point loads and that no script has an inline event handler.@vaadin/vaadin-usage-statistics2.1.3 to thevite-basicstest app, and aBasicsITcheck that its usage statistics run through the Vite dev server withoutnew Function.Working on behalf of @mcollovati