From 2798537b83b3da02e95b5000747cd81e44c802b1 Mon Sep 17 00:00:00 2001 From: "totally-not-ai[bot]" <290682512+totally-not-ai[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:11:34 +0000 Subject: [PATCH 01/25] fix(spring): keep Spring Security headers on responses forwarded to Vaadin 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 --- .../SpringSecurityPolicyIT.java | 19 ++++++++++++++- .../com/vaadin/flow/spring/SpringServlet.java | 24 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java b/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java index 56fa74908da..55561ec597e 100644 --- a/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java +++ b/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java @@ -19,6 +19,7 @@ import java.net.CookieManager; import java.net.URI; import java.net.http.HttpClient; +import java.net.http.HttpHeaders; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.List; @@ -33,7 +34,8 @@ /** * Checks which Content Security Policy a response carries when both Vaadin, in - * the {@code strict} mode, and Spring Security are set to send one. + * the {@code strict} mode, and Spring Security are set to send one, and that + * the other headers of Spring Security reach the bootstrap page. */ public class SpringSecurityPolicyIT { @@ -76,6 +78,21 @@ public void bootstrapPage_carriesOnlyThePolicyOfVaadinWithTheAddedDirective() } } + @Test + public void bootstrapPage_carriesTheOtherHeadersOfSpringSecurity() + throws Exception { + try (HttpClient client = HttpClient.newHttpClient()) { + HttpHeaders headers = fetch(client, "/").headers(); + + // Spring Security writes these only when the response is + // committed, which the forward to the Vaadin servlet must let it + // see + assertEquals(List.of("nosniff"), + headers.allValues("X-Content-Type-Options")); + assertEquals(List.of("DENY"), headers.allValues("X-Frame-Options")); + } + } + @Test public void bundleScript_carriesThePolicyOfSpringSecurity() throws Exception { diff --git a/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringServlet.java b/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringServlet.java index 2714276b198..213caadb05a 100644 --- a/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringServlet.java +++ b/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringServlet.java @@ -15,6 +15,7 @@ */ package com.vaadin.flow.spring; +import jakarta.servlet.DispatcherType; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @@ -109,6 +110,29 @@ public SpringServlet(ApplicationContext context, boolean rootMapping) { protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.service(wrapRequest(request), response); + if (request.getDispatcherType() == DispatcherType.FORWARD + && !request.isAsyncStarted()) { + closeResponse(response); + } + } + + /** + * Closes a response after a forward through the response the servlet was + * given, as the container ends the response once the forward returns + * anyway. Wrappers of filters earlier in the chain, such as the one Spring + * Security writes its headers with, only see the response being committed + * when it happens through them. Tomcat 11 by default ends a forwarded + * response on the innermost response, past those wrappers, so their headers + * would be dropped. + */ + private static void closeResponse(HttpServletResponse response) + throws IOException { + try { + response.getOutputStream().close(); + } catch (IllegalStateException e) { + // The response was written through the writer + response.getWriter().close(); + } } @Override From c14993c1fabdb0f30079ab199f614010575d54ec Mon Sep 17 00:00:00 2001 From: "totally-not-ai[bot]" <290682512+totally-not-ai[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:13:55 +0000 Subject: [PATCH 02/25] fix(spring): ignore a failed close after a forward like the container does --- .../com/vaadin/flow/spring/SpringServlet.java | 42 +++++--- .../vaadin/flow/spring/SpringServletTest.java | 100 ++++++++++++++++++ 2 files changed, 128 insertions(+), 14 deletions(-) create mode 100644 vaadin-spring/src/test/java/com/vaadin/flow/spring/SpringServletTest.java diff --git a/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringServlet.java b/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringServlet.java index 213caadb05a..701d7cfe471 100644 --- a/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringServlet.java +++ b/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringServlet.java @@ -110,28 +110,42 @@ public SpringServlet(ApplicationContext context, boolean rootMapping) { protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.service(wrapRequest(request), response); - if (request.getDispatcherType() == DispatcherType.FORWARD - && !request.isAsyncStarted()) { - closeResponse(response); - } + closeResponseAfterForward(request, response); } /** - * Closes a response after a forward through the response the servlet was - * given, as the container ends the response once the forward returns - * anyway. Wrappers of filters earlier in the chain, such as the one Spring - * Security writes its headers with, only see the response being committed - * when it happens through them. Tomcat 11 by default ends a forwarded - * response on the innermost response, past those wrappers, so their headers - * would be dropped. + * Closes the response at the end of a forward through the response the + * servlet was given, as the container ends the response once the forward + * returns anyway. Wrappers of filters earlier in the chain, such as the one + * Spring Security writes its headers with, only see the response being + * committed when it happens through them. Tomcat 11 by default + * ({@code suspendWrappedResponseAfterForward}) ends a forwarded response on + * the innermost response, past those wrappers, so their headers would be + * dropped. Does nothing for a request that was not forwarded or that + * started asynchronous processing. + * + * @param request + * the request the servlet handled + * @param response + * the response the servlet was given */ - private static void closeResponse(HttpServletResponse response) - throws IOException { + static void closeResponseAfterForward(HttpServletRequest request, + HttpServletResponse response) { + if (request.getDispatcherType() != DispatcherType.FORWARD + || request.isAsyncStarted()) { + return; + } try { response.getOutputStream().close(); } catch (IllegalStateException e) { // The response was written through the writer - response.getWriter().close(); + try { + response.getWriter().close(); + } catch (IOException | IllegalStateException ignore) { + // Ignored like the container does when it closes the response + } + } catch (IOException ignore) { + // The client went away; the container ignores this too } } diff --git a/vaadin-spring/src/test/java/com/vaadin/flow/spring/SpringServletTest.java b/vaadin-spring/src/test/java/com/vaadin/flow/spring/SpringServletTest.java new file mode 100644 index 00000000000..323fc156898 --- /dev/null +++ b/vaadin-spring/src/test/java/com/vaadin/flow/spring/SpringServletTest.java @@ -0,0 +1,100 @@ +/* + * Copyright 2000-2026 Vaadin Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.vaadin.flow.spring; + +import jakarta.servlet.DispatcherType; +import jakarta.servlet.ServletOutputStream; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import java.io.IOException; +import java.io.PrintWriter; + +import org.junit.jupiter.api.Test; + +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +class SpringServletTest { + + private final HttpServletResponse response = mock( + HttpServletResponse.class); + private final ServletOutputStream outputStream = mock( + ServletOutputStream.class); + private final PrintWriter writer = mock(PrintWriter.class); + + @Test + void forward_closesOutputStreamThroughGivenResponse() throws IOException { + when(response.getOutputStream()).thenReturn(outputStream); + + SpringServlet.closeResponseAfterForward( + request(DispatcherType.FORWARD, false), response); + + verify(outputStream).close(); + verify(response, never()).getWriter(); + } + + @Test + void forwardWrittenWithWriter_closesWriter() throws IOException { + when(response.getOutputStream()) + .thenThrow(new IllegalStateException("writer in use")); + when(response.getWriter()).thenReturn(writer); + + SpringServlet.closeResponseAfterForward( + request(DispatcherType.FORWARD, false), response); + + verify(writer).close(); + } + + @Test + void forwardToDisconnectedClient_doesNotThrow() throws IOException { + when(response.getOutputStream()).thenReturn(outputStream); + doThrow(new IOException("client went away")).when(outputStream).close(); + + SpringServlet.closeResponseAfterForward( + request(DispatcherType.FORWARD, false), response); + + verify(outputStream).close(); + } + + @Test + void asyncForward_leavesResponseOpen() { + SpringServlet.closeResponseAfterForward( + request(DispatcherType.FORWARD, true), response); + + verifyNoInteractions(response); + } + + @Test + void directRequest_leavesResponseOpen() { + SpringServlet.closeResponseAfterForward( + request(DispatcherType.REQUEST, false), response); + + verifyNoInteractions(response); + } + + private static HttpServletRequest request(DispatcherType type, + boolean asyncStarted) { + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getDispatcherType()).thenReturn(type); + when(request.isAsyncStarted()).thenReturn(asyncStarted); + return request; + } +} From 8ae7c06c50d657faaf54cdd14488624bb20eb21c Mon Sep 17 00:00:00 2001 From: "totally-not-ai[bot]" <290682512+totally-not-ai[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:37:46 +0000 Subject: [PATCH 03/25] fix(spring): log the ignored close failures of a forwarded response --- .../com/vaadin/flow/spring/SpringServlet.java | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringServlet.java b/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringServlet.java index 701d7cfe471..2c94ff602a4 100644 --- a/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringServlet.java +++ b/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringServlet.java @@ -26,6 +26,8 @@ import java.util.Properties; import java.util.stream.Collectors; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.core.env.Environment; import org.springframework.web.servlet.mvc.ServletForwardingController; @@ -138,17 +140,28 @@ static void closeResponseAfterForward(HttpServletRequest request, try { response.getOutputStream().close(); } catch (IllegalStateException e) { - // The response was written through the writer + getLogger().trace( + "The forwarded response was written through the writer", e); try { response.getWriter().close(); - } catch (IOException | IllegalStateException ignore) { - // Ignored like the container does when it closes the response + } catch (IOException | IllegalStateException closeException) { + logIgnoredCloseFailure(closeException); } - } catch (IOException ignore) { - // The client went away; the container ignores this too + } catch (IOException e) { + logIgnoredCloseFailure(e); } } + private static void logIgnoredCloseFailure(Exception e) { + // The container ignores a failed close too, typically a client that + // went away + getLogger().debug("Unable to close the forwarded response", e); + } + + private static Logger getLogger() { + return LoggerFactory.getLogger(SpringServlet.class); + } + @Override protected VaadinServletService createServletService( DeploymentConfiguration deploymentConfiguration) From 46c75286827b8fb1c4b6a67c2e7fb4946c88284f Mon Sep 17 00:00:00 2001 From: "totally-not-ai[bot]" <290682512+totally-not-ai[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:47:32 +0000 Subject: [PATCH 04/25] fix: only fall back to the writer when the stream is unavailable 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. --- .../com/vaadin/flow/spring/SpringServlet.java | 17 +++++++++++++---- .../vaadin/flow/spring/SpringServletTest.java | 13 +++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringServlet.java b/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringServlet.java index 2c94ff602a4..6db358853a1 100644 --- a/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringServlet.java +++ b/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringServlet.java @@ -20,6 +20,7 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import java.io.Closeable; import java.io.IOException; import java.util.Arrays; import java.util.List; @@ -137,18 +138,26 @@ static void closeResponseAfterForward(HttpServletRequest request, || request.isAsyncStarted()) { return; } + Closeable output; try { - response.getOutputStream().close(); + output = response.getOutputStream(); } catch (IllegalStateException e) { getLogger().trace( "The forwarded response was written through the writer", e); try { - response.getWriter().close(); - } catch (IOException | IllegalStateException closeException) { - logIgnoredCloseFailure(closeException); + output = response.getWriter(); + } catch (IOException | IllegalStateException writerException) { + logIgnoredCloseFailure(writerException); + return; } } catch (IOException e) { logIgnoredCloseFailure(e); + return; + } + try { + output.close(); + } catch (IOException | IllegalStateException e) { + logIgnoredCloseFailure(e); } } diff --git a/vaadin-spring/src/test/java/com/vaadin/flow/spring/SpringServletTest.java b/vaadin-spring/src/test/java/com/vaadin/flow/spring/SpringServletTest.java index 323fc156898..0fe67685ffe 100644 --- a/vaadin-spring/src/test/java/com/vaadin/flow/spring/SpringServletTest.java +++ b/vaadin-spring/src/test/java/com/vaadin/flow/spring/SpringServletTest.java @@ -74,6 +74,19 @@ void forwardToDisconnectedClient_doesNotThrow() throws IOException { verify(outputStream).close(); } + @Test + void forwardWithOutputStreamFailingToClose_doesNotFallBackToWriter() + throws IOException { + when(response.getOutputStream()).thenReturn(outputStream); + doThrow(new IllegalStateException("already closed")).when(outputStream) + .close(); + + SpringServlet.closeResponseAfterForward( + request(DispatcherType.FORWARD, false), response); + + verify(response, never()).getWriter(); + } + @Test void asyncForward_leavesResponseOpen() { SpringServlet.closeResponseAfterForward( From 793285acc3252a03b5287bcece6da8252763fea9 Mon Sep 17 00:00:00 2001 From: "totally-not-ai[bot]" <290682512+totally-not-ai[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:11:08 +0000 Subject: [PATCH 05/25] test: cover failures to get the forwarded response's stream or writer --- .../vaadin/flow/spring/SpringServletTest.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/vaadin-spring/src/test/java/com/vaadin/flow/spring/SpringServletTest.java b/vaadin-spring/src/test/java/com/vaadin/flow/spring/SpringServletTest.java index 0fe67685ffe..655773fc929 100644 --- a/vaadin-spring/src/test/java/com/vaadin/flow/spring/SpringServletTest.java +++ b/vaadin-spring/src/test/java/com/vaadin/flow/spring/SpringServletTest.java @@ -87,6 +87,32 @@ void forwardWithOutputStreamFailingToClose_doesNotFallBackToWriter() verify(response, never()).getWriter(); } + @Test + void forwardWithFailingOutputStream_doesNotFallBackToWriter() + throws IOException { + when(response.getOutputStream()) + .thenThrow(new IOException("client went away")); + + SpringServlet.closeResponseAfterForward( + request(DispatcherType.FORWARD, false), response); + + verify(response, never()).getWriter(); + } + + @Test + void forwardWithNeitherStreamNorWriterAvailable_doesNotThrow() + throws IOException { + when(response.getOutputStream()) + .thenThrow(new IllegalStateException("writer in use")); + when(response.getWriter()) + .thenThrow(new IOException("client went away")); + + SpringServlet.closeResponseAfterForward( + request(DispatcherType.FORWARD, false), response); + + verify(response).getWriter(); + } + @Test void asyncForward_leavesResponseOpen() { SpringServlet.closeResponseAfterForward( From 020ee3612bbdf8b840b4a8fceb0afaff775cbf92 Mon Sep 17 00:00:00 2001 From: Giovanni Lovato Date: Fri, 27 Nov 2026 12:39:55 +0100 Subject: [PATCH 06/25] feat: use Spring Security nonce for strict Content Security Policy Part of #26688 --- .../ContentSecurityPolicyNonceProvider.java | 48 ++++++ .../IndexHtmlRequestHandler.java | 66 ++++++-- .../communication/IndexHtmlResponse.java | 24 +-- .../IndexHtmlRequestHandlerTest.java | 38 +++++ .../testutil/ClassesSerializableTest.java | 1 + .../test-csp-strict-spring-security/README.md | 17 +- .../springsecurity/PolicyAdjuster.java | 5 +- .../springsecurity/SecurityConfig.java | 19 ++- .../SpringSecurityPolicyIT.java | 63 ++++--- .../SpringSecurityAutoConfiguration.java | 14 ++ ...ityContentSecurityPolicyNonceProvider.java | 51 ++++++ .../spring/SpringClassesSerializableTest.java | 1 + ...ontentSecurityPolicyNonceProviderTest.java | 156 ++++++++++++++++++ 13 files changed, 440 insertions(+), 63 deletions(-) create mode 100644 flow-server/src/main/java/com/vaadin/flow/internal/ContentSecurityPolicyNonceProvider.java create mode 100644 vaadin-spring/src/main/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProvider.java create mode 100644 vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/ContentSecurityPolicyNonceProvider.java b/flow-server/src/main/java/com/vaadin/flow/internal/ContentSecurityPolicyNonceProvider.java new file mode 100644 index 00000000000..3c5cb124e74 --- /dev/null +++ b/flow-server/src/main/java/com/vaadin/flow/internal/ContentSecurityPolicyNonceProvider.java @@ -0,0 +1,48 @@ +/* + * Copyright 2000-2026 Vaadin Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.vaadin.flow.internal; + +import org.jspecify.annotations.Nullable; + +import com.vaadin.flow.di.Lookup; +import com.vaadin.flow.server.VaadinRequest; + +/** + * Provides the Content Security Policy nonce of a request when something other + * than Vaadin sends the policy of the application, such as Spring Security. + *

+ * In the strict mode, Vaadin asks the implementation it finds through + * {@link Lookup} for the nonce of each index HTML request. When there is one, + * Vaadin puts that nonce on the scripts of the page and sends no policy of its + * own: the policy that allows the nonce is sent by whoever created it. + *

+ * For internal use only. May be renamed or removed in a future release. + */ +@FunctionalInterface +public interface ContentSecurityPolicyNonceProvider { + + /** + * Finds the nonce that the Content Security Policy of the response to a + * request allows. + * + * @param request + * the request the page is written for, not null + * @return the nonce, or {@code null} if no policy with a nonce is sent for + * the request, in which case Vaadin sends its own + */ + @Nullable + String findNonce(VaadinRequest request); +} diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java index 8d1e3f8b093..8360252a177 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java @@ -37,6 +37,7 @@ import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; +import org.jspecify.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import tools.jackson.databind.JsonNode; @@ -47,11 +48,13 @@ import com.vaadin.experimental.FeatureFlags; import com.vaadin.flow.component.UI; import com.vaadin.flow.component.page.ColorScheme; +import com.vaadin.flow.di.Lookup; import com.vaadin.flow.function.DeploymentConfiguration; import com.vaadin.flow.internal.BootstrapHandlerHelper; import com.vaadin.flow.internal.BrowserLiveReload; import com.vaadin.flow.internal.BrowserLiveReload.Backend; import com.vaadin.flow.internal.BrowserLiveReloadAccessor; +import com.vaadin.flow.internal.ContentSecurityPolicyNonceProvider; import com.vaadin.flow.internal.FileIOUtils; import com.vaadin.flow.internal.FrontendUtils; import com.vaadin.flow.internal.JacksonUtils; @@ -98,6 +101,9 @@ public class IndexHtmlRequestHandler extends JavaScriptBootstrapHandler { private static final String SCRIPT_INITIAL = "initial"; public static final String LIVE_RELOAD_PORT_ATTR = "livereload.port"; private static final String CONTENT_SECURITY_POLICY_HEADER = "Content-Security-Policy"; + + private transient @Nullable ContentSecurityPolicyNonceProvider contentSecurityPolicyNonceProvider; + private transient boolean contentSecurityPolicyNonceProviderLookedUp; private static final String CSP_SELF = "'self'"; private static final String CSP_DATA = "data:"; @@ -154,9 +160,16 @@ public boolean synchronizedHandleRequest(VaadinSession session, if (config .getContentSecurityPolicyMode() == ContentSecurityPolicyMode.STRICT) { - String nonce = createContentSecurityPolicyNonce(); - indexHtmlResponse.setContentSecurityPolicy(nonce, - createDefaultContentSecurityPolicy(nonce)); + String providedNonce = findProvidedContentSecurityPolicyNonce( + request); + if (providedNonce != null) { + // The policy that allows the nonce is sent by its provider + indexHtmlResponse.setContentSecurityPolicy(providedNonce, null); + } else { + String nonce = createContentSecurityPolicyNonce(); + indexHtmlResponse.setContentSecurityPolicy(nonce, + createDefaultContentSecurityPolicy(nonce)); + } } addInitialFlow(initialJson, indexDocument, request); @@ -258,12 +271,17 @@ public boolean synchronizedHandleRequest(VaadinSession session, addCommercialBanner(service.getDeploymentConfiguration(), indexDocument); - // The dev server and dev tools need eval, so the policy is only sent - // in production mode if (config - .getContentSecurityPolicyMode() == ContentSecurityPolicyMode.STRICT - && config.isProductionMode()) { - applyContentSecurityPolicy(indexHtmlResponse); + .getContentSecurityPolicyMode() == ContentSecurityPolicyMode.STRICT) { + if (indexHtmlResponse.getContentSecurityPolicy() == null) { + // A policy with the nonce is sent by its provider, whatever + // the mode, so the scripts need the nonce to run + addNonceToScripts(indexHtmlResponse); + } else if (config.isProductionMode()) { + // The dev server and dev tools need eval, so the policy of + // Vaadin is only sent in production mode + applyContentSecurityPolicy(indexHtmlResponse); + } } try { @@ -318,18 +336,36 @@ private static void applyContentSecurityPolicy( CONTENT_SECURITY_POLICY_HEADER, InitParameters.CONTENT_SECURITY_POLICY)); } - // Both are created for the strict mode, which the caller checks - String nonce = Objects.requireNonNull( - indexHtmlResponse.getContentSecurityPolicyNonce()); + addNonceToScripts(indexHtmlResponse); + // Created for the strict mode, which the caller checks ContentSecurityPolicy policy = Objects .requireNonNull(indexHtmlResponse.getContentSecurityPolicy()); - // Done after the listeners have run so that every script in the page - // gets the nonce, whichever code added it + response.setHeader(CONTENT_SECURITY_POLICY_HEADER, + policy.toHeaderValue()); + } + + // Done after the listeners have run so that every script in the page gets + // the nonce, whichever code added it + private static void addNonceToScripts(IndexHtmlResponse indexHtmlResponse) { + // Created for the strict mode, which the caller checks + String nonce = Objects.requireNonNull( + indexHtmlResponse.getContentSecurityPolicyNonce()); indexHtmlResponse.getDocument().select( "script, link[rel=modulepreload], link[rel=preload][as=script]") .attr("nonce", nonce); - response.setHeader(CONTENT_SECURITY_POLICY_HEADER, - policy.toHeaderValue()); + } + + private @Nullable String findProvidedContentSecurityPolicyNonce( + VaadinRequest request) { + // Looked up once: a lookup can be a search for beans + if (!contentSecurityPolicyNonceProviderLookedUp) { + contentSecurityPolicyNonceProvider = request.getService() + .getContext().getAttribute(Lookup.class) + .lookup(ContentSecurityPolicyNonceProvider.class); + contentSecurityPolicyNonceProviderLookedUp = true; + } + ContentSecurityPolicyNonceProvider provider = contentSecurityPolicyNonceProvider; + return provider == null ? null : provider.findNonce(request); } private void initializeFeatureFlags(Document indexDocument, diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java index 7254c7b8d59..8bcea88804c 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java @@ -125,10 +125,11 @@ public Optional getUI() { * {@code script-src} directive of the Content Security Policy. *

* A new nonce is created for every response when the application runs with - * the {@link ContentSecurityPolicyMode#STRICT} mode. Scripts added by an - * {@link IndexHtmlRequestListener} get the nonce automatically, but the - * value can also be used for other content that needs it. The nonce is not - * put on the scripts in development mode. + * the {@link ContentSecurityPolicyMode#STRICT} mode. It is the nonce of + * Spring Security when a Content Security Policy is configured there. + * Scripts added by an {@link IndexHtmlRequestListener} get the nonce + * automatically, but the value can also be used for other content that + * needs it. The nonce is not put on the scripts in development mode. * * @return the nonce, or {@code null} if the mode is not * {@link ContentSecurityPolicyMode#STRICT} @@ -160,13 +161,16 @@ public Optional getUI() { * tools need {@code eval}. In production mode, the request fails with an * {@link IllegalStateException} if the response already has a * {@code Content-Security-Policy} header when the page is written, for - * example from a servlet filter that runs before Vaadin. A filter that - * writes its header only when the response is committed, such as Spring - * Security's {@code HeaderWriterFilter} by default, cannot be detected; its - * policy should be configured here instead. + * example from a servlet filter that runs before Vaadin. + *

+ * There is no policy to adjust when the application sends its own with a + * nonce it shares with Vaadin, which is the case when a Content Security + * Policy is configured in Spring Security. That policy is sent with the + * page as configured, and is adjusted where it is configured. * * @return the mutable policy, or {@code null} if the mode is not - * {@link ContentSecurityPolicyMode#STRICT} + * {@link ContentSecurityPolicyMode#STRICT} or if the policy is not + * sent by Vaadin * @since 25.4 */ public @Nullable ContentSecurityPolicy getContentSecurityPolicy() { @@ -174,7 +178,7 @@ public Optional getUI() { } void setContentSecurityPolicy(String contentSecurityPolicyNonce, - ContentSecurityPolicy contentSecurityPolicy) { + @Nullable ContentSecurityPolicy contentSecurityPolicy) { this.contentSecurityPolicyNonce = contentSecurityPolicyNonce; this.contentSecurityPolicy = contentSecurityPolicy; } diff --git a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java index aa53e3945d0..b3c4f8630b5 100644 --- a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java +++ b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java @@ -60,6 +60,7 @@ import com.vaadin.flow.component.page.ColorScheme; import com.vaadin.flow.di.Lookup; import com.vaadin.flow.di.ResourceProvider; +import com.vaadin.flow.internal.ContentSecurityPolicyNonceProvider; import com.vaadin.flow.internal.JacksonUtils; import com.vaadin.flow.internal.UsageStatistics; import com.vaadin.flow.internal.menu.MenuRegistry; @@ -315,6 +316,43 @@ public void serveIndexHtml_strictCsp_sendsPolicyWithNonceOnEveryScript() "Every response should get a new nonce"); } + @Test + public void serveIndexHtml_strictCspAndNonceProvided_scriptsGetItAndNoPolicyIsSent() + throws IOException { + deploymentConfiguration + .setContentSecurityPolicyMode(ContentSecurityPolicyMode.STRICT); + // The provider of the nonce may have written its policy already + when(response.containsHeader("Content-Security-Policy")) + .thenReturn(true); + ContentSecurityPolicyNonceProvider provider = request -> "provided-nonce"; + when(context.getAttribute(Lookup.class) + .lookup(ContentSecurityPolicyNonceProvider.class)) + .thenReturn(provider); + List responses = new ArrayList<>(); + service.addIndexHtmlRequestListener(evt -> { + responses.add(evt); + evt.getDocument().body().appendElement("script").attr("src", + "listener.js"); + }); + + indexHtmlRequestHandler.synchronizedHandleRequest(session, + createVaadinRequest("/"), response); + + verify(response, never()).setHeader(eq("Content-Security-Policy"), + any()); + assertEquals("provided-nonce", + responses.get(0).getContentSecurityPolicyNonce()); + assertNull(responses.get(0).getContentSecurityPolicy()); + Elements scripts = Jsoup + .parse(responseOutput.toString(StandardCharsets.UTF_8)) + .getElementsByTag("script"); + assertTrue(scripts.size() > 1); + for (Element script : scripts) { + assertEquals("provided-nonce", script.attr("nonce"), + script.outerHtml()); + } + } + @Test public void serveIndexHtml_strictCspAndHeaderAlreadyPresent_throws() { deploymentConfiguration diff --git a/flow-test-generic/src/main/java/com/vaadin/flow/testutil/ClassesSerializableTest.java b/flow-test-generic/src/main/java/com/vaadin/flow/testutil/ClassesSerializableTest.java index 64858c3f15b..ee46d0045be 100644 --- a/flow-test-generic/src/main/java/com/vaadin/flow/testutil/ClassesSerializableTest.java +++ b/flow-test-generic/src/main/java/com/vaadin/flow/testutil/ClassesSerializableTest.java @@ -140,6 +140,7 @@ protected Stream getExcludedPatterns() { "com\\.vaadin\\.flow\\.internal\\.nodefeature\\.NodeFeatureRegistry", "com\\.vaadin\\.flow\\.internal\\.nodefeature\\.NodeFeatures", "com\\.vaadin\\.flow\\.internal\\.CustomElementNameValidator", + "com\\.vaadin\\.flow\\.internal\\.ContentSecurityPolicyNonceProvider", "com\\.vaadin\\.flow\\.internal\\.ContentSecurityPolicyViolationReporter(\\$.*)?", "com\\.vaadin\\.flow\\.internal\\.JsStringFallbacks(\\$.*)?", "com\\.vaadin\\.flow\\.internal\\.StackTraceUtil", diff --git a/flow-tests/test-csp-strict-spring-security/README.md b/flow-tests/test-csp-strict-spring-security/README.md index 6c1d7076f30..2fc019e3930 100644 --- a/flow-tests/test-csp-strict-spring-security/README.md +++ b/flow-tests/test-csp-strict-spring-security/README.md @@ -1,20 +1,25 @@ # test-csp-strict-spring-security Integration tests for the `contentSecurityPolicy=strict` setting in an application that also -uses Spring Security, where Spring Security is configured with a -`Content-Security-Policy` of its own. +uses Spring Security, where the `Content-Security-Policy` of the application is +configured in Spring Security. -Both Vaadin and Spring Security want to send the header. The tests pin what -each response carries: +Spring Security creates a nonce for each request and puts it in place of the +`{nonce}` placeholder of the policy. Vaadin puts that nonce on the scripts of a +bootstrap page and sends no policy of its own. The tests pin what each response +carries: | Response | Policy | |---|---| -| A bootstrap page | Only the nonce-based policy of Vaadin. The policy of Spring Security is not sent and not merged in. | -| A bootstrap page, with a directive added through `IndexHtmlResponse.getContentSecurityPolicy()` in an `IndexHtmlRequestListener` | The policy of Vaadin with that directive. This is how an application adds what it would otherwise configure in Spring Security. | +| A bootstrap page | The policy of Spring Security, with the nonce that every script of the page has. | | A file of the production bundle, `VAADIN/build/*.js` | The policy of Spring Security. | | A download served by a `DownloadHandler` | The policy of Spring Security. | | A response that Spring Security writes itself, such as a 403 | The policy of Spring Security. | +A directive added through `IndexHtmlResponse.getContentSecurityPolicy()` in an +`IndexHtmlRequestListener` is not sent: that policy is only there when Vaadin +sends it. + The tests read the response headers and need no browser. The browser scenarios of the `strict` mode are in `test-csp-strict`; the policy of a bootstrap page is the same here, so they are not repeated. diff --git a/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/PolicyAdjuster.java b/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/PolicyAdjuster.java index 83714287422..976576e57e3 100644 --- a/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/PolicyAdjuster.java +++ b/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/PolicyAdjuster.java @@ -23,8 +23,9 @@ /** * Adds a directive to the policy that Vaadin sends with a bootstrap page. This - * is how an application adjusts the policy in the {@code strict} mode, also for - * what it would otherwise configure in Spring Security. + * is how an application adjusts the policy in the {@code strict} mode when + * Vaadin sends it. In this application Spring Security sends the policy, so + * there is none to adjust and the directive must not show up. */ @Component public class PolicyAdjuster implements VaadinServiceInitListener { diff --git a/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/SecurityConfig.java b/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/SecurityConfig.java index 3236e88e569..3772d066154 100644 --- a/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/SecurityConfig.java +++ b/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/SecurityConfig.java @@ -24,8 +24,9 @@ import static com.vaadin.flow.spring.security.VaadinSecurityConfigurer.vaadin; /** - * A Vaadin security configuration where Spring Security is also told to send a - * Content Security Policy, as an application may have done before it turned on + * A Vaadin security configuration where the Content Security Policy of the + * application is configured in Spring Security, which is where an application + * with Spring Security configures it for * {@code vaadin.contentSecurityPolicy=strict}. */ @EnableWebSecurity @@ -33,11 +34,17 @@ public class SecurityConfig { /** - * The policy Spring Security is configured with. {@code form-action} is in - * no other policy of this application, so a policy that has it comes from - * Spring Security. + * The policy Spring Security is configured with. It is the policy Vaadin + * sends in the {@code strict} mode, with the {@code {nonce}} placeholder + * that Spring Security replaces with the nonce of the request, and with + * {@code form-action}, which only this policy has. */ - public static final String SPRING_SECURITY_POLICY = "default-src 'self'; form-action 'self'"; + public static final String SPRING_SECURITY_POLICY = "default-src 'self'; " + + "script-src 'nonce-{nonce}' 'strict-dynamic'; " + + "style-src 'self' 'unsafe-inline'; img-src 'self' data:; " + + "font-src 'self' data:; connect-src 'self' data:; " + + "worker-src 'self'; object-src 'none'; base-uri 'self'; " + + "form-action 'self'"; @Bean SecurityFilterChain vaadinSecurityFilterChain(HttpSecurity http) { diff --git a/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java b/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java index 55561ec597e..64cb892f66e 100644 --- a/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java +++ b/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java @@ -29,7 +29,6 @@ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -56,25 +55,22 @@ public class SpringSecurityPolicyIT { + System.getProperty("serverPort", "8891"); @Test - public void bootstrapPage_carriesOnlyThePolicyOfVaadinWithTheAddedDirective() + public void bootstrapPage_carriesThePolicyOfSpringSecurityWithTheNonceOfItsScripts() throws Exception { try (HttpClient client = HttpClient.newHttpClient()) { - List policies = fetch(client, "/").headers() - .allValues(HEADER); - - assertEquals(1, policies.size(), - "The bootstrap page should have one policy: " + policies); - String policy = policies.get(0); - assertTrue(policy.contains("script-src 'nonce-"), - "The policy should be the nonce-based one of Vaadin: " - + policy); - assertFalse(policy.contains("form-action"), - "The policy of Spring Security should not be merged in: " - + policy); - String directive = PolicyAdjuster.DIRECTIVE + " " - + PolicyAdjuster.SOURCE; - assertTrue(List.of(policy.split("; ")).contains(directive), - "No " + directive + " in the policy: " + policy); + HttpResponse response = fetch(client, "/"); + + String nonce = assertPolicyOfSpringSecurity(response); + Matcher scripts = Pattern.compile("]*>") + .matcher(response.body()); + int count = 0; + while (scripts.find()) { + count++; + assertTrue(scripts.group().contains("nonce=\"" + nonce + "\""), + "Every script should have the nonce of the policy: " + + scripts.group()); + } + assertTrue(count > 0, "No script in: " + response.body()); } } @@ -102,8 +98,7 @@ public void bundleScript_carriesThePolicyOfSpringSecurity() HttpResponse response = fetch(client, "/" + script); assertEquals(200, response.statusCode()); - assertEquals(List.of(SecurityConfig.SPRING_SECURITY_POLICY), - response.headers().allValues(HEADER)); + assertPolicyOfSpringSecurity(response); } } @@ -121,8 +116,7 @@ public void download_carriesThePolicyOfSpringSecurity() throws Exception { assertEquals(200, response.statusCode()); assertEquals(DownloadLink.CONTENT_TYPE, response.headers().firstValue("Content-Type").orElse(null)); - assertEquals(List.of(SecurityConfig.SPRING_SECURITY_POLICY), - response.headers().allValues(HEADER)); + assertPolicyOfSpringSecurity(response); } } @@ -135,11 +129,32 @@ public void responseOfSpringSecurity_carriesThePolicyOfSpringSecurity() HttpResponse response = fetch(client, "/needs-login"); assertEquals(403, response.statusCode()); - assertEquals(List.of(SecurityConfig.SPRING_SECURITY_POLICY), - response.headers().allValues(HEADER)); + assertPolicyOfSpringSecurity(response); } } + /** + * Checks that a response has one policy, which is the one configured in + * Spring Security with a nonce in place of the placeholder. + * + * @return the nonce + */ + private static String assertPolicyOfSpringSecurity( + HttpResponse response) { + List policies = response.headers().allValues(HEADER); + assertEquals(1, policies.size(), + "The response should have one policy: " + policies); + String[] parts = SecurityConfig.SPRING_SECURITY_POLICY + .split(Pattern.quote("{nonce}")); + Matcher matcher = Pattern.compile(Pattern.quote(parts[0]) + + "([A-Za-z0-9+/]{22})" + Pattern.quote(parts[1])) + .matcher(policies.get(0)); + assertTrue(matcher.matches(), + "The policy should be the one of Spring Security with a nonce: " + + policies.get(0)); + return matcher.group(1); + } + private static String find(Pattern pattern, String body) { Matcher matcher = pattern.matcher(body); assertTrue(matcher.find(), "No " + pattern + " in: " + body); diff --git a/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringSecurityAutoConfiguration.java b/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringSecurityAutoConfiguration.java index beb42839f26..1090cb68cc8 100644 --- a/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringSecurityAutoConfiguration.java +++ b/vaadin-spring/src/main/java/com/vaadin/flow/spring/SpringSecurityAutoConfiguration.java @@ -53,6 +53,7 @@ import com.vaadin.flow.spring.security.RequestUtil; import com.vaadin.flow.spring.security.SpringAccessPathChecker; import com.vaadin.flow.spring.security.SpringNavigationAccessControl; +import com.vaadin.flow.spring.security.SpringSecurityContentSecurityPolicyNonceProvider; import com.vaadin.flow.spring.security.VaadinAwareSecurityContextHolderStrategy; import com.vaadin.flow.spring.security.VaadinDefaultRequestCache; import com.vaadin.flow.spring.security.VaadinRolePrefixHolder; @@ -118,6 +119,19 @@ public VaadinDefaultRequestCache vaadinDefaultRequestCache() { return new VaadinDefaultRequestCache(); } + /** + * Makes Vaadin use the Content Security Policy nonce of Spring Security in + * the strict mode, so that the policy configured in Spring Security is sent + * with Vaadin pages. Vaadin finds it through + * {@link com.vaadin.flow.di.Lookup}. + * + * @return the provider of the nonce of Spring Security + */ + @Bean + public SpringSecurityContentSecurityPolicyNonceProvider springSecurityContentSecurityPolicyNonceProvider() { + return new SpringSecurityContentSecurityPolicyNonceProvider(); + } + /** * Makes the default navigation access control initializer available for * security configuration. diff --git a/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProvider.java b/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProvider.java new file mode 100644 index 00000000000..0a7a3763c72 --- /dev/null +++ b/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProvider.java @@ -0,0 +1,51 @@ +/* + * Copyright 2000-2026 Vaadin Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.vaadin.flow.spring.security; + +import org.jspecify.annotations.Nullable; +import org.springframework.security.web.header.ContentSecurityPolicyNonce; + +import com.vaadin.flow.internal.ContentSecurityPolicyNonceProvider; +import com.vaadin.flow.server.VaadinRequest; + +/** + * Makes Vaadin use the Content Security Policy nonce of Spring Security in the + * strict mode, so that an application configures its policy in Spring Security + * only. + *

+ * When a Content Security Policy is configured in Spring Security, it creates a + * nonce for each request and replaces the {@code {nonce}} placeholder of the + * policy with it, for example in + * {@code script-src 'nonce-{nonce}' 'strict-dynamic'}. Vaadin then puts that + * nonce on the scripts of its page and sends no policy of its own, so the page + * is sent with the policy of Spring Security, as configured. + *

+ * For internal use only. May be renamed or removed in a future release. + */ +public final class SpringSecurityContentSecurityPolicyNonceProvider + implements ContentSecurityPolicyNonceProvider { + + @Override + public @Nullable String findNonce(VaadinRequest request) { + // Spring Security sets the attribute for the requests of a filter + // chain that has a Content Security Policy + if (request.getAttribute(ContentSecurityPolicyNonce.class + .getName()) instanceof ContentSecurityPolicyNonce nonce) { + return nonce.getNonce(); + } + return null; + } +} diff --git a/vaadin-spring/src/test/java/com/vaadin/flow/spring/SpringClassesSerializableTest.java b/vaadin-spring/src/test/java/com/vaadin/flow/spring/SpringClassesSerializableTest.java index 4e9866fbf45..5e32321fab1 100644 --- a/vaadin-spring/src/test/java/com/vaadin/flow/spring/SpringClassesSerializableTest.java +++ b/vaadin-spring/src/test/java/com/vaadin/flow/spring/SpringClassesSerializableTest.java @@ -115,6 +115,7 @@ protected Stream getExcludedPatterns() { "com\\.vaadin\\.flow\\.spring\\.security\\.NavigationAccessControlConfigurer", "com\\.vaadin\\.flow\\.spring\\.security\\.VaadinAwareSecurityContextHolderStrategy", "com\\.vaadin\\.flow\\.spring\\.security\\.VaadinAwareSecurityContextHolderStrategyConfiguration", + "com\\.vaadin\\.flow\\.spring\\.security\\.SpringSecurityContentSecurityPolicyNonceProvider", "com\\.vaadin\\.flow\\.spring\\.security\\.VaadinSecurityConfigurer", "com\\.vaadin\\.flow\\.spring\\.security\\.VaadinSecurityConfigurer(\\$.*)?", "com\\.vaadin\\.flow\\.spring\\.security\\.VaadinDefaultRequestCache", diff --git a/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java b/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java new file mode 100644 index 00000000000..f4c2c97a492 --- /dev/null +++ b/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java @@ -0,0 +1,156 @@ +/* + * Copyright 2000-2026 Vaadin Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.vaadin.flow.spring.security; + +import jakarta.servlet.Filter; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.mock.web.MockFilterChain; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.security.authentication.TestingAuthenticationProvider; +import org.springframework.security.config.Customizer; +import org.springframework.security.config.ObjectPostProcessor; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer.AuthorizedUrl; +import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.vaadin.flow.internal.ContentSecurityPolicyNonceProvider; +import com.vaadin.flow.internal.hilla.EndpointRequestUtil; +import com.vaadin.flow.internal.hilla.FileRouterRequestUtil; +import com.vaadin.flow.server.VaadinRequest; +import com.vaadin.flow.spring.SpringBootAutoConfiguration; +import com.vaadin.flow.spring.SpringSecurityAutoConfiguration; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@WebAppConfiguration +@ContextConfiguration(classes = { SpringBootAutoConfiguration.class, + SpringSecurityAutoConfiguration.class, + ObjectPostProcessorConfiguration.class, + VaadinSecurityConfigurerTest.TestConfig.class }) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) +@ExtendWith(SpringExtension.class) +class SpringSecurityContentSecurityPolicyNonceProviderTest { + + private static final String HEADER = "Content-Security-Policy"; + + @Autowired + private ApplicationContext applicationContext; + + @Autowired + private ObjectPostProcessor postProcessor; + + @Autowired + private PathPatternRequestMatcher.Builder requestMatcherBuilder; + + @Autowired + private ContentSecurityPolicyNonceProvider nonceProvider; + + @MockitoBean + private EndpointRequestUtil endpointRequestUtil; + + @MockitoBean + private FileRouterRequestUtil fileRouterRequestUtil; + + private HttpSecurity http; + + @BeforeEach + void setUp() { + var authManagerBuilder = new AuthenticationManagerBuilder(postProcessor) + .authenticationProvider(new TestingAuthenticationProvider()); + http = new HttpSecurity(postProcessor, authManagerBuilder, + Map.of(ApplicationContext.class, applicationContext, + PathPatternRequestMatcher.Builder.class, + requestMatcherBuilder)); + } + + @Test + void policyInSpringSecurity_nonceIsTheOneOfThePolicySentWithTheResponse() + throws Exception { + http.headers(headers -> headers + .contentSecurityPolicy(policy -> policy.policyDirectives( + "script-src 'nonce-{nonce}' 'strict-dynamic'"))); + + List nonces = new ArrayList<>(); + MockHttpServletResponse response = serve(nonces); + + assertEquals(1, nonces.size()); + assertEquals(22, nonces.get(0).length(), nonces.get(0)); + assertEquals(List.of( + "script-src 'nonce-" + nonces.get(0) + "' 'strict-dynamic'"), + response.getHeaders(HEADER)); + } + + @Test + void noPolicyInSpringSecurity_noNonce() throws Exception { + http.headers(Customizer.withDefaults()); + + List nonces = new ArrayList<>(); + serve(nonces); + + // The policy and its nonce are then left to Vaadin + assertNull(nonces.get(0)); + } + + /** + * Sends a request through the security filter chain to a servlet that asks + * for the nonce of the request, as Vaadin does when it creates a page. + */ + private MockHttpServletResponse serve(List nonces) + throws Exception { + List filters = http + .with(VaadinSecurityConfigurer.vaadin(), + vaadin -> vaadin.anyRequest(AuthorizedUrl::permitAll)) + .build().getFilters(); + HttpServlet servlet = new HttpServlet() { + @Override + protected void service(HttpServletRequest request, + HttpServletResponse response) { + VaadinRequest vaadinRequest = mock(VaadinRequest.class); + when(vaadinRequest.getAttribute(anyString())).thenAnswer( + call -> request.getAttribute(call.getArgument(0))); + nonces.add(nonceProvider.findNonce(vaadinRequest)); + } + }; + MockHttpServletResponse response = new MockHttpServletResponse(); + new MockFilterChain(servlet, filters.toArray(Filter[]::new)) + .doFilter(new MockHttpServletRequest("GET", "/"), response); + return response; + } +} From e820ed185fd2fe93de11a0c1219e992c8cdad26b Mon Sep 17 00:00:00 2001 From: Giovanni Lovato Date: Fri, 27 Nov 2026 18:57:10 +0100 Subject: [PATCH 07/25] test: pin that Spring Security decides where its policy applies A Vaadin page of a path the policy of Spring Security is not sent for gets no policy: Vaadin does not send its own in place of it. --- .../test-csp-strict-spring-security/README.md | 1 + .../cspstrict/springsecurity/PublicView.java | 5 ++++- .../springsecurity/SecurityConfig.java | 16 ++++++++++++++-- .../springsecurity/SpringSecurityPolicyIT.java | 18 ++++++++++++++++++ ...ContentSecurityPolicyNonceProviderTest.java | 15 +++++++++++++++ 5 files changed, 52 insertions(+), 3 deletions(-) diff --git a/flow-tests/test-csp-strict-spring-security/README.md b/flow-tests/test-csp-strict-spring-security/README.md index 2fc019e3930..cf3b5a28929 100644 --- a/flow-tests/test-csp-strict-spring-security/README.md +++ b/flow-tests/test-csp-strict-spring-security/README.md @@ -12,6 +12,7 @@ carries: | Response | Policy | |---|---| | A bootstrap page | The policy of Spring Security, with the nonce that every script of the page has. | +| A bootstrap page of a path the policy of Spring Security is not sent for | No policy. Spring Security decides where its policy applies. | | A file of the production bundle, `VAADIN/build/*.js` | The policy of Spring Security. | | A download served by a `DownloadHandler` | The policy of Spring Security. | | A response that Spring Security writes itself, such as a 403 | The policy of Spring Security. | diff --git a/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/PublicView.java b/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/PublicView.java index 480ecbecb66..2a94d715cb4 100644 --- a/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/PublicView.java +++ b/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/PublicView.java @@ -18,13 +18,16 @@ import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.Span; import com.vaadin.flow.router.Route; +import com.vaadin.flow.router.RouteAlias; import com.vaadin.flow.server.auth.AnonymousAllowed; /** * A view anyone can open, so that its bootstrap page can be fetched without - * logging in. + * logging in. It also has a path that the policy of Spring Security does not + * apply to. */ @Route("") +@RouteAlias(SecurityConfig.PATH_WITHOUT_SPRING_SECURITY_POLICY) @AnonymousAllowed public class PublicView extends Div { diff --git a/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/SecurityConfig.java b/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/SecurityConfig.java index 3772d066154..a42a2773702 100644 --- a/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/SecurityConfig.java +++ b/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/SecurityConfig.java @@ -20,6 +20,8 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher; +import org.springframework.security.web.util.matcher.NegatedRequestMatcher; import static com.vaadin.flow.spring.security.VaadinSecurityConfigurer.vaadin; @@ -46,10 +48,20 @@ public class SecurityConfig { + "worker-src 'self'; object-src 'none'; base-uri 'self'; " + "form-action 'self'"; + /** + * A path that the policy of Spring Security is not sent for. Spring + * Security decides where its policy applies, so a Vaadin page of this path + * is sent without a policy. + */ + public static final String PATH_WITHOUT_SPRING_SECURITY_POLICY = "no-spring-security-policy"; + @Bean SecurityFilterChain vaadinSecurityFilterChain(HttpSecurity http) { - http.headers(headers -> headers.contentSecurityPolicy( - csp -> csp.policyDirectives(SPRING_SECURITY_POLICY))); + http.headers(headers -> headers.contentSecurityPolicy(csp -> csp + .policyDirectives(SPRING_SECURITY_POLICY) + .requestMatcher(new NegatedRequestMatcher( + PathPatternRequestMatcher.withDefaults().matcher( + "/" + PATH_WITHOUT_SPRING_SECURITY_POLICY))))); http.with(vaadin(), cfg -> { }); return http.build(); diff --git a/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java b/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java index 64cb892f66e..635ab05dd34 100644 --- a/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java +++ b/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java @@ -74,6 +74,24 @@ public void bootstrapPage_carriesThePolicyOfSpringSecurityWithTheNonceOfItsScrip } } + @Test + public void bootstrapPageOfPathWithoutPolicyOfSpringSecurity_carriesNoPolicy() + throws Exception { + try (HttpClient client = HttpClient.newHttpClient()) { + HttpResponse response = fetch(client, + "/" + SecurityConfig.PATH_WITHOUT_SPRING_SECURITY_POLICY); + + assertEquals(200, response.statusCode()); + // Where the policy applies is configured in Spring Security, and + // Vaadin does not send its own policy in place of it + assertEquals(List.of(), response.headers().allValues(HEADER)); + assertTrue( + Pattern.compile("]* nonce=\"[^\"]+\"") + .matcher(response.body()).find(), + "No script with a nonce in: " + response.body()); + } + } + @Test public void bootstrapPage_carriesTheOtherHeadersOfSpringSecurity() throws Exception { diff --git a/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java b/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java index f4c2c97a492..d10c5b97931 100644 --- a/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java +++ b/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java @@ -117,6 +117,21 @@ void policyInSpringSecurity_nonceIsTheOneOfThePolicySentWithTheResponse() response.getHeaders(HEADER)); } + @Test + void policyInSpringSecurityForOtherPaths_noPolicyIsSent() throws Exception { + http.headers(headers -> headers.contentSecurityPolicy(policy -> policy + .policyDirectives("script-src 'nonce-{nonce}' 'strict-dynamic'") + .requestMatchers("/api/**"))); + + List nonces = new ArrayList<>(); + MockHttpServletResponse response = serve(nonces); + + // Spring Security creates the nonce for every request, and decides + // where its policy applies + assertEquals(22, nonces.get(0).length(), nonces.get(0)); + assertEquals(List.of(), response.getHeaders(HEADER)); + } + @Test void noPolicyInSpringSecurity_noNonce() throws Exception { http.headers(Customizer.withDefaults()); From edcadf77e9c20b67df644d5cdea8bffe40760e42 Mon Sep 17 00:00:00 2001 From: Giovanni Lovato Date: Mon, 30 Nov 2026 18:41:19 +0100 Subject: [PATCH 08/25] docs: describe provided nonce without naming Spring Security --- .../communication/IndexHtmlResponse.java | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java index 8bcea88804c..c6507d64953 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java @@ -125,11 +125,13 @@ public Optional getUI() { * {@code script-src} directive of the Content Security Policy. *

* A new nonce is created for every response when the application runs with - * the {@link ContentSecurityPolicyMode#STRICT} mode. It is the nonce of - * Spring Security when a Content Security Policy is configured there. - * Scripts added by an {@link IndexHtmlRequestListener} get the nonce - * automatically, but the value can also be used for other content that - * needs it. The nonce is not put on the scripts in development mode. + * the {@link ContentSecurityPolicyMode#STRICT} mode. An integration with a + * security framework, such as the one for Spring Security in + * {@code vaadin-spring}, can provide the nonce of the policy of that + * framework, which is then used instead. Scripts added by an + * {@link IndexHtmlRequestListener} get the nonce automatically, but the + * value can also be used for other content that needs it. A nonce created + * by Vaadin is not put on the scripts in development mode. * * @return the nonce, or {@code null} if the mode is not * {@link ContentSecurityPolicyMode#STRICT} @@ -164,9 +166,9 @@ public Optional getUI() { * example from a servlet filter that runs before Vaadin. *

* There is no policy to adjust when the application sends its own with a - * nonce it shares with Vaadin, which is the case when a Content Security - * Policy is configured in Spring Security. That policy is sent with the - * page as configured, and is adjusted where it is configured. + * nonce it shares with Vaadin, which an integration with a security + * framework can make possible. That policy is sent with the page as + * configured, and is adjusted where it is configured. * * @return the mutable policy, or {@code null} if the mode is not * {@link ContentSecurityPolicyMode#STRICT} or if the policy is not From 71a788ee28d51a340b00b50e10133b60e4a4e1db Mon Sep 17 00:00:00 2001 From: Giovanni Lovato Date: Mon, 30 Nov 2026 19:11:19 +0100 Subject: [PATCH 09/25] test: remove test method duplicated by merge --- .../springsecurity/SpringSecurityPolicyIT.java | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java b/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java index 29650138fdd..635ab05dd34 100644 --- a/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java +++ b/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java @@ -107,21 +107,6 @@ public void bootstrapPage_carriesTheOtherHeadersOfSpringSecurity() } } - @Test - public void bootstrapPage_carriesTheOtherHeadersOfSpringSecurity() - throws Exception { - try (HttpClient client = HttpClient.newHttpClient()) { - HttpHeaders headers = fetch(client, "/").headers(); - - // Spring Security writes these only when the response is - // committed, which the forward to the Vaadin servlet must let it - // see - assertEquals(List.of("nosniff"), - headers.allValues("X-Content-Type-Options")); - assertEquals(List.of("DENY"), headers.allValues("X-Frame-Options")); - } - } - @Test public void bundleScript_carriesThePolicyOfSpringSecurity() throws Exception { From 2f53b4ee9089ba49b53e092504384c86b9b50c86 Mon Sep 17 00:00:00 2001 From: Giovanni Lovato Date: Mon, 30 Nov 2026 19:11:26 +0100 Subject: [PATCH 10/25] feat: provide strict Content Security Policy for Spring Security VaadinSecurityConfigurer.getDefaultContentSecurityPolicy() returns the policy of the strict mode with the {nonce} placeholder of Spring Security, so an application does not have to copy the directives. --- .../internal/StrictContentSecurityPolicy.java | 62 +++++++++++++++++++ .../IndexHtmlRequestHandler.java | 24 +------ .../testutil/ClassesSerializableTest.java | 1 + .../springsecurity/SecurityConfig.java | 15 +++-- .../security/VaadinSecurityConfigurer.java | 33 ++++++++++ ...ontentSecurityPolicyNonceProviderTest.java | 21 +++++++ 6 files changed, 129 insertions(+), 27 deletions(-) create mode 100644 flow-server/src/main/java/com/vaadin/flow/internal/StrictContentSecurityPolicy.java diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/StrictContentSecurityPolicy.java b/flow-server/src/main/java/com/vaadin/flow/internal/StrictContentSecurityPolicy.java new file mode 100644 index 00000000000..7e7a1a8d9f6 --- /dev/null +++ b/flow-server/src/main/java/com/vaadin/flow/internal/StrictContentSecurityPolicy.java @@ -0,0 +1,62 @@ +/* + * Copyright 2000-2026 Vaadin Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.vaadin.flow.internal; + +import com.vaadin.flow.server.ContentSecurityPolicy; +import com.vaadin.flow.server.ContentSecurityPolicyMode; + +/** + * Creates the Content Security Policy that a Vaadin page needs in the + * {@link ContentSecurityPolicyMode#STRICT} mode. + *

+ * For internal use only. May be renamed or removed in a future release. + */ +public final class StrictContentSecurityPolicy { + + private static final String SELF = "'self'"; + private static final String DATA = "data:"; + + private StrictContentSecurityPolicy() { + // Only static methods + } + + /** + * Creates the default policy of the strict mode, which allows scripts by + * the given nonce. + * + * @param nonce + * the nonce of the scripts of the page, or the placeholder that + * whoever sends the policy replaces with it, not null + * @return a new policy, which can be changed + */ + public static ContentSecurityPolicy create(String nonce) { + // 'strict-dynamic' trusts the scripts that nonced scripts load, such + // as the chunks of the bundle. connect-src also covers push. Workers + // need their own directive since script-src only allows nonced + // scripts. connect-src allows data: because vaadin-icon fetches the + // src of SvgIcon, which can be a data: URL. + return new ContentSecurityPolicy().setDirective("default-src", SELF) + .setDirective("script-src", "'nonce-" + nonce + "'", + "'strict-dynamic'") + .setDirective("style-src", SELF, "'unsafe-inline'") + .setDirective("img-src", SELF, DATA) + .setDirective("font-src", SELF, DATA) + .setDirective("connect-src", SELF, DATA) + .setDirective("worker-src", SELF) + .setDirective("object-src", "'none'") + .setDirective("base-uri", SELF); + } +} diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java index 8360252a177..d4c2be6d249 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java @@ -59,6 +59,7 @@ import com.vaadin.flow.internal.FrontendUtils; import com.vaadin.flow.internal.JacksonUtils; import com.vaadin.flow.internal.LocaleUtil; +import com.vaadin.flow.internal.StrictContentSecurityPolicy; import com.vaadin.flow.internal.ThemeUtils; import com.vaadin.flow.internal.UsageStatisticsExporter; import com.vaadin.flow.internal.springcsrf.SpringCsrfTokenUtil; @@ -104,8 +105,6 @@ public class IndexHtmlRequestHandler extends JavaScriptBootstrapHandler { private transient @Nullable ContentSecurityPolicyNonceProvider contentSecurityPolicyNonceProvider; private transient boolean contentSecurityPolicyNonceProviderLookedUp; - private static final String CSP_SELF = "'self'"; - private static final String CSP_DATA = "data:"; // Not static: a SecureRandom in a static field would be created at build // time in native images that initialize classes at build time (Quarkus) @@ -168,7 +167,7 @@ public boolean synchronizedHandleRequest(VaadinSession session, } else { String nonce = createContentSecurityPolicyNonce(); indexHtmlResponse.setContentSecurityPolicy(nonce, - createDefaultContentSecurityPolicy(nonce)); + StrictContentSecurityPolicy.create(nonce)); } } @@ -301,25 +300,6 @@ private String createContentSecurityPolicyNonce() { return Base64.getEncoder().withoutPadding().encodeToString(bytes); } - private static ContentSecurityPolicy createDefaultContentSecurityPolicy( - String nonce) { - // 'strict-dynamic' trusts the scripts that nonced scripts load, such - // as the chunks of the bundle. connect-src also covers push. Workers - // need their own directive since script-src only allows nonced - // scripts. connect-src allows data: because vaadin-icon fetches the - // src of SvgIcon, which can be a data: URL. - return new ContentSecurityPolicy().setDirective("default-src", CSP_SELF) - .setDirective("script-src", "'nonce-" + nonce + "'", - "'strict-dynamic'") - .setDirective("style-src", CSP_SELF, "'unsafe-inline'") - .setDirective("img-src", CSP_SELF, CSP_DATA) - .setDirective("font-src", CSP_SELF, CSP_DATA) - .setDirective("connect-src", CSP_SELF, CSP_DATA) - .setDirective("worker-src", CSP_SELF) - .setDirective("object-src", "'none'") - .setDirective("base-uri", CSP_SELF); - } - private static void applyContentSecurityPolicy( IndexHtmlResponse indexHtmlResponse) { VaadinResponse response = indexHtmlResponse.getVaadinResponse(); diff --git a/flow-test-generic/src/main/java/com/vaadin/flow/testutil/ClassesSerializableTest.java b/flow-test-generic/src/main/java/com/vaadin/flow/testutil/ClassesSerializableTest.java index ee46d0045be..11233760814 100644 --- a/flow-test-generic/src/main/java/com/vaadin/flow/testutil/ClassesSerializableTest.java +++ b/flow-test-generic/src/main/java/com/vaadin/flow/testutil/ClassesSerializableTest.java @@ -144,6 +144,7 @@ protected Stream getExcludedPatterns() { "com\\.vaadin\\.flow\\.internal\\.ContentSecurityPolicyViolationReporter(\\$.*)?", "com\\.vaadin\\.flow\\.internal\\.JsStringFallbacks(\\$.*)?", "com\\.vaadin\\.flow\\.internal\\.StackTraceUtil", + "com\\.vaadin\\.flow\\.internal\\.StrictContentSecurityPolicy", "com\\.vaadin\\.flow\\.internal\\.SessionLockScope", "com\\.vaadin\\.flow\\.router\\.HighlightActions", "com\\.vaadin\\.flow\\.router\\.HighlightConditions", diff --git a/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/SecurityConfig.java b/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/SecurityConfig.java index a42a2773702..921f665d5cc 100644 --- a/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/SecurityConfig.java +++ b/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/SecurityConfig.java @@ -23,6 +23,8 @@ import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher; import org.springframework.security.web.util.matcher.NegatedRequestMatcher; +import com.vaadin.flow.spring.security.VaadinSecurityConfigurer; + import static com.vaadin.flow.spring.security.VaadinSecurityConfigurer.vaadin; /** @@ -36,10 +38,11 @@ public class SecurityConfig { /** - * The policy Spring Security is configured with. It is the policy Vaadin - * sends in the {@code strict} mode, with the {@code {nonce}} placeholder - * that Spring Security replaces with the nonce of the request, and with - * {@code form-action}, which only this policy has. + * The policy Spring Security sends. It is the policy Vaadin sends in the + * {@code strict} mode, which {@code VaadinSecurityConfigurer} provides with + * the {@code {nonce}} placeholder that Spring Security replaces with the + * nonce of the request, and {@code form-action}, which this application + * adds. */ public static final String SPRING_SECURITY_POLICY = "default-src 'self'; " + "script-src 'nonce-{nonce}' 'strict-dynamic'; " @@ -58,7 +61,9 @@ public class SecurityConfig { @Bean SecurityFilterChain vaadinSecurityFilterChain(HttpSecurity http) { http.headers(headers -> headers.contentSecurityPolicy(csp -> csp - .policyDirectives(SPRING_SECURITY_POLICY) + .policyDirectives(VaadinSecurityConfigurer + .getDefaultContentSecurityPolicy() + .setDirective("form-action", "'self'").toHeaderValue()) .requestMatcher(new NegatedRequestMatcher( PathPatternRequestMatcher.withDefaults().matcher( "/" + PATH_WITHOUT_SPRING_SECURITY_POLICY))))); diff --git a/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java b/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java index 3fb52681931..288f09b6dd3 100644 --- a/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java +++ b/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java @@ -68,9 +68,11 @@ import com.vaadin.flow.component.Component; import com.vaadin.flow.internal.AnnotationReader; +import com.vaadin.flow.internal.StrictContentSecurityPolicy; import com.vaadin.flow.internal.hilla.EndpointRequestUtil; import com.vaadin.flow.router.Route; import com.vaadin.flow.router.internal.RouteUtil; +import com.vaadin.flow.server.ContentSecurityPolicy; import com.vaadin.flow.server.HandlerHelper; import com.vaadin.flow.server.VaadinServletContext; import com.vaadin.flow.server.auth.NavigationAccessControl; @@ -797,6 +799,37 @@ public void configure(HttpSecurity http) { } } + /** + * Gets the Content Security Policy that a Vaadin page needs when the + * application runs with {@code vaadin.contentSecurityPolicy=strict}, to + * configure it in Spring Security. + *

+ * It is the policy Vaadin sends in the strict mode when Spring Security has + * none. Its {@code script-src} directive has the {@code 'nonce-{nonce}'} + * source, where Spring Security puts the nonce it creates for each request. + * Vaadin puts that nonce on the scripts of its pages, and no script of a + * Vaadin page runs without it. + *

+ * The returned policy can be changed before it is given to Spring Security: + * + *

+     * http.headers(headers -> headers.contentSecurityPolicy(
+     *         policy -> policy.policyDirectives(VaadinSecurityConfigurer
+     *                 .getDefaultContentSecurityPolicy()
+     *                 .addSources("img-src", "https://cdn.example.com")
+     *                 .setDirective("form-action", "'self'").toHeaderValue())));
+     * 
+ * + * Only use this when the strict mode is enabled: otherwise the scripts of a + * Vaadin page have no nonce and the policy blocks them. + * + * @return a new policy with the {@code {nonce}} placeholder of Spring + * Security + */ + public static ContentSecurityPolicy getDefaultContentSecurityPolicy() { + return StrictContentSecurityPolicy.create("{nonce}"); + } + /** * Matcher for framework internal requests. * diff --git a/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java b/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java index d10c5b97931..6417c0a59cd 100644 --- a/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java +++ b/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java @@ -132,6 +132,27 @@ void policyInSpringSecurityForOtherPaths_noPolicyIsSent() throws Exception { assertEquals(List.of(), response.getHeaders(HEADER)); } + @Test + void defaultPolicyOfVaadinInSpringSecurity_isSentWithTheNonce() + throws Exception { + http.headers(headers -> headers.contentSecurityPolicy( + policy -> policy.policyDirectives(VaadinSecurityConfigurer + .getDefaultContentSecurityPolicy() + .setDirective("form-action", "'self'") + .toHeaderValue()))); + + List nonces = new ArrayList<>(); + MockHttpServletResponse response = serve(nonces); + + assertEquals(22, nonces.get(0).length(), nonces.get(0)); + assertEquals(List.of("default-src 'self'; script-src 'nonce-" + + nonces.get(0) + "' 'strict-dynamic'; " + + "style-src 'self' 'unsafe-inline'; img-src 'self' data:; " + + "font-src 'self' data:; connect-src 'self' data:; " + + "worker-src 'self'; object-src 'none'; base-uri 'self'; " + + "form-action 'self'"), response.getHeaders(HEADER)); + } + @Test void noPolicyInSpringSecurity_noNonce() throws Exception { http.headers(Customizer.withDefaults()); From 497e95fab7e3fb85363368d574e62dddd3fac5c4 Mon Sep 17 00:00:00 2001 From: Giovanni Lovato Date: Mon, 30 Nov 2026 19:17:06 +0100 Subject: [PATCH 11/25] refactor: configure strict Content Security Policy through VaadinSecurityConfigurer Replaces the static getDefaultContentSecurityPolicy() with contentSecurityPolicy() options on the configurer, which follow the pattern of its other options. A second customizer sets the other options of the policy in Spring Security, such as the request matcher. --- .../springsecurity/SecurityConfig.java | 18 +-- .../security/VaadinSecurityConfigurer.java | 139 ++++++++++++++---- ...ontentSecurityPolicyNonceProviderTest.java | 74 ++++++++-- 3 files changed, 174 insertions(+), 57 deletions(-) diff --git a/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/SecurityConfig.java b/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/SecurityConfig.java index 921f665d5cc..518fe1e118e 100644 --- a/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/SecurityConfig.java +++ b/flow-tests/test-csp-strict-spring-security/src/main/java/com/vaadin/flow/test/cspstrict/springsecurity/SecurityConfig.java @@ -23,8 +23,6 @@ import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher; import org.springframework.security.web.util.matcher.NegatedRequestMatcher; -import com.vaadin.flow.spring.security.VaadinSecurityConfigurer; - import static com.vaadin.flow.spring.security.VaadinSecurityConfigurer.vaadin; /** @@ -39,9 +37,9 @@ public class SecurityConfig { /** * The policy Spring Security sends. It is the policy Vaadin sends in the - * {@code strict} mode, which {@code VaadinSecurityConfigurer} provides with - * the {@code {nonce}} placeholder that Spring Security replaces with the - * nonce of the request, and {@code form-action}, which this application + * {@code strict} mode, which {@code VaadinSecurityConfigurer} configures + * with the {@code {nonce}} placeholder that Spring Security replaces with + * the nonce of the request, and {@code form-action}, which this application * adds. */ public static final String SPRING_SECURITY_POLICY = "default-src 'self'; " @@ -60,15 +58,11 @@ public class SecurityConfig { @Bean SecurityFilterChain vaadinSecurityFilterChain(HttpSecurity http) { - http.headers(headers -> headers.contentSecurityPolicy(csp -> csp - .policyDirectives(VaadinSecurityConfigurer - .getDefaultContentSecurityPolicy() - .setDirective("form-action", "'self'").toHeaderValue()) - .requestMatcher(new NegatedRequestMatcher( + http.with(vaadin(), cfg -> cfg.contentSecurityPolicy( + policy -> policy.setDirective("form-action", "'self'"), + config -> config.requestMatcher(new NegatedRequestMatcher( PathPatternRequestMatcher.withDefaults().matcher( "/" + PATH_WITHOUT_SPRING_SECURITY_POLICY))))); - http.with(vaadin(), cfg -> { - }); return http.build(); } } diff --git a/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java b/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java index 288f09b6dd3..681ba303c0e 100644 --- a/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java +++ b/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java @@ -30,6 +30,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.config.Customizer; import org.springframework.security.config.ObjectPostProcessor; import org.springframework.security.config.annotation.SecurityConfigurer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; @@ -39,6 +40,7 @@ import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; import org.springframework.security.config.annotation.web.configurers.ExceptionHandlingConfigurer; import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer; +import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer; import org.springframework.security.config.annotation.web.configurers.LogoutConfigurer; import org.springframework.security.config.annotation.web.configurers.RequestCacheConfigurer; import org.springframework.security.config.annotation.web.configurers.SessionManagementConfigurer; @@ -193,6 +195,10 @@ public final class VaadinSecurityConfigurer private boolean enableNavigationAccessControl = true; + private Consumer contentSecurityPolicyCustomizer; + + private Customizer.ContentSecurityPolicyConfig> contentSecurityPolicyConfigCustomizer; + private boolean alreadyInitializedOnce = false; /** @@ -662,6 +668,98 @@ public VaadinSecurityConfigurer enableNavigationAccessControl( return this; } + /** + * Configures Spring Security to send the Content Security Policy that a + * Vaadin page needs when the application runs with + * {@code vaadin.contentSecurityPolicy=strict}. + *

+ * The policy is the one Vaadin sends in the strict mode when Spring + * Security has none. Its {@code script-src} directive allows scripts by the + * nonce that Spring Security creates for each request, which Vaadin puts on + * the scripts of its pages. Spring Security sends the policy with every + * response of the filter chain, also in development mode. + *

+ * This replaces a Content Security Policy configured with + * {@code HttpSecurity.headers()} for the same filter chain. Only use it + * when the strict mode is enabled: otherwise the scripts of a Vaadin page + * have no nonce and the policy blocks them. + * + * @return this configurer, for chaining + * @see #contentSecurityPolicy(Consumer) + * @see #contentSecurityPolicy(Consumer, Customizer) + */ + public VaadinSecurityConfigurer contentSecurityPolicy() { + return contentSecurityPolicy(policy -> { + }); + } + + /** + * Configures Spring Security to send the Content Security Policy that a + * Vaadin page needs when the application runs with + * {@code vaadin.contentSecurityPolicy=strict}, with the changes of the + * given customizer. + *

+ * The customizer gets the policy described in + * {@link #contentSecurityPolicy()} and adds what the application needs: + * + *

+     * http.with(vaadin(),
+     *         vaadin -> vaadin.contentSecurityPolicy(policy -> policy
+     *                 .addSources("img-src", "https://cdn.example.com")
+     *                 .setDirective("form-action", "'self'")));
+     * 
+ * + * The {@code script-src} directive of the policy has the + * {@code 'nonce-{nonce}'} source, where Spring Security puts the nonce of + * the request. No script of a Vaadin page runs without it. + * + * @param policyCustomizer + * changes the policy before it is given to Spring Security, not + * null + * @return this configurer, for chaining + */ + public VaadinSecurityConfigurer contentSecurityPolicy( + Consumer policyCustomizer) { + return contentSecurityPolicy(policyCustomizer, config -> { + }); + } + + /** + * Configures Spring Security to send the Content Security Policy that a + * Vaadin page needs when the application runs with + * {@code vaadin.contentSecurityPolicy=strict}, with the changes of the + * given customizers. + *

+ * The second customizer sets the other options of the Content Security + * Policy of Spring Security, such as the requests the policy is sent for: + * + *

+     * http.with(vaadin(), vaadin -> vaadin.contentSecurityPolicy(policy -> {
+     * }, config -> config.requestMatchers("/app/**")));
+     * 
+ * + * It runs after the policy directives are set, so directives it sets + * replace the policy. + * + * @param policyCustomizer + * changes the policy described in + * {@link #contentSecurityPolicy()} before it is given to Spring + * Security, not null + * @param configCustomizer + * sets other options of the Content Security Policy + * configuration of Spring Security, not null + * @return this configurer, for chaining + */ + public VaadinSecurityConfigurer contentSecurityPolicy( + Consumer policyCustomizer, + Customizer.ContentSecurityPolicyConfig> configCustomizer) { + this.contentSecurityPolicyCustomizer = Objects.requireNonNull( + policyCustomizer, "policyCustomizer must not be null"); + this.contentSecurityPolicyConfigCustomizer = Objects.requireNonNull( + configCustomizer, "configCustomizer must not be null"); + return this; + } + /** * Creates and returns a composite {@link RequestMatcher} for identifying * requests that should be permitted without authentication within a Vaadin @@ -735,6 +833,16 @@ public void init(HttpSecurity http) { + "is configured, so it has no effect. Configure " + "one with VaadinSecurityConfigurer.oauth2LoginPage()."); } + if (contentSecurityPolicyCustomizer != null + && !alreadyInitializedOnce) { + ContentSecurityPolicy policy = StrictContentSecurityPolicy + .create("{nonce}"); + contentSecurityPolicyCustomizer.accept(policy); + http.headers(headers -> headers.contentSecurityPolicy(config -> { + config.policyDirectives(policy.toHeaderValue()); + contentSecurityPolicyConfigCustomizer.customize(config); + })); + } if (enableCsrfConfiguration) { http.csrf(this::customizeCsrf); } @@ -799,37 +907,6 @@ public void configure(HttpSecurity http) { } } - /** - * Gets the Content Security Policy that a Vaadin page needs when the - * application runs with {@code vaadin.contentSecurityPolicy=strict}, to - * configure it in Spring Security. - *

- * It is the policy Vaadin sends in the strict mode when Spring Security has - * none. Its {@code script-src} directive has the {@code 'nonce-{nonce}'} - * source, where Spring Security puts the nonce it creates for each request. - * Vaadin puts that nonce on the scripts of its pages, and no script of a - * Vaadin page runs without it. - *

- * The returned policy can be changed before it is given to Spring Security: - * - *

-     * http.headers(headers -> headers.contentSecurityPolicy(
-     *         policy -> policy.policyDirectives(VaadinSecurityConfigurer
-     *                 .getDefaultContentSecurityPolicy()
-     *                 .addSources("img-src", "https://cdn.example.com")
-     *                 .setDirective("form-action", "'self'").toHeaderValue())));
-     * 
- * - * Only use this when the strict mode is enabled: otherwise the scripts of a - * Vaadin page have no nonce and the policy blocks them. - * - * @return a new policy with the {@code {nonce}} placeholder of Spring - * Security - */ - public static ContentSecurityPolicy getDefaultContentSecurityPolicy() { - return StrictContentSecurityPolicy.create("{nonce}"); - } - /** * Matcher for framework internal requests. * diff --git a/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java b/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java index 6417c0a59cd..e83f1e37c0b 100644 --- a/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java +++ b/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java @@ -23,6 +23,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.function.Consumer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -69,6 +70,11 @@ class SpringSecurityContentSecurityPolicyNonceProviderTest { private static final String HEADER = "Content-Security-Policy"; + private static final String DEFAULT_POLICY = "default-src 'self'; " + + "script-src 'nonce-{nonce}' 'strict-dynamic'; " + + "style-src 'self' 'unsafe-inline'; img-src 'self' data:; " + + "font-src 'self' data:; connect-src 'self' data:; " + + "worker-src 'self'; object-src 'none'; base-uri 'self'"; @Autowired private ApplicationContext applicationContext; @@ -133,24 +139,57 @@ void policyInSpringSecurityForOtherPaths_noPolicyIsSent() throws Exception { } @Test - void defaultPolicyOfVaadinInSpringSecurity_isSentWithTheNonce() + void policyOfVaadinSecurityConfigurer_defaultPolicyIsSentWithTheNonce() throws Exception { - http.headers(headers -> headers.contentSecurityPolicy( - policy -> policy.policyDirectives(VaadinSecurityConfigurer - .getDefaultContentSecurityPolicy() - .setDirective("form-action", "'self'") - .toHeaderValue()))); + List nonces = new ArrayList<>(); + MockHttpServletResponse response = serve(nonces, + VaadinSecurityConfigurer::contentSecurityPolicy); + assertEquals(22, nonces.get(0).length(), nonces.get(0)); + assertEquals(List.of(DEFAULT_POLICY.replace("{nonce}", nonces.get(0))), + response.getHeaders(HEADER)); + } + + @Test + void policyOfVaadinSecurityConfigurer_changesOfCustomizerAreSent() + throws Exception { List nonces = new ArrayList<>(); - MockHttpServletResponse response = serve(nonces); + MockHttpServletResponse response = serve(nonces, + vaadin -> vaadin.contentSecurityPolicy(policy -> policy + .addSources("img-src", "https://cdn.example.com") + .setDirective("form-action", "'self'"))); + + assertEquals(List.of(DEFAULT_POLICY.replace("{nonce}", nonces.get(0)) + .replace("img-src 'self' data:", + "img-src 'self' data: https://cdn.example.com") + + "; form-action 'self'"), response.getHeaders(HEADER)); + } + + @Test + void policyOfVaadinSecurityConfigurer_optionsOfSpringSecurityApply() + throws Exception { + List nonces = new ArrayList<>(); + MockHttpServletResponse response = serve(nonces, + vaadin -> vaadin.contentSecurityPolicy(policy -> { + }, config -> config.requestMatchers("/api/**"))); + // The request is for another path, so the policy is not sent assertEquals(22, nonces.get(0).length(), nonces.get(0)); - assertEquals(List.of("default-src 'self'; script-src 'nonce-" - + nonces.get(0) + "' 'strict-dynamic'; " - + "style-src 'self' 'unsafe-inline'; img-src 'self' data:; " - + "font-src 'self' data:; connect-src 'self' data:; " - + "worker-src 'self'; object-src 'none'; base-uri 'self'; " - + "form-action 'self'"), response.getHeaders(HEADER)); + assertEquals(List.of(), response.getHeaders(HEADER)); + } + + @Test + void policyOfVaadinSecurityConfigurer_replacesPolicyOfHttpSecurity() + throws Exception { + http.headers(headers -> headers.contentSecurityPolicy( + policy -> policy.policyDirectives("default-src 'none'"))); + + List nonces = new ArrayList<>(); + MockHttpServletResponse response = serve(nonces, + VaadinSecurityConfigurer::contentSecurityPolicy); + + assertEquals(List.of(DEFAULT_POLICY.replace("{nonce}", nonces.get(0))), + response.getHeaders(HEADER)); } @Test @@ -170,9 +209,16 @@ void noPolicyInSpringSecurity_noNonce() throws Exception { */ private MockHttpServletResponse serve(List nonces) throws Exception { + return serve(nonces, vaadin -> { + }); + } + + private MockHttpServletResponse serve(List nonces, + Consumer customizer) throws Exception { List filters = http .with(VaadinSecurityConfigurer.vaadin(), - vaadin -> vaadin.anyRequest(AuthorizedUrl::permitAll)) + vaadin -> customizer.accept( + vaadin.anyRequest(AuthorizedUrl::permitAll))) .build().getFilters(); HttpServlet servlet = new HttpServlet() { @Override From 2d7db03818e05569f6cb0dd5c36ee5b72ae7e58a Mon Sep 17 00:00:00 2001 From: Giovanni Lovato Date: Tue, 1 Dec 2026 13:47:44 +0100 Subject: [PATCH 12/25] fix: keep disabled headers off and use provided nonce in every mode VaadinSecurityConfigurer.contentSecurityPolicy() no longer brings back the default headers of Spring Security when the application has disabled them. A nonce from a ContentSecurityPolicyNonceProvider is put on the scripts in every Content Security Policy mode, so a policy that uses it does not block the page when the mode is not strict. The provider lookup is cached in one volatile field. --- .../ContentSecurityPolicyNonceProvider.java | 10 ++- .../IndexHtmlRequestHandler.java | 59 +++++++------ .../communication/IndexHtmlResponse.java | 4 +- .../IndexHtmlRequestHandlerTest.java | 66 ++++++++++++++ .../SpringSecurityPolicyIT.java | 6 +- .../security/VaadinSecurityConfigurer.java | 32 +++++-- ...ontentSecurityPolicyNonceProviderTest.java | 69 +-------------- .../VaadinSecurityConfigurerTest.java | 87 +++++++++++++++++++ 8 files changed, 221 insertions(+), 112 deletions(-) diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/ContentSecurityPolicyNonceProvider.java b/flow-server/src/main/java/com/vaadin/flow/internal/ContentSecurityPolicyNonceProvider.java index 3c5cb124e74..e6bd117b0ff 100644 --- a/flow-server/src/main/java/com/vaadin/flow/internal/ContentSecurityPolicyNonceProvider.java +++ b/flow-server/src/main/java/com/vaadin/flow/internal/ContentSecurityPolicyNonceProvider.java @@ -24,10 +24,12 @@ * Provides the Content Security Policy nonce of a request when something other * than Vaadin sends the policy of the application, such as Spring Security. *

- * In the strict mode, Vaadin asks the implementation it finds through - * {@link Lookup} for the nonce of each index HTML request. When there is one, - * Vaadin puts that nonce on the scripts of the page and sends no policy of its - * own: the policy that allows the nonce is sent by whoever created it. + * Vaadin asks the implementation it finds through {@link Lookup} for the nonce + * of each index HTML request. When there is one, Vaadin puts that nonce on the + * scripts of the page and sends no policy of its own: the policy that allows + * the nonce is sent by whoever created it. This is done in every Content + * Security Policy mode of Vaadin, since a nonce on a script does nothing when + * no policy uses it, and a policy that uses it blocks a script without it. *

* For internal use only. May be renamed or removed in a future release. */ diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java index d4c2be6d249..45588b27d4d 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java @@ -103,8 +103,11 @@ public class IndexHtmlRequestHandler extends JavaScriptBootstrapHandler { public static final String LIVE_RELOAD_PORT_ATTR = "livereload.port"; private static final String CONTENT_SECURITY_POLICY_HEADER = "Content-Security-Policy"; - private transient @Nullable ContentSecurityPolicyNonceProvider contentSecurityPolicyNonceProvider; - private transient boolean contentSecurityPolicyNonceProviderLookedUp; + private static final ContentSecurityPolicyNonceProvider NO_NONCE_PROVIDER = request -> null; + + // Null until looked up. A single volatile field, so that requests served + // at the same time never see a lookup that is half done + private transient volatile @Nullable ContentSecurityPolicyNonceProvider contentSecurityPolicyNonceProvider; // Not static: a SecureRandom in a static field would be created at build // time in native images that initialize classes at build time (Quarkus) @@ -157,18 +160,16 @@ public boolean synchronizedHandleRequest(VaadinSession session, indexDocument); } - if (config + // A provided nonce is used in every mode: the policy that allows it is + // sent by its provider, which does not know the mode of Vaadin + String providedNonce = findProvidedContentSecurityPolicyNonce(request); + if (providedNonce != null) { + indexHtmlResponse.setContentSecurityPolicy(providedNonce, null); + } else if (config .getContentSecurityPolicyMode() == ContentSecurityPolicyMode.STRICT) { - String providedNonce = findProvidedContentSecurityPolicyNonce( - request); - if (providedNonce != null) { - // The policy that allows the nonce is sent by its provider - indexHtmlResponse.setContentSecurityPolicy(providedNonce, null); - } else { - String nonce = createContentSecurityPolicyNonce(); - indexHtmlResponse.setContentSecurityPolicy(nonce, - StrictContentSecurityPolicy.create(nonce)); - } + String nonce = createContentSecurityPolicyNonce(); + indexHtmlResponse.setContentSecurityPolicy(nonce, + StrictContentSecurityPolicy.create(nonce)); } addInitialFlow(initialJson, indexDocument, request); @@ -270,17 +271,16 @@ public boolean synchronizedHandleRequest(VaadinSession session, addCommercialBanner(service.getDeploymentConfiguration(), indexDocument); - if (config - .getContentSecurityPolicyMode() == ContentSecurityPolicyMode.STRICT) { - if (indexHtmlResponse.getContentSecurityPolicy() == null) { - // A policy with the nonce is sent by its provider, whatever - // the mode, so the scripts need the nonce to run - addNonceToScripts(indexHtmlResponse); - } else if (config.isProductionMode()) { + if (indexHtmlResponse.getContentSecurityPolicy() != null) { + if (config.isProductionMode()) { // The dev server and dev tools need eval, so the policy of // Vaadin is only sent in production mode applyContentSecurityPolicy(indexHtmlResponse); } + } else if (indexHtmlResponse.getContentSecurityPolicyNonce() != null) { + // A policy with the nonce is sent by its provider, whatever the + // mode, so the scripts need the nonce to run + addNonceToScripts(indexHtmlResponse); } try { @@ -317,7 +317,7 @@ private static void applyContentSecurityPolicy( InitParameters.CONTENT_SECURITY_POLICY)); } addNonceToScripts(indexHtmlResponse); - // Created for the strict mode, which the caller checks + // The caller checks that there is one ContentSecurityPolicy policy = Objects .requireNonNull(indexHtmlResponse.getContentSecurityPolicy()); response.setHeader(CONTENT_SECURITY_POLICY_HEADER, @@ -327,7 +327,7 @@ private static void applyContentSecurityPolicy( // Done after the listeners have run so that every script in the page gets // the nonce, whichever code added it private static void addNonceToScripts(IndexHtmlResponse indexHtmlResponse) { - // Created for the strict mode, which the caller checks + // The caller checks that there is one String nonce = Objects.requireNonNull( indexHtmlResponse.getContentSecurityPolicyNonce()); indexHtmlResponse.getDocument().select( @@ -338,14 +338,17 @@ private static void addNonceToScripts(IndexHtmlResponse indexHtmlResponse) { private @Nullable String findProvidedContentSecurityPolicyNonce( VaadinRequest request) { // Looked up once: a lookup can be a search for beans - if (!contentSecurityPolicyNonceProviderLookedUp) { - contentSecurityPolicyNonceProvider = request.getService() - .getContext().getAttribute(Lookup.class) + ContentSecurityPolicyNonceProvider provider = contentSecurityPolicyNonceProvider; + if (provider == null) { + provider = request.getService().getContext() + .getAttribute(Lookup.class) .lookup(ContentSecurityPolicyNonceProvider.class); - contentSecurityPolicyNonceProviderLookedUp = true; + if (provider == null) { + provider = NO_NONCE_PROVIDER; + } + contentSecurityPolicyNonceProvider = provider; } - ContentSecurityPolicyNonceProvider provider = contentSecurityPolicyNonceProvider; - return provider == null ? null : provider.findNonce(request); + return provider.findNonce(request); } private void initializeFeatureFlags(Document indexDocument, diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java index c6507d64953..59d96541ee4 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java @@ -128,13 +128,13 @@ public Optional getUI() { * the {@link ContentSecurityPolicyMode#STRICT} mode. An integration with a * security framework, such as the one for Spring Security in * {@code vaadin-spring}, can provide the nonce of the policy of that - * framework, which is then used instead. Scripts added by an + * framework, which is then used instead, in every mode. Scripts added by an * {@link IndexHtmlRequestListener} get the nonce automatically, but the * value can also be used for other content that needs it. A nonce created * by Vaadin is not put on the scripts in development mode. * * @return the nonce, or {@code null} if the mode is not - * {@link ContentSecurityPolicyMode#STRICT} + * {@link ContentSecurityPolicyMode#STRICT} and no nonce is provided * @since 25.4 */ public @Nullable String getContentSecurityPolicyNonce() { diff --git a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java index b3c4f8630b5..db7d06db8c2 100644 --- a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java +++ b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java @@ -353,6 +353,72 @@ public void serveIndexHtml_strictCspAndNonceProvided_scriptsGetItAndNoPolicyIsSe } } + @ParameterizedTest + @CsvSource({ "OFF, true", "WARN, true", "STRICT, false", "OFF, false" }) + public void serveIndexHtml_nonceProvided_scriptsGetItInEveryMode( + ContentSecurityPolicyMode contentSecurityPolicyMode, + boolean productionMode) throws Exception { + deploymentConfiguration + .setContentSecurityPolicyMode(contentSecurityPolicyMode); + if (!productionMode) { + File projectRootFolder = Files + .createTempDirectory(temporaryFolder, "temp").toFile(); + TestUtil.createIndexHtmlStub(projectRootFolder); + TestUtil.createStatsJsonStub(projectRootFolder); + deploymentConfiguration.setProductionMode(false); + deploymentConfiguration.setProjectFolder(projectRootFolder); + } + ContentSecurityPolicyNonceProvider provider = request -> "provided-nonce"; + when(context.getAttribute(Lookup.class) + .lookup(ContentSecurityPolicyNonceProvider.class)) + .thenReturn(provider); + List responses = new ArrayList<>(); + service.addIndexHtmlRequestListener(responses::add); + + indexHtmlRequestHandler.synchronizedHandleRequest(session, + createVaadinRequest("/"), response); + + // The policy that uses the nonce is sent by its provider, which does + // not know the mode of Vaadin + verify(response, never()).setHeader(eq("Content-Security-Policy"), + any()); + assertEquals("provided-nonce", + responses.get(0).getContentSecurityPolicyNonce()); + assertNull(responses.get(0).getContentSecurityPolicy()); + Elements scripts = Jsoup + .parse(responseOutput.toString(StandardCharsets.UTF_8)) + .getElementsByTag("script"); + assertFalse(scripts.isEmpty()); + for (Element script : scripts) { + assertEquals("provided-nonce", script.attr("nonce"), + script.outerHtml()); + } + } + + @Test + public void serveIndexHtml_strictCspAndProviderWithoutNonce_policyOfVaadinIsSent() + throws IOException { + deploymentConfiguration + .setContentSecurityPolicyMode(ContentSecurityPolicyMode.STRICT); + ContentSecurityPolicyNonceProvider provider = request -> null; + when(context.getAttribute(Lookup.class) + .lookup(ContentSecurityPolicyNonceProvider.class)) + .thenReturn(provider); + + String header = serveIndexHtmlAndCaptureCspHeader(); + + Matcher matcher = Pattern.compile( + "script-src 'nonce-([A-Za-z0-9+/]{22})' 'strict-dynamic'") + .matcher(header); + assertTrue(matcher.find(), header); + for (Element script : Jsoup + .parse(responseOutput.toString(StandardCharsets.UTF_8)) + .getElementsByTag("script")) { + assertEquals(matcher.group(1), script.attr("nonce"), + script.outerHtml()); + } + } + @Test public void serveIndexHtml_strictCspAndHeaderAlreadyPresent_throws() { deploymentConfiguration diff --git a/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java b/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java index 635ab05dd34..d9241ed6988 100644 --- a/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java +++ b/flow-tests/test-csp-strict-spring-security/src/test/java/com/vaadin/flow/test/cspstrict/springsecurity/SpringSecurityPolicyIT.java @@ -32,9 +32,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue; /** - * Checks which Content Security Policy a response carries when both Vaadin, in - * the {@code strict} mode, and Spring Security are set to send one, and that - * the other headers of Spring Security reach the bootstrap page. + * Checks which Content Security Policy a response carries when Vaadin runs in + * the {@code strict} mode and the policy is configured in Spring Security, and + * that the other headers of Spring Security reach the bootstrap page. */ public class SpringSecurityPolicyIT { diff --git a/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java b/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java index 681ba303c0e..ee11dd5ddf8 100644 --- a/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java +++ b/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java @@ -680,9 +680,12 @@ public VaadinSecurityConfigurer enableNavigationAccessControl( * response of the filter chain, also in development mode. *

* This replaces a Content Security Policy configured with - * {@code HttpSecurity.headers()} for the same filter chain. Only use it - * when the strict mode is enabled: otherwise the scripts of a Vaadin page - * have no nonce and the policy blocks them. + * {@code HttpSecurity.headers()} for the same filter chain. When the + * headers of Spring Security are disabled for the filter chain, only the + * policy is added and the default headers stay off. + *

+ * Only use it when the strict mode is enabled: in the other modes Vaadin + * runs JavaScript in ways that the policy blocks. * * @return this configurer, for chaining * @see #contentSecurityPolicy(Consumer) @@ -740,6 +743,11 @@ public VaadinSecurityConfigurer contentSecurityPolicy( * * It runs after the policy directives are set, so directives it sets * replace the policy. + *

+ * These options can leave Vaadin pages without the protection of the strict + * mode, and nothing reports it: a Vaadin page of a request that the request + * matcher does not match is sent without any policy, and a report-only + * policy is not enforced. * * @param policyCustomizer * changes the policy described in @@ -838,10 +846,20 @@ public void init(HttpSecurity http) { ContentSecurityPolicy policy = StrictContentSecurityPolicy .create("{nonce}"); contentSecurityPolicyCustomizer.accept(policy); - http.headers(headers -> headers.contentSecurityPolicy(config -> { - config.policyDirectives(policy.toHeaderValue()); - contentSecurityPolicyConfigCustomizer.customize(config); - })); + // HttpSecurity.headers() adds the configurer again when the + // application has disabled it, which would bring back the default + // headers: only the policy is asked for here + boolean headersDisabled = http + .getConfigurer(HeadersConfigurer.class) == null; + http.headers(headers -> { + if (headersDisabled) { + headers.defaultsDisabled(); + } + headers.contentSecurityPolicy(config -> { + config.policyDirectives(policy.toHeaderValue()); + contentSecurityPolicyConfigCustomizer.customize(config); + }); + }); } if (enableCsrfConfiguration) { http.csrf(this::customizeCsrf); diff --git a/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java b/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java index e83f1e37c0b..d10c5b97931 100644 --- a/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java +++ b/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/SpringSecurityContentSecurityPolicyNonceProviderTest.java @@ -23,7 +23,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.function.Consumer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -70,11 +69,6 @@ class SpringSecurityContentSecurityPolicyNonceProviderTest { private static final String HEADER = "Content-Security-Policy"; - private static final String DEFAULT_POLICY = "default-src 'self'; " - + "script-src 'nonce-{nonce}' 'strict-dynamic'; " - + "style-src 'self' 'unsafe-inline'; img-src 'self' data:; " - + "font-src 'self' data:; connect-src 'self' data:; " - + "worker-src 'self'; object-src 'none'; base-uri 'self'"; @Autowired private ApplicationContext applicationContext; @@ -138,60 +132,6 @@ void policyInSpringSecurityForOtherPaths_noPolicyIsSent() throws Exception { assertEquals(List.of(), response.getHeaders(HEADER)); } - @Test - void policyOfVaadinSecurityConfigurer_defaultPolicyIsSentWithTheNonce() - throws Exception { - List nonces = new ArrayList<>(); - MockHttpServletResponse response = serve(nonces, - VaadinSecurityConfigurer::contentSecurityPolicy); - - assertEquals(22, nonces.get(0).length(), nonces.get(0)); - assertEquals(List.of(DEFAULT_POLICY.replace("{nonce}", nonces.get(0))), - response.getHeaders(HEADER)); - } - - @Test - void policyOfVaadinSecurityConfigurer_changesOfCustomizerAreSent() - throws Exception { - List nonces = new ArrayList<>(); - MockHttpServletResponse response = serve(nonces, - vaadin -> vaadin.contentSecurityPolicy(policy -> policy - .addSources("img-src", "https://cdn.example.com") - .setDirective("form-action", "'self'"))); - - assertEquals(List.of(DEFAULT_POLICY.replace("{nonce}", nonces.get(0)) - .replace("img-src 'self' data:", - "img-src 'self' data: https://cdn.example.com") - + "; form-action 'self'"), response.getHeaders(HEADER)); - } - - @Test - void policyOfVaadinSecurityConfigurer_optionsOfSpringSecurityApply() - throws Exception { - List nonces = new ArrayList<>(); - MockHttpServletResponse response = serve(nonces, - vaadin -> vaadin.contentSecurityPolicy(policy -> { - }, config -> config.requestMatchers("/api/**"))); - - // The request is for another path, so the policy is not sent - assertEquals(22, nonces.get(0).length(), nonces.get(0)); - assertEquals(List.of(), response.getHeaders(HEADER)); - } - - @Test - void policyOfVaadinSecurityConfigurer_replacesPolicyOfHttpSecurity() - throws Exception { - http.headers(headers -> headers.contentSecurityPolicy( - policy -> policy.policyDirectives("default-src 'none'"))); - - List nonces = new ArrayList<>(); - MockHttpServletResponse response = serve(nonces, - VaadinSecurityConfigurer::contentSecurityPolicy); - - assertEquals(List.of(DEFAULT_POLICY.replace("{nonce}", nonces.get(0))), - response.getHeaders(HEADER)); - } - @Test void noPolicyInSpringSecurity_noNonce() throws Exception { http.headers(Customizer.withDefaults()); @@ -209,16 +149,9 @@ void noPolicyInSpringSecurity_noNonce() throws Exception { */ private MockHttpServletResponse serve(List nonces) throws Exception { - return serve(nonces, vaadin -> { - }); - } - - private MockHttpServletResponse serve(List nonces, - Consumer customizer) throws Exception { List filters = http .with(VaadinSecurityConfigurer.vaadin(), - vaadin -> customizer.accept( - vaadin.anyRequest(AuthorizedUrl::permitAll))) + vaadin -> vaadin.anyRequest(AuthorizedUrl::permitAll)) .build().getFilters(); HttpServlet servlet = new HttpServlet() { @Override diff --git a/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurerTest.java b/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurerTest.java index cfdffb0affd..5f2b5208bc2 100644 --- a/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurerTest.java +++ b/vaadin-spring/src/test/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurerTest.java @@ -51,6 +51,7 @@ import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer; import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer.AuthorizedUrl; import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; @@ -113,6 +114,13 @@ @ExtendWith(MockitoExtension.class) class VaadinSecurityConfigurerTest { + private static final String CSP_HEADER = "Content-Security-Policy"; + private static final String DEFAULT_CSP_PATTERN = "default-src 'self'; " + + "script-src 'nonce-[A-Za-z0-9+/_-]{22}' 'strict-dynamic'; " + + "style-src 'self' 'unsafe-inline'; img-src 'self' data:; " + + "font-src 'self' data:; connect-src 'self' data:; " + + "worker-src 'self'; object-src 'none'; base-uri 'self'"; + @Autowired private ApplicationContext applicationContext; @@ -157,6 +165,85 @@ void tearDown() { SecurityContextHolder.clearContext(); } + @Test + void contentSecurityPolicy_defaultPolicyIsSentWithNonce() throws Exception { + configurer.contentSecurityPolicy(); + + assertThat(serveAndGetHeaders().getHeaders(CSP_HEADER)).singleElement() + .asString().matches(DEFAULT_CSP_PATTERN); + } + + @Test + void contentSecurityPolicy_changesOfCustomizerAreSent() throws Exception { + configurer.contentSecurityPolicy(policy -> policy + .addSources("img-src", "https://cdn.example.com") + .setDirective("form-action", "'self'")); + + assertThat(serveAndGetHeaders().getHeaders(CSP_HEADER)).singleElement() + .asString() + .matches(DEFAULT_CSP_PATTERN.replace("img-src 'self' data:", + "img-src 'self' data: https://cdn\\.example\\.com") + + "; form-action 'self'"); + } + + @Test + void contentSecurityPolicy_optionsOfSpringSecurityApply() throws Exception { + configurer.contentSecurityPolicy(policy -> { + }, config -> config.requestMatchers("/api/**")); + + // The request is for another path, so the policy is not sent + assertThat(serveAndGetHeaders().getHeaders(CSP_HEADER)).isEmpty(); + } + + @Test + void contentSecurityPolicy_replacesPolicyOfHttpSecurity() throws Exception { + http.headers(headers -> headers.contentSecurityPolicy( + policy -> policy.policyDirectives("default-src 'none'"))); + configurer.contentSecurityPolicy(); + + assertThat(serveAndGetHeaders().getHeaders(CSP_HEADER)).singleElement() + .asString().matches(DEFAULT_CSP_PATTERN); + } + + @Test + void contentSecurityPolicy_keepsDefaultHeadersOfSpringSecurity() + throws Exception { + // As Spring Security sets up the HttpSecurity of an application + http.headers(Customizer.withDefaults()); + configurer.contentSecurityPolicy(); + + MockHttpServletResponse servedResponse = serveAndGetHeaders(); + + assertThat(servedResponse.getHeader("X-Frame-Options")) + .isEqualTo("DENY"); + assertThat(servedResponse.getHeader("X-Content-Type-Options")) + .isEqualTo("nosniff"); + } + + @Test + void contentSecurityPolicy_headersDisabled_onlyPolicyIsSent() + throws Exception { + http.headers(AbstractHttpConfigurer::disable); + configurer.contentSecurityPolicy(); + + MockHttpServletResponse servedResponse = serveAndGetHeaders(); + + // The application asked for the policy, and for no other header + assertThat(servedResponse.getHeaderNames()).containsExactly(CSP_HEADER); + assertThat(servedResponse.getHeader(CSP_HEADER)) + .matches(DEFAULT_CSP_PATTERN); + } + + private MockHttpServletResponse serveAndGetHeaders() throws Exception { + var filters = http.with(configurer.anyRequest(AuthorizedUrl::permitAll), + Customizer.withDefaults()).build().getFilters(); + MockHttpServletResponse servedResponse = new MockHttpServletResponse(); + new MockFilterChain(new HttpServlet() { + }, filters.toArray(Filter[]::new)).doFilter( + new MockHttpServletRequest("GET", "/"), servedResponse); + return servedResponse; + } + @Test void withDefaults_chainHasDefaultFilters() { var filters = http.with(configurer, Customizer.withDefaults()).build() From af17290f8672765e8b137dc81ac493faf5b659a9 Mon Sep 17 00:00:00 2001 From: Giovanni Lovato Date: Tue, 1 Dec 2026 14:27:05 +0100 Subject: [PATCH 13/25] refactor: look up Content Security Policy nonce provider for each page Removes the cached provider from IndexHtmlRequestHandler. A volatile field for it is flagged by Sonar (java:S3077), and the lookup only runs once for each bootstrap page. --- .../IndexHtmlRequestHandler.java | 22 ++++--------------- 1 file changed, 4 insertions(+), 18 deletions(-) diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java index 45588b27d4d..d7fa1af4d6e 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java @@ -103,12 +103,6 @@ public class IndexHtmlRequestHandler extends JavaScriptBootstrapHandler { public static final String LIVE_RELOAD_PORT_ATTR = "livereload.port"; private static final String CONTENT_SECURITY_POLICY_HEADER = "Content-Security-Policy"; - private static final ContentSecurityPolicyNonceProvider NO_NONCE_PROVIDER = request -> null; - - // Null until looked up. A single volatile field, so that requests served - // at the same time never see a lookup that is half done - private transient volatile @Nullable ContentSecurityPolicyNonceProvider contentSecurityPolicyNonceProvider; - // Not static: a SecureRandom in a static field would be created at build // time in native images that initialize classes at build time (Quarkus) private final SecureRandom nonceRandom = new SecureRandom(); @@ -337,18 +331,10 @@ private static void addNonceToScripts(IndexHtmlResponse indexHtmlResponse) { private @Nullable String findProvidedContentSecurityPolicyNonce( VaadinRequest request) { - // Looked up once: a lookup can be a search for beans - ContentSecurityPolicyNonceProvider provider = contentSecurityPolicyNonceProvider; - if (provider == null) { - provider = request.getService().getContext() - .getAttribute(Lookup.class) - .lookup(ContentSecurityPolicyNonceProvider.class); - if (provider == null) { - provider = NO_NONCE_PROVIDER; - } - contentSecurityPolicyNonceProvider = provider; - } - return provider.findNonce(request); + ContentSecurityPolicyNonceProvider provider = request.getService() + .getContext().getAttribute(Lookup.class) + .lookup(ContentSecurityPolicyNonceProvider.class); + return provider == null ? null : provider.findNonce(request); } private void initializeFeatureFlags(Document indexDocument, From 59219000293b9e0e55a5216e8e3295f0772084ac Mon Sep 17 00:00:00 2001 From: "totally-not-ai[bot]" <290682512+totally-not-ai[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:03:56 +0000 Subject: [PATCH 14/25] feat: send report-only Content Security Policy in csp warn mode In production mode, the warn mode now sends the policy of the strict mode as a Content-Security-Policy-Report-Only header, with the nonce on the scripts of the page, so that the browser reports what the strict mode would block. A report-only header that the response already has is kept and logged as a warning. A nonce provided by a security framework is still used in every mode, with no policy of Vaadin. --- .../internal/StrictContentSecurityPolicy.java | 3 +- .../flow/server/ContentSecurityPolicy.java | 8 ++- .../server/ContentSecurityPolicyMode.java | 21 +++++- .../IndexHtmlRequestHandler.java | 37 ++++++++-- .../communication/IndexHtmlResponse.java | 23 +++++-- .../IndexHtmlRequestHandlerTest.java | 67 ++++++++++++++----- .../security/VaadinSecurityConfigurer.java | 14 +++- 7 files changed, 139 insertions(+), 34 deletions(-) diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/StrictContentSecurityPolicy.java b/flow-server/src/main/java/com/vaadin/flow/internal/StrictContentSecurityPolicy.java index 7e7a1a8d9f6..363d54f5345 100644 --- a/flow-server/src/main/java/com/vaadin/flow/internal/StrictContentSecurityPolicy.java +++ b/flow-server/src/main/java/com/vaadin/flow/internal/StrictContentSecurityPolicy.java @@ -20,7 +20,8 @@ /** * Creates the Content Security Policy that a Vaadin page needs in the - * {@link ContentSecurityPolicyMode#STRICT} mode. + * {@link ContentSecurityPolicyMode#STRICT} mode, which the + * {@link ContentSecurityPolicyMode#WARN} mode sends as a report-only policy. *

* For internal use only. May be renamed or removed in a future release. */ diff --git a/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicy.java b/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicy.java index a865e5cfc17..9af89f06c0b 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicy.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicy.java @@ -32,15 +32,17 @@ /** * A mutable Content Security Policy, i.e. a set of directives and the sources * of each directive, that is serialized as the value of a - * {@code Content-Security-Policy} HTTP header. + * {@code Content-Security-Policy} or + * {@code Content-Security-Policy-Report-Only} HTTP header. *

* Directive names are case-insensitive and kept in lower case. Directives are * written to the header in the order they were first set. Sources are written * as given, so keywords need their quotes, for example {@code "'self'"} or * {@code "'none'"}. *

- * In the {@link ContentSecurityPolicyMode#STRICT} mode, Vaadin creates the - * policy for each index HTML response and exposes it through + * In the {@link ContentSecurityPolicyMode#STRICT} and + * {@link ContentSecurityPolicyMode#WARN} modes, Vaadin creates the policy for + * each index HTML response and exposes it through * {@link com.vaadin.flow.server.communication.IndexHtmlResponse#getContentSecurityPolicy()}, * so that an * {@link com.vaadin.flow.server.communication.IndexHtmlRequestListener} can diff --git a/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java b/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java index 441cfc9e660..88a73eb39e1 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java @@ -30,8 +30,11 @@ * {@link com.vaadin.flow.dom.Element#executeJs(String, Object...)}, because the * browser has to compile it, which a strict policy blocks. This applies to the * calls that Vaadin itself makes as well, and in development mode as much as in - * production mode. The {@link #STRICT} mode also sends the Content Security - * Policy header in production mode. + * production mode. In production mode, both modes also send the Content + * Security Policy that a Vaadin page needs: the {@link #WARN} mode as a + * {@code Content-Security-Policy-Report-Only} header, which the browser only + * reports on, and the {@link #STRICT} mode as a {@code Content-Security-Policy} + * header, which the browser enforces. * * @since 25.4 */ @@ -47,6 +50,20 @@ public enum ContentSecurityPolicyMode { * trace that leads from the API to its caller. A warning is logged once per * call site, or, when a component reports what the JavaScript belongs to, * once per call site and reported part, such as a chart option. + *

+ * In production mode, Vaadin also sends the policy of the {@link #STRICT} + * mode, with a new nonce on the scripts of every index HTML response, but + * as a {@code Content-Security-Policy-Report-Only} header. The browser then + * reports in its console what the policy would block, such as inline + * scripts, {@code eval} in client-side code or resources from other + * origins, but still runs and loads it. A {@code report-uri} or + * {@code report-to} directive added through + * {@link com.vaadin.flow.server.communication.IndexHtmlResponse#getContentSecurityPolicy()} + * also sends the reports to a collector of the application. Switching to + * the {@link #STRICT} mode then enforces the same policy. No header is sent + * in development mode, and none if the response already has a + * {@code Content-Security-Policy-Report-Only} header, which is logged as a + * warning. */ WARN, /** diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java index d7fa1af4d6e..c337bf8afa5 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java @@ -102,6 +102,7 @@ public class IndexHtmlRequestHandler extends JavaScriptBootstrapHandler { private static final String SCRIPT_INITIAL = "initial"; public static final String LIVE_RELOAD_PORT_ATTR = "livereload.port"; private static final String CONTENT_SECURITY_POLICY_HEADER = "Content-Security-Policy"; + private static final String CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER = "Content-Security-Policy-Report-Only"; // Not static: a SecureRandom in a static field would be created at build // time in native images that initialize classes at build time (Quarkus) @@ -160,7 +161,9 @@ public boolean synchronizedHandleRequest(VaadinSession session, if (providedNonce != null) { indexHtmlResponse.setContentSecurityPolicy(providedNonce, null); } else if (config - .getContentSecurityPolicyMode() == ContentSecurityPolicyMode.STRICT) { + .getContentSecurityPolicyMode() != ContentSecurityPolicyMode.OFF) { + // The warn mode creates the same policy as the strict mode, so + // that the policy it reports on is the one that will be enforced String nonce = createContentSecurityPolicyNonce(); indexHtmlResponse.setContentSecurityPolicy(nonce, StrictContentSecurityPolicy.create(nonce)); @@ -269,7 +272,8 @@ public boolean synchronizedHandleRequest(VaadinSession session, if (config.isProductionMode()) { // The dev server and dev tools need eval, so the policy of // Vaadin is only sent in production mode - applyContentSecurityPolicy(indexHtmlResponse); + applyContentSecurityPolicy(indexHtmlResponse, + config.getContentSecurityPolicyMode()); } } else if (indexHtmlResponse.getContentSecurityPolicyNonce() != null) { // A policy with the nonce is sent by its provider, whatever the @@ -295,9 +299,27 @@ private String createContentSecurityPolicyNonce() { } private static void applyContentSecurityPolicy( - IndexHtmlResponse indexHtmlResponse) { + IndexHtmlResponse indexHtmlResponse, + ContentSecurityPolicyMode mode) { VaadinResponse response = indexHtmlResponse.getVaadinResponse(); - if (response.containsHeader(CONTENT_SECURITY_POLICY_HEADER)) { + if (mode == ContentSecurityPolicyMode.WARN) { + if (response.containsHeader( + CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER)) { + // The warn mode must not break the page, and replacing the + // header would drop the reports the application asked for + getLogger().warn( + "The response already has a {} header, so Vaadin does " + + "not send the policy of the '{}=warn' " + + "setting. Remove the code that sets the " + + "header to test the policy Vaadin enforces " + + "in the strict mode, and adjust it through " + + "IndexHtmlResponse.getContentSecurityPolicy() " + + "in an IndexHtmlRequestListener instead.", + CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER, + InitParameters.CONTENT_SECURITY_POLICY); + return; + } + } else if (response.containsHeader(CONTENT_SECURITY_POLICY_HEADER)) { // Sending the page without Vaadin's policy would silently drop // the protection the strict mode promises throw new IllegalStateException(String.format( @@ -314,7 +336,12 @@ private static void applyContentSecurityPolicy( // The caller checks that there is one ContentSecurityPolicy policy = Objects .requireNonNull(indexHtmlResponse.getContentSecurityPolicy()); - response.setHeader(CONTENT_SECURITY_POLICY_HEADER, + // The browser reports what the report-only policy would block, but + // still loads it + response.setHeader( + mode == ContentSecurityPolicyMode.WARN + ? CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER + : CONTENT_SECURITY_POLICY_HEADER, policy.toHeaderValue()); } diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java index 59d96541ee4..6c486545aaf 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java @@ -125,7 +125,8 @@ public Optional getUI() { * {@code script-src} directive of the Content Security Policy. *

* A new nonce is created for every response when the application runs with - * the {@link ContentSecurityPolicyMode#STRICT} mode. An integration with a + * the {@link ContentSecurityPolicyMode#STRICT} or + * {@link ContentSecurityPolicyMode#WARN} mode. An integration with a * security framework, such as the one for Spring Security in * {@code vaadin-spring}, can provide the nonce of the policy of that * framework, which is then used instead, in every mode. Scripts added by an @@ -133,8 +134,8 @@ public Optional getUI() { * value can also be used for other content that needs it. A nonce created * by Vaadin is not put on the scripts in development mode. * - * @return the nonce, or {@code null} if the mode is not - * {@link ContentSecurityPolicyMode#STRICT} and no nonce is provided + * @return the nonce, or {@code null} if the mode is + * {@link ContentSecurityPolicyMode#OFF} and no nonce is provided * @since 25.4 */ public @Nullable String getContentSecurityPolicyNonce() { @@ -145,7 +146,11 @@ public Optional getUI() { * Gets the Content Security Policy that is sent with this response. *

* The policy is created when the application runs with the - * {@link ContentSecurityPolicyMode#STRICT} mode. An + * {@link ContentSecurityPolicyMode#STRICT} mode, where it is sent as a + * {@code Content-Security-Policy} header, or with the + * {@link ContentSecurityPolicyMode#WARN} mode, where the same policy is + * sent as a {@code Content-Security-Policy-Report-Only} header, so that the + * browser reports what it would block without blocking it. An * {@link IndexHtmlRequestListener} can add or override directives for * resources of the application, such as {@code connect-src}, * {@code img-src}, {@code frame-src} or {@code report-to}. @@ -163,15 +168,19 @@ public Optional getUI() { * tools need {@code eval}. In production mode, the request fails with an * {@link IllegalStateException} if the response already has a * {@code Content-Security-Policy} header when the page is written, for - * example from a servlet filter that runs before Vaadin. + * example from a servlet filter that runs before Vaadin. In the + * {@link ContentSecurityPolicyMode#WARN} mode, a + * {@code Content-Security-Policy-Report-Only} header that the response + * already has is kept, and the policy of Vaadin is not sent, which is + * logged as a warning. *

* There is no policy to adjust when the application sends its own with a * nonce it shares with Vaadin, which an integration with a security * framework can make possible. That policy is sent with the page as * configured, and is adjusted where it is configured. * - * @return the mutable policy, or {@code null} if the mode is not - * {@link ContentSecurityPolicyMode#STRICT} or if the policy is not + * @return the mutable policy, or {@code null} if the mode is + * {@link ContentSecurityPolicyMode#OFF} or if the policy is not * sent by Vaadin * @since 25.4 */ diff --git a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java index db7d06db8c2..9a7a27bada6 100644 --- a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java +++ b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java @@ -266,11 +266,19 @@ public void serveIndexHtml_listenerSetsCacheControl_overridesDefault() inOrder.verify(response).setHeader("Cache-Control", "max-age=60"); } - @Test - public void serveIndexHtml_strictCsp_sendsPolicyWithNonceOnEveryScript() - throws IOException { + @ParameterizedTest + @CsvSource({ + "STRICT, Content-Security-Policy, " + + "Content-Security-Policy-Report-Only", + "WARN, Content-Security-Policy-Report-Only, " + + "Content-Security-Policy" }) + public void serveIndexHtml_cspInProduction_sendsPolicyWithNonceOnEveryScript( + ContentSecurityPolicyMode contentSecurityPolicyMode, + String headerName, String otherHeaderName) throws IOException { deploymentConfiguration - .setContentSecurityPolicyMode(ContentSecurityPolicyMode.STRICT); + .setContentSecurityPolicyMode(contentSecurityPolicyMode); + // A policy of the other kind is evaluated on its own by the browser + when(response.containsHeader(otherHeaderName)).thenReturn(true); service.addIndexHtmlRequestListener(evt -> { evt.getDocument().body().appendElement("script").attr("src", "listener.js"); @@ -285,7 +293,8 @@ public void serveIndexHtml_strictCsp_sendsPolicyWithNonceOnEveryScript() "https://api.example.com"); }); - String header = serveIndexHtmlAndCaptureCspHeader(); + String header = serveIndexHtmlAndCaptureCspHeader(headerName); + verify(response, never()).setHeader(eq(otherHeaderName), any()); Matcher matcher = Pattern.compile( "script-src 'nonce-([A-Za-z0-9+/]{22})' 'strict-dynamic'") .matcher(header); @@ -312,7 +321,8 @@ public void serveIndexHtml_strictCsp_sendsPolicyWithNonceOnEveryScript() .hasAttr("nonce")); responseOutput.reset(); - assertFalse(serveIndexHtmlAndCaptureCspHeader().contains(nonce), + assertFalse( + serveIndexHtmlAndCaptureCspHeader(headerName).contains(nonce), "Every response should get a new nonce"); } @@ -382,6 +392,8 @@ public void serveIndexHtml_nonceProvided_scriptsGetItInEveryMode( // not know the mode of Vaadin verify(response, never()).setHeader(eq("Content-Security-Policy"), any()); + verify(response, never()) + .setHeader(eq("Content-Security-Policy-Report-Only"), any()); assertEquals("provided-nonce", responses.get(0).getContentSecurityPolicyNonce()); assertNull(responses.get(0).getContentSecurityPolicy()); @@ -405,7 +417,8 @@ public void serveIndexHtml_strictCspAndProviderWithoutNonce_policyOfVaadinIsSent .lookup(ContentSecurityPolicyNonceProvider.class)) .thenReturn(provider); - String header = serveIndexHtmlAndCaptureCspHeader(); + String header = serveIndexHtmlAndCaptureCspHeader( + "Content-Security-Policy"); Matcher matcher = Pattern.compile( "script-src 'nonce-([A-Za-z0-9+/]{22})' 'strict-dynamic'") @@ -437,9 +450,29 @@ public void serveIndexHtml_strictCspAndHeaderAlreadyPresent_throws() { assertEquals(0, responseOutput.size()); } + @Test + public void serveIndexHtml_warnCspAndReportOnlyHeaderAlreadyPresent_keepsIt() + throws IOException { + deploymentConfiguration + .setContentSecurityPolicyMode(ContentSecurityPolicyMode.WARN); + when(response.containsHeader("Content-Security-Policy-Report-Only")) + .thenReturn(true); + + indexHtmlRequestHandler.synchronizedHandleRequest(session, + createVaadinRequest("/"), response); + + verify(response, never()) + .setHeader(eq("Content-Security-Policy-Report-Only"), any()); + verify(response, never()).setHeader(eq("Content-Security-Policy"), + any()); + String html = responseOutput.toString(StandardCharsets.UTF_8); + assertTrue(html.contains(" header = ArgumentCaptor.forClass(String.class); - verify(response).setHeader(eq("Content-Security-Policy"), - header.capture()); + verify(response).setHeader(eq(headerName), header.capture()); return header.getValue(); } diff --git a/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java b/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java index ee11dd5ddf8..68559e4aa24 100644 --- a/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java +++ b/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java @@ -685,7 +685,10 @@ public VaadinSecurityConfigurer enableNavigationAccessControl( * policy is added and the default headers stay off. *

* Only use it when the strict mode is enabled: in the other modes Vaadin - * runs JavaScript in ways that the policy blocks. + * runs JavaScript in ways that the policy blocks. In the + * {@code vaadin.contentSecurityPolicy=warn} mode, send the policy as + * report-only instead, see + * {@link #contentSecurityPolicy(Consumer, Customizer)}. * * @return this configurer, for chaining * @see #contentSecurityPolicy(Consumer) @@ -744,6 +747,15 @@ public VaadinSecurityConfigurer contentSecurityPolicy( * It runs after the policy directives are set, so directives it sets * replace the policy. *

+ * With {@code vaadin.contentSecurityPolicy=warn}, the policy is sent as + * report-only, so that the browser reports what it would block in the + * strict mode without blocking it: + * + *

+     * http.with(vaadin(), vaadin -> vaadin.contentSecurityPolicy(policy -> {
+     * }, config -> config.reportOnly()));
+     * 
+ *

* These options can leave Vaadin pages without the protection of the strict * mode, and nothing reports it: a Vaadin page of a request that the request * matcher does not match is sent without any policy, and a report-only From 400180080b0bf8f471cebb3d012c67dc849f9583 Mon Sep 17 00:00:00 2001 From: "totally-not-ai[bot]" <290682512+totally-not-ai[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 07:07:47 +0000 Subject: [PATCH 15/25] feat: warn once about existing report-only header in csp warn mode --- .../server/ContentSecurityPolicyMode.java | 3 ++- .../IndexHtmlRequestHandler.java | 11 ++++++-- .../communication/IndexHtmlResponse.java | 6 +++-- .../IndexHtmlRequestHandlerTest.java | 27 +++++++++++++++---- .../security/VaadinSecurityConfigurer.java | 5 ++-- 5 files changed, 40 insertions(+), 12 deletions(-) diff --git a/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java b/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java index 88a73eb39e1..55440e2e9f6 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java @@ -63,7 +63,8 @@ public enum ContentSecurityPolicyMode { * the {@link #STRICT} mode then enforces the same policy. No header is sent * in development mode, and none if the response already has a * {@code Content-Security-Policy-Report-Only} header, which is logged as a - * warning. + * warning once. An enforced {@code Content-Security-Policy} header that the + * application sends is left as it is. */ WARN, /** diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java index c337bf8afa5..585aca965d1 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java @@ -28,6 +28,7 @@ import java.util.Locale; import java.util.Objects; import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -108,6 +109,9 @@ public class IndexHtmlRequestHandler extends JavaScriptBootstrapHandler { // time in native images that initialize classes at build time (Quarkus) private final SecureRandom nonceRandom = new SecureRandom(); + // The header is usually set for every page, so it is reported only once + private final AtomicBoolean reportOnlyHeaderPresenceLogged = new AtomicBoolean(); + @Override public boolean synchronizedHandleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException { @@ -298,8 +302,7 @@ private String createContentSecurityPolicyNonce() { return Base64.getEncoder().withoutPadding().encodeToString(bytes); } - private static void applyContentSecurityPolicy( - IndexHtmlResponse indexHtmlResponse, + private void applyContentSecurityPolicy(IndexHtmlResponse indexHtmlResponse, ContentSecurityPolicyMode mode) { VaadinResponse response = indexHtmlResponse.getVaadinResponse(); if (mode == ContentSecurityPolicyMode.WARN) { @@ -307,6 +310,10 @@ private static void applyContentSecurityPolicy( CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER)) { // The warn mode must not break the page, and replacing the // header would drop the reports the application asked for + if (!reportOnlyHeaderPresenceLogged.compareAndSet(false, + true)) { + return; + } getLogger().warn( "The response already has a {} header, so Vaadin does " + "not send the policy of the '{}=warn' " diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java index 6c486545aaf..fcb212d4d3d 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java @@ -165,14 +165,16 @@ public Optional getUI() { *

* The header is written after all listeners have run. It is not written in * development mode, because the development server and the development - * tools need {@code eval}. In production mode, the request fails with an + * tools need {@code eval}. In production mode and the + * {@link ContentSecurityPolicyMode#STRICT} mode, the request fails with an * {@link IllegalStateException} if the response already has a * {@code Content-Security-Policy} header when the page is written, for * example from a servlet filter that runs before Vaadin. In the * {@link ContentSecurityPolicyMode#WARN} mode, a * {@code Content-Security-Policy-Report-Only} header that the response * already has is kept, and the policy of Vaadin is not sent, which is - * logged as a warning. + * logged as a warning once. A {@code Content-Security-Policy} header that + * the response already has is enforced next to the report-only policy. *

* There is no policy to adjust when the application sends its own with a * nonce it shares with Vaadin, which an integration with a security diff --git a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java index 9a7a27bada6..8e3e9252568 100644 --- a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java +++ b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java @@ -51,6 +51,9 @@ import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import tools.jackson.databind.node.ObjectNode; import com.vaadin.experimental.Feature; @@ -451,15 +454,31 @@ public void serveIndexHtml_strictCspAndHeaderAlreadyPresent_throws() { } @Test - public void serveIndexHtml_warnCspAndReportOnlyHeaderAlreadyPresent_keepsIt() + public void serveIndexHtml_warnCspAndReportOnlyHeaderAlreadyPresent_keepsItAndWarnsOnce() throws IOException { deploymentConfiguration .setContentSecurityPolicyMode(ContentSecurityPolicyMode.WARN); when(response.containsHeader("Content-Security-Policy-Report-Only")) .thenReturn(true); + Logger logger = mock(Logger.class); + // Other classes log through the real loggers + try (MockedStatic loggerFactory = mockStatic( + LoggerFactory.class, Mockito.CALLS_REAL_METHODS)) { + loggerFactory + .when(() -> LoggerFactory + .getLogger(IndexHtmlRequestHandler.class)) + .thenReturn(logger); - indexHtmlRequestHandler.synchronizedHandleRequest(session, - createVaadinRequest("/"), response); + indexHtmlRequestHandler.synchronizedHandleRequest(session, + createVaadinRequest("/"), response); + responseOutput.reset(); + indexHtmlRequestHandler.synchronizedHandleRequest(session, + createVaadinRequest("/"), response); + } + + verify(logger).warn(anyString(), + eq("Content-Security-Policy-Report-Only"), + eq("contentSecurityPolicy")); verify(response, never()) .setHeader(eq("Content-Security-Policy-Report-Only"), any()); @@ -480,8 +499,6 @@ public void serveIndexHtml_noCspInProduction_noHeaderOrNonce( // A header set elsewhere is fine when Vaadin sends no policy when(response.containsHeader("Content-Security-Policy")) .thenReturn(true); - when(response.containsHeader("Content-Security-Policy-Report-Only")) - .thenReturn(true); if (!productionMode) { File projectRootFolder = Files .createTempDirectory(temporaryFolder, "temp").toFile(); diff --git a/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java b/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java index 68559e4aa24..07a93aeb00a 100644 --- a/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java +++ b/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java @@ -733,8 +733,9 @@ public VaadinSecurityConfigurer contentSecurityPolicy( /** * Configures Spring Security to send the Content Security Policy that a * Vaadin page needs when the application runs with - * {@code vaadin.contentSecurityPolicy=strict}, with the changes of the - * given customizers. + * {@code vaadin.contentSecurityPolicy=strict}, or as report-only with + * {@code vaadin.contentSecurityPolicy=warn}, with the changes of the given + * customizers. *

* The second customizer sets the other options of the Content Security * Policy of Spring Security, such as the requests the policy is sent for: From 30ebc1ca4b3ed230fc00bc85e17c7dc0a5fc067f Mon Sep 17 00:00:00 2001 From: "totally-not-ai[bot]" <290682512+totally-not-ai[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:40:35 +0000 Subject: [PATCH 16/25] docs: say that the app asks for report-only policy in Spring Security --- .../spring/security/VaadinSecurityConfigurer.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java b/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java index 07a93aeb00a..876b4dc3b74 100644 --- a/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java +++ b/vaadin-spring/src/main/java/com/vaadin/flow/spring/security/VaadinSecurityConfigurer.java @@ -733,9 +733,9 @@ public VaadinSecurityConfigurer contentSecurityPolicy( /** * Configures Spring Security to send the Content Security Policy that a * Vaadin page needs when the application runs with - * {@code vaadin.contentSecurityPolicy=strict}, or as report-only with - * {@code vaadin.contentSecurityPolicy=warn}, with the changes of the given - * customizers. + * {@code vaadin.contentSecurityPolicy=strict}, with the changes of the + * given customizers. With {@code vaadin.contentSecurityPolicy=warn}, use + * the second customizer to send the policy as report-only. *

* The second customizer sets the other options of the Content Security * Policy of Spring Security, such as the requests the policy is sent for: @@ -748,9 +748,10 @@ public VaadinSecurityConfigurer contentSecurityPolicy( * It runs after the policy directives are set, so directives it sets * replace the policy. *

- * With {@code vaadin.contentSecurityPolicy=warn}, the policy is sent as - * report-only, so that the browser reports what it would block in the - * strict mode without blocking it: + * The configurer does not read the Content Security Policy mode of Vaadin, + * so with {@code vaadin.contentSecurityPolicy=warn} the application asks + * for a report-only policy itself. The browser then reports what the policy + * would block in the strict mode without blocking it: * *

      * http.with(vaadin(), vaadin -> vaadin.contentSecurityPolicy(policy -> {

From 07aa51f125eed4bc9069c9897e19c871bb8ec1f7 Mon Sep 17 00:00:00 2001
From: "totally-not-ai[bot]"
 <290682512+totally-not-ai[bot]@users.noreply.github.com>
Date: Wed, 2 Dec 2026 14:49:16 +0000
Subject: [PATCH 17/25] feat: send report-only policy of csp warn mode in
 development mode too

A report-only policy blocks nothing that the development server and
the development tools need, so warn mode now shows the client-side
violations in the browser console during the normal dev loop.
---
 .../IndexHtmlRequestHandler.java              |  9 +++--
 .../communication/IndexHtmlResponse.java      | 15 ++++++--
 .../IndexHtmlRequestHandlerTest.java          | 34 ++++++++++++-------
 3 files changed, 40 insertions(+), 18 deletions(-)

diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java
index f87095683d0..5ddf2b79995 100644
--- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java
+++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java
@@ -273,9 +273,12 @@ public boolean synchronizedHandleRequest(VaadinSession session,
                 indexDocument);
 
         if (indexHtmlResponse.getContentSecurityPolicy() != null) {
-            if (config.isProductionMode()) {
-                // The dev server and dev tools need eval, so the policy of
-                // Vaadin is only sent in production mode
+            // The dev server and dev tools need eval, so an enforced policy is
+            // only sent in production mode. A report-only policy blocks
+            // nothing, so it is sent in development mode too, where the
+            // developer sees its reports.
+            if (config.isProductionMode() || config
+                    .getContentSecurityPolicyMode() == ContentSecurityPolicyMode.WARN) {
                 applyContentSecurityPolicy(indexHtmlResponse,
                         config.getContentSecurityPolicyMode());
             }
diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java
index b228c333f0e..6058bcfd3c3 100644
--- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java
+++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java
@@ -132,7 +132,13 @@ public Optional getUI() {
      * framework, which is then used instead, in every mode. Scripts added by an
      * {@link IndexHtmlRequestListener} get the nonce automatically, but the
      * value can also be used for other content that needs it. A nonce created
-     * by Vaadin is not put on the scripts in development mode.
+     * by Vaadin is not put on the scripts in development mode in the
+     * {@link ContentSecurityPolicyMode#STRICT} mode, nor when Vaadin does not
+     * send its policy because the response already has a
+     * {@code Content-Security-Policy-Report-Only} header in the
+     * {@link ContentSecurityPolicyMode#WARN} mode, see
+     * {@link #getContentSecurityPolicy()}. No policy that is sent then uses the
+     * nonce.
      *
      * @return the nonce, or {@code null} if the mode is
      *         {@link ContentSecurityPolicyMode#OFF} and no nonce is provided
@@ -165,9 +171,12 @@ public Optional getUI() {
      * document, which gets the nonce, or load it from a script that is already
      * trusted.
      * 

- * The header is written after all listeners have run. It is not written in + * The header is written after all listeners have run. In the + * {@link ContentSecurityPolicyMode#STRICT} mode, it is not written in * development mode, because the development server and the development - * tools need {@code eval}. In production mode and the + * tools need {@code eval}. The report-only header of the + * {@link ContentSecurityPolicyMode#WARN} mode blocks nothing, so it is + * written in development mode too. In production mode and the * {@link ContentSecurityPolicyMode#STRICT} mode, the request fails with an * {@link IllegalStateException} if the response already has a * {@code Content-Security-Policy} header when the page is written, for diff --git a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java index e16299db335..6dea87a6d77 100644 --- a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java +++ b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java @@ -274,15 +274,21 @@ public void serveIndexHtml_listenerSetsCacheControl_overridesDefault() @ParameterizedTest @CsvSource({ - "STRICT, Content-Security-Policy, " + "STRICT, true, Content-Security-Policy, " + "Content-Security-Policy-Report-Only", - "WARN, Content-Security-Policy-Report-Only, " + "WARN, true, Content-Security-Policy-Report-Only, " + + "Content-Security-Policy", + "WARN, false, Content-Security-Policy-Report-Only, " + "Content-Security-Policy" }) - public void serveIndexHtml_cspInProduction_sendsPolicyWithNonceOnEveryScript( + public void serveIndexHtml_policySent_sendsPolicyWithNonceOnEveryScript( ContentSecurityPolicyMode contentSecurityPolicyMode, - String headerName, String otherHeaderName) throws IOException { + boolean productionMode, String headerName, String otherHeaderName) + throws IOException { deploymentConfiguration .setContentSecurityPolicyMode(contentSecurityPolicyMode); + if (!productionMode) { + useDevelopmentMode(); + } // A policy of the other kind is evaluated on its own by the browser when(response.containsHeader(otherHeaderName)).thenReturn(true); service.addIndexHtmlRequestListener(evt -> { @@ -518,8 +524,8 @@ public void serveIndexHtml_warnCspAndReportOnlyHeaderAlreadyPresent_keepsItAndWa } @ParameterizedTest - @CsvSource({ "OFF, true", "WARN, false", "STRICT, false" }) - public void serveIndexHtml_noCspInProduction_noHeaderOrNonce( + @CsvSource({ "OFF, true", "STRICT, false" }) + public void serveIndexHtml_noPolicySent_noHeaderOrNonce( ContentSecurityPolicyMode contentSecurityPolicyMode, boolean productionMode) throws Exception { deploymentConfiguration @@ -528,12 +534,7 @@ public void serveIndexHtml_noCspInProduction_noHeaderOrNonce( when(response.containsHeader("Content-Security-Policy")) .thenReturn(true); if (!productionMode) { - File projectRootFolder = Files - .createTempDirectory(temporaryFolder, "temp").toFile(); - TestUtil.createIndexHtmlStub(projectRootFolder); - TestUtil.createStatsJsonStub(projectRootFolder); - deploymentConfiguration.setProductionMode(false); - deploymentConfiguration.setProjectFolder(projectRootFolder); + useDevelopmentMode(); } List responses = new ArrayList<>(); service.addIndexHtmlRequestListener(responses::add); @@ -556,6 +557,15 @@ public void serveIndexHtml_noCspInProduction_noHeaderOrNonce( .contains("nonce=")); } + private void useDevelopmentMode() throws IOException { + File projectRootFolder = Files + .createTempDirectory(temporaryFolder, "temp").toFile(); + TestUtil.createIndexHtmlStub(projectRootFolder); + TestUtil.createStatsJsonStub(projectRootFolder); + deploymentConfiguration.setProductionMode(false); + deploymentConfiguration.setProjectFolder(projectRootFolder); + } + private String serveIndexHtmlAndCaptureCspHeader(String headerName) throws IOException { clearInvocations(response); From 559492b1c90473257c2c484d5c169b50d9b2fcfb Mon Sep 17 00:00:00 2001 From: "totally-not-ai[bot]" <290682512+totally-not-ai[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:33:37 +0000 Subject: [PATCH 18/25] docs: say that warn mode sends no policy when nonce is provided --- .../com/vaadin/flow/server/ContentSecurityPolicyMode.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java b/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java index 6b8d402db43..9ab327cabcd 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java @@ -71,6 +71,11 @@ public enum ContentSecurityPolicyMode { * already has a {@code Content-Security-Policy-Report-Only} header, which * is logged as a warning once. An enforced {@code Content-Security-Policy} * header that the application sends is left as it is. + *

+ * When an integration with a security framework provides the nonce, as + * described for the {@link #STRICT} mode, Vaadin puts that nonce on the + * scripts and sends no policy of its own in this mode either. To get the + * reports, configure the policy of the security framework as report-only. */ WARN, /** From c54d628bf340d92983577edd71ed9d55c660a003 Mon Sep 17 00:00:00 2001 From: "totally-not-ai[bot]" <290682512+totally-not-ai[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:34:50 +0000 Subject: [PATCH 19/25] test: cover provided nonce in warn mode in development mode --- .../flow/server/communication/IndexHtmlRequestHandlerTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java index 6dea87a6d77..88c1f26a74a 100644 --- a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java +++ b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java @@ -376,7 +376,8 @@ public void serveIndexHtml_strictCspAndNonceProvided_scriptsGetItAndNoPolicyIsSe } @ParameterizedTest - @CsvSource({ "OFF, true", "WARN, true", "STRICT, false", "OFF, false" }) + @CsvSource({ "OFF, true", "WARN, true", "STRICT, false", "OFF, false", + "WARN, false" }) public void serveIndexHtml_nonceProvided_scriptsGetItInEveryMode( ContentSecurityPolicyMode contentSecurityPolicyMode, boolean productionMode) throws Exception { From e18c190ab39224d1350e5dcf62c3cd1c080919a2 Mon Sep 17 00:00:00 2001 From: "totally-not-ai[bot]" <290682512+totally-not-ai[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:43:50 +0000 Subject: [PATCH 20/25] docs: say that report-to needs a Reporting-Endpoints header --- .../server/ContentSecurityPolicyMode.java | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java b/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java index 9ab327cabcd..2c23f3273c6 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java @@ -60,17 +60,20 @@ public enum ContentSecurityPolicyMode { * {@code Content-Security-Policy-Report-Only} header. The browser then * reports in its console what the policy would block, such as inline * scripts, {@code eval} in client-side code or resources from other - * origins, but still runs and loads it. A {@code report-uri} or - * {@code report-to} directive added through + * origins, but still runs and loads it. A {@code report-uri} directive + * added through * {@link com.vaadin.flow.server.communication.IndexHtmlResponse#getContentSecurityPolicy()} - * also sends the reports to a collector of the application. Switching to - * the {@link #STRICT} mode then enforces the same policy. The header is - * sent in development mode too, since a report-only policy blocks nothing - * that the development server and the development tools need, so the - * reports show up during development. No header is sent if the response - * already has a {@code Content-Security-Policy-Report-Only} header, which - * is logged as a warning once. An enforced {@code Content-Security-Policy} - * header that the application sends is left as it is. + * also sends the reports to a collector of the application. A + * {@code report-to} directive only names an endpoint group, which the + * application also declares in a {@code Reporting-Endpoints} response + * header. Switching to the {@link #STRICT} mode then enforces the same + * policy. The header is sent in development mode too, since a report-only + * policy blocks nothing that the development server and the development + * tools need, so the reports show up during development. No header is sent + * if the response already has a {@code Content-Security-Policy-Report-Only} + * header, which is logged as a warning once. An enforced + * {@code Content-Security-Policy} header that the application sends is left + * as it is. *

* When an integration with a security framework provides the nonce, as * described for the {@link #STRICT} mode, Vaadin puts that nonce on the From 40a11e27046ddbaf299e99af45ef899f18af7f49 Mon Sep 17 00:00:00 2001 From: "totally-not-ai[bot]" <290682512+totally-not-ai[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:44:37 +0000 Subject: [PATCH 21/25] docs: name report-uri as the reporting directive example --- .../com/vaadin/flow/server/communication/IndexHtmlResponse.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java index 6058bcfd3c3..e5a242b30d8 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java @@ -159,7 +159,7 @@ public Optional getUI() { * browser reports what it would block without blocking it. An * {@link IndexHtmlRequestListener} can add or override directives for * resources of the application, such as {@code connect-src}, - * {@code img-src}, {@code frame-src} or {@code report-to}. + * {@code img-src}, {@code frame-src} or {@code report-uri}. *

* Do not change {@code script-src}, and do not add {@code script-src-elem} * or {@code script-src-attr}: {@code script-src} holds the nonce and From 48a5f90fe391c4e382c2d42aadde314e41225580 Mon Sep 17 00:00:00 2001 From: "totally-not-ai[bot]" <290682512+totally-not-ai[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 06:49:43 +0000 Subject: [PATCH 22/25] feat: send report-only policy in csp strict mode in development mode The browser then reports the client-side violations that the enforced policy would block in production, while the development server and the development tools, which need eval, keep working. --- .../server/ContentSecurityPolicyMode.java | 20 +++++++--- .../IndexHtmlRequestHandler.java | 32 ++++++++-------- .../communication/IndexHtmlResponse.java | 37 +++++++++---------- .../IndexHtmlRequestHandlerTest.java | 21 +++++------ 4 files changed, 55 insertions(+), 55 deletions(-) diff --git a/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java b/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java index 2c23f3273c6..3d4167d9d49 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/ContentSecurityPolicyMode.java @@ -31,11 +31,11 @@ * browser has to compile it, which a strict policy blocks. This applies to the * calls that Vaadin itself makes as well, and in development mode as much as in * production mode. Both modes also send the Content Security Policy that a - * Vaadin page needs: the {@link #WARN} mode as a + * Vaadin page needs. The {@link #STRICT} mode sends it in production mode as a + * {@code Content-Security-Policy} header, which the browser enforces. In + * development mode, and in the {@link #WARN} mode, it is sent as a * {@code Content-Security-Policy-Report-Only} header, which the browser only - * reports on, also in development mode, and the {@link #STRICT} mode as a - * {@code Content-Security-Policy} header, which the browser enforces, in - * production mode only. + * reports on. * * @since 25.4 */ @@ -93,8 +93,16 @@ public enum ContentSecurityPolicyMode { * that nonce and the scripts they load. Applications adjust the policy * through * {@link com.vaadin.flow.server.communication.IndexHtmlResponse#getContentSecurityPolicy()}. - * No header is sent in development mode, because the development server and - * the development tools need {@code eval}. + *

+ * In development mode, the same policy is sent as a + * {@code Content-Security-Policy-Report-Only} header, with the nonce on the + * scripts, because the development server and the development tools need + * {@code eval}. The browser then reports in its console what the policy + * would block in production mode, such as inline scripts, {@code eval} in + * client-side code or resources from other origins, without blocking it. As + * in the {@link #WARN} mode, no header is sent if the response already has + * a {@code Content-Security-Policy-Report-Only} header, which is logged as + * a warning once. *

* An integration with a security framework, such as the one for Spring * Security in vaadin-spring, can provide the nonce instead. This is the diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java index 5ddf2b79995..f0f17705312 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java @@ -273,15 +273,13 @@ public boolean synchronizedHandleRequest(VaadinSession session, indexDocument); if (indexHtmlResponse.getContentSecurityPolicy() != null) { - // The dev server and dev tools need eval, so an enforced policy is - // only sent in production mode. A report-only policy blocks + // The dev server and dev tools need eval, so the policy is only + // enforced in production mode. A report-only policy blocks // nothing, so it is sent in development mode too, where the // developer sees its reports. - if (config.isProductionMode() || config - .getContentSecurityPolicyMode() == ContentSecurityPolicyMode.WARN) { - applyContentSecurityPolicy(indexHtmlResponse, - config.getContentSecurityPolicyMode()); - } + boolean enforced = config.isProductionMode() && config + .getContentSecurityPolicyMode() == ContentSecurityPolicyMode.STRICT; + applyContentSecurityPolicy(indexHtmlResponse, enforced); } else if (indexHtmlResponse.getContentSecurityPolicyNonce() != null) { // A policy with the nonce is sent by its provider, whatever the // mode, so the scripts need the nonce to run @@ -306,23 +304,24 @@ private String createContentSecurityPolicyNonce() { } private void applyContentSecurityPolicy(IndexHtmlResponse indexHtmlResponse, - ContentSecurityPolicyMode mode) { + boolean enforced) { VaadinResponse response = indexHtmlResponse.getVaadinResponse(); - if (mode == ContentSecurityPolicyMode.WARN) { + if (!enforced) { if (response.containsHeader( CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER)) { - // The warn mode must not break the page, and replacing the - // header would drop the reports the application asked for + // A report-only policy must not break the page, and replacing + // the header would drop the reports the application asked for if (!reportOnlyHeaderPresenceLogged.compareAndSet(false, true)) { return; } getLogger().warn( "The response already has a {} header, so Vaadin does " - + "not send the policy of the '{}=warn' " - + "setting. Remove the code that sets the " + + "not send its report-only policy for the " + + "'{}' setting. Remove the code that sets the " + "header to test the policy Vaadin enforces " - + "in the strict mode, and adjust it through " + + "in the strict mode in production, and " + + "adjust it through " + "IndexHtmlResponse.getContentSecurityPolicy() " + "in an IndexHtmlRequestListener instead.", CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER, @@ -349,9 +348,8 @@ private void applyContentSecurityPolicy(IndexHtmlResponse indexHtmlResponse, // The browser reports what the report-only policy would block, but // still loads it response.setHeader( - mode == ContentSecurityPolicyMode.WARN - ? CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER - : CONTENT_SECURITY_POLICY_HEADER, + enforced ? CONTENT_SECURITY_POLICY_HEADER + : CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER, policy.toHeaderValue()); } diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java index e5a242b30d8..e37a69cf60c 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlResponse.java @@ -132,11 +132,9 @@ public Optional getUI() { * framework, which is then used instead, in every mode. Scripts added by an * {@link IndexHtmlRequestListener} get the nonce automatically, but the * value can also be used for other content that needs it. A nonce created - * by Vaadin is not put on the scripts in development mode in the - * {@link ContentSecurityPolicyMode#STRICT} mode, nor when Vaadin does not - * send its policy because the response already has a - * {@code Content-Security-Policy-Report-Only} header in the - * {@link ContentSecurityPolicyMode#WARN} mode, see + * by Vaadin is not put on the scripts when Vaadin does not send its + * report-only policy because the response already has a + * {@code Content-Security-Policy-Report-Only} header, see * {@link #getContentSecurityPolicy()}. No policy that is sent then uses the * nonce. * @@ -153,7 +151,7 @@ public Optional getUI() { *

* The policy is created when the application runs with the * {@link ContentSecurityPolicyMode#STRICT} mode, where it is sent as a - * {@code Content-Security-Policy} header, or with the + * {@code Content-Security-Policy} header in production mode, or with the * {@link ContentSecurityPolicyMode#WARN} mode, where the same policy is * sent as a {@code Content-Security-Policy-Report-Only} header, so that the * browser reports what it would block without blocking it. An @@ -171,21 +169,20 @@ public Optional getUI() { * document, which gets the nonce, or load it from a script that is already * trusted. *

- * The header is written after all listeners have run. In the - * {@link ContentSecurityPolicyMode#STRICT} mode, it is not written in - * development mode, because the development server and the development - * tools need {@code eval}. The report-only header of the - * {@link ContentSecurityPolicyMode#WARN} mode blocks nothing, so it is - * written in development mode too. In production mode and the - * {@link ContentSecurityPolicyMode#STRICT} mode, the request fails with an - * {@link IllegalStateException} if the response already has a + * The header is written after all listeners have run. The + * {@link ContentSecurityPolicyMode#STRICT} mode sends the policy as a + * {@code Content-Security-Policy-Report-Only} header in development mode, + * because the development server and the development tools need + * {@code eval}, and a report-only policy blocks nothing. In production mode + * and the {@link ContentSecurityPolicyMode#STRICT} mode, the request fails + * with an {@link IllegalStateException} if the response already has a * {@code Content-Security-Policy} header when the page is written, for - * example from a servlet filter that runs before Vaadin. In the - * {@link ContentSecurityPolicyMode#WARN} mode, a - * {@code Content-Security-Policy-Report-Only} header that the response - * already has is kept, and the policy of Vaadin is not sent, which is - * logged as a warning once. A {@code Content-Security-Policy} header that - * the response already has is enforced next to the report-only policy. + * example from a servlet filter that runs before Vaadin. When the policy is + * sent as report-only, a {@code Content-Security-Policy-Report-Only} header + * that the response already has is kept, and the policy of Vaadin is not + * sent, which is logged as a warning once. A + * {@code Content-Security-Policy} header that the response already has is + * enforced next to the report-only policy. *

* There is no policy to adjust when the application sends its own with a * nonce it shares with Vaadin, which an integration with a security diff --git a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java index 88c1f26a74a..c3b6cf557e2 100644 --- a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java +++ b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java @@ -49,6 +49,7 @@ import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatcher; import org.mockito.InOrder; @@ -279,6 +280,8 @@ public void serveIndexHtml_listenerSetsCacheControl_overridesDefault() "WARN, true, Content-Security-Policy-Report-Only, " + "Content-Security-Policy", "WARN, false, Content-Security-Policy-Report-Only, " + + "Content-Security-Policy", + "STRICT, false, Content-Security-Policy-Report-Only, " + "Content-Security-Policy" }) public void serveIndexHtml_policySent_sendsPolicyWithNonceOnEveryScript( ContentSecurityPolicyMode contentSecurityPolicyMode, @@ -525,12 +528,11 @@ public void serveIndexHtml_warnCspAndReportOnlyHeaderAlreadyPresent_keepsItAndWa } @ParameterizedTest - @CsvSource({ "OFF, true", "STRICT, false" }) - public void serveIndexHtml_noPolicySent_noHeaderOrNonce( - ContentSecurityPolicyMode contentSecurityPolicyMode, - boolean productionMode) throws Exception { + @ValueSource(booleans = { true, false }) + public void serveIndexHtml_offMode_noHeaderOrNonce(boolean productionMode) + throws Exception { deploymentConfiguration - .setContentSecurityPolicyMode(contentSecurityPolicyMode); + .setContentSecurityPolicyMode(ContentSecurityPolicyMode.OFF); // A header set elsewhere is fine when Vaadin sends no policy when(response.containsHeader("Content-Security-Policy")) .thenReturn(true); @@ -542,14 +544,9 @@ public void serveIndexHtml_noPolicySent_noHeaderOrNonce( indexHtmlRequestHandler.synchronizedHandleRequest(session, createVaadinRequest("/"), response); - // In development mode, listeners still get the policy so that they - // work the same way in both modes assertEquals(1, responses.size()); - boolean policyCreated = contentSecurityPolicyMode != ContentSecurityPolicyMode.OFF; - assertEquals(policyCreated, - responses.get(0).getContentSecurityPolicyNonce() != null); - assertEquals(policyCreated, - responses.get(0).getContentSecurityPolicy() != null); + assertNull(responses.get(0).getContentSecurityPolicyNonce()); + assertNull(responses.get(0).getContentSecurityPolicy()); verify(response, never()).setHeader(eq("Content-Security-Policy"), any()); verify(response, never()) From 1a614f06dd9858ae3a633fcc178357d03044e7f8 Mon Sep 17 00:00:00 2001 From: "totally-not-ai[bot]" <290682512+totally-not-ai[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 06:51:41 +0000 Subject: [PATCH 23/25] test: cover existing report-only header in strict development mode Also name the mode in the warning about an existing report-only header, since strict mode in development mode now logs it too. --- .../internal/StrictContentSecurityPolicy.java | 5 +++-- .../communication/IndexHtmlRequestHandler.java | 10 ++++++---- .../IndexHtmlRequestHandlerTest.java | 17 ++++++++++++----- 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/StrictContentSecurityPolicy.java b/flow-server/src/main/java/com/vaadin/flow/internal/StrictContentSecurityPolicy.java index 363d54f5345..b736f0f951b 100644 --- a/flow-server/src/main/java/com/vaadin/flow/internal/StrictContentSecurityPolicy.java +++ b/flow-server/src/main/java/com/vaadin/flow/internal/StrictContentSecurityPolicy.java @@ -20,8 +20,9 @@ /** * Creates the Content Security Policy that a Vaadin page needs in the - * {@link ContentSecurityPolicyMode#STRICT} mode, which the - * {@link ContentSecurityPolicyMode#WARN} mode sends as a report-only policy. + * {@link ContentSecurityPolicyMode#STRICT} mode. The strict mode sends it as a + * report-only policy in development mode, and the + * {@link ContentSecurityPolicyMode#WARN} mode always does. *

* For internal use only. May be renamed or removed in a future release. */ diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java index f0f17705312..72c95d250f6 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java @@ -279,7 +279,8 @@ public boolean synchronizedHandleRequest(VaadinSession session, // developer sees its reports. boolean enforced = config.isProductionMode() && config .getContentSecurityPolicyMode() == ContentSecurityPolicyMode.STRICT; - applyContentSecurityPolicy(indexHtmlResponse, enforced); + applyContentSecurityPolicy(indexHtmlResponse, + config.getContentSecurityPolicyMode(), enforced); } else if (indexHtmlResponse.getContentSecurityPolicyNonce() != null) { // A policy with the nonce is sent by its provider, whatever the // mode, so the scripts need the nonce to run @@ -304,7 +305,7 @@ private String createContentSecurityPolicyNonce() { } private void applyContentSecurityPolicy(IndexHtmlResponse indexHtmlResponse, - boolean enforced) { + ContentSecurityPolicyMode mode, boolean enforced) { VaadinResponse response = indexHtmlResponse.getVaadinResponse(); if (!enforced) { if (response.containsHeader( @@ -318,14 +319,15 @@ private void applyContentSecurityPolicy(IndexHtmlResponse indexHtmlResponse, getLogger().warn( "The response already has a {} header, so Vaadin does " + "not send its report-only policy for the " - + "'{}' setting. Remove the code that sets the " + + "'{}={}' setting. Remove the code that sets the " + "header to test the policy Vaadin enforces " + "in the strict mode in production, and " + "adjust it through " + "IndexHtmlResponse.getContentSecurityPolicy() " + "in an IndexHtmlRequestListener instead.", CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER, - InitParameters.CONTENT_SECURITY_POLICY); + InitParameters.CONTENT_SECURITY_POLICY, + mode.name().toLowerCase(Locale.ROOT)); return; } } else if (response.containsHeader(CONTENT_SECURITY_POLICY_HEADER)) { diff --git a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java index c3b6cf557e2..5d2a41af917 100644 --- a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java +++ b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java @@ -30,6 +30,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.UUID; @@ -491,11 +492,16 @@ public void serveIndexHtml_strictCspAndHeaderAlreadyPresent_throws() { assertEquals(0, responseOutput.size()); } - @Test - public void serveIndexHtml_warnCspAndReportOnlyHeaderAlreadyPresent_keepsItAndWarnsOnce() - throws IOException { + @ParameterizedTest + @CsvSource({ "WARN, true", "WARN, false", "STRICT, false" }) + public void serveIndexHtml_reportOnlyPolicyAndHeaderAlreadyPresent_keepsItAndWarnsOnce( + ContentSecurityPolicyMode contentSecurityPolicyMode, + boolean productionMode) throws IOException { deploymentConfiguration - .setContentSecurityPolicyMode(ContentSecurityPolicyMode.WARN); + .setContentSecurityPolicyMode(contentSecurityPolicyMode); + if (!productionMode) { + useDevelopmentMode(); + } when(response.containsHeader("Content-Security-Policy-Report-Only")) .thenReturn(true); Logger logger = mock(Logger.class); @@ -516,7 +522,8 @@ public void serveIndexHtml_warnCspAndReportOnlyHeaderAlreadyPresent_keepsItAndWa verify(logger).warn(anyString(), eq("Content-Security-Policy-Report-Only"), - eq("contentSecurityPolicy")); + eq("contentSecurityPolicy"), + eq(contentSecurityPolicyMode.name().toLowerCase(Locale.ROOT))); verify(response, never()) .setHeader(eq("Content-Security-Policy-Report-Only"), any()); From d4b53f146df57f087c2275886be72b21ddd33267 Mon Sep 17 00:00:00 2001 From: "totally-not-ai[bot]" <290682512+totally-not-ai[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:25:37 +0000 Subject: [PATCH 24/25] refactor: build csp warning arguments only when warn is enabled --- .../IndexHtmlRequestHandler.java | 29 +++++++++---------- .../IndexHtmlRequestHandlerTest.java | 1 + 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java index 72c95d250f6..77c767fed33 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java @@ -312,22 +312,21 @@ private void applyContentSecurityPolicy(IndexHtmlResponse indexHtmlResponse, CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER)) { // A report-only policy must not break the page, and replacing // the header would drop the reports the application asked for - if (!reportOnlyHeaderPresenceLogged.compareAndSet(false, - true)) { - return; + if (reportOnlyHeaderPresenceLogged.compareAndSet(false, true) + && getLogger().isWarnEnabled()) { + getLogger().warn( + "The response already has a {} header, so Vaadin does " + + "not send its report-only policy for the " + + "'{}={}' setting. Remove the code that sets the " + + "header to test the policy Vaadin enforces " + + "in the strict mode in production, and " + + "adjust it through " + + "IndexHtmlResponse.getContentSecurityPolicy() " + + "in an IndexHtmlRequestListener instead.", + CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER, + InitParameters.CONTENT_SECURITY_POLICY, + mode.name().toLowerCase(Locale.ROOT)); } - getLogger().warn( - "The response already has a {} header, so Vaadin does " - + "not send its report-only policy for the " - + "'{}={}' setting. Remove the code that sets the " - + "header to test the policy Vaadin enforces " - + "in the strict mode in production, and " - + "adjust it through " - + "IndexHtmlResponse.getContentSecurityPolicy() " - + "in an IndexHtmlRequestListener instead.", - CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER, - InitParameters.CONTENT_SECURITY_POLICY, - mode.name().toLowerCase(Locale.ROOT)); return; } } else if (response.containsHeader(CONTENT_SECURITY_POLICY_HEADER)) { diff --git a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java index 5d2a41af917..f90b754ee90 100644 --- a/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java +++ b/flow-server/src/test/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandlerTest.java @@ -505,6 +505,7 @@ public void serveIndexHtml_reportOnlyPolicyAndHeaderAlreadyPresent_keepsItAndWar when(response.containsHeader("Content-Security-Policy-Report-Only")) .thenReturn(true); Logger logger = mock(Logger.class); + when(logger.isWarnEnabled()).thenReturn(true); // Other classes log through the real loggers try (MockedStatic loggerFactory = mockStatic( LoggerFactory.class, Mockito.CALLS_REAL_METHODS)) { From c375bb75cd1ce1616ed41510d09c12925af5ba9b Mon Sep 17 00:00:00 2001 From: "totally-not-ai[bot]" <290682512+totally-not-ai[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:26:52 +0000 Subject: [PATCH 25/25] fix: keep csp warning for later when warn logging is off --- .../flow/server/communication/IndexHtmlRequestHandler.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java index 77c767fed33..0cd2482bf30 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java @@ -312,8 +312,9 @@ private void applyContentSecurityPolicy(IndexHtmlResponse indexHtmlResponse, CONTENT_SECURITY_POLICY_REPORT_ONLY_HEADER)) { // A report-only policy must not break the page, and replacing // the header would drop the reports the application asked for - if (reportOnlyHeaderPresenceLogged.compareAndSet(false, true) - && getLogger().isWarnEnabled()) { + if (getLogger().isWarnEnabled() + && reportOnlyHeaderPresenceLogged.compareAndSet(false, + true)) { getLogger().warn( "The response already has a {} header, so Vaadin does " + "not send its report-only policy for the "