Repository navigation
Add default configurable Grails security response headers - #15967
Conversation
Register a OncePerRequestFilter for X-Content-Type-Options, X-Frame-Options, Referrer-Policy, optional HSTS on secure requests, and optional CSP. Configurable via grails.security.headers.* with opt-out and ConditionalOnMissingBean. Assisted-by: Sisyphus:xai/grok-4.5 [gpt-coding]
There was a problem hiding this comment.
Pull request overview
This PR introduces a default, configurable servlet filter in grails-controllers that applies baseline browser-hardening response headers for Grails 8 servlet web applications, along with auto-configuration, configuration metadata, tests, and documentation updates in the user guide and upgrade notes.
Changes:
- Added
GrailsSecurityHeadersFilterplusGrailsSecurityHeadersPropertiesand a servlet-only Boot auto-configuration to register it by default (with opt-out viagrails.security.headers.*). - Added configuration metadata for IDE/property hinting and documented the defaults + customization in the Security guide and Grails 8 upgrade notes.
- Added a Spock spec verifying auto-config behavior, default headers, per-header disablement, overrides, and secure-request HSTS behavior.
Reviewed changes
Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| grails-doc/src/en/guide/upgrading/upgrading80x.adoc | Adds Grails 8 upgrade note about the new default security headers filter and how to disable/configure it. |
| grails-doc/src/en/guide/security.adoc | Documents default headers, rationale for HSTS/CSP being opt-in, and example application.yml configuration. |
| grails-controllers/src/test/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfigurationSpec.groovy | Adds test coverage for auto-configuration and header application behavior. |
| grails-controllers/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports | Registers the new auto-configuration class for Spring Boot discovery. |
| grails-controllers/src/main/resources/META-INF/additional-spring-configuration-metadata.json | Adds Spring configuration metadata entries for grails.security.headers.* properties. |
| grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersProperties.java | Introduces bindable configuration properties and defaults for each supported header. |
| grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java | Implements the OncePerRequestFilter that applies headers conditionally based on configuration and existing response headers. |
| grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfiguration.java | Adds servlet-only auto-config with conditional registration and a FilterRegistrationBean for ordering. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
The proposed change to move header application into a grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## 8.0.x #15967 +/- ##
==================================================
+ Coverage 57.4441% 57.6152% +0.1710%
- Complexity 22558 22700 +142
==================================================
Files 2129 2133 +4
Lines 103840 104226 +386
Branches 18646 18692 +46
==================================================
+ Hits 59650 60050 +400
+ Misses 35929 35888 -41
- Partials 8261 8288 +27
🚀 New features to boost your workflow:
|
The Copilot suggestion to apply the headers in a post-chain finally block would skip every security header on responses that commit during the chain (sendRedirect, sendError, flushBuffer, streaming), which is exactly where the headers are needed. Keep applying the headers eagerly before the filter chain (values already present still win, explicit downstream setHeader still replaces) and add a regression test proving the headers are present on a redirect-committed response. Assisted-by: Sisyphus:openai/gpt-5.6-terra [gpt-coding]
OncePerRequestFilter.shouldNotFilterErrorDispatch() defaults to true, so the filter was skipped on ERROR redispatches even though the ERROR dispatcher type is registered, leaving error responses without the security headers. Override it to return false and cover the behavior with a DispatcherType.ERROR test. Assisted-by: Sisyphus:openai/gpt-5.6-terra [gpt-coding]
Review feedback addressedMerged the latest Copilot review comment - apply headers in a
Follow-up (documented, not changed here): when the optional Spring Security plugin is installed, its header writers skip headers already present, so eagerly-set Grails defaults can win over a Spring-Security-configured policy. The robust fix is an on-commit response wrapper that fills only-missing headers after downstream writers run; that is a larger change and Spring Security is an optional plugin, so I left it as a follow-up rather than expand this starter filter's scope. Local verification: |
jdaugherty
left a comment
There was a problem hiding this comment.
Took a look at this with reverse-proxy deployments (nginx/haproxy) in mind, since that's how most production Grails apps run. A few concerns inline — the common thread is that the containsHeader guard only protects against headers set inside the servlet container, but in real deployments these headers are frequently owned by the edge proxy or by Spring Security, and in both cases the current behavior is surprising.
|
The reverse proxy scenarios are real regressions that need addressed. |
Assisted-by: opencode:gpt-5.6-sol
… gaps
Addresses jdaugherty's 3 unresolved review findings, all confirmed
against the current code before fixing:
- Spring Security precedence (verified inverted doc claim): this filter
registers at GrailsFilters.LAST (order -110), before Spring Security's
chain (-100), and applied its defaults eagerly - so Spring Security's
header writers (which skip a header that's already present) never got
a chance to win, contrary to what the upgrade notes claimed. Fixed by
adding @ConditionalOnMissingClass("...HeaderWriterFilter") to
GrailsSecurityHeadersAutoConfiguration so the whole auto-configuration
backs off when Spring Security's header-writing infrastructure is on
the classpath, per jdaugherty's suggested option - Spring Security
already ships its own configurable header defaults. Added a
spring-security-web test-only dependency and a
FilteredClassLoader-based helper so the existing "Spring Security
absent" tests keep exercising that path explicitly, plus a new test
confirming the back-off.
- HSTS silently never sent behind a TLS-terminating reverse proxy
(request.isSecure() is false unless server.forward-headers-strategy
is configured): this isn't a code bug - request.isSecure() is the
correct check, and Spring Boot's forward-headers-strategy is the
standard way to make it proxy-aware - so documented the proxy case
and the mitigation in the security guide instead of changing behavior.
- Reverse-proxy header duplication (nginx add_header appends rather than
replaces, so the client can receive a header twice once the app also
sends it): also not something a code change here can generally detect
or fix, since the proxy operates entirely outside the request
pipeline. Documented the risk (with the concrete Chrome/CSP/
Referrer-Policy duplicate-header failure modes jdaugherty identified)
and the mitigation (disable the affected header(s) at the app and let
the proxy own them, or strip the app's copy at the proxy).
Co-Authored-By: Claude Sonnet 5 <[email protected]>
jdaugherty
left a comment
There was a problem hiding this comment.
Re-reviewed after the latest push. The three reverse-proxy / Spring Security findings from the previous round are still open: two of them were addressed with documentation only, and the one code change (backing off on HeaderWriterFilter class presence) removes headers from the largest group of users this feature is meant to protect. Details inline. The short version of what I think the fix needs to be:
- Write the headers at commit time via a response wrapper (the same pattern Spring Security's
HeaderWriterFilteruses) instead of eagerly before the chain, and drop the@ConditionalOnMissingClassback-off. That lets any later writer win and still covers redirects,sendError, and streaming responses. - Make HSTS forwarded-proto aware when
request.isSecure()is false. - Detect that a request arrived through a reverse proxy and, by default, apply only explicitly configured headers in that case, so proxy-managed deployments do not double-send on upgrade.
Documentation alone is not a fix for on-by-default behavior that changes what existing deployments send to browsers.
|
I'm going to make pass at fixing this PR |
Backing the auto-configuration off whenever Spring Security's HeaderWriterFilter was on the classpath removed the default headers for every Grails Spring Security user: the plugin never registers a header writer (it only reserves SecurityFilterPosition.HEADERS_FILTER) yet exposes spring-security-web as an api dependency, so those applications ended up with no security headers from either side. The condition also sat on the whole auto-configuration, so explicitly configured values were silently ignored in the same situation. Replace the eager, before-chain header writes with a response wrapper that fills still-missing headers immediately before the response commits (redirect, error, buffer flush, writer or stream flush/close, declared Content-Length reached) or when the chain returns. Anything set downstream - a controller, an interceptor, another filter, or Spring Security's writers - now wins regardless of filter order, so the classpath back-off is removed. Honor the forwarded scheme for HSTS when the container saw plain HTTP behind a TLS-terminating proxy: X-Forwarded-Proto and the RFC 7239 Forwarded proto parameter are consulted as a fallback. This is safe without a trust configuration because user agents ignore Strict-Transport-Security received over a non-secure transport (RFC 6797 section 8.1). Detect requests relayed through a reverse proxy and, by default, send only explicitly configured headers for them so proxy-managed deployments do not start double-sending headers on upgrade (nginx add_header appends rather than replaces). Detection uses the Forwarded, X-Forwarded-For, X-Forwarded-Proto, X-Forwarded-Host, Via and X-Real-IP request headers, a configured server.forward-headers-strategy (the forwarding filter or valve strips those request headers before this filter sees them), or an active Spring Boot CloudPlatform. The new grails.security.headers.defaults setting (auto, always, never) controls this; explicitly configured headers are always applied, and a single INFO log line explains when defaults are withheld. Tests cover downstream and Spring Security precedence, every commit path, forwarded-scheme HSTS, each proxy signal, the defaults modes, configuration binding of explicit headers, and the environment-driven proxy detection in the auto-configuration. The security guide and 8.0 upgrade notes describe the behavior and the new setting.
|
@jamesfredley I've adjusted this PR so it supports reverse proxies the way Spring does. Can you please take a look so I know if we can merge? |
codeconsole
left a comment
There was a problem hiding this comment.
Checked the commit-time wrapper against a real container (the filter in front of a servlet on embedded Tomcat 11.0.26). Two commit paths still drop the headers, and at its current order the filter never sees asset-pipeline responses. Details inline; the two wrapper suggestions were verified in that run.
Two things outside the diff:
grails-doc/src/en/guide/introduction/whatsNew.adocneeds an entry. This changes the headers every servlet app sends by default, so it should appear there as well as in the upgrade notes.- The new public classes (
GrailsSecurityHeadersFilter,GrailsSecurityHeadersProperties,GrailsSecurityHeadersAutoConfiguration) need@since 8.0in their class Javadoc, asGrailsHiddenHttpMethodFilterAutoConfigurationhas.
…rst, default to always Running the filter against embedded Tomcat showed two commit paths the response wrapper missed. With no Content-Length and no explicit flush the container commits as soon as the body outgrows getBufferSize() (8 KB by default), so large JSON responses, downloads and any page not buffered by SiteMesh went out without the headers. And PrintWriter.println() writes the line separator to the underlying writer through its private newLine(), bypassing the write overrides, so a declared Content-Length reached through println was never seen. The wrapper now fires when the count reaches the buffer size as well as the declared length, checks a declared length at once in case the body was written first, counts println's separator, and tracks a Content-Length declared through setIntHeader/addIntHeader. Register the filter at GrailsFilters.FIRST instead of LAST. Commit-time writers nest and the innermost fires first, so only the outermost one is the gap filler: at LAST (-110) the Grails wrapper wrote SAMEORIGIN before an XFrameOptionsHeaderWriter placed ahead of it (spring.security.filter.order below -110) could run, and the asset-pipeline filter at -190, which streams assets and flushes without continuing the chain, never reached the filter at all, so /assets/** carried no nosniff. Default grails.security.headers.defaults to always. Every load balancer, ingress and platform router adds X-Forwarded-For, and every Kubernetes pod is detected as a cloud platform, so with auto the defaults were sent only to direct requests, which in practice meant local development. Duplicates of the four default headers are benign or stricter (nosniff twice is nosniff, conflicting X-Frame-Options blocks framing, Referrer-Policy resolves to the proxy's appended token, no browser implements X-XSS-Protection), and CSP, where duplicates do hurt, is never sent unless configured. auto remains the opt-in for proxies that own these headers. Add GrailsSecurityHeadersFilterTomcatSpec, which runs the filter on embedded Tomcat and asserts the headers on the wire for bodies that outgrow the buffer through the output stream and the writer, a Content-Length reached by println, a redirect, sendError, and a response served by an inner filter that never continues the chain. The Spring mocks accept header writes after commit, so they cannot catch these; mock-based tests still cover each commit path, the registration order, Spring Security ordered ahead of the filter, and the three defaults modes. Document the entry in whatsNew, reword the upgrade note and security guide for the new default and ordering, and add @SInCE 8.0 to the public classes.
…cument Spring Security ordering The response wrapper now re-arms its commit callback on reset() and restarts its content tracking on resetBuffer(), so a response replaced by an error handler after the headers were written still receives them. The buffer size is read once and refreshed only by setBufferSize(), reset() or resetBuffer(). The auto-configuration also backs off when the application declares a FilterRegistrationBean<GrailsSecurityHeadersFilter> under any bean name, for both the raw filter bean and the Grails registration, so a user registration is never duplicated at GrailsFilters.FIRST on /*. The filter honors grails.security.headers.enabled when constructed directly, warns once when an enabled header has a blank value, reads the forwarded scheme through Spring's ForwardedHeaderUtils, and only resolves the scheme when HSTS is enabled. The docs and javadoc no longer claim that Spring Security's header writers win wherever the chain is ordered, or that the filter runs first in the servlet chain. They describe the default-order behavior, the case where the Security chain is ordered ahead of GrailsFilters.FIRST, and the Boot filters that run outside the Grails filter.
|
Reviewed at head What I ran locally:
The commit-time wrapper, the move to 1. With HSTS enabled, URLs Tomcat accepts but
|
… the request URL The response wrapper compared writer output, counted in characters, against the container's buffer and Content-Length, which are both in bytes. Three-byte UTF-8 text therefore filled and committed an enlarged buffer before the callback fired, and the headers were dropped. Tomcat keeps an enlarged buffer on the recycled processor, so later requests were affected even on new connections. Writer output is now counted as its encoded length: exactly for UTF-8 and single-byte encodings, and at the encoding's maximum bytes per character otherwise. HSTS resolved the forwarded scheme through ServletServerHttpRequest.getURI(), which throws for request paths that java.net.URI rejects but Tomcat accepts through relaxedPathChars, turning those requests into 500s. The forwarded headers are now applied to the request's scheme alone. The upgrade note moves to its own section, the explicit-configuration wording in the security guide matches the behavior, and the docs no longer place the Grails character-encoding filter outside the security headers filter. REVERSE_PROXY_REQUEST_HEADERS is no longer public API. The Tomcat spec checks every default header value, covers multi-byte writer output, and uses @tempdir.
Addressed: headers are written at commit time from GrailsFilters.FIRST, so Spring Security header writers at the default filter order win; HSTS honors the forwarded scheme behind a TLS-terminating proxy; and grails.security.headers.defaults (auto/never) covers proxy-managed deployments.
|
@matrei thanks, both behaviour findings reproduced on embedded Tomcat and are fixed in 8da7b05.
|
|
Re-reviewed at head What I ran locally:
Everything from the last round is addressed, and I have nothing blocking. Both behaviour problems are fixed on the wire. The PR description now matches the code. One optional nit is below. Re-run of the previous findingsRelaxed path chars ( Writer output with Nit (optional)
Verified as correct
|
|
Once @codeconsole approves, we can merge this. |
codeconsole
left a comment
There was a problem hiding this comment.
Re-ran my Tomcat probes at 8da7b05c58. Everything I raised is fixed on the wire:
case ee6be46 8da7b05
50 KB body, OutputStream, no Content-Length <missing> sent
50 KB body, getWriter(), no Content-Length <missing> sent
setContentLength(3) + println('hi') <missing> sent
direct request, KUBERNETES_SERVICE_HOST/PORT set <missing> sent
request with X-Forwarded-For <missing> sent
I also read through the byte counting, the reset() re-arming, the typed-registration condition and the ForwardedHeaderUtils scheme resolution, and found nothing blocking. Two optional nits inline.
The one failing check, the Groovy snapshot canary, failed to download Gradle 8.14.4 (HTTP 500 from GitHub) and doesn't run this PR's code.
…warded header catch The response wrapper now hands back the same writer and output stream on every call, as the container does, instead of building a new wrapper (and resolving the charset again) each time. reset() drops the cached writer, since the character encoding can change after a reset. The HSTS scheme resolution catch covers any malformed forwarded header, not only a non-numeric port; the comment and the test now say so.
🚨 All tests passed but jobs failed 🚨Failed Jobs without Test Failures❌ CI / Build Grails-Core (Windows JDK 25 shard 1) 🏷️ Commit: 63aaf3d Rerun ControlsClick the checkbox to trigger a rerun: 🔲 Rerun jobs Learn more about TestLens at testlens.app/docs. |
Apache Grails tagged 8.0.0-RC2 on 2026-09-29. RC1 has since been promoted to Maven Central, but RC2 is again in the ASF staging group only while its release vote runs, so the TEMP staging-repository entries in build.gradle stay and their comments are retargeted at RC2. RC2's BOM keeps Spring Boot 4.1.1 and Groovy 5.1.3; the cloud.wondrify asset-pipeline plugin follows the BOM to 5.2.0-RC3 (on Maven Central). RC2 itself is built on Gradle 9.8.0, the current release, so the wrapper moves from 9.7.1 to 9.8.0 to stay on the combination Grails tests. This is alignment rather than a requirement: RC2 still assembles on 9.7.1. .gitlab-ci.yml moves to bbb-build:grails-8--2026-10-02-140644, rebuilt today with the Grails 8.0.0-RC2 CLI. It also picks up the toolchain the current v4.0.x-release image has (Go 1.27.0, Node 22.23.2), which the previous grails-8 image predated. Behavior change that comes with RC2 (apache/grails-core#15967): Grails now sends browser-hardening headers on every response by default, so every bbb-web response gains X-Content-Type-Options: nosniff X-Frame-Options: SAMEORIGIN Referrer-Policy: strict-origin-when-cross-origin X-XSS-Protection: 0 The defaults are left in place. Joining through a cross-origin iframe keeps working: the join call answers with a redirect, and the framed document is the client served by nginx, which carries no such header. What changes is that a document rendered by bbb-web itself (for example the XML of /bigbluebutton/api) is no longer displayed inside a cross-origin frame. A deployment that needs that can opt out per header in /etc/bigbluebutton/bbb-web.properties, e.g. grails.security.headers.frame-options.enabled=false. Checked, nothing to do: the RC2 JSON date/time rendering change (apache/grails-core#16411) concerns grails.converters.JSON and JSON views, while bbb-web builds its JSON with groovy.json.JsonBuilder and ships no gson views; the link-resolution change (apache/grails-core#16272) has nothing to act on, bbb-web's only generated link is one redirect(action:). Verified together with the Tomcat pin in the next commit.
Add bbbWebSecurityHeaders (@ci). It requests three kinds of bbb-web response - a document (GET /api), the join redirect, and an error (404 for an unmapped URL) - and expects each to carry X-Frame-Options: SAMEORIGIN X-Content-Type-Options: nosniff Referrer-Policy: strict-origin-when-cross-origin X-XSS-Protection: 0 Since 8.0.0-RC2 Grails adds these browser-hardening headers to every response by default (apache/grails-core#15967); bbb-web on Grails 7 sent none of them. We keep the Grails defaults, and this test pins that decision: a later change in Grails, in bbb-web's packaged configuration or a site opt-out leaking into the defaults shows up in CI instead of going unnoticed. On a 4.0.0-rc.5 server the test fails against the stock Grails 7 bbb-web (no headers) and against this branch with grails.security.headers.frame-options.enabled=false (no X-Frame-Options), and passes against this branch as it is.
…rails 8 Two defaults change with the Grails 8 / Spring Boot 4.1 stack; 3.0 keeps the behaviour it has on Grails 7: - grails.security.headers.enabled=false. Grails 8 adds X-Frame-Options: SAMEORIGIN, X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin and X-XSS-Protection: 0 to every response (apache/grails-core#15967). The visible effect is that pages bbb-web renders itself can no longer be shown in a frame on another origin; joining through an LMS frame is not affected. A site can turn them on with grails.security.headers.enabled=true in /etc/bigbluebutton/bbb-web.properties (checked). - server.tomcat.max-parameter-count=10000. Spring Boot 4.1 lowered the default to 1000, and Tomcat 11 answers a request with more parameters (query string plus form body) with HTTP 500 instead of dropping the extras. With the setting, 1200 form parameters work as before. On a 3.0 -> 4.0 forward merge, the headers line stays out of 4.0, which keeps the Grails defaults (4.0's bbbWebSecurityHeaders test would fail otherwise). 4.0 gets the same parameter limit.
Description
Grails servlet applications did not send common browser-hardening response headers by default. This adds a filter that sends a baseline set on every response, with per-header opt-out and overrides.
Behaviour
X-Content-Type-Options: nosniff,X-Frame-Options: SAMEORIGIN,Referrer-Policy: strict-origin-when-cross-origin,X-XSS-Protection: 0Forwarded,X-Forwarded-ProtoorX-Forwarded-Ssl(read the way Spring'sForwardedHeaderFilterreads them)sendRedirect,sendError,flushBuffer, writer and streamflush/close, a declaredContent-Lengthbeing reached (including throughprintln), and the response buffer filling (writer output counted in encoded bytes). Areset()re-arms the headers for the replacement responseGrailsFilters.FIRST, the outermost Grails filter, so responses that other Grails filters serve without continuing the chain (asset-pipeline assets) are covered toograils.security.headers.defaults:always(default);autowithholds the built-in defaults on requests detected as proxied (forwarded request headers,server.forward-headers-strategy, or an active cloud platform) while still sending explicitly configured headers;neversends only explicitly configured headersgrails.security.headers.enabled,grails.security.headers.defaults, andenabled/valuefor each headerGrailsSecurityHeadersFilterbean, a bean namedgrailsSecurityHeadersFilter, or aFilterRegistrationBean<GrailsSecurityHeadersFilter>The filter stays active when Spring Security is on the classpath. The Grails Spring Security plugin does not register a
HeaderWriterFilter, so these are the only security headers its users get by default.Tests
GrailsSecurityHeadersAutoConfigurationSpec: auto-configuration and back-off conditions, defaults and overrides, every commit path, Spring Security'sHeaderWriterFilteron both sides of the filter, forwarded-scheme HSTS, and thedefaultsmodes.GrailsSecurityHeadersFilterTomcatSpec: runs the filter on embedded Tomcat, because the Spring mocks accept header writes after the response has committed. Covers buffer-full commits (output stream, writer, and multi-byte writer output),Content-Lengthreached throughprintln, redirects,sendError,reset, and a filter that serves the response without continuing the chain.Documentation
defaultsmodes.Out of scope
Permissions-PolicydefaultsContributor Checklist
Issue and Scope
8.0.x.Code Quality
Licensing and Attribution
ai-generated-starting-pointlabel applied.Documentation
Assisted-by: Sisyphus:xai/grok-4.5 [gpt-coding]