Repository navigation
fix(spring): keep Spring Security headers on responses forwarded to Vaadin - #27161
Conversation
…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
Type of change
How to test
|
|
Fixed the three |
📦 Snapshot published
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 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 |
heruan
left a comment
There was a problem hiding this comment.
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.
|
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 Async forwards: they behave the same as on 24.x, so this PR neither fixes nor regresses them. Tomcat's |
|
Added unit tests for the two remaining uncovered paths in |
| protected void service(HttpServletRequest request, | ||
| HttpServletResponse response) throws ServletException, IOException { | ||
| super.service(wrapRequest(request), response); | ||
| closeResponseAfterForward(request, response); |
There was a problem hiding this comment.
Is this relevant only for Spring or also for apps otherwise running on a default Tomcat 11?
There was a problem hiding this comment.
@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 whendoFilterreturns, before the container finishes the response. Not affected. - Spring with Vaadin at the root mapping:
ServletForwardingControllerforwards fromDispatcherServlettoSpringServlet, and the response is wrapped by Spring Security's filters. This is the affected case, and it is the reason the fix lives inSpringServlet. - Spring with
vaadin.url-mappingset (for example/ui/*):SpringServletis mapped directly, sogetDispatcherType()isREQUESTand the new code does nothing. - A non-Spring app that forwards to
VaadinServletfrom 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 inSpringServlet. The close could move toVaadinServlet.serviceto cover it too; theDispatcherType.FORWARDcheck means it would still do nothing for direct requests. Let me know if you'd prefer that.
|
heruan
left a comment
There was a problem hiding this comment.
Thanks, the nit is fixed and the async answer makes sense. Approving again after the new commits.
|
Documentation Bot: No documentation needed for this change. This is a Nothing was opened in vaadin/docs. If you disagree, the change has to be documented by hand there.
|
…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>
…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>



Fixes #27159
regression · vaadin-spring · Spring Boot apps on Tomcat 11 with the default root
vaadin.url-mappingBackground — lazy security headers. Spring Security's header filter writes headers such as
X-Frame-Options,X-Content-Type-OptionsandContent-Security-Policywhen 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
suspendWrappedResponseAfterForwardback tofalse, or to set the headers again from anIndexHtmlRequestListener.Risks:
X-Frame-Options: DENYreplaces Vaadin's defaultSAMEORIGINwhen Spring Security is set toDENY.Context. With the root mapping, Vaadin runs behind a
ServletForwardingController. Tomcat 11 changed the default ofsuspendWrappedResponseAfterForwardtotrue. 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.SpringServletclosed a forwarded response through the response it was given at the end ofservice, the way Tomcat 10.1 did. It uses the output stream, or the writer if that was used.X-Content-Type-OptionsandX-Frame-Options.Working on behalf of @Artur-