Skip to content

fix(spring): keep Spring Security headers on responses forwarded to Vaadin - #27161

Merged
Artur- merged 8 commits into
mainfrom
fix/spring-security-headers-on-forwarded-responses
Nov 30, 2026
Merged

Artur- merged 8 commits into
mainfrom
fix/spring-security-headers-on-forwarded-responses

Conversation

@totally-not-ai

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

Copy link
Copy Markdown
Contributor

Fixes #27159

regression · vaadin-spring · Spring Boot apps on Tomcat 11 with the default root vaadin.url-mapping

Background — lazy security headers. Spring Security's header filter writes headers such as X-Frame-Options, X-Content-Type-Options and Content-Security-Policy when the response is committed through the response wrapper it adds, not up front.

Since Vaadin 25 (Spring Boot 4, Tomcat 11), the bootstrap page and other responses that Spring MVC forwards to the Vaadin servlet go out without the headers Spring Security writes. This happens whenever the response fits in Tomcat's response buffer (8 KB by default). Larger responses are committed while they are still being written, so they still get the headers. The workaround is to set Tomcat's suspendWrappedResponseAfterForward back to false, or to set the headers again from an IndexHtmlRequestListener.

Risks:

  • ⚠️ Behaviour change: forwarded Vaadin responses are now closed by the servlet, through the wrappers, instead of by the container. Spring Security's values then apply as on 24.x, e.g. X-Frame-Options: DENY replaces Vaadin's default SAMEORIGIN when Spring Security is set to DENY.
  • 🔒 Security: the change brings back the headers the application configured. It does not change any access rules.
  • ✅ No API, threading, memory, serialization or migration impact.

Context. With the root mapping, Vaadin runs behind a ServletForwardingController. Tomcat 11 changed the default of suspendWrappedResponseAfterForward to true. It now ends a forwarded response on the innermost response, so the wrapper never sees the commit and the headers are dropped. Up to Tomcat 10.1, it closed the response through the wrappers.

  • SpringServlet closed a forwarded response through the response it was given at the end of service, the way Tomcat 10.1 did. It uses the output stream, or the writer if that was used.
    • The close is skipped when the request started async processing, and close errors such as a client abort are ignored, as the container does.
    • Chosen over changing the Tomcat setting from Vaadin's auto-configuration, because this works on any container and in WAR deployments, and does not change the forwards of the rest of the application.
  • Added unit tests for when the response is closed, and an HTTP check in the strict CSP Spring Security IT module that the bootstrap page carries Spring Security's X-Content-Type-Options and X-Frame-Options.

Working on behalf of @Artur-

…aadin

Tomcat 11 by default ends a forwarded response on the innermost
response, so filters that write headers when the response is committed
through their wrapper, like Spring Security's HeaderWriterFilter, never
get to write them. With the root mapping every Vaadin response is
forwarded, so the bootstrap page lost those headers. Close the response
through the wrapper chain at the end of a forward, as the container did
before.

Fixes #27159
@totally-not-ai

Copy link
Copy Markdown
Contributor Author

Type of change

  • Bugfix

How to test

  1. Run flow-tests/test-csp-strict-spring-security (mvn verify -pl flow-tests/test-csp-strict-spring-security), or any Spring Boot app with the default root mapping and Spring Security.
  2. Run curl -s -D - -o /dev/null http://localhost:8891/.
  3. The response has X-Content-Type-Options: nosniff and X-Frame-Options: DENY from Spring Security. Without the fix, both are missing or replaced by Vaadin's own SAMEORIGIN.

@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Test Results

 1 710 files  +1   1 800 suites  +1   2h 8m 2s ⏱️ - 4m 6s
13 926 tests +9  13 854 ✅ +9  72 💤 ±0  0 ❌ ±0 
14 604 runs  +9  14 532 ✅ +9  72 💤 ±0  0 ❌ ±0 

Results for commit d01ccd8. ± Comparison against base commit e23aabe.

♻️ This comment has been updated with latest results.

@totally-not-ai

Copy link
Copy Markdown
Contributor Author

Fixed the three java:S1166 findings. Close failures after a forward are still ignored, the same way the container ignores them, but they are now logged at debug level (a client that went away is the usual cause). Falling back to the writer is logged at trace level. Behaviour is unchanged, and the unit tests still pass.

@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

📦 Snapshot published

25.5.spring-security-headers-on-forwarded-responses-SNAPSHOT — built from d01ccd8 (run).

Built without running tests. Look at the checks on this pull request before relying on it.

Every new commit on this branch republishes it while the snapshot build label is there. Add -U to pick the newest build up.

How to use it
<repository>
  <id>vaadin-snapshots</id>
  <url>https://maven.vaadin.com/vaadin-prereleases</url>
  <snapshots><enabled>true</enabled></snapshots>
</repository>

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.vaadin</groupId>
      <artifactId>flow-bom</artifactId>
      <version>25.5.spring-security-headers-on-forwarded-responses-SNAPSHOT</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
    <!-- After flow-bom, so that its Flow version wins -->
    <dependency>
      <groupId>com.vaadin</groupId>
      <artifactId>vaadin-bom</artifactId>
      <version>25.5-SNAPSHOT</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

Replace the application's own vaadin-bom import with these two rather than adding them next to it: with two vaadin-bom imports, the first one decides the platform version. flow-bom has to come before vaadin-bom: Maven takes the first version it finds for an artifact, so the other order leaves the platform's own Flow version in use. 25.5-SNAPSHOT is the unreleased platform snapshot of the same minor version as this one, so this also moves the application off its released platform version.

@Artur-
Artur- marked this pull request as ready for review November 25, 2026 15:52
heruan
heruan previously approved these changes Nov 27, 2026

@heruan heruan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good. The close only moves to the response the servlet was given, which the container closes anyway after the forward, so I see no risk for other containers.

One nit: in closeResponseAfterForward the IllegalStateException catch covers both getOutputStream() and close(). If close() throws it, the fallback calls getWriter(), which throws again, and the real cause is only logged at trace. Getting the stream in its own try would avoid that.

One question, not blocking: forwarded requests that start async (long-polling push) skip the close. Do they still get the Spring Security headers?

A close() failing with IllegalStateException made the code try the
writer, which then failed too and hid the real cause at trace level.
Get the stream or writer first, and close it separately.
@totally-not-ai

Copy link
Copy Markdown
Contributor Author

Thanks for the review, @heruan, and sorry for the late reply.

Nit: fixed. The stream (or, if the writer is in use, the writer) is now obtained in its own try, and closing happens separately, so an IllegalStateException from close() no longer triggers the writer fallback. It is logged at debug like other close failures. A unit test covers that case and fails without the change.

Async forwards: they behave the same as on 24.x, so this PR neither fixes nor regresses them. Tomcat's ApplicationDispatcher.doForward returns before closing the response when request.isAsyncStarted(), with or without suspendWrappedResponseAfterForward, so Tomcat 10.1 and 11 treat a forward that starts async the same way and the skip here matches that. The response then stays open, and Atmosphere writes to it through the wrapped response it was given, so Spring Security's wrapper sees a commit triggered by a flush. A small message that is never flushed before the async context completes would be committed by the container past the wrappers, as it already was before Tomcat 11. I have not measured the long-polling headers. Those responses are XHR payloads rather than documents, so Content-Security-Policy and X-Frame-Options have no effect on them anyway.

@totally-not-ai

Copy link
Copy Markdown
Contributor Author

Added unit tests for the two remaining uncovered paths in closeResponseAfterForward: getting the output stream fails with an IOException, and neither the stream nor the writer can be obtained. In both cases the failure is ignored and nothing else is tried. This should bring new-code coverage above the quality gate's 80%. No production code changed.

protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
super.service(wrapRequest(request), response);
closeResponseAfterForward(request, response);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is this relevant only for Spring or also for apps otherwise running on a default Tomcat 11?

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.

@Artur- Only for apps where the Vaadin servlet is reached through a RequestDispatcher.forward. A plain app on a default Tomcat 11 is not affected.

The Tomcat 11 change is limited to the end of ApplicationDispatcher.doForward. When the forwarded response is a ServletResponseWrapper and suspendWrappedResponseAfterForward is true (the new default), Tomcat unwraps it down to the ResponseFacade and calls finish() on that. Once the response is suspended, isCommitted() reports true, so a filter that writes headers later through its wrapper gets them ignored. On 10.1 Tomcat instead closed the writer or stream of the wrapped response, which is the commit Spring Security's wrapper reacts to.

What that means for each setup:

  • Plain servlet app, or any app where the request is mapped straight to VaadinServlet: there is no forward. A filter that wraps the response writes its headers when doFilter returns, before the container finishes the response. Not affected.
  • Spring with Vaadin at the root mapping: ServletForwardingController forwards from DispatcherServlet to SpringServlet, and the response is wrapped by Spring Security's filters. This is the affected case, and it is the reason the fix lives in SpringServlet.
  • Spring with vaadin.url-mapping set (for example /ui/*): SpringServlet is mapped directly, so getDispatcherType() is REQUEST and the new code does nothing.
  • A non-Spring app that forwards to VaadinServlet from its own servlet or filter, with a response-wrapping filter in front, would hit the same Tomcat behaviour. That setup is not something Flow creates, so I kept the fix in SpringServlet. The close could move to VaadinServlet.service to cover it too; the DispatcherType.FORWARD check means it would still do nothing for direct requests. Let me know if you'd prefer that.

@sonarqubecloud

Copy link
Copy Markdown

@heruan heruan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks, the nit is fixed and the async answer makes sense. Approving again after the new commits.

@Artur-
Artur- added this pull request to the merge queue Nov 30, 2026
Merged via the queue into main with commit 8be78b3 Nov 30, 2026
105 of 107 checks passed
@Artur-
Artur- deleted the fix/spring-security-headers-on-forwarded-responses branch November 30, 2026 08:36
@github-actions

Copy link
Copy Markdown
Contributor

Documentation Bot: No documentation needed for this change.

This is a BEHAVIOR_CHANGE restoring a regression in SpringServlet: on Tomcat 11 with the default root URL mapping, Spring Security headers were silently dropped from forwarded responses. The documentation already describes the intended behavior — articles/flow/security/protections/vulnerabilities.adoc states that Vaadin only sets X-Frame-Options when the response does not already carry one set by other means such as Spring Security, and articles/flow/configuration/properties.adoc says the same for the frameOptions property. The fix makes the code match that existing documentation; nothing needs to change.

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

Generated by Documentation Bot for #27161 · agent · 60.6 AIC · ⊞ 11.7K · ◷

vaadin-bot pushed a commit that referenced this pull request Nov 30, 2026
…aadin (#27161) (CP: 25.4)

Fixes #27159

**regression** · vaadin-spring · Spring Boot apps on Tomcat 11 with the
default root `vaadin.url-mapping`

**Background — lazy security headers.** Spring Security's header filter
writes headers such as `X-Frame-Options`, `X-Content-Type-Options` and
`Content-Security-Policy` when the response is committed through the
response wrapper it adds, not up front.

Since Vaadin 25 (Spring Boot 4, Tomcat 11), the bootstrap page and other
responses that Spring MVC forwards to the Vaadin servlet go out without
the headers Spring Security writes. This happens whenever the response
fits in Tomcat's response buffer (8 KB by default). Larger responses are
committed while they are still being written, so they still get the
headers. The workaround is to set Tomcat's
`suspendWrappedResponseAfterForward` back to `false`, or to set the
headers again from an `IndexHtmlRequestListener`.

**Risks:**
- ⚠️ Behaviour change: forwarded Vaadin responses are now closed by the
servlet, through the wrappers, instead of by the container. Spring
Security's values then apply as on 24.x, e.g. `X-Frame-Options: DENY`
replaces Vaadin's default `SAMEORIGIN` when Spring Security is set to
`DENY`.
- 🔒 Security: the change brings back the headers the application
configured. It does not change any access rules.
- ✅ No API, threading, memory, serialization or migration impact.

**Context.** With the root mapping, Vaadin runs behind a
`ServletForwardingController`. Tomcat 11 changed the default of
`suspendWrappedResponseAfterForward` to `true`. It now ends a forwarded
response on the innermost response, so the wrapper never sees the commit
and the headers are dropped. Up to Tomcat 10.1, it closed the response
through the wrappers.

- `SpringServlet` closed a forwarded response through the response it
was given at the end of `service`, the way Tomcat 10.1 did. It uses the
output stream, or the writer if that was used.
- The close is skipped when the request started async processing, and
close errors such as a client abort are ignored, as the container does.
- Chosen over changing the Tomcat setting from Vaadin's
auto-configuration, because this works on any container and in WAR
deployments, and does not change the forwards of the rest of the
application.
- Added unit tests for when the response is closed, and an HTTP check in
the strict CSP Spring Security IT module that the bootstrap page carries
Spring Security's `X-Content-Type-Options` and `X-Frame-Options`.

Working on behalf of @Artur-

---------

Co-authored-by: totally-not-ai[bot] <290682512+totally-not-ai[bot]@users.noreply.github.com>
Co-authored-by: Artur Signell <artur@vaadin.com>
Co-authored-by: caalador <mikael.grankvist@vaadin.com>
mshabarov pushed a commit that referenced this pull request Dec 2, 2026
…27471) (CP: 25.4) (#27613)

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

---

> Part of #26688
> Part of vaadin/platform#9488
> 
> **new feature** · flow-server, vaadin-spring · Spring Security apps
that configure a Content Security Policy and use
`contentSecurityPolicy=strict`
> 
> **Background — Spring Security nonce support.** Since Spring Security
7.2, a Content Security Policy configured with `http.headers(h ->
h.contentSecurityPolicy(...))` can contain a `{nonce}` placeholder, for
example `script-src 'nonce-{nonce}' 'strict-dynamic'`. Spring Security
creates a nonce for each request, puts it in the header, and exposes it
as a request attribute so that whatever renders the page can put it on
the scripts.
> 
> An app can now configure its Content Security Policy in Spring
Security only. Vaadin puts the nonce of Spring Security on the scripts
of its page and sends no policy of its own, so the page is sent with
what Spring Security is configured to send, unchanged. Until now Vaadin
sent its own policy with its own nonce, and the Spring Security policy
was dropped from Vaadin pages without any message.
> 
> **Risks:**
> - ⚠️ Behaviour change: when a security filter chain has a policy,
Spring Security decides what a Vaadin page in strict mode is sent with,
and Vaadin adds nothing. `IndexHtmlResponse.getContentSecurityPolicy()`
then returns `null`.
> - ⚠️ Behaviour change: the nonce of Spring Security is put on the
scripts in the `off` and `warn` modes too, and
`IndexHtmlResponse.getContentSecurityPolicyNonce()` returns it there. A
policy that uses the nonce would otherwise block the whole page.
> - ⚠️ Public API: added `contentSecurityPolicy()` to
`VaadinSecurityConfigurer`, in three variants. It configures the policy
Vaadin needs in Spring Security, and replaces a policy set with
`http.headers()` for the same filter chain. It does not check that
strict mode is enabled; in the other modes the page loads, but
JavaScript that Vaadin runs from strings is blocked.
> - ⚠️ Migration needed: a policy written by hand must allow the nonce
(`'nonce-{nonce}'` in `script-src`) and what Vaadin needs, like
`'unsafe-inline'` in `style-src`. A policy that restricts scripts
without the nonce blocks the page, which the browser console reports.
> - 🔒 Security: Spring Security creates the nonce whenever a policy is
configured, also for a response it sends no nonce policy with. A policy
without the placeholder that does not restrict scripts (`frame-ancestors
'self'`), a report-only policy, or a policy limited to other paths with
`requestMatcher`, also when set through `contentSecurityPolicy()`,
leaves a strict Vaadin page without a policy that restricts its scripts.
This follows the configuration and is not reported.
> - 🔒 Security: the header of the page is written by Spring Security
when the response is committed. This relies on #27161, which makes that
happen for a small page forwarded to the Vaadin servlet on Tomcat 11.
> - ⚠️ Behaviour change: Spring Security sends its policy in development
mode too, where Vaadin sends none. Tested by hand: the app, dev tools
and the Copilot UI work under a nonce policy. Three things are blocked
without breaking the page: the `onerror` reload handler of the Vite dev
mode script, a `new Function` call in the development mode detector of
the web components (usage statistics), and the Copilot account picture
from `vaadin.com`. A real Copilot edit and hot reload are not tested.
Details in the first comment.
> - ❓ Open question: the nonce classes exist since Spring Security 7.2.
Whether the provider needs a guard for older versions depends on what
this branch supports.
> - ✅ No change without Spring Security or in a filter chain without a
policy.
> 
> **Context.** Spring Security gives no access to the policy it is
configured with, which made every way of combining its policy with the
one of Vaadin a workaround, see #27465. Sharing the nonce needs neither
policy to be read or changed. An app that wants the policy of Vaadin on
its Vaadin pages and its own policy elsewhere uses two filter chains,
with a policy in only one.
> 
> - Added `ContentSecurityPolicyNonceProvider` in
`com.vaadin.flow.internal`, found through `Lookup`
> - `IndexHtmlRequestHandler` uses the nonce of the provider when there
is one: it puts it on the scripts, creates no policy and sets no header
> - This applies in development mode and in every Content Security
Policy mode, because the policy is sent by its provider, which does not
know the mode of Vaadin
> - Added `SpringSecurityContentSecurityPolicyNonceProvider`, registered
by `SpringSecurityAutoConfiguration`, which reads the nonce attribute of
Spring Security
> - Added `VaadinSecurityConfigurer.contentSecurityPolicy()`, which
configures the default policy of the strict mode in Spring Security with
the `{nonce}` placeholder
> - One variant changes the policy, another also sets the options of
Spring Security for it, such as the request matcher
> - When the application has disabled the headers of Spring Security,
only the policy is added and the default headers stay off
> - The default policy moved to `StrictContentSecurityPolicy` in
`com.vaadin.flow.internal`, so Vaadin and the configurer build the same
one
> - The `test-csp-strict-spring-security` application now configures its
policy this way, with one more directive and one excluded path
> - Its tests check that every other response carries that policy, that
the scripts of the bootstrap page have its nonce, and that a Vaadin page
of the excluded path has the nonce and no policy
> 
> 
>

Co-authored-by: Giovanni Lovato <giovanni@vaadin.com>
Co-authored-by: totally-not-ai[bot] <290682512+totally-not-ai[bot]@users.noreply.github.com>
Co-authored-by: Artur Signell <artur@vaadin.com>
Co-authored-by: caalador <mikael.grankvist@vaadin.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.

Hackathon 25.4: Since 25.0 the bootstrap page is served without the headers Spring Security writes

4 participants