Skip to content

fix: keep fallback sources when addSources creates a directive - #27618

Merged
mcollovati merged 4 commits into
mainfrom
fix/csp-add-sources-fallback
Dec 2, 2026
Merged

mcollovati merged 4 commits into
mainfrom
fix/csp-add-sources-fallback

Conversation

@totally-not-ai

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

Copy link
Copy Markdown
Contributor

Fixes #27617

behavior deviation · flow-server · apps that add sources to a Content Security Policy directive that is not set yet

Background — CSP fallback. A fetch directive that is not in the policy falls back to another one in the browser: frame-src uses child-src, then default-src; worker-src uses child-src, script-src, then default-src. So with only default-src 'self', frames from the app's own server are allowed.

Adding a source to a directive the policy did not have, such as an external map in frame-src, also blocked the frames, media or manifest from the app's own server, because the new directive had only the added source. The new directive now starts with the sources it used to fall back to, so adding a source only allows more. The workaround was to add 'self' by hand.

Risks:

  • ⚠️ Behaviour change: addSources on a fetch directive that is not set now also keeps the fallback sources. The API is new in 25.4 and not yet in a final release. setDirective still sets exactly the given sources.

  • ✅ No public API, security, memory, serialization, threading or performance concerns.

  • ContentSecurityPolicy.addSources now creates a missing fetch directive with the sources of the first directive in its fallback list that is set (CSP Level 3 fallback list), without 'none'.

    • The sources are copied when the directive is created; later changes to the fallback do not follow.
    • Directives that do not fall back (form-action, base-uri, …) and directives with no fallback set start empty as before.
  • Javadoc of addSources explains the fallback and when a new directive still restricts.

  • Javadoc of addSources and IndexHtmlResponse.getContentSecurityPolicy() warns that a new script-src-elem or script-src-attr copies the nonce and 'strict-dynamic' from script-src, so host sources added to it are ignored by the browser; applications should not add those directives in strict mode.

  • Tests cover the fallback chains, 'none' (also as the first set fallback), no fallback, non-fetch directives, and that later fallback changes are not copied.

Chose this over only documenting the old behaviour in the Javadoc, since a method named "add" that can block what was allowed before is easy to misuse.

A fetch directive that is not set falls back to another one in the
browser, e.g. frame-src to child-src and default-src. Creating it with
only the added sources blocked what the fallback allowed, such as
'self' frames under the strict policy. The new directive now starts
with the sources of the directive it falls back to.

Fixes #27617
@totally-not-ai

totally-not-ai Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Type of change

  • Bugfix

@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 a chain where the first set fallback is 'none' but a later fallback is set.
📝 Copying 'strict-dynamic' from script-src makes the newly added host source a no-op, which nothing documents.

"default-src 'self' 'unsafe-eval'; script-src 'nonce-n' | script-src-elem | script-src-elem 'nonce-n' https://x.example.com",
"default-src 'self'; style-src 'self' 'unsafe-inline' | style-src-attr | style-src-attr 'self' 'unsafe-inline' https://x.example.com",
// 'none' only allows nothing, which the added source widens
"default-src 'NONE' | media-src | media-src https://x.example.com",

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 a chain where the first set fallback is 'none' but a later fallback is set.

The break fires on the first fallback that is set, not on the first one that yields sources. That distinction is what keeps the result correct for default-src 'self'; child-src 'none' + addSources("frame-src", …), which must not pick up 'self' from default-src.

The 'NONE' case only has default-src in the chain, so it passes either way. Moving the break inside the non-empty branch would silently widen the policy and every case here would still be green.

ContentSecurityPolicyTest.java:59 · 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.

Added the case default-src 'self'; child-src 'none' + frame-src to the parameterized test. It expects only the added source, so it fails if the lookup skips a fallback that holds only 'none'.

* directives that is set, so that adding sources does not block what the
* fallback allowed before. For example, with {@code default-src 'self'},
* adding {@code https://maps.example.com} to {@code frame-src} gives
* {@code frame-src 'self' https://maps.example.com}. The sources are copied

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.

📝 Copying 'strict-dynamic' from script-src makes the newly added host source a no-op, which nothing documents.

In strict mode script-src is 'nonce-…' 'strict-dynamic'. addSources("script-src-elem", "https://cdn.example.com") now yields script-src-elem 'nonce-…' 'strict-dynamic' https://cdn.example.com, and the browser ignores the host source because of 'strict-dynamic'. Before this change the add worked for the CDN (while breaking the page's own scripts), so the failure was loud; now it fails silently.

IndexHtmlResponse.getContentSecurityPolicy() already warns about exactly this for script-src. That warning should extend to script-src-elem and script-src-attr, or the addSources Javadoc should say that a copied 'strict-dynamic' makes added host sources ineffective.

ContentSecurityPolicy.java:129 · 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.

Documented it in two places. The addSources Javadoc now says that a new script-src-elem or script-src-attr copies 'strict-dynamic' from script-src, so the browser ignores host sources added to it. The warning in IndexHtmlResponse.getContentSecurityPolicy() now also says not to add script-src-elem or script-src-attr. I kept the copy itself: without it, adding either directive would block every nonced script of the page.

@mcollovati
mcollovati marked this pull request as ready for review December 2, 2026 11:34
@github-actions github-actions Bot added the +0.0.1 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 1 comment.

Finding
🧪 The test for "later fallback changes are not copied" passes whether or not the sources are copied.

}

@Test
void addSources_directiveNotSet_laterFallbackChangeNotCopied() {

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 test for "later fallback changes are not copied" passes whether or not the sources are copied.

setDirective always installs a fresh ArrayList, so changing default-src afterwards can never reach media-src — not even if collectFallbackSources returned the live fallback list. The only mutation that could propagate is addSources on the fallback directive, which appends in place:

.setDirective("default-src", "'self'")
.addSources("media-src", "https://x.example.com")
.addSources("default-src", "https://y.example.com")

That sequence fails on a sharing implementation and passes on the current one.

ContentSecurityPolicyTest.java:79 · 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.

Good catch. The test now calls addSources on default-src after media-src is created. That appends to the fallback list in place, so the test fails if the new directive shares that list.

@github-actions

github-actions Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Test Results

 1 656 files  ± 0   1 747 suites  ±0   1h 42m 3s ⏱️ + 3m 25s
14 104 tests +10  14 032 ✅ +10  72 💤 ±0  0 ❌ ±0 
14 530 runs  +10  14 458 ✅ +10  72 💤 ±0  0 ❌ ±0 

Results for commit 2502a9c. ± Comparison against base commit e248423.

♻️ This comment has been updated with latest results.

@totally-not-ai

totally-not-ai Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

SonarCloud java:S2203: collectFallbackSources now returns the filtered stream collected with Collectors.toCollection(ArrayList::new) and no longer uses forEach(sources::add). Behaviour is unchanged.

@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
📝 Javadoc says the new directive starts with the fallback's sources, but 'none' is silently dropped.

* set falls back to another directive in the browser, such as
* {@code frame-src} to {@code child-src} and then to {@code default-src}.
* The new directive then starts with the sources of the first of those
* directives that is set, so that adding sources does not block what the

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.

📝 Javadoc says the new directive starts with the fallback's sources, but 'none' is silently dropped.

With default-src 'none', addSources("frame-src", "https://maps.example.com") yields frame-src https://maps.example.com, not the frame-src 'none' https://maps.example.com the sentence promises. The code is right and the comment on collectFallbackSources explains why, but that exception never reaches the public Javadoc — and default-src 'none' is a common base policy.

ContentSecurityPolicy.java:126 · 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.

The addSources Javadoc now says that 'none' is not copied, because it must be the only source of a directive. It gives the default-src 'none' example: the same call gives frame-src https://maps.example.com.

@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.

@sonarqubecloud

sonarqubecloud Bot commented Dec 2, 2026

Copy link
Copy Markdown

@mcollovati
mcollovati added this pull request to the merge queue Dec 2, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Dec 2, 2026
@mcollovati
mcollovati added this pull request to the merge queue Dec 2, 2026
mcollovati added a commit to mcollovati/skeleton-starter-flow-spring that referenced this pull request Dec 2, 2026
CspConfiguration adds only the OpenStreetMap source to frame-src. With
the current 25.4-SNAPSHOT this blocks the new local IFrame on the reports
view (vaadin/flow#27617); with vaadin/flow#27618 frame-src keeps 'self'
and both IFrames load in a production build under strict.
Merged via the queue into main with commit 18667b4 Dec 2, 2026
68 checks passed
@mcollovati
mcollovati deleted the fix/csp-add-sources-fallback branch December 2, 2026 13:13
@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Documentation Bot: No documentation needed for this change.

This is a BEHAVIOR_CHANGE to ContentSecurityPolicy.addSources, but the API is new in 25.4 and not yet in a final release, so no reader has seen the old (buggy) behavior in production. The existing addSources examples in content-security-policy.adoc and components/map/index.adoc only use directives Vaadin's built-in policy already sets (img-src, connect-src), which this bug never affected, so nothing there is now incorrect. The one new edge case worth knowing — that a script-src-elem/script-src-attr created this way inherits 'strict-dynamic' and silently ignores added host sources — is already covered by the Javadoc this PR adds to addSources and IndexHtmlResponse.getContentSecurityPolicy().

Nothing was opened in vaadin/docs. If you disagree, the change has to be documented by hand there.

Generated by Documentation Bot for #27618 · agent · 69.3 AIC · ⊞ 6.6K · ◷

vaadin-bot added a commit that referenced this pull request Dec 2, 2026
… (CP: 25.4) (#27623)

This PR cherry-picks changes from the original PR #27618 to branch 25.4.

---

> Fixes #27617
> 
> **behavior deviation** · flow-server · apps that add sources to a
Content Security Policy directive that is not set yet
> 
> **Background — CSP fallback.** A fetch directive that is not in the
policy falls back to another one in the browser: `frame-src` uses
`child-src`, then `default-src`; `worker-src` uses `child-src`,
`script-src`, then `default-src`. So with only `default-src 'self'`,
frames from the app's own server are allowed.
> 
> Adding a source to a directive the policy did not have, such as an
external map in `frame-src`, also blocked the frames, media or manifest
from the app's own server, because the new directive had only the added
source. The new directive now starts with the sources it used to fall
back to, so adding a source only allows more. The workaround was to add
`'self'` by hand.
> 
> **Risks:**
> - ⚠️ Behaviour change: `addSources` on a fetch directive that is not
set now also keeps the fallback sources. The API is new in 25.4 and not
yet in a final release. `setDirective` still sets exactly the given
sources.
> - ✅ No public API, security, memory, serialization, threading or
performance concerns.
> 
> - `ContentSecurityPolicy.addSources` now creates a missing fetch
directive with the sources of the first directive in its fallback list
that is set (CSP Level 3 fallback list), without `'none'`.
> - The sources are copied when the directive is created; later changes
to the fallback do not follow.
> - Directives that do not fall back (`form-action`, `base-uri`, …) and
directives with no fallback set start empty as before.
> - Javadoc of `addSources` explains the fallback and when a new
directive still restricts.
> - Javadoc of `addSources` and
`IndexHtmlResponse.getContentSecurityPolicy()` warns that a new
`script-src-elem` or `script-src-attr` copies the nonce and
`'strict-dynamic'` from `script-src`, so host sources added to it are
ignored by the browser; applications should not add those directives in
strict mode.
> - Tests cover the fallback chains, `'none'` (also as the first set
fallback), no fallback, non-fetch directives, and that later fallback
changes are not copied.
> 
> Chose this over only documenting the old behaviour in the Javadoc,
since a method named "add" that can block what was allowed before is
easy to misuse.
> 
>

Co-authored-by: totally-not-ai[bot] <290682512+totally-not-ai[bot]@users.noreply.github.com>
mcollovati pushed a commit to vaadin/docs that referenced this pull request Dec 2, 2026
## 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. The warn-mode messages and the `addSources()`
behavior the guide describes come from vaadin/flow#27620 (25.4:
vaadin/flow#27626), vaadin/flow-components#10901 and vaadin/flow#27618
(25.4: vaadin/flow#27623), which are merged after 25.4.0-rc1.

## 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
don't reach the application code (Lit renderers, chart options), where
the message quotes the JavaScript to search for, 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
vaadin/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:

- Link the `JsModuleInvokers` part to the reference section that #6805
adds, once it's merged.
- `CompiledLitTemplate` isn't documented on the Grid renderers reference
page yet. The guide shows a short example in the meantime.

Working on behalf of Mikhail

---------

Co-authored-by: Vaadin Bot <vaadin-bot@users.noreply.github.com>
Co-authored-by: totally-not-ai[bot] <290682512+totally-not-ai[bot]@users.noreply.github.com>
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.

ContentSecurityPolicy.addSources() on a directive that is not set drops the default-src fallback

3 participants