From d1170498f5696286ff6247a5c249ec78ac104fcd Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 09:10:21 -0800
Subject: [PATCH 01/78] Upgrade to Spring Boot 4.2.0-RC2
---
dependencies.gradle | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/dependencies.gradle b/dependencies.gradle
index 93aacfae836..69d22b29664 100644
--- a/dependencies.gradle
+++ b/dependencies.gradle
@@ -39,7 +39,7 @@ ext {
'jna.version' : '5.19.1',
'maven-model.version' : '3.9.16',
'objenesis.version' : '3.6',
- 'spring-boot.version' : '4.2.0-RC1',
+ 'spring-boot.version' : '4.2.0-RC2',
]
// Note: the name of the dependency must be the prefix of the property name so properties in the pom are resolved correctly
From 991a702a803e264d23195aab698c8d0ab49e4b13 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 09:10:38 -0800
Subject: [PATCH 02/78] Describe the Jackson pins against Spring Boot 4.2.0-RC2
Spring Boot 4.2.0-RC2 manages Jackson 3.1.8 and 2.21.8. No advisory
published since 3.2.3 and 2.22.3 affects either pin, so Jackson 2 stays at
2.22.3, which Groovy YAML 6.0.0 needs, and Jackson 3 stays at 3.2.3, so
that moving to Spring Boot 4.2 does not take it from the 3.2 line back to
3.1.
---
dependencies.gradle | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/dependencies.gradle b/dependencies.gradle
index 69d22b29664..e0c2953dbe3 100644
--- a/dependencies.gradle
+++ b/dependencies.gradle
@@ -86,15 +86,15 @@ ext {
'groovy.version' : '6.0.0',
// Security: 33.7.2 addresses CVE-2026-102554 (uncontrolled resource consumption).
'guava.version' : '33.7.2-jre',
- // Groovy YAML 6.0.0 depends on Jackson 2.22.2, which wins over the 2.21.7 Spring Boot 4.2
+ // Groovy YAML 6.0.0 depends on Jackson 2.22.2, which wins over the 2.21.8 Spring Boot 4.2
// manages, so the BOM must manage at least that. Jackson 2 only releases
// jackson-annotations on the minor, hence the separate 2.22 below.
'jackson-2-bom.version' : '2.22.3',
'jackson2-annotations.version' : '2.22',
- // Overrides the 3.1.7 Spring Boot 4.2 manages. Pinned first as a security override of
+ // Overrides the 3.1.8 Spring Boot 4.2 manages. Pinned first as a security override of
// 3.1.6 (CVE-2026-89425, CVE-2026-89407, CVE-2026-91777 and CVE-2026-91776), which 3.1.7
- // also fixes; kept so that moving to Spring Boot 4.2 does not take Jackson 3 from the 3.2
- // line Grails 8 and 9.0 manage back to 3.1.
+ // and later also fix; kept so that moving to Spring Boot 4.2 does not take Jackson 3 from
+ // the 3.2 line Grails 8 and 9.0 manage back to 3.1.
'jackson-bom.version' : '3.2.3',
'jquery.version' : '4.0.0',
'nimbus-jose-jwt.version' : '10.10',
@@ -187,7 +187,7 @@ ext {
'groovy-xml' : "org.apache.groovy:groovy-xml:${bomDependencyVersions['groovy.version']}",
'groovy-yaml' : "org.apache.groovy:groovy-yaml:${bomDependencyVersions['groovy.version']}",
'guava' : "com.google.guava:guava:${bomDependencyVersions['guava.version']}",
- // Overrides the 2.21.7 spring-boot-dependencies imports through
+ // Overrides the 2.21.8 spring-boot-dependencies imports through
// com.fasterxml.jackson:jackson-bom - see jackson-2-bom.version. groovy-yaml 6.0.0
// also pulls jackson-dataformat-yaml, so the BOM must manage it at >= the resolved version.
'jackson2-annotations' : "com.fasterxml.jackson.core:jackson-annotations:${bomDependencyVersions['jackson2-annotations.version']}",
@@ -195,7 +195,7 @@ ext {
'jackson-2-bom-databind' : "com.fasterxml.jackson.core:jackson-databind:${bomDependencyVersions['jackson-2-bom.version']}",
'jackson-2-bom-dataformat-yaml': "com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:${bomDependencyVersions['jackson-2-bom.version']}",
'jackson-2-bom-datatype-jsr310': "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:${bomDependencyVersions['jackson-2-bom.version']}",
- // Override of the 3.1.7 spring-boot-dependencies imports through
+ // Override of the 3.1.8 spring-boot-dependencies imports through
// tools.jackson:jackson-bom - see jackson-bom.version
'jackson-bom-core' : "tools.jackson.core:jackson-core:${bomDependencyVersions['jackson-bom.version']}",
'jackson-bom-databind' : "tools.jackson.core:jackson-databind:${bomDependencyVersions['jackson-bom.version']}",
From d67b11b03b8b8d76d0fa8fcb93cc60504b4f814a Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 09:10:47 -0800
Subject: [PATCH 03/78] Describe the CVE-2026-47842 exclusion against Spring
Boot 4.2.0-RC2
Spring Boot 4.2.0-RC2 still manages Spring Security 7.2.0-RC1, which the
advisory does not list and which carries the 7.1.1 fix.
---
.../apache/grails/buildsrc/scan/VulnerabilityScanPlugin.groovy | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/build-logic/vulnerability-scan/src/main/groovy/org/apache/grails/buildsrc/scan/VulnerabilityScanPlugin.groovy b/build-logic/vulnerability-scan/src/main/groovy/org/apache/grails/buildsrc/scan/VulnerabilityScanPlugin.groovy
index 14134673dfc..f7fffef5cb3 100644
--- a/build-logic/vulnerability-scan/src/main/groovy/org/apache/grails/buildsrc/scan/VulnerabilityScanPlugin.groovy
+++ b/build-logic/vulnerability-scan/src/main/groovy/org/apache/grails/buildsrc/scan/VulnerabilityScanPlugin.groovy
@@ -97,7 +97,7 @@ class VulnerabilityScanPlugin implements Plugin {
'CVE-2026-22747. Remove once Sonatype narrows its affected range'),
new VulnerabilityExclusion('CVE-2026-47842', 'org.springframework.security:spring-security-crypto',
'Sonatype flagged 7.1.1, but https://spring.io/security/cve-2026-47842 lists only 7.1.0 on ' +
- 'the 7.1 line as affected and 7.1.1 as fixed. Spring Boot 4.2.0-RC1 manages 7.2.0-RC1, which ' +
+ 'the 7.1 line as affected and 7.1.1 as fixed. Spring Boot 4.2.0-RC2 manages 7.2.0-RC1, which ' +
'the advisory does not list and which carries the fix (the AesCbcBytesEncryptor and ' +
'AesGcmBytesEncryptor replacements 7.1.1 introduced). Remove once Sonatype corrects its ' +
'affected range; reassess on any Spring Security upgrade'),
From 892459346c58e5b1df95042b63394cdbca65aa8f Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 09:13:54 -0800
Subject: [PATCH 04/78] Drop the json-smart CVE-2026-113602 exclusion now that
Spring Boot manages 2.6.1
Spring Boot 4.2.0-RC2 manages json-smart 2.6.1, which rejects a literal
0x1A after the value in strict mode (netplex/json-smart-v2#305). That
fixes CVE-2026-113602, so the exclusion's removal condition, a patched
release, is met.
---
.../grails/buildsrc/scan/VulnerabilityScanPlugin.groovy | 4 ----
1 file changed, 4 deletions(-)
diff --git a/build-logic/vulnerability-scan/src/main/groovy/org/apache/grails/buildsrc/scan/VulnerabilityScanPlugin.groovy b/build-logic/vulnerability-scan/src/main/groovy/org/apache/grails/buildsrc/scan/VulnerabilityScanPlugin.groovy
index f7fffef5cb3..6b146735914 100644
--- a/build-logic/vulnerability-scan/src/main/groovy/org/apache/grails/buildsrc/scan/VulnerabilityScanPlugin.groovy
+++ b/build-logic/vulnerability-scan/src/main/groovy/org/apache/grails/buildsrc/scan/VulnerabilityScanPlugin.groovy
@@ -83,10 +83,6 @@ class VulnerabilityScanPlugin implements Plugin {
'and no fixed release exists. A long pause can terminate the pause-detector dispatch thread ' +
'and leave its queue growing, see https://github.com/LatencyUtils/LatencyUtils/issues/22. ' +
'Remove once a patched release is available or micrometer no longer requires LatencyUtils'),
- new VulnerabilityExclusion('CVE-2026-113602', 'net.minidev:json-smart',
- 'Managed by spring-boot-dependencies; every release through 2.6.0, the newest, is affected and ' +
- 'no fixed release exists. Strict-mode parsing accepts a trailing 0x1A character. Remove ' +
- 'once a patched release ships'),
new VulnerabilityExclusion('CVE-2026-110974', 'com.vaadin.external.google:android-json',
'Pulled transitively via spring-boot-cli; com.vaadin.external.google:android-json is unmaintained ' +
'and 0.0.20131108.vaadin1, its newest release, is affected. Remove once spring-boot-cli no ' +
From cdf0aa6d40712dc391a9cbf303660b176091cd67 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 09:16:50 -0800
Subject: [PATCH 05/78] Manage ASM 9.11.1, which json-smart 2.6.1 depends on
Spring Boot 4.2.0-RC2 manages json-smart 2.6.1, whose accessors-smart
2.6.1 depends on ASM 9.11.1. That wins over the 9.10.1 the BOM managed,
and validateDependencyVersions failed for every project with json-smart on
its classpath, such as the gsp-spring-boot and scaffolding test examples.
---
dependencies.gradle | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/dependencies.gradle b/dependencies.gradle
index e0c2953dbe3..13a1eaa380d 100644
--- a/dependencies.gradle
+++ b/dependencies.gradle
@@ -25,7 +25,7 @@ ext {
'ant.version' : '1.10.18',
'asciidoctor-gradle-jvm.version': '4.0.5',
'asciidoctorj.version' : '3.0.1',
- 'asm.version' : '9.10.1',
+ 'asm.version' : '9.11.1',
'asset-pipeline-gradle.version' : '5.2.3',
'commons-text.version' : '1.15.0',
'directory-watcher.version' : '0.19.1',
From 8731c9a803ff62cb8964522fc4051d068bfac43a Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 09:21:08 -0800
Subject: [PATCH 06/78] Re-declare Hibernate 7 at the 7.4.14.Final Spring Boot
manages
Spring Boot 4.2.0-RC2 manages Hibernate ORM 7.4.14.Final. The Hibernate 7
BOM strictly re-declares Spring Boot's version so that enforcedPlatform
consumers are forced to it, and was still at RC1's 7.4.13.Final. 7.4.14
depends on the same hibernate-models 1.1.2, so that pin does not move.
---
dependencies.gradle | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/dependencies.gradle b/dependencies.gradle
index 13a1eaa380d..639559ddf19 100644
--- a/dependencies.gradle
+++ b/dependencies.gradle
@@ -326,7 +326,7 @@ ext {
// platform() import is not enforced.
'hibernate-models.version' : '1.1.2',
'hibernate-tools.version' : '7.3.13.Final',
- 'hibernate.version' : '7.4.13.Final',
+ 'hibernate.version' : '7.4.14.Final',
'jandex.version' : '3.6.0',
'liquibase-test-harness.version': '1.0.11',
'liquibase.version' : '4.27.0', // liquibase-hibernate5 stops at 4.27.0, and Spring Boot's Liquibase 5.0.4 is a new major.
From 3a48ce0bfb9b87cddad2abd3e2b5666af5d318d0 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 09:52:47 -0800
Subject: [PATCH 07/78] Manage Hibernate ORM 7 at the version Spring Boot
manages
The Hibernate 7 BOM pinned Hibernate ORM in dependencies.gradle, so every
Spring Boot upgrade that moved Hibernate needed a matching manual bump, and
a forgotten one held the BOM back.
grails-hibernate7-bom now reads the version spring-boot-dependencies
manages for hibernate-core and strictly re-declares hibernate-core,
hibernate-envers and hibernate-jcache at it, under Spring Boot's
hibernate.version, so enforcedPlatform consumers are still forced to it.
The published POM is unchanged apart from the order of those entries.
When Spring Boot lags behind a Hibernate ORM 7 release Grails needs,
hibernate7VersionOverride in dependencies.gradle manages that release
instead. The build fails while the override is not newer than Spring
Boot's version, so it cannot silently downgrade Hibernate once Spring Boot
catches up.
hibernate-models is strictly re-declared too, and now moves without anyone
editing the Hibernate block, so the build also fails when
hibernate-models.version differs from the version the managed Hibernate
ORM release depends on.
---
.agents/skills/gradle-developer/SKILL.md | 1 +
dependencies.gradle | 18 +++++----
grails-bom/hibernate7/build.gradle | 47 ++++++++++++++++++++++++
3 files changed, 59 insertions(+), 7 deletions(-)
diff --git a/.agents/skills/gradle-developer/SKILL.md b/.agents/skills/gradle-developer/SKILL.md
index cb53a930ea4..6748a85a995 100644
--- a/.agents/skills/gradle-developer/SKILL.md
+++ b/.agents/skills/gradle-developer/SKILL.md
@@ -366,6 +366,7 @@ A module the parent manages through an imported BOM belongs to the property the
3. Use the unversioned coordinate in module `dependencies {}`.
4. Run `./gradlew :that-module:validateDependencyVersions` (and affected consumers).
5. Security overrides: comment with CVE and previous Boot version (see existing httpcore5/jackson/logback pins).
+6. Hibernate ORM 7 has no pin: `grails-hibernate7-bom` reads the version `spring-boot-dependencies` manages and strictly re-declares `hibernateOrmModules` at it. To move ahead of a Spring Boot that lags behind, set `hibernate7VersionOverride` in `dependencies.gradle`; the build fails while it is not newer than Spring Boot's version, so a Boot bump that catches up forces its removal. The build also fails when `hibernate-models.version` differs from the version the managed Hibernate ORM release depends on.
### Exclusions
diff --git a/dependencies.gradle b/dependencies.gradle
index 639559ddf19..40a827d0c79 100644
--- a/dependencies.gradle
+++ b/dependencies.gradle
@@ -262,8 +262,8 @@ ext {
// Drift tripwire for extended-scalars compatibility on later Boot graphql-java bumps,
// not an equal-version upgrade of extended-scalars - see graphql-java.version.
'graphql-java.version',
- // The Hibernate 7 BOM strictly re-declares the version so enforcedPlatform consumers are
- // forced to it, so the pin stays even when it matches the version Spring Boot manages.
+ // The Hibernate 7 BOM strictly re-declares the version Spring Boot manages, so that
+ // enforcedPlatform consumers are forced to it - see hibernate7VersionOverride.
'hibernate.version',
]
@@ -317,16 +317,23 @@ ext {
]
combinedDependencies += customBomDependencies
} else if (project.name in ['grails-hibernate7-bom'] || project.name.startsWith('grails-data-hibernate7')) {
+ // Hibernate ORM follows the version spring-boot-dependencies manages. grails-hibernate7-bom reads it
+ // from there and re-declares these modules at it, strictly, under Spring Boot's hibernate.version.
+ hibernateOrmModules = ['hibernate-core', 'hibernate-envers', 'hibernate-jcache']
+ // A Hibernate ORM 7 release to manage instead, for when Spring Boot lags behind one Grails needs.
+ // It must be newer than the version Spring Boot manages, so the build fails once Spring Boot
+ // catches up with it: remove it then.
+ hibernate7VersionOverride = null
customBomVersions = [
'cache-ri-impl.version' : '1.1.1',
'derby.version' : '10.17.1.0',
// Spring Boot 4.2 can select Hibernate ORM 7.4.x through Spring Dependency
// Management, and Hibernate ORM 7.4.x requires hibernate-models 1.1.x. This BOM
// strictly re-declares the version so enforcedPlatform consumers are forced to it; a
- // platform() import is not enforced.
+ // platform() import is not enforced. grails-hibernate7-bom fails the build when it
+ // differs from the version the managed Hibernate ORM release depends on.
'hibernate-models.version' : '1.1.2',
'hibernate-tools.version' : '7.3.13.Final',
- 'hibernate.version' : '7.4.14.Final',
'jandex.version' : '3.6.0',
'liquibase-test-harness.version': '1.0.11',
'liquibase.version' : '4.27.0', // liquibase-hibernate5 stops at 4.27.0, and Spring Boot's Liquibase 5.0.4 is a new major.
@@ -339,9 +346,6 @@ ext {
'derbyclient' : "org.apache.derby:derbyclient:${combinedVersions['derby.version']}",
'derbyshared' : "org.apache.derby:derbyshared:${combinedVersions['derby.version']}",
'derbytools' : "org.apache.derby:derbytools:${combinedVersions['derby.version']}",
- 'hibernate-core' : "org.hibernate.orm:hibernate-core:${combinedVersions['hibernate.version']}",
- 'hibernate-envers' : "org.hibernate.orm:hibernate-envers:${combinedVersions['hibernate.version']}",
- 'hibernate-jcache' : "org.hibernate.orm:hibernate-jcache:${combinedVersions['hibernate.version']}",
'hibernate-models' : "org.hibernate.models:hibernate-models:${combinedVersions['hibernate-models.version']}",
'hibernate-tools-orm' : "org.hibernate.tool:hibernate-tools-orm:${combinedVersions['hibernate-tools.version']}",
'hibernate-tools-utils' : "org.hibernate.tool:hibernate-tools-utils:${combinedVersions['hibernate-tools.version']}",
diff --git a/grails-bom/hibernate7/build.gradle b/grails-bom/hibernate7/build.gradle
index ca629ae6704..c6a8be10a78 100644
--- a/grails-bom/hibernate7/build.gradle
+++ b/grails-bom/hibernate7/build.gradle
@@ -17,6 +17,8 @@
* under the License.
*/
+import org.apache.grails.buildsrc.ParentBomVersions
+import org.apache.grails.buildsrc.PomVersions
import org.apache.grails.gradle.tasks.bom.ExtractDependenciesTask
import org.apache.grails.gradle.tasks.bom.ExtractedDependencyConstraint
import org.apache.grails.gradle.tasks.bom.PropertyNameCalculator
@@ -53,6 +55,51 @@ ext {
]
}
+def pomFile = { String coordinates ->
+ Configuration pom = configurations.detachedConfiguration(dependencies.create("${coordinates}@pom"))
+ pom.transitive = false
+ pom.singleFile
+}
+
+// Hibernate ORM follows the version spring-boot-dependencies manages, unless dependencies.gradle sets
+// hibernate7VersionOverride to a newer release
+String springBootHibernateVersion = ParentBomVersions.resolve(parentBoms, pomFile).versions['org.hibernate.orm:hibernate-core']
+if (!springBootHibernateVersion) {
+ throw new GradleException("${parentBoms.join(', ')} does not manage org.hibernate.orm:hibernate-core: " +
+ 'set hibernate7VersionOverride in dependencies.gradle to the Hibernate ORM 7 release to manage')
+}
+String hibernateVersion = springBootHibernateVersion
+if (hibernate7VersionOverride) {
+ // Gradle's conflict resolution selects the newer of two requested versions, by its own version ordering
+ Configuration bothVersions = configurations.detachedConfiguration(
+ dependencies.create("org.hibernate.orm:hibernate-core:${hibernate7VersionOverride}"),
+ dependencies.create("org.hibernate.orm:hibernate-core:${springBootHibernateVersion}"))
+ bothVersions.transitive = false
+ String newer = bothVersions.incoming.resolutionResult.allComponents
+ .find { it.moduleVersion.name == 'hibernate-core' }.moduleVersion.version
+ if (hibernate7VersionOverride == springBootHibernateVersion || newer != hibernate7VersionOverride) {
+ throw new GradleException("hibernate7VersionOverride ${hibernate7VersionOverride} is not newer than the " +
+ "Hibernate ORM ${springBootHibernateVersion} that spring-boot-dependencies manages: remove it from dependencies.gradle")
+ }
+ hibernateVersion = hibernate7VersionOverride
+}
+
+// hibernate-models is strictly re-declared too, so it must move with Hibernate ORM
+String ormHibernateModels = PomVersions.read(pomFile("org.hibernate.orm:hibernate-core:${hibernateVersion}")).dependencies
+ .find { it.groupId == 'org.hibernate.models' && it.artifactId == 'hibernate-models' }?.version
+if (ormHibernateModels && ormHibernateModels != customBomVersions['hibernate-models.version']) {
+ throw new GradleException("Hibernate ORM ${hibernateVersion} depends on hibernate-models ${ormHibernateModels}, " +
+ "but dependencies.gradle manages ${customBomVersions['hibernate-models.version']}: set hibernate-models.version to ${ormHibernateModels}")
+}
+
+customBomVersions['hibernate.version'] = hibernateVersion
+combinedVersions['hibernate.version'] = hibernateVersion
+for (String module : hibernateOrmModules) {
+ String coordinates = "org.hibernate.orm:${module}:${hibernateVersion}"
+ customBomDependencies[module] = coordinates
+ combinedDependencies[module] = coordinates
+}
+
dependencies {
api platform(project(':grails-base-bom'))
From b4afca6ffb62818e62a29b5817e317bcd5befc7f Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 11:37:06 -0800
Subject: [PATCH 08/78] Keep requests browsers send on their own out of the
request cache
Spring Security 7.2's configuration DSL no longer saves requests for
/favicon.*, /apple-touch-icon*.png, /manifest.json, /manifest.webmanifest,
/browserconfig.xml and Chrome DevTools'
/.well-known/appspecific/com.chrome.devtools.json. The plugin builds its beans
without the DSL and saved every request, so a denied request for one of these
paths became the page a login redirected to.
The default requestMatcher now leaves out the paths the new
requestCache.ignoredPatterns setting names, by default the same list, which is
private to the DSL. A class set with requestMatcherBeanClass is left as it was.
---
.../src/en/guide/introduction/whatsNew.adoc | 8 ++
.../springSecurity/core/miscProperties.adoc | 4 +
.../src/en/guide/upgrading/upgrading90x.adoc | 5 +
.../conf/DefaultSecurityConfig.groovy | 9 ++
.../SpringSecurityCoreGrailsPlugin.groovy | 10 +-
.../web/SavedRequestMatcher.groovy | 52 +++++++++
.../web/SavedRequestMatcherSpec.groovy | 108 ++++++++++++++++++
.../groovy/specs/SavedRequestSpec.groovy | 96 ++++++++++++++++
8 files changed, 290 insertions(+), 2 deletions(-)
create mode 100644 grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/web/SavedRequestMatcher.groovy
create mode 100644 grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/SavedRequestMatcherSpec.groovy
create mode 100644 grails-test-examples/spring-security/core/functional-test-app/src/integration-test/groovy/specs/SavedRequestSpec.groovy
diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc
index ff83f9dff1d..574275970bc 100644
--- a/grails-doc/src/en/guide/introduction/whatsNew.adoc
+++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc
@@ -603,6 +603,14 @@ A view renders the request's nonce with the new `` tag, as in `>
diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
index 7a9fb7c83fc..399b469bcbc 100644
--- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
+++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
@@ -108,6 +108,11 @@ The Spring TestContext Framework used to ignore such a class unless its class hi
Grails 8 already logs a warning for each one it ignores, so a test run on Grails 8 shows the affected tests.
Remove the `@Configuration` annotation, or move the class to a top-level class, if the test should not load it.
+* *The Spring Security plugin no longer saves the requests browsers send on their own.*
+A denied request for `/apple-touch-icon.png`, `/manifest.json` or the `/.well-known/appspecific/com.chrome.devtools.json` that Chrome DevTools sends used to be saved, so a login redirected to it instead of to the page the user asked for.
+Spring Security 7.2's configuration DSL ignores these paths, which the plugin does not use, so the plugin now ignores them too, with `grails.plugin.springsecurity.requestCache.ignoredPatterns`.
+An application that secures a page at one of these paths and wants a login to return to it can leave the path out of that list.
+
[TIP]
====
The Spring Boot properties migrator, described in the link:upgrading.html#upgrading80x[Grails 8 upgrade guide], finds the configuration properties Spring Boot 4.2 renames, such as `server.tomcat.use-relative-redirects`.
diff --git a/grails-spring-security/plugin/grails-app/conf/DefaultSecurityConfig.groovy b/grails-spring-security/plugin/grails-app/conf/DefaultSecurityConfig.groovy
index 56ff07ebe29..0f2088e87a2 100644
--- a/grails-spring-security/plugin/grails-app/conf/DefaultSecurityConfig.groovy
+++ b/grails-spring-security/plugin/grails-app/conf/DefaultSecurityConfig.groovy
@@ -132,6 +132,15 @@ security {
// requestCache
requestCache {
createSession = true
+ // what browsers and their tools request on their own, which Spring Security's DSL does not save either
+ ignoredPatterns = [
+ '/favicon.*',
+ '/apple-touch-icon*.png',
+ '/manifest.json',
+ '/manifest.webmanifest',
+ '/browserconfig.xml',
+ '/.well-known/appspecific/com.chrome.devtools.json'
+ ]
}
// redirectStrategy
diff --git a/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/SpringSecurityCoreGrailsPlugin.groovy b/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/SpringSecurityCoreGrailsPlugin.groovy
index 6d74ff6e174..317581b75ee 100644
--- a/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/SpringSecurityCoreGrailsPlugin.groovy
+++ b/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/SpringSecurityCoreGrailsPlugin.groovy
@@ -32,6 +32,7 @@ import grails.plugin.springsecurity.userdetails.GormUserDetailsService
import grails.plugin.springsecurity.userdetails.NoStackUsernameNotFoundException
import grails.plugin.springsecurity.web.GrailsRedirectStrategy
import grails.plugin.springsecurity.web.NullFilterChainValidator
+import grails.plugin.springsecurity.web.SavedRequestMatcher
import grails.plugin.springsecurity.web.SecurityRequestHolderFilter
import grails.plugin.springsecurity.web.UpdateRequestContextHolderExceptionTranslationFilter
import grails.plugin.springsecurity.web.access.AjaxAwareAccessDeniedHandler
@@ -135,7 +136,6 @@ import org.springframework.security.web.savedrequest.HttpSessionRequestCache
import org.springframework.security.web.savedrequest.NullRequestCache
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter
import org.springframework.security.web.session.HttpSessionEventPublisher
-import org.springframework.security.web.util.matcher.AnyRequestMatcher
import jakarta.servlet.DispatcherType
@@ -1106,7 +1106,13 @@ class SpringSecurityCoreGrailsPlugin extends Plugin {
authenticationDetailsSource(classFor('authenticationDetailsSource', WebAuthenticationDetailsSource))
- requestMatcher(classFor('requestMatcher', AnyRequestMatcher))
+ Class requestMatcherClass = classFor('requestMatcher', SavedRequestMatcher)
+ requestMatcher(requestMatcherClass) {
+ // a class the application configures in its place need not have this property
+ if (SavedRequestMatcher.isAssignableFrom(requestMatcherClass)) {
+ ignoredPatterns = conf.requestCache.ignoredPatterns ?: []
+ }
+ }
requestCache(classFor('requestCache', HttpSessionRequestCache)) {
createSessionAllowed = conf.requestCache.createSession // true
diff --git a/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/web/SavedRequestMatcher.groovy b/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/web/SavedRequestMatcher.groovy
new file mode 100644
index 00000000000..01b5b34533d
--- /dev/null
+++ b/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/web/SavedRequestMatcher.groovy
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * https://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 grails.plugin.springsecurity.web
+
+import groovy.transform.CompileStatic
+
+import jakarta.servlet.http.HttpServletRequest
+
+import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher
+import org.springframework.security.web.util.matcher.RequestMatcher
+
+/**
+ * Decides which requests the request cache saves as the page to redirect to after a login: all but those the
+ * {@code requestCache.ignoredPatterns} setting names, which browsers and their tools send on their own. Spring Security
+ * leaves the same paths out of the matcher its configuration DSL builds, which the plugin does not use, and that list
+ * is private to the DSL.
+ *
+ * @since 9.1
+ */
+@CompileStatic
+class SavedRequestMatcher implements RequestMatcher {
+
+ private List ignored = []
+
+ /**
+ * @param patterns the path patterns, relative to the context path, of the requests not to save
+ */
+ void setIgnoredPatterns(Collection patterns) {
+ ignored = patterns.collect { String pattern -> PathPatternRequestMatcher.pathPattern(pattern) as RequestMatcher }
+ }
+
+ @Override
+ boolean matches(HttpServletRequest request) {
+ !ignored.any { RequestMatcher matcher -> matcher.matches(request) }
+ }
+}
diff --git a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/SavedRequestMatcherSpec.groovy b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/SavedRequestMatcherSpec.groovy
new file mode 100644
index 00000000000..bb131471da6
--- /dev/null
+++ b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/SavedRequestMatcherSpec.groovy
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * https://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 grails.plugin.springsecurity.web
+
+import org.springframework.mock.web.MockHttpServletRequest
+import org.springframework.mock.web.MockHttpServletResponse
+import org.springframework.security.web.savedrequest.HttpSessionRequestCache
+import org.springframework.web.util.ServletRequestPathUtils
+import spock.lang.Specification
+
+class SavedRequestMatcherSpec extends Specification {
+
+ private static final List DEFAULT_PATTERNS = new ConfigSlurper()
+ .parse(new GroovyClassLoader(SavedRequestMatcherSpec.classLoader).loadClass('DefaultSecurityConfig'))
+ .security.requestCache.ignoredPatterns as List
+
+ void 'the request cache does not save #path, with the default patterns'() {
+ expect:
+ savedRequest(path, new SavedRequestMatcher(ignoredPatterns: DEFAULT_PATTERNS)) == null
+
+ where:
+ path << [
+ '/favicon.ico',
+ '/favicon.png',
+ '/apple-touch-icon.png',
+ '/apple-touch-icon-precomposed.png',
+ '/apple-touch-icon-152x152.png',
+ '/manifest.json',
+ '/manifest.webmanifest',
+ '/browserconfig.xml',
+ '/.well-known/appspecific/com.chrome.devtools.json'
+ ]
+ }
+
+ void 'the request cache saves #path, with the default patterns'() {
+ expect:
+ savedRequest(path, new SavedRequestMatcher(ignoredPatterns: DEFAULT_PATTERNS)).redirectUrl == "http://localhost$path"
+
+ where:
+ path << ['/', '/book/show/1', '/images/favicon.ico', '/manifest', '/manifest.json/1', '/.well-known/security.txt']
+ }
+
+ void 'the patterns are relative to the context path'() {
+ given:
+ def request = request('/manifest.json')
+ request.contextPath = '/app'
+ request.requestURI = '/app/manifest.json'
+
+ expect:
+ !new SavedRequestMatcher(ignoredPatterns: ['/manifest.json']).matches(request)
+ }
+
+ void 'the application names its own patterns'() {
+ given:
+ def matcher = new SavedRequestMatcher(ignoredPatterns: ['/poll/**'])
+
+ expect:
+ savedRequest('/poll/status', matcher) == null
+ savedRequest('/manifest.json', matcher) != null
+ }
+
+ void 'no patterns save every request'() {
+ expect:
+ savedRequest('/manifest.json', new SavedRequestMatcher(ignoredPatterns: [])) != null
+ savedRequest('/manifest.json', new SavedRequestMatcher()) != null
+ }
+
+ void 'a request parsed for Spring MVC keeps its parsed path'() {
+ given:
+ def request = request('/manifest.json')
+ def parsed = ServletRequestPathUtils.parseAndCache(request)
+
+ when:
+ def matched = new SavedRequestMatcher(ignoredPatterns: ['/manifest.json']).matches(request)
+
+ then:
+ !matched
+ ServletRequestPathUtils.getParsedRequestPath(request).is(parsed)
+ }
+
+ private static savedRequest(String path, SavedRequestMatcher matcher) {
+ def cache = new HttpSessionRequestCache(requestMatcher: matcher, matchingRequestParameterName: null)
+ def request = request(path)
+ def response = new MockHttpServletResponse()
+ cache.saveRequest(request, response)
+ cache.getRequest(request, response)
+ }
+
+ private static MockHttpServletRequest request(String path) {
+ new MockHttpServletRequest('GET', path)
+ }
+}
diff --git a/grails-test-examples/spring-security/core/functional-test-app/src/integration-test/groovy/specs/SavedRequestSpec.groovy b/grails-test-examples/spring-security/core/functional-test-app/src/integration-test/groovy/specs/SavedRequestSpec.groovy
new file mode 100644
index 00000000000..b720bd70d55
--- /dev/null
+++ b/grails-test-examples/spring-security/core/functional-test-app/src/integration-test/groovy/specs/SavedRequestSpec.groovy
@@ -0,0 +1,96 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * https://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 specs
+
+import java.net.http.HttpClient
+
+import org.apache.grails.testing.http.client.HttpClientSupport
+import org.apache.grails.testing.http.client.TestHttpResponse
+import org.springframework.beans.factory.annotation.Autowired
+import spock.lang.IgnoreIf
+import spock.lang.Shared
+import spock.lang.Specification
+
+import com.testapp.TestDataService
+import grails.testing.mixin.integration.Integration
+
+/**
+ * A login redirects to the page whose request was denied, but not to a request the browser sent on its own. It runs in
+ * a configuration that adds no other specification's data to the roles and users the browser specifications count.
+ */
+@IgnoreIf({ System.getProperty('TESTCONFIG') != 'oncePerRequest' })
+@Integration(applicationClass = functional.test.app.Application)
+class SavedRequestSpec extends Specification implements HttpClientSupport {
+
+ private static final String USERNAME = 'saved_request_user'
+
+ @Autowired
+ TestDataService testDataService
+
+ @Shared
+ private boolean userAdded
+
+ void setup() {
+ if (!userAdded) {
+ testDataService.addTestUser(USERNAME)
+ userAdded = true
+ }
+ }
+
+ void 'a login redirects to the page whose request was denied'() {
+ when:
+ def response = loginAfterRequestOf('/secureAnnotated')
+
+ then:
+ response.statusCode() == 302
+ response.headerValue('Location').contains('/secureAnnotated')
+ }
+
+ void 'a login does not redirect to #path, which a browser requests on its own'() {
+ when:
+ def response = loginAfterRequestOf(path)
+
+ then:
+ response.statusCode() == 302
+ response.headerValue('Location').endsWith('/')
+ !response.headerValue('Location').contains(path)
+
+ where:
+ path << [
+ '/apple-touch-icon.png',
+ '/apple-touch-icon-152x152.png',
+ '/manifest.json',
+ '/manifest.webmanifest',
+ '/browserconfig.xml',
+ '/.well-known/appspecific/com.chrome.devtools.json'
+ ]
+ }
+
+ private TestHttpResponse loginAfterRequestOf(String path) {
+ def client = newHttpClientWith {
+ followRedirects(HttpClient.Redirect.NEVER)
+ cookieHandler(new CookieManager())
+ }
+ def denied = http([:], path, client)
+ assert denied.statusCode() == 302
+ assert denied.headerValue('Location').endsWith('/login/auth')
+ httpPostForm([:], '/login/authenticate', [username: USERNAME, password: 'password'], client)
+ }
+}
From 7180786d3b631ed3a4ae8ee08df8c17818140cc9 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 11:42:13 -0800
Subject: [PATCH 09/78] Support the HTTP QUERY method of Spring Framework 7.1
Spring Framework 7.1 adds HttpMethod.QUERY, for RFC 10008, and its
FormContentFilter now parses form-encoded QUERY bodies.
A mapping with method: 'QUERY' already routed, and a body bound as a POST's does,
so URL mappings gain the query prefix they have for the other methods.
GrailsMockHttpServletRequest stands in for FormContentFilter and did not parse a
QUERY body, so a unit test saw different params from the running application.
The app1, enable-mvc-check and Spring Security functional apps send QUERY
requests with JSON and form-encoded bodies, and the guide says what QUERY does
not do: an HTML form cannot send it, OpenAPI has no operation for it, and
Spring Security's own DSL needs it allowed on its firewall.
---
...ilsFormContentFilterAutoConfiguration.java | 8 +-
grails-doc/src/en/guide/REST/openApi.adoc | 2 +-
.../src/en/guide/introduction/whatsNew.adoc | 13 +++
.../theWebLayer/urlmappings/mappingHTTP.adoc | 33 +++++-
.../GrailsMockHttpServletRequest.groovy | 4 +-
...sMockHttpServletRequestFormBodySpec.groovy | 79 ++++++++++++++
.../HttpQueryController.groovy | 43 ++++++++
.../functionaltests/UrlMappings.groovy | 4 +
.../FormContentFunctionalSpec.groovy | 2 +-
.../HttpQueryFunctionalSpec.groovy | 101 ++++++++++++++++++
.../WebMvcDefaultsFunctionalSpec.groovy | 2 +-
.../testapp/TestFormParamsController.groovy | 6 +-
.../specs/TestFormParamsControllerSpec.groovy | 9 ++
.../web/servlet/mvc/GrailsParameterMap.java | 6 +-
.../mapping/DefaultUrlMappingEvaluator.java | 37 +++++++
.../UrlMappingsWithHttpMethodSpec.groovy | 63 +++++++++++
16 files changed, 396 insertions(+), 16 deletions(-)
create mode 100644 grails-test-core/src/test/groovy/org/grails/plugins/testing/GrailsMockHttpServletRequestFormBodySpec.groovy
create mode 100644 grails-test-examples/app1/grails-app/controllers/functionaltests/HttpQueryController.groovy
create mode 100644 grails-test-examples/app1/src/integration-test/groovy/functionaltests/HttpQueryFunctionalSpec.groovy
diff --git a/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsFormContentFilterAutoConfiguration.java b/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsFormContentFilterAutoConfiguration.java
index 17381dcfebd..fb649c0e1d0 100644
--- a/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsFormContentFilterAutoConfiguration.java
+++ b/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsFormContentFilterAutoConfiguration.java
@@ -35,8 +35,8 @@
/**
* Guarantees a {@link FormContentFilter} for every Grails servlet web application, so
- * {@code application/x-www-form-urlencoded} bodies of {@code PUT}, {@code PATCH} and {@code DELETE}
- * requests are parsed into request parameters and are visible through the standard
+ * {@code application/x-www-form-urlencoded} bodies of {@code PUT}, {@code PATCH}, {@code DELETE} and
+ * {@code QUERY} requests are parsed into request parameters and are visible through the standard
* {@code request.getParameter(...)} API. Only that content type is affected — other request bodies
* (JSON, multipart, etc.) are untouched and remain available to data binding.
*
@@ -69,7 +69,7 @@ public OrderedFormContentFilter formContentFilter() {
/**
* Warns, once at startup, that form-content parsing has been switched off. Registered only when
* {@code spring.mvc.formcontent.filter.enabled=false} is set and no {@link FormContentFilter} is
- * present, so a deliberate opt-out is visible rather than silently leaving PUT/PATCH/DELETE form
+ * present, so a deliberate opt-out is visible rather than silently leaving PUT/PATCH/DELETE/QUERY form
* bodies unparsed — for controllers or for a plugin such as Spring Security.
*/
@Bean
@@ -77,7 +77,7 @@ public OrderedFormContentFilter formContentFilter() {
@ConditionalOnProperty(name = "spring.mvc.formcontent.filter.enabled", havingValue = "false")
public FormContentParsingDisabledWarning formContentParsingDisabledWarning() {
logger.warn("Form-content parsing is disabled (spring.mvc.formcontent.filter.enabled=false): " +
- "form-encoded PUT, PATCH and DELETE request bodies will not be parsed into request " +
+ "form-encoded PUT, PATCH, DELETE and QUERY request bodies will not be parsed into request " +
"parameters, for controllers or for the Spring Security filter chain.");
return new FormContentParsingDisabledWarning();
}
diff --git a/grails-doc/src/en/guide/REST/openApi.adoc b/grails-doc/src/en/guide/REST/openApi.adoc
index 53d30e13c0d..ac71521808c 100644
--- a/grails-doc/src/en/guide/REST/openApi.adoc
+++ b/grails-doc/src/en/guide/REST/openApi.adoc
@@ -872,7 +872,7 @@ listing. Its other actions are described as any controller's are.
* A mapping that accepts any HTTP method for an action `allowedMethods` does not restrict is
documented as `GET`, because OpenAPI requires a concrete operation.
-* A mapping declared for an HTTP method OpenAPI has no operation for is skipped, and logged.
+* A mapping declared for an HTTP method OpenAPI has no operation for, such as `QUERY`, is skipped, and logged.
* A `RestfulController` is known to be read only, and the resource it serves where it declares no
type argument, from the controller the application serves requests with, which is not created to
be described. So one in a scope other than singleton is described with its write actions, and one
diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc
index 574275970bc..a92e68d3207 100644
--- a/grails-doc/src/en/guide/introduction/whatsNew.adoc
+++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc
@@ -79,6 +79,19 @@ The Grails 8 upgrade guide calls out the major application-impacting changes and
For the changes since Spring Boot 4.1, see the https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-4.2-Release-Notes[Spring Boot 4.2 Release Notes] and the https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-7.1-Release-Notes[Spring Framework 7.1 Release Notes].
The xref:upgrading#upgrading90x[Upgrading from Grails 8 to Grails {grailsMajorVersion}] section covers the upgrade, including the graphql-java 26 changes that affect GraphQL applications.
+==== The HTTP QUERY Method
+
+Spring Framework 7.1 supports the `QUERY` method of https://www.rfc-editor.org/info/rfc10008/[RFC 10008], a safe, idempotent request with a body. URL mappings gain a `query` prefix for it, next to `get`, `post` and the others, and an action binds the body of a `QUERY` as it binds that of a `POST`:
+
+[source,groovy]
+----
+static mappings = {
+ query "/books/search"(controller: 'book', action: 'search')
+}
+----
+
+See xref:theWebLayer#mappingHTTP[Mapping to HTTP methods].
+
==== JSON Dates and Times Render as Spring Boot Renders Them
`render ... as JSON`, `respond` and JSON views now write `Date`, `Calendar`, `TimeZone`, the `java.sql` date types,
diff --git a/grails-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc b/grails-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc
index a3fa27a86ae..21927df7b85 100644
--- a/grails-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc
+++ b/grails-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc
@@ -17,7 +17,7 @@ specific language governing permissions and limitations
under the License.
////
-URL mappings can also be configured to map based on the HTTP method (GET, POST, PUT or DELETE). This is very useful for RESTful APIs and for restricting mappings based on HTTP method.
+URL mappings can also be configured to map based on the HTTP method, such as GET, POST, PUT, DELETE or QUERY. This is very useful for RESTful APIs and for restricting mappings based on HTTP method.
As an example the following mappings provide a RESTful API URL mappings for the `ProductController`:
@@ -29,3 +29,34 @@ static mappings = {
----
Note that if you specify a HTTP method other than GET in your URL mapping, you also have to specify it when creating the corresponding link by passing the `method` argument to `g:link` or `g:createLink` to get a link of the desired format.
+
+The `QUERY` method of https://www.rfc-editor.org/info/rfc10008/[RFC 10008] is a safe, idempotent request with a body, for a search whose criteria do not fit in a URL. Map it with `method: 'QUERY'` or with the `query` prefix, and restrict an action to it with `allowedMethods`:
+
+[source,groovy]
+.grails-app/controllers/UrlMappings.groovy
+----
+static mappings = {
+ query "/books/search"(controller: 'book', action: 'search')
+}
+----
+
+[source,groovy]
+.grails-app/controllers/com/demo/BookController.groovy
+----
+class BookController {
+
+ static allowedMethods = [search: 'QUERY']
+
+ def search(BookSearch criteria) {
+ respond Book.findAllByTitleLike("%${criteria.title}%")
+ }
+}
+----
+
+A JSON body is bound to the command object the action takes, and a form-encoded body is also available in `params`, through the same `FormContentFilter` that parses `PUT`, `PATCH` and `DELETE` bodies. As for `GET`, a domain class the action takes is looked up by its identifier but not bound to the body, because a `QUERY` does not change anything.
+
+Other things to know about `QUERY`:
+
+* An HTML form cannot send it, and `` submits a `POST`. Call it from JavaScript or another HTTP client.
+* `grails-openapi` leaves these mappings out of the document it generates, and logs each one, because OpenAPI has no operation for the method.
+* The Spring Security plugin accepts `QUERY` requests. An application that configures Spring Security with its own configuration DSL instead gets a `StrictHttpFirewall`, which rejects the method until it is added with `setAllowedHttpMethods`, and whichever one it uses, `CsrfFilter` asks a `QUERY` for a token where CSRF protection is on.
diff --git a/grails-test-core/src/main/groovy/org/grails/plugins/testing/GrailsMockHttpServletRequest.groovy b/grails-test-core/src/main/groovy/org/grails/plugins/testing/GrailsMockHttpServletRequest.groovy
index a81842b7d17..14e8600ac9c 100644
--- a/grails-test-core/src/main/groovy/org/grails/plugins/testing/GrailsMockHttpServletRequest.groovy
+++ b/grails-test-core/src/main/groovy/org/grails/plugins/testing/GrailsMockHttpServletRequest.groovy
@@ -515,7 +515,7 @@ class GrailsMockHttpServletRequest extends MockHttpServletRequest implements Mul
/**
* Simulates Spring's {@code FormContentFilter}: parses an {@code application/x-www-form-urlencoded}
- * body of a {@code PUT}, {@code PATCH} or {@code DELETE} request into request parameters, so a mock
+ * body of a {@code PUT}, {@code PATCH}, {@code DELETE} or {@code QUERY} request into request parameters, so a mock
* request reflects what application code sees after that filter has run in a real deployment. Runs
* once, the first time a non-empty form body is observed on parameter access.
*/
@@ -524,7 +524,7 @@ class GrailsMockHttpServletRequest extends MockHttpServletRequest implements Mul
return
}
String httpMethod = getMethod()
- if (httpMethod != 'PUT' && httpMethod != 'PATCH' && httpMethod != 'DELETE') {
+ if (!(httpMethod in ['PUT', 'PATCH', 'DELETE', 'QUERY'])) {
return
}
String currentContentType = getContentType()
diff --git a/grails-test-core/src/test/groovy/org/grails/plugins/testing/GrailsMockHttpServletRequestFormBodySpec.groovy b/grails-test-core/src/test/groovy/org/grails/plugins/testing/GrailsMockHttpServletRequestFormBodySpec.groovy
new file mode 100644
index 00000000000..1f79d769683
--- /dev/null
+++ b/grails-test-core/src/test/groovy/org/grails/plugins/testing/GrailsMockHttpServletRequestFormBodySpec.groovy
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * https://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 org.grails.plugins.testing
+
+import jakarta.servlet.FilterChain
+
+import org.springframework.mock.web.MockHttpServletRequest
+import org.springframework.mock.web.MockHttpServletResponse
+import org.springframework.web.filter.FormContentFilter
+import spock.lang.Specification
+
+class GrailsMockHttpServletRequestFormBodySpec extends Specification {
+
+ private static final String FORM = 'application/x-www-form-urlencoded'
+
+ void 'a form-encoded #method body is #outcome, as Spring FormContentFilter treats it'() {
+ given:
+ def request = new GrailsMockHttpServletRequest()
+ request.method = method
+ request.contentType = FORM
+ request.content = 'title=Grails'.bytes
+
+ expect:
+ request.getParameter('title') == title
+
+ and: 'the filter this request stands in for agrees'
+ filteredTitle(method) == title
+
+ where:
+ method | title
+ 'PUT' | 'Grails'
+ 'PATCH' | 'Grails'
+ 'DELETE' | 'Grails'
+ 'QUERY' | 'Grails'
+ 'POST' | null
+ 'GET' | null
+
+ outcome = title ? 'parsed' : 'left unparsed'
+ }
+
+ void 'a QUERY body of another content type is left unparsed'() {
+ given:
+ def request = new GrailsMockHttpServletRequest()
+ request.method = 'QUERY'
+ request.contentType = 'application/json'
+ request.content = '{"title":"Grails"}'.bytes
+
+ expect:
+ request.getParameter('title') == null
+ new String(request.contentAsByteArray) == '{"title":"Grails"}'
+ }
+
+ private static String filteredTitle(String method) {
+ def request = new MockHttpServletRequest(method, '/')
+ request.contentType = FORM
+ request.content = 'title=Grails'.bytes
+ String title = null
+ new FormContentFilter().doFilter(request, new MockHttpServletResponse(), { req, res ->
+ title = req.getParameter('title')
+ } as FilterChain)
+ title
+ }
+}
diff --git a/grails-test-examples/app1/grails-app/controllers/functionaltests/HttpQueryController.groovy b/grails-test-examples/app1/grails-app/controllers/functionaltests/HttpQueryController.groovy
new file mode 100644
index 00000000000..b339535d48d
--- /dev/null
+++ b/grails-test-examples/app1/grails-app/controllers/functionaltests/HttpQueryController.groovy
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * https://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 functionaltests
+
+import grails.converters.JSON
+
+class HttpQueryController {
+
+ static allowedMethods = [restricted: 'QUERY']
+
+ def books(BookCriteria criteria) {
+ render([method: request.method, title: criteria.title, pages: criteria.pages] as JSON)
+ }
+
+ def restricted() {
+ render 'restricted'
+ }
+
+ def lookup(Book book) {
+ render([id: book?.id, title: book?.title, changed: book?.dirty ?: false] as JSON)
+ }
+}
+
+class BookCriteria {
+ String title
+ Integer pages
+}
diff --git a/grails-test-examples/app1/grails-app/controllers/functionaltests/UrlMappings.groovy b/grails-test-examples/app1/grails-app/controllers/functionaltests/UrlMappings.groovy
index 56115b5afc7..41431269397 100644
--- a/grails-test-examples/app1/grails-app/controllers/functionaltests/UrlMappings.groovy
+++ b/grails-test-examples/app1/grails-app/controllers/functionaltests/UrlMappings.groovy
@@ -34,6 +34,10 @@ class UrlMappings {
// See RequestPathSpec.groovy - one request through filter chain, dispatcher, mapping and controller
"/request-path"(resources: 'requestPath')
+ // See HttpQueryFunctionalSpec.groovy
+ query "/http-query/books"(controller: 'httpQuery', action: 'books')
+ query "/http-query/lookup/$id"(controller: 'httpQuery', action: 'lookup')
+
"/alphaDemo"(controller: 'demo', action: 'doit', namespace: 'alpha')
"/betaDemo"(controller: 'demo', action: 'doit', namespace: 'beta')
diff --git a/grails-test-examples/app1/src/integration-test/groovy/functionaltests/FormContentFunctionalSpec.groovy b/grails-test-examples/app1/src/integration-test/groovy/functionaltests/FormContentFunctionalSpec.groovy
index 5c146e01fcb..c94afa69a12 100644
--- a/grails-test-examples/app1/src/integration-test/groovy/functionaltests/FormContentFunctionalSpec.groovy
+++ b/grails-test-examples/app1/src/integration-test/groovy/functionaltests/FormContentFunctionalSpec.groovy
@@ -57,7 +57,7 @@ class FormContentFunctionalSpec extends Specification implements HttpClientSuppo
json.pages == '1153'
where:
- httpMethod << ['PUT', 'PATCH', 'DELETE']
+ httpMethod << ['PUT', 'PATCH', 'DELETE', 'QUERY']
}
void 'a form-encoded POST body is parsed into request parameters'() {
diff --git a/grails-test-examples/app1/src/integration-test/groovy/functionaltests/HttpQueryFunctionalSpec.groovy b/grails-test-examples/app1/src/integration-test/groovy/functionaltests/HttpQueryFunctionalSpec.groovy
new file mode 100644
index 00000000000..1daba4f0b16
--- /dev/null
+++ b/grails-test-examples/app1/src/integration-test/groovy/functionaltests/HttpQueryFunctionalSpec.groovy
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * https://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 functionaltests
+
+import java.net.http.HttpRequest
+
+import org.junit.jupiter.api.Tag
+import spock.lang.Specification
+
+import grails.testing.mixin.integration.Integration
+import org.apache.grails.testing.http.client.HttpClientSupport
+import org.apache.grails.testing.http.client.TestHttpResponse
+
+@Integration
+@Tag('http-client')
+class HttpQueryFunctionalSpec extends Specification implements HttpClientSupport {
+
+ private static final String JSON_TYPE = 'application/json'
+ private static final String FORM_TYPE = 'application/x-www-form-urlencoded'
+
+ void 'the query prefix maps a URL to the QUERY method, and a JSON body is bound to the command object'() {
+ when:
+ def response = send('QUERY', '/http-query/books', '{"title":"The Stand","pages":1153}', JSON_TYPE)
+
+ then:
+ response.assertStatus(200)
+ with(response.json()) {
+ method == 'QUERY'
+ title == 'The Stand'
+ pages == 1153
+ }
+ }
+
+ void 'a form-encoded body is bound to the command object'() {
+ when:
+ def response = send('QUERY', '/http-query/books', 'title=The%20Stand&pages=1153', FORM_TYPE)
+
+ then:
+ response.assertStatus(200)
+ with(response.json()) {
+ method == 'QUERY'
+ title == 'The Stand'
+ pages == 1153
+ }
+ }
+
+ void 'a mapping for the QUERY method does not match another method'() {
+ when:
+ def response = send('POST', '/http-query/books', '{"title":"The Stand"}', JSON_TYPE)
+
+ then:
+ response.statusCode() == 404
+ }
+
+ void 'allowedMethods restricts an action to the QUERY method'() {
+ expect:
+ send('QUERY', '/httpQuery/restricted', '{}', JSON_TYPE).statusCode() == 200
+ send('POST', '/httpQuery/restricted', '{}', JSON_TYPE).statusCode() == 405
+ }
+
+ void 'a domain class is looked up by its identifier and not bound to the body'() {
+ given:
+ Long id = Book.withNewTransaction { new Book(title: 'Original').save(failOnError: true, flush: true).id }
+
+ when:
+ def response = send('QUERY', "/http-query/lookup/$id", '{"title":"Changed"}', JSON_TYPE)
+
+ then:
+ response.assertStatus(200)
+ with(response.json()) {
+ title == 'Original'
+ changed == false
+ }
+
+ cleanup:
+ Book.withNewTransaction { Book.get(id)?.delete(flush: true) }
+ }
+
+ private TestHttpResponse send(String httpMethod, String path, String body, String contentType) {
+ sendHttpRequest(newHttpRequestWith(path) {
+ header('Content-Type', contentType)
+ method(httpMethod, HttpRequest.BodyPublishers.ofString(body))
+ })
+ }
+}
diff --git a/grails-test-examples/enable-mvc-check/src/integration-test/groovy/enablemvccheck/WebMvcDefaultsFunctionalSpec.groovy b/grails-test-examples/enable-mvc-check/src/integration-test/groovy/enablemvccheck/WebMvcDefaultsFunctionalSpec.groovy
index 2ab72472e72..a51190b1090 100644
--- a/grails-test-examples/enable-mvc-check/src/integration-test/groovy/enablemvccheck/WebMvcDefaultsFunctionalSpec.groovy
+++ b/grails-test-examples/enable-mvc-check/src/integration-test/groovy/enablemvccheck/WebMvcDefaultsFunctionalSpec.groovy
@@ -71,7 +71,7 @@ class WebMvcDefaultsFunctionalSpec extends Specification implements HttpClientSu
json.pages == '1153'
where:
- httpMethod << ['PUT', 'PATCH', 'DELETE']
+ httpMethod << ['PUT', 'PATCH', 'DELETE', 'QUERY']
}
void 'a form-encoded POST body is parsed into request parameters'() {
diff --git a/grails-test-examples/spring-security/core/functional-test-app/grails-app/controllers/com/testapp/TestFormParamsController.groovy b/grails-test-examples/spring-security/core/functional-test-app/grails-app/controllers/com/testapp/TestFormParamsController.groovy
index 94ec7346f8d..215d07b7fed 100644
--- a/grails-test-examples/spring-security/core/functional-test-app/grails-app/controllers/com/testapp/TestFormParamsController.groovy
+++ b/grails-test-examples/spring-security/core/functional-test-app/grails-app/controllers/com/testapp/TestFormParamsController.groovy
@@ -23,13 +23,13 @@ import grails.plugin.springsecurity.annotation.Secured
import grails.validation.Validateable
/**
- * This controller is used to verify that form parameters on PUT and PATCH requests are available
+ * This controller is used to verify that form parameters on PUT, PATCH and QUERY requests are available
*/
class TestFormParamsController {
static allowedMethods = [
- permitAll : ["PUT", "PATCH"],
- permitAdmin: ["PUT", "PATCH"]
+ permitAll : ["PUT", "PATCH", "QUERY"],
+ permitAdmin: ["PUT", "PATCH", "QUERY"]
]
@Secured(['permitAll'])
diff --git a/grails-test-examples/spring-security/core/functional-test-app/src/integration-test/groovy/specs/TestFormParamsControllerSpec.groovy b/grails-test-examples/spring-security/core/functional-test-app/src/integration-test/groovy/specs/TestFormParamsControllerSpec.groovy
index 0113b5c6174..c625a48ce12 100644
--- a/grails-test-examples/spring-security/core/functional-test-app/src/integration-test/groovy/specs/TestFormParamsControllerSpec.groovy
+++ b/grails-test-examples/spring-security/core/functional-test-app/src/integration-test/groovy/specs/TestFormParamsControllerSpec.groovy
@@ -127,6 +127,15 @@ class TestFormParamsControllerSpec extends Specification implements HttpClientSu
response.body() == "username: ${USERNAME}, password: ${PASSWORD}"
}
+ void 'QUERY request with parameters as x-www-form-urlencoded'() {
+ when: "A QUERY request with form params is made"
+ TestHttpResponse response = exchange('QUERY', '/testFormParams/permitAll', "username=${USERNAME}&password=${PASSWORD}", FORM)
+
+ then: "the firewall lets it through, and the controller responds with the correct status and parameters are extracted"
+ response.statusCode() == 200
+ response.body() == "username: ${USERNAME}, password: ${PASSWORD}"
+ }
+
void 'PUT request to secured endpoint with parameters as x-www-form-urlencoded'() {
when: "A PUT request with form params is made to a secured endpoint"
TestHttpResponse response = exchange('PUT', '/testFormParams/permitAdmin', "username=${USERNAME}&password=${PASSWORD}", FORM)
diff --git a/grails-web-common/src/main/groovy/grails/web/servlet/mvc/GrailsParameterMap.java b/grails-web-common/src/main/groovy/grails/web/servlet/mvc/GrailsParameterMap.java
index a950d66bf2f..ad32623c228 100644
--- a/grails-web-common/src/main/groovy/grails/web/servlet/mvc/GrailsParameterMap.java
+++ b/grails-web-common/src/main/groovy/grails/web/servlet/mvc/GrailsParameterMap.java
@@ -64,8 +64,8 @@ public class GrailsParameterMap extends TypeConvertingMap implements Cloneable {
private final HttpServletRequest request;
/**
- * Retained for binary compatibility. Request-body parsing for form-encoded {@code PUT}, {@code PATCH}
- * and {@code DELETE} requests is now handled at the servlet layer by Spring's {@code FormContentFilter}
+ * Retained for binary compatibility. Request-body parsing for form-encoded {@code PUT}, {@code PATCH},
+ * {@code DELETE} and {@code QUERY} requests is now handled at the servlet layer by Spring's {@code FormContentFilter}
* (registered by Boot's {@code WebMvcAutoConfiguration}), not by this map.
*/
public static final String REQUEST_BODY_PARSED = "org.codehaus.groovy.grails.web.REQUEST_BODY_PARSED";
@@ -89,7 +89,7 @@ public GrailsParameterMap(Map values, HttpServletRequest request) {
*/
public GrailsParameterMap(HttpServletRequest request) {
this.request = request;
- // Request parameters (including form-encoded PUT/PATCH/DELETE bodies parsed at the servlet
+ // Request parameters (including form-encoded PUT/PATCH/DELETE/QUERY bodies parsed at the servlet
// layer by Spring's FormContentFilter) are read straight from the request parameter map.
// updateNestedKeys only reads this map, so the servlet's own is used directly and copied only when
// there is something to merge into it. Read tolerantly because a multipart body the container
diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/DefaultUrlMappingEvaluator.java b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/DefaultUrlMappingEvaluator.java
index 5aa34a648ad..6929d1251af 100644
--- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/DefaultUrlMappingEvaluator.java
+++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/DefaultUrlMappingEvaluator.java
@@ -675,6 +675,43 @@ public UrlMapping options(RegexUrlMapping regexUrlMapping) {
return regexUrlMapping;
}
+ /**
+ * Matches the QUERY method of RFC 10008
+ *
+ * @param arguments The arguments
+ * @param uri The URI
+ * @return the UrlMapping
+ * @since 9.1
+ */
+ public UrlMapping query(Map arguments, String uri, Closure> callable) {
+ arguments.put(HTTP_METHOD, HttpMethod.QUERY);
+ return (UrlMapping) _invoke(uri, new Object[]{ arguments, callable }, this);
+ }
+
+ /**
+ * Matches the QUERY method of RFC 10008
+ *
+ * @param arguments The arguments
+ * @param uri The URI
+ * @return the UrlMapping
+ * @since 9.1
+ */
+ public UrlMapping query(Map arguments, String uri) {
+ return query(arguments, uri, null);
+ }
+
+ /**
+ * Matches the QUERY method of RFC 10008
+ *
+ * @param regexUrlMapping The mapping
+ * @return the UrlMapping
+ * @since 9.1
+ */
+ public UrlMapping query(RegexUrlMapping regexUrlMapping) {
+ regexUrlMapping.httpMethod = HttpMethod.QUERY.toString();
+ return regexUrlMapping;
+ }
+
/**
* Define Url mapping collections that are nested directly below the parent resource (without the id)
*
diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/UrlMappingsWithHttpMethodSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/UrlMappingsWithHttpMethodSpec.groovy
index 2d0e0e66977..2c7fa78e143 100644
--- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/UrlMappingsWithHttpMethodSpec.groovy
+++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/UrlMappingsWithHttpMethodSpec.groovy
@@ -29,6 +29,7 @@ import org.grails.web.mapping.DefaultLinkGenerator
import org.grails.web.mapping.DefaultUrlMappingEvaluator
import org.grails.web.mapping.DefaultUrlMappingsHolder
import org.grails.web.util.WebUtils
+import org.springframework.http.HttpMethod
import org.springframework.mock.web.MockServletContext
import org.springframework.web.context.request.RequestContextHolder
import spock.lang.IgnoreIf
@@ -58,6 +59,68 @@ class UrlMappingsWithHttpMethodSpec extends Specification{
}
+ void 'the query prefix maps a URL to the QUERY method of RFC 10008 alone'() {
+ given:
+ def holder = urlMappingsHolder {
+ query "/books/search"(controller: 'book', action: 'search')
+ query "/books/find"(controller: 'book') {
+ action = 'find'
+ }
+ }
+
+ expect:
+ holder.matchAll('/books/search', 'QUERY').size() == 1
+ holder.matchAll('/books/search', 'QUERY')[0].actionName == 'search'
+ holder.matchAll('/books/find', 'QUERY')[0].actionName == 'find'
+ !holder.matchAll('/books/search', 'POST')
+ !holder.matchAll('/books/search', 'GET')
+ }
+
+ void 'the method argument maps a URL to the QUERY method of RFC 10008, in any case'() {
+ given:
+ def holder = urlMappingsHolder {
+ "/books/search"(controller: 'book', action: 'search', method: 'QUERY')
+ }
+
+ expect:
+ holder.matchAll('/books/search', 'QUERY')[0].actionName == 'search'
+ holder.matchAll('/books/search', 'query')[0].actionName == 'search'
+ !holder.matchAll('/books/search', 'GET')
+ }
+
+ void 'a mapping for any method matches the QUERY method, and offers it among the methods of its URL'() {
+ given:
+ def holder = urlMappingsHolder {
+ "/books/any"(controller: 'book', action: 'any')
+ query "/books/search"(controller: 'book', action: 'search')
+ }
+
+ expect:
+ holder.matchAll('/books/any', 'QUERY')[0].actionName == 'any'
+ holder.allowedMethods('/books/any').contains(HttpMethod.QUERY)
+ holder.allowedMethods('/books/search') == [HttpMethod.QUERY] as Set
+ }
+
+ void 'a link to a QUERY mapping is generated with the method it is mapped to'() {
+ given:
+ def holder = urlMappingsHolder {
+ query "/books/search"(controller: 'book', action: 'search')
+ "/$controller/$action?"()
+ }
+ def linkGenerator = new DefaultLinkGenerator('http://localhost', '')
+ linkGenerator.urlMappingsHolder = holder
+
+ expect:
+ linkGenerator.link(controller: 'book', action: 'search', method: 'QUERY') == '/books/search'
+ linkGenerator.link(controller: 'book', action: 'search') == '/book/search'
+ }
+
+ private static UrlMappingsHolder urlMappingsHolder(Closure mappings) {
+ def ctx = new MockApplicationContext()
+ ctx.registerMockBean(GrailsApplication.APPLICATION_ID, new DefaultGrailsApplication())
+ new DefaultUrlMappingsHolder(new DefaultUrlMappingEvaluator(ctx).evaluateMappings(mappings))
+ }
+
void "Test that the http method can be used as a prefix to URL mappings"() {
given:"A URL mapping evaluator"
def ctx = new MockApplicationContext()
From 7e3bd247a7d0d79fa624af04660cbd682186c760 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 11:53:38 -0800
Subject: [PATCH 10/78] Write an exception no handler method handles as an RFC
9457 problem
Spring Framework 7.1 can render any unhandled exception as a problem with
ProblemDetailsConfigurer.renderUnhandledExceptions, but in a Grails application
that switch takes every exception of every action ahead of the Grails exception
resolver, so a browser gets JSON and "500" URL mappings no longer apply.
grails.exceptionresolver.problemDetails, off by default, uses the same
translation for an exception an action throws and no @ExceptionHandler method
handles, written by Spring MVC's handler adapter with its advice and
interceptors. A client that prefers HTML, and an exception a URL mapping names,
still go to the Grails exception resolver.
As Spring MVC does, a server error is recorded on the HTTP server observation,
and a failure to write the problem leaves the exception to the other resolvers.
Spring's translation logs an unexpected exception without its request, so the
resolver logs the method and URI too.
---
.../main/groovy/grails/config/Settings.groovy | 11 +
...itional-spring-configuration-metadata.json | 6 +
.../en/guide/conf/config/builtInOptions.adoc | 1 +
.../src/en/guide/introduction/whatsNew.adoc | 5 +
.../controllerExceptionHandling.adoc | 31 ++
.../src/en/guide/upgrading/upgrading90x.adoc | 7 +
.../skills/grails-9-upgrade/SKILL.md | 2 +
.../grails-app/conf/application.yml | 1 +
.../grails-app/controllers/UrlMappings.groovy | 4 +
.../springjson/BookController.groovy | 9 +
.../springjson/ErrorsController.groovy | 31 ++
.../springjson/SpringJsonRespondSpec.groovy | 66 +++-
.../springjson/BookArchivedException.groovy | 27 ++
.../mvc/ActionExceptionHandlerResolver.groovy | 143 ++++++-
.../web/mapping/mvc/ActionReturnValues.groovy | 46 ++-
.../ActionExceptionProblemDetailsSpec.groovy | 373 ++++++++++++++++++
16 files changed, 757 insertions(+), 6 deletions(-)
create mode 100644 grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/springjson/ErrorsController.groovy
create mode 100644 grails-test-examples/hibernate7/spring-json-respond/src/main/groovy/springjson/BookArchivedException.groovy
create mode 100644 grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionExceptionProblemDetailsSpec.groovy
diff --git a/grails-core/src/main/groovy/grails/config/Settings.groovy b/grails-core/src/main/groovy/grails/config/Settings.groovy
index c5f7bf615f9..0ea8762f761 100644
--- a/grails-core/src/main/groovy/grails/config/Settings.groovy
+++ b/grails-core/src/main/groovy/grails/config/Settings.groovy
@@ -412,6 +412,17 @@ interface Settings {
* @since 9.0
*/
String SETTING_EXCEPTION_RESOLVER_SPRING_HANDLERS_DEFAULT = 'false'
+
+ /**
+ * Whether an exception a controller action throws, that no {@code @ExceptionHandler} method handles, is written as an
+ * RFC 9457 problem, as Spring MVC writes one with {@code ProblemDetailsConfigurer.renderUnhandledExceptions}, except
+ * to a client that prefers HTML or where a URL mapping names the exception, which the Grails exception resolver
+ * resolves as without it. Defaults to {@code false}.
+ *
+ * @since 9.1
+ */
+ String SETTING_EXCEPTION_RESOLVER_PROBLEM_DETAILS = 'grails.exceptionresolver.problemDetails'
+
/**
* The class to use for stacktrace filtering. Should be an instanceof {@link org.grails.exceptions.reporting.StackTraceFilterer}
*/
diff --git a/grails-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/grails-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json
index fdffe19f262..f30aaf2a109 100644
--- a/grails-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json
+++ b/grails-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json
@@ -250,6 +250,12 @@
"description": "Whether an exception a controller action throws is resolved first by the @ExceptionHandler methods Spring MVC resolves those of a handler method with: those of the controller's class and of the @ControllerAdvice beans that apply to it, Spring Boot's handler of spring.mvc.problemdetails.enabled among them. One none of them handles is resolved as before. Grails 10 makes it the default.",
"defaultValue": false
},
+ {
+ "name": "grails.exceptionresolver.problemDetails",
+ "type": "java.lang.Boolean",
+ "description": "Whether an exception a controller action throws, that no @ExceptionHandler method handles, is written as an RFC 9457 problem, as Spring MVC writes one with ProblemDetailsConfigurer.renderUnhandledExceptions, except to a client that prefers HTML or where a URL mapping names the exception, which the Grails exception resolver resolves as without it.",
+ "defaultValue": false
+ },
{
"name": "grails.controllers.responseBody",
"type": "java.lang.Boolean",
diff --git a/grails-doc/src/en/guide/conf/config/builtInOptions.adoc b/grails-doc/src/en/guide/conf/config/builtInOptions.adoc
index 64ffb941a45..ed1991bb4fc 100644
--- a/grails-doc/src/en/guide/conf/config/builtInOptions.adoc
+++ b/grails-doc/src/en/guide/conf/config/builtInOptions.adoc
@@ -29,6 +29,7 @@ On the runtime front, i.e. `grails-app/conf/application.yml`, there are quite a
* `grails.enable.native2ascii` - Set this to false if you do not require native2ascii conversion of Grails i18n properties files (default: true).
* `grails.converters.encoding` - The character encoding for converter output (JSON or XML) and for the response content types stamped by the default renderers used by `respond()` (default: 'UTF-8'). JSON that `respond` writes through Spring MVC, with `grails.web.rendering.json.spring` or a named configuration, and problems are written in UTF-8, as Spring MVC writes JSON.
* `grails.exceptionresolver.springHandlers` - Whether an exception a controller action throws is resolved first by the `@ExceptionHandler` methods Spring MVC resolves those of a handler method with, those of the controller and of the `@ControllerAdvice` beans that apply to it, Spring Boot's handler of `spring.mvc.problemdetails.enabled` among them (default: false; true from Grails 10). See <>.
+* `grails.exceptionresolver.problemDetails` - Whether an exception a controller action throws, that no exception handler method handles, is written as an RFC 9457 problem to a client that does not prefer HTML, while the application's error page stays for browsers (default: false). See <>.
* `grails.controllers.responseBody` - Whether Spring MVC writes any value of a controller action annotated `@ResponseBody`, or of an action of a controller annotated so, as the body of the response, as it writes the value of a handler method annotated so, rather than Grails rendering the action's view for a model. A `ResponseEntity`, a `ProblemDetail` and the other values Spring MVC writes whatever a handler method is annotated with are written whatever it says (default: false; true from Grails 10). See <>.
* `grails.views.default.codec` - Sets the default encoding regime for GSPs - can be one of 'none', 'html', or 'base64' (default: 'none'). To reduce risk of XSS attacks, set this to 'html'.
* `grails.views.gsp.encoding` - The file encoding used for GSP source files (default: 'utf-8').
diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc
index a92e68d3207..a77eeeb03c1 100644
--- a/grails-doc/src/en/guide/introduction/whatsNew.adoc
+++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc
@@ -141,6 +141,11 @@ of the controller and of the `@ControllerAdvice` beans that apply to it, Spring
`spring.mvc.problemdetails.enabled` among them, which answers the exceptions of Spring MVC with RFC 9457 problems. See
xref:theWebLayer#controllerExceptionHandling[Declarative Controller Exception Handling].
+With `grails.exceptionresolver.problemDetails: true`, an exception no such method handles is written as a problem to a
+client that does not prefer HTML, with the translation Spring Framework 7.1 adds, which keeps the status and detail of an
+`ErrorResponse` or a `@ResponseStatus` exception and never exposes the message of any other. The application's error page
+stays for browsers, and for an exception a URL mapping names.
+
An action can return what a Spring MVC handler method returns to write the response, such as a `ResponseEntity`, a
`ProblemDetail` or a `StreamingResponseBody`, and Spring MVC writes it with the return value handlers of its handler
adapter, the `ResponseBodyAdvice` beans that apply to the controller, and the action's `@JsonView` and
diff --git a/grails-doc/src/en/guide/theWebLayer/controllers/controllerExceptionHandling.adoc b/grails-doc/src/en/guide/theWebLayer/controllers/controllerExceptionHandling.adoc
index c4b0eb39ba8..1a7ea4273c8 100644
--- a/grails-doc/src/en/guide/theWebLayer/controllers/controllerExceptionHandling.adoc
+++ b/grails-doc/src/en/guide/theWebLayer/controllers/controllerExceptionHandling.adoc
@@ -148,3 +148,34 @@ class BookExceptionAdvice {
----
Declare the advice as a bean, in `grails-app/conf/spring/resources.groovy` or as a `@Bean` of a configuration class.
+
+With `grails.exceptionresolver.problemDetails: true`, an exception an action throws that no exception handler method handles is written as an https://www.rfc-editor.org/rfc/rfc9457.html[RFC 9457] problem to a client that does not prefer HTML, using the translation Spring Framework 7.1 adds, and the application's error page stays for browsers:
+
+[source,yaml]
+.grails-app/conf/application.yml
+----
+grails:
+ exceptionresolver:
+ problemDetails: true
+----
+
+----
+HTTP/1.1 500
+Content-Type: application/problem+json
+
+{"status":500,"title":"Internal Server Error"}
+----
+
+* An `ErrorResponse`, a `ResponseStatusException` or an exception annotated `@ResponseStatus`, or one caused by such an exception, keeps its status and detail. Any other exception is a `500` without a detail, so its message is never exposed.
+* The type, title and detail can be customized in the message bundles, with the codes `ErrorResponse` defines.
+* The `ResponseBodyAdvice` beans that apply to the controller and the `ErrorResponse.Interceptor` beans apply to it, as to a problem a handler method returns.
+* An unexpected exception is logged at `ERROR`, by Spring's `org.springframework.web.method.annotation.ProblemDetailExceptionHandler` logger with its stack trace, and by Grails with the method and URI of the request.
+
+The Grails exception resolver and the application's error page still resolve an exception for:
+
+* A client that prefers HTML: a request whose format, from its URL or its `Accept` header, is `html`, or, where Grails resolves any format, as for a browser under `grails.mime.disable.accept.header.userAgents`, whose first concrete `Accept` type is HTML. A client that accepts any type, such as `curl`, gets the problem.
+* An exception that a URL mapping names, or whose root cause it names, such as `"500"(controller: 'errors', action: 'denied', exception: AccessDeniedException)`. A `"500"` mapping without an `exception` is the error page of the clients that prefer HTML, and does not apply to the others.
+
+An exception a view throws while it renders is not one an action throws, and goes to the error page for every client.
+
+WARNING: Do not use Spring Framework's `ProblemDetailsConfigurer.renderUnhandledExceptions(true)` in a `WebMvcConfigurer` for this. It makes Spring MVC's resolver, which runs ahead of the Grails exception resolver, answer every exception of every action with a problem, a browser's included, and `"500"` URL mappings no longer apply.
diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
index 399b469bcbc..f3bba752809 100644
--- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
+++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
@@ -1243,6 +1243,13 @@ grails:
springHandlers: true
----
+Spring Framework 7.1 adds `ProblemDetailsConfigurer.renderUnhandledExceptions`, which renders any exception no exception
+handler method handles as a problem. Turned on in a `WebMvcConfigurer`, it applies to Grails actions whatever
+`grails.exceptionresolver.springHandlers` says, and answers every exception, a browser's included, ahead of the Grails
+exception resolver, so `"500"` URL mappings no longer apply. Set `grails.exceptionresolver.problemDetails: true` instead,
+which writes the same problems and leaves the error page to the clients that prefer HTML. See
+<>.
+
==== 18. Actions Can Return Spring MVC Responses
An action that returns a `ResponseEntity` or another `HttpEntity`, a `ProblemDetail`, an `ErrorResponse`,
diff --git a/grails-skills/upgrade-guide-9/skills/grails-9-upgrade/SKILL.md b/grails-skills/upgrade-guide-9/skills/grails-9-upgrade/SKILL.md
index 678851fd5a2..741d365c960 100644
--- a/grails-skills/upgrade-guide-9/skills/grails-9-upgrade/SKILL.md
+++ b/grails-skills/upgrade-guide-9/skills/grails-9-upgrade/SKILL.md
@@ -352,6 +352,8 @@ The Grails HAL JSON renderers remain available through explicit renderer registr
With `grails.exceptionresolver.springHandlers: true`, the `@ExceptionHandler` methods of the controller and of the `@ControllerAdvice` beans that apply to it, Spring Boot's `spring.mvc.problemdetails.enabled` handler among them, resolve the exceptions actions throw before the Grails exception resolver. An exception none of them handles is resolved as before. Grails 10 makes it the default, so scope `@ControllerAdvice` beans meant only for Spring MVC controllers by `assignableTypes`, `basePackages` or `annotations` before then.
+Do not turn on Spring Framework 7.1's `ProblemDetailsConfigurer.renderUnhandledExceptions` in a `WebMvcConfigurer`: it answers every exception of every action with a problem, a browser's included, ahead of the Grails exception resolver, so `"500"` URL mappings no longer apply. Set `grails.exceptionresolver.problemDetails: true` instead, which writes the same problems and leaves the error page to the clients that prefer HTML and to an exception a URL mapping names.
+
## Actions Can Return Spring MVC Responses
- Whatever the settings, an action that returns a `ResponseEntity` or another `HttpEntity`, a `ProblemDetail`, an `ErrorResponse`, `HttpHeaders`, a `StreamingResponseBody` or a `ResponseBodyEmitter` has it written as Spring MVC writes a handler method's return value, where Grails 8 did not write it. An action that returns `null`, renders with `render`, `respond` or `redirect`, or forwards, is unaffected. Look for actions that return one of these types.
diff --git a/grails-test-examples/hibernate7/spring-json-respond/grails-app/conf/application.yml b/grails-test-examples/hibernate7/spring-json-respond/grails-app/conf/application.yml
index 7a2e02a9d88..98d99fa03b9 100644
--- a/grails-test-examples/hibernate7/spring-json-respond/grails-app/conf/application.yml
+++ b/grails-test-examples/hibernate7/spring-json-respond/grails-app/conf/application.yml
@@ -118,6 +118,7 @@ grails:
jackson: true
exceptionresolver:
springHandlers: true
+ problemDetails: true
controllers:
responseBody: true
spring:
diff --git a/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/UrlMappings.groovy b/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/UrlMappings.groovy
index 2dc628cc93a..74358688fb3 100644
--- a/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/UrlMappings.groovy
+++ b/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/UrlMappings.groovy
@@ -17,9 +17,13 @@
* under the License.
*/
+import springjson.BookArchivedException
+
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?(.$format)?"()
+ "500"(controller: 'errors', action: 'serverError')
+ "500"(controller: 'errors', action: 'archived', exception: BookArchivedException)
}
}
diff --git a/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/springjson/BookController.groovy b/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/springjson/BookController.groovy
index 1546ae7cd4d..fa762de68e7 100644
--- a/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/springjson/BookController.groovy
+++ b/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/springjson/BookController.groovy
@@ -30,6 +30,7 @@ import org.springframework.http.ProblemDetail
import org.springframework.http.ResponseEntity
import org.springframework.web.ErrorResponseException
import org.springframework.web.bind.MissingServletRequestParameterException
+import org.springframework.web.server.ResponseStatusException
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody
@@ -75,6 +76,14 @@ class BookController {
throw new IllegalStateException('Not handled by any exception handler')
}
+ def gone() {
+ throw new ResponseStatusException(HttpStatus.GONE, 'The book was withdrawn')
+ }
+
+ def archived() {
+ throw new BookArchivedException('Handled by the URL mapping that names it')
+ }
+
def search() {
throw new MissingServletRequestParameterException('title', 'String')
}
diff --git a/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/springjson/ErrorsController.groovy b/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/springjson/ErrorsController.groovy
new file mode 100644
index 00000000000..a4871376902
--- /dev/null
+++ b/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/springjson/ErrorsController.groovy
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * https://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 springjson
+
+class ErrorsController {
+
+ def serverError() {
+ render status: 500, text: 'the error page'
+ }
+
+ def archived() {
+ render status: 500, text: 'the mapping for an archived book'
+ }
+}
diff --git a/grails-test-examples/hibernate7/spring-json-respond/src/integration-test/groovy/springjson/SpringJsonRespondSpec.groovy b/grails-test-examples/hibernate7/spring-json-respond/src/integration-test/groovy/springjson/SpringJsonRespondSpec.groovy
index e9b63cd7fea..8665c841507 100644
--- a/grails-test-examples/hibernate7/spring-json-respond/src/integration-test/groovy/springjson/SpringJsonRespondSpec.groovy
+++ b/grails-test-examples/hibernate7/spring-json-respond/src/integration-test/groovy/springjson/SpringJsonRespondSpec.groovy
@@ -30,7 +30,8 @@ import org.apache.grails.testing.http.client.HttpClientSupport
* grails.databinding.json.jackson, the defaults later releases change to, as application.yml sets them: respond writes JSON
* through Spring MVC's converter with the Grails mapper, binds JSON bodies with Jackson, and Spring MVC writes the
* problems it responds with, with the application's advice. With grails.exceptionresolver.springHandlers, the exception
- * handlers of the application and of spring.mvc.problemdetails.enabled answer the exceptions an action throws. What an
+ * handlers of the application and of spring.mvc.problemdetails.enabled answer the exceptions an action throws, and with
+ * grails.exceptionresolver.problemDetails, a problem answers one they do not, unless the error page is for it. What an
* action returns, where Spring MVC writes what a handler method returns as the response, such as a ResponseEntity, Spring
* MVC writes, and with grails.controllers.responseBody, so is the value of an action annotated @ResponseBody.
*/
@@ -38,6 +39,10 @@ import org.apache.grails.testing.http.client.HttpClientSupport
@Tag('http-client')
class SpringJsonRespondSpec extends Specification implements HttpClientSupport {
+ private static final String HTML = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
+
+ private static final String BROWSER = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36'
+
Long bookId
Long authorId
@@ -163,12 +168,67 @@ class SpringJsonRespondSpec extends Specification implements HttpClientSupport {
response.json().bookId == 42
}
- void 'an exception no exception handler answers is resolved as without the setting'() {
+ void 'an exception no exception handler answers is written as a problem that does not expose its message to #client'() {
+ when:
+ def response = http(headers, '/book/broken')
+
+ then:
+ response.assertStatus(500)
+ response.contentType == 'application/problem+json'
+ response.headerValue('X-Advised-By') == 'ProblemAdvice'
+ response.json().status == 500
+ response.json().title == 'Internal Server Error'
+ response.json().advisedBy == 'ProblemAdvice'
+ !response.body().contains('Not handled by any exception handler')
+
+ where:
+ client | headers
+ 'a client without an Accept header' | [:]
+ 'a client that accepts any type' | [Accept: '*/*']
+ 'a client that asks for JSON' | [Accept: 'application/json']
+ 'a browser that asks for JSON' | [Accept: 'application/json', 'User-Agent': BROWSER]
+ }
+
+ void 'an action named with the json extension is answered with a problem, whatever the Accept header prefers'() {
+ when:
+ def response = http([Accept: HTML], '/book/broken.json')
+
+ then:
+ response.assertStatus(500)
+ response.contentType == 'application/problem+json'
+ }
+
+ void 'the status and detail of a ResponseStatusException are those of the problem'() {
+ when:
+ def response = http('/book/gone')
+
+ then:
+ response.assertStatus(410)
+ response.contentType == 'application/problem+json'
+ response.json().detail == 'The book was withdrawn'
+ }
+
+ void 'an exception no exception handler answers renders the error page for #client'() {
+ when:
+ def response = http(headers, '/book/broken')
+
+ then:
+ response.assertStatus(500)
+ response.body() == 'the error page'
+
+ where:
+ client | headers
+ 'a client that asks for HTML' | [Accept: 'text/html']
+ 'a browser' | [Accept: HTML, 'User-Agent': BROWSER]
+ }
+
+ void 'an exception a URL mapping names is answered by that mapping, whatever the client asks for'() {
when:
- def response = http('/book/broken')
+ def response = http([Accept: 'application/json'], '/book/archived')
then:
response.assertStatus(500)
+ response.body() == 'the mapping for an archived book'
}
void 'a ResponseEntity an action returns is written by Spring MVC, with the advice of the application'() {
diff --git a/grails-test-examples/hibernate7/spring-json-respond/src/main/groovy/springjson/BookArchivedException.groovy b/grails-test-examples/hibernate7/spring-json-respond/src/main/groovy/springjson/BookArchivedException.groovy
new file mode 100644
index 00000000000..0381a2190e0
--- /dev/null
+++ b/grails-test-examples/hibernate7/spring-json-respond/src/main/groovy/springjson/BookArchivedException.groovy
@@ -0,0 +1,27 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * https://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 springjson
+
+class BookArchivedException extends RuntimeException {
+
+ BookArchivedException(String message) {
+ super(message)
+ }
+}
diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionExceptionHandlerResolver.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionExceptionHandlerResolver.groovy
index 3055b9e564a..88d2dc3a25d 100644
--- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionExceptionHandlerResolver.groovy
+++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionExceptionHandlerResolver.groovy
@@ -19,6 +19,8 @@
package org.grails.web.mapping.mvc
import groovy.transform.CompileStatic
+import groovy.util.logging.Slf4j
+import org.codehaus.groovy.runtime.InvokerInvocationException
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
@@ -26,14 +28,30 @@ import jakarta.servlet.http.HttpServletResponse
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.core.Ordered
+import org.springframework.http.HttpStatus
+import org.springframework.http.HttpStatusCode
+import org.springframework.http.MediaType
+import org.springframework.http.server.observation.ServerRequestObservationContext
+import org.springframework.web.ErrorResponse
+import org.springframework.web.HttpMediaTypeNotAcceptableException
+import org.springframework.web.accept.ContentNegotiationManager
+import org.springframework.web.context.request.ServletWebRequest
+import org.springframework.web.filter.ServerHttpObservationFilter
import org.springframework.web.method.HandlerMethod
+import org.springframework.web.method.annotation.ProblemDetailExceptionHandler
import org.springframework.web.servlet.HandlerExceptionResolver
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.handler.HandlerExceptionResolverComposite
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver
+import org.springframework.web.servlet.support.RequestContextUtils
import grails.config.Settings
+import grails.web.mapping.UrlMappingsHolder
+import grails.web.mime.MimeType
+import grails.web.mime.MimeTypeResolver
+import org.grails.exceptions.ExceptionUtils
import org.grails.web.servlet.mvc.GrailsWebRequest
+import org.grails.web.servlet.mvc.exceptions.GrailsMVCException
import org.grails.web.util.GrailsApplicationAttributes
/**
@@ -44,11 +62,20 @@ import org.grails.web.util.GrailsApplicationAttributes
* ordered ahead of Spring MVC's resolvers, as that resolver is ahead of Spring MVC's others, so that an exception none of
* those methods handles is resolved by them and by the Grails exception resolver, as without it.
*
+ *
With {@code grails.exceptionresolver.problemDetails}, it writes an exception none of those methods handles as an
+ * RFC 9457 problem, as Spring MVC writes one with {@code ProblemDetailsConfigurer.renderUnhandledExceptions}, except to
+ * a client that prefers HTML, or where a URL mapping names the exception. Those are left to the Grails exception
+ * resolver and the application's error page, which turning on that switch of Spring MVC would take every exception from.
+ *
* @since 9.0
*/
@CompileStatic
+@Slf4j
class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordered, ApplicationContextAware {
+ /** The name of the bean Spring MVC's content negotiation manager is. */
+ private static final String MVC_CONTENT_NEGOTIATION_MANAGER = 'mvcContentNegotiationManager'
+
/** Ahead of Spring MVC's resolvers, which its configuration orders at 0, behind Spring Boot's error attributes. */
int order = -1
@@ -58,10 +85,23 @@ class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordere
*/
Boolean enabled
+ /**
+ * Whether it writes an exception no handler method handles as a problem, as
+ * {@code grails.exceptionresolver.problemDetails} says, which it reads from the environment of its application
+ * context where it is not set.
+ *
+ * @since 9.1
+ */
+ Boolean problemDetails
+
private ApplicationContext applicationContext
private volatile ExceptionHandlerExceptionResolver resolver
+ private ActionReturnValues returnValues
+
+ private ProblemDetailExceptionHandler problemDetailHandler
+
@Override
void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext
@@ -69,18 +109,117 @@ class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordere
enabled = applicationContext.environment.getProperty(Settings.SETTING_EXCEPTION_RESOLVER_SPRING_HANDLERS, Boolean,
Boolean.valueOf(Settings.SETTING_EXCEPTION_RESOLVER_SPRING_HANDLERS_DEFAULT))
}
+ if (problemDetails == null) {
+ problemDetails = applicationContext.environment.getProperty(Settings.SETTING_EXCEPTION_RESOLVER_PROBLEM_DETAILS,
+ Boolean, false)
+ }
+ returnValues = new ActionReturnValues(applicationContext)
+ problemDetailHandler = new ProblemDetailExceptionHandler(applicationContext)
}
@Override
ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
- if (!enabled || !(handler instanceof GrailsControllerUrlMappingInfo)) {
+ if (!(handler instanceof GrailsControllerUrlMappingInfo)) {
return null
}
- HandlerMethod action = action(request, (GrailsControllerUrlMappingInfo) handler)
+ ModelAndView resolved = enabled ? resolveWithHandlerMethods(request, response, (GrailsControllerUrlMappingInfo) handler, ex) : null
+ return resolved == null && problemDetails ? resolveAsProblem(request, response, ex) : resolved
+ }
+
+ private ModelAndView resolveWithHandlerMethods(HttpServletRequest request, HttpServletResponse response,
+ GrailsControllerUrlMappingInfo handler, Exception ex) {
+ HandlerMethod action = action(request, handler)
ExceptionHandlerExceptionResolver springResolver = action != null ? exceptionHandlerResolver() : null
return springResolver?.resolveException(request, response, action, ex)
}
+ /**
+ * Writes an exception as Spring MVC writes one no handler method handles, with Spring MVC's translation of it, which
+ * logs an unexpected one and never exposes its message. A failure to write it leaves the exception to the other
+ * resolvers, as a failure of an exception handler method leaves it in Spring MVC.
+ */
+ private ModelAndView resolveAsProblem(HttpServletRequest request, HttpServletResponse response, Exception thrown) {
+ Exception ex = unwrap(thrown)
+ try {
+ if (response.committed || !returnValues.writesErrorResponses() || prefersHtml(request) || isMappedToErrorHandler(ex)) {
+ return null
+ }
+ ErrorResponse errorResponse = problemDetailHandler.handleException(ex, RequestContextUtils.getLocale(request))
+ ModelAndView written = errorResponse == null ? new ModelAndView() : returnValues.writeErrorResponse(errorResponse,
+ request.getAttribute(GrailsApplicationAttributes.CONTROLLER), request, response)
+ if (HttpStatusCode.valueOf(response.status).is5xxServerError()) {
+ recordServerError(request, ex)
+ // Spring MVC's translation logs an unexpected exception without the request it failed
+ if (!(ex instanceof ErrorResponse)) {
+ log.error('{} occurred when processing request: [{}] {}', ex.class.simpleName, request.method, request.requestURI)
+ }
+ }
+ return written
+ }
+ catch (Exception e) {
+ log.warn('Could not write a problem for an exception of [{}], so leaving it to the other exception resolvers',
+ request.requestURI, e)
+ return null
+ }
+ }
+
+ /** As the Grails exception resolver finds the exception an action threw. */
+ private static Exception unwrap(Exception ex) {
+ if (ex instanceof InvokerInvocationException || ex instanceof GrailsMVCException) {
+ Throwable rootCause = ExceptionUtils.getRootCause(ex)
+ if (rootCause instanceof Exception) {
+ return (Exception) rootCause
+ }
+ }
+ return ex
+ }
+
+ /**
+ * Whether the application's error page is what the client asks for: the format Grails resolves for the response,
+ * from a {@code format} parameter or the {@code Accept} header, or else, where that is any format, as for a browser
+ * whose {@code Accept} header {@code grails.mime.disable.accept.header.userAgents} disregards, whether the first
+ * concrete type of the {@code Accept} header is HTML, as Spring MVC decides to render a problem as a view.
+ */
+ private boolean prefersHtml(HttpServletRequest request) {
+ GrailsWebRequest webRequest = GrailsWebRequest.lookup(request)
+ MimeType format = webRequest != null ? applicationContext.getBeanProvider(MimeTypeResolver).getIfAvailable()
+ ?.resolveResponseMimeType(webRequest) : null
+ if (format != null && format.extension != MimeType.ALL.extension) {
+ return format.extension == MimeType.HTML.extension
+ }
+ try {
+ MediaType first = contentNegotiationManager().resolveMediaTypes(new ServletWebRequest(request))
+ .find { MediaType type -> type.concrete }
+ return first != null && MediaType.TEXT_HTML.isCompatibleWith(first)
+ }
+ catch (HttpMediaTypeNotAcceptableException ignored) {
+ return false
+ }
+ }
+
+ private ContentNegotiationManager contentNegotiationManager() {
+ return applicationContext.containsBean(MVC_CONTENT_NEGOTIATION_MANAGER) ?
+ applicationContext.getBean(MVC_CONTENT_NEGOTIATION_MANAGER, ContentNegotiationManager) :
+ new ContentNegotiationManager()
+ }
+
+ /** Whether the application maps the exception, as a {@code "500"} mapping with an {@code exception} names it. */
+ private boolean isMappedToErrorHandler(Exception ex) {
+ if (!applicationContext.containsBean(UrlMappingsHolder.BEAN_ID)) {
+ return false
+ }
+ UrlMappingsHolder urlMappings = applicationContext.getBean(UrlMappingsHolder.BEAN_ID, UrlMappingsHolder)
+ int status = HttpStatus.INTERNAL_SERVER_ERROR.value()
+ return urlMappings.matchStatusCode(status, ex) != null || urlMappings.matchStatusCode(status, ExceptionUtils.getRootCause(ex)) != null
+ }
+
+ /** As Spring MVC records an exception it translates to a server error, which the observation would not see otherwise. */
+ private static void recordServerError(HttpServletRequest request, Exception ex) {
+ ServerHttpObservationFilter.findObservationContext(request).ifPresent { ServerRequestObservationContext context ->
+ context.error = ex
+ }
+ }
+
/** The action as a handler method: the controller that handles the request, and its method of the action. */
private static HandlerMethod action(HttpServletRequest request, GrailsControllerUrlMappingInfo info) {
String actionName = GrailsWebRequest.lookup(request)?.actionName ?: info.actionName ?: info.controllerClass.defaultAction
diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionReturnValues.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionReturnValues.groovy
index a95be909958..bcf2e430b98 100644
--- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionReturnValues.groovy
+++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionReturnValues.groovy
@@ -29,6 +29,7 @@ import jakarta.servlet.http.HttpServletResponse
import org.springframework.context.ApplicationContext
import org.springframework.context.MessageSource
+import org.springframework.core.MethodParameter
import org.springframework.core.annotation.AnnotatedElementUtils
import org.springframework.core.task.AsyncTaskExecutor
import org.springframework.http.HttpEntity
@@ -83,6 +84,9 @@ class ActionReturnValues {
/** The request attribute that holds the action whose asynchronous value the request completes. */
private static final String ASYNC_ACTION = ActionReturnValues.name + '.ASYNC_ACTION'
+ /** The method an error response is written as the return value of, where it is not the value of an action. */
+ private static final Method RETURNED_ERROR_RESPONSE = ActionReturnValues.getDeclaredMethod('returnedErrorResponse')
+
/** The method of each action of each controller class, by its name. */
private static final Map, Map> ACTIONS = new ConcurrentReferenceHashMap<>()
@@ -178,6 +182,42 @@ class ActionReturnValues {
return write(value, action, request, response)
}
+ /**
+ * Whether Spring MVC's handler adapter is there to write an error response.
+ *
+ * @return whether it is
+ * @since 9.1
+ */
+ boolean writesErrorResponses() {
+ return adapter() != null
+ }
+
+ /**
+ * Writes an error response with the return value handler Spring MVC's handler adapter selects for one, as Spring MVC
+ * writes what an exception handler method returns: with its content negotiation, its {@code ErrorResponse.Interceptor}
+ * beans and the {@code ResponseBodyAdvice} beans that apply to the controller, which the action of the exception may
+ * not have got as far as creating.
+ *
+ * @param errorResponse the error response
+ * @param controller the controller, or {@code null}
+ * @param request the request
+ * @param response the response
+ * @return the view a handler selected, or an empty one where it wrote the response
+ * @since 9.1
+ */
+ ModelAndView writeErrorResponse(ErrorResponse errorResponse, Object controller, HttpServletRequest request, HttpServletResponse response) {
+ GrailsWebRequest.lookup(request)?.renderView = false
+ MethodParameter returnType = new MethodParameter(RETURNED_ERROR_RESPONSE, -1)
+ .withContainingClass(controller?.getClass() ?: ActionReturnValues)
+ ModelAndViewContainer container = new ModelAndViewContainer()
+ adapter().returnValueHandlers.handleReturnValue(errorResponse, returnType, container, new ServletWebRequest(request, response))
+ return container.requestHandled ? new ModelAndView() : viewOf(container)
+ }
+
+ private static ErrorResponse returnedErrorResponse() {
+ return null
+ }
+
private ModelAndView write(Object value, ActionHandlerMethod action, HttpServletRequest request, HttpServletResponse response) {
MvcAdapter adapter = adapter()
GrailsWebRequest.lookup(request)?.renderView = false
@@ -210,7 +250,11 @@ class ActionReturnValues {
if (container.requestHandled) {
return null
}
- // a value Spring MVC renders a view for, such as a ModelAndView an action annotated @ResponseBody returns
+ return viewOf(container)
+ }
+
+ /** A value Spring MVC renders a view for, such as a ModelAndView an action annotated @ResponseBody returns. */
+ private static ModelAndView viewOf(ModelAndViewContainer container) {
ModelAndView modelAndView = container.viewReference ? new ModelAndView(container.viewName, container.model) :
new ModelAndView((View) container.view, container.model)
if (container.status != null) {
diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionExceptionProblemDetailsSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionExceptionProblemDetailsSpec.groovy
new file mode 100644
index 00000000000..8a6319cc87f
--- /dev/null
+++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionExceptionProblemDetailsSpec.groovy
@@ -0,0 +1,373 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * https://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 org.grails.web.mapping.mvc
+
+import groovy.json.JsonSlurper
+import org.codehaus.groovy.runtime.InvokerInvocationException
+
+import org.springframework.core.env.MapPropertySource
+import org.springframework.http.HttpHeaders
+import org.springframework.http.HttpStatus
+import org.springframework.http.ProblemDetail
+import org.springframework.http.converter.HttpMessageConverter
+import org.springframework.http.converter.json.JacksonJsonHttpMessageConverter
+import org.springframework.http.server.observation.ServerRequestObservationContext
+import org.springframework.mock.web.MockHttpServletRequest
+import org.springframework.mock.web.MockHttpServletResponse
+import org.springframework.mock.web.MockServletContext
+import org.springframework.web.ErrorResponse
+import org.springframework.web.ErrorResponseException
+import org.springframework.web.bind.annotation.ControllerAdvice
+import org.springframework.web.bind.annotation.ExceptionHandler
+import org.springframework.web.bind.annotation.ResponseStatus
+import org.springframework.web.context.request.async.AsyncRequestNotUsableException
+import org.springframework.web.context.support.GenericWebApplicationContext
+import org.springframework.web.filter.ServerHttpObservationFilter
+import org.springframework.web.server.ResponseStatusException
+import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver
+import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
+
+import grails.core.DefaultGrailsApplication
+import grails.core.GrailsApplication
+import grails.web.mapping.UrlMappingInfo
+import grails.web.mapping.UrlMappingsHolder
+import org.grails.core.DefaultGrailsControllerClass
+import org.grails.support.MockApplicationContext
+import org.grails.web.mapping.DefaultUrlMappingEvaluator
+import org.grails.web.mapping.DefaultUrlMappingsHolder
+import org.grails.web.servlet.mvc.GrailsWebRequest
+import org.grails.web.util.GrailsApplicationAttributes
+import org.apache.grails.core.testing.support.LogCapture
+import spock.lang.Specification
+
+/**
+ * An exception a controller action throws is written as a problem where {@code grails.exceptionresolver.problemDetails}
+ * is set, by Spring MVC's translation and its handler adapter, unless the application's error page is for it.
+ */
+class ActionExceptionProblemDetailsSpec extends Specification {
+
+ private GenericWebApplicationContext context
+
+ private MockHttpServletRequest request
+
+ private MockHttpServletResponse response
+
+ private List interceptors = []
+
+ void setup() {
+ request = new MockHttpServletRequest(new MockServletContext())
+ request.requestURI = '/problem/index'
+ response = new MockHttpServletResponse()
+ new GrailsWebRequest(request, response, request.servletContext)
+ }
+
+ void cleanup() {
+ context?.close()
+ }
+
+ void 'with the setting, an exception is written as a problem that does not expose its message, to a client that #client'() {
+ given:
+ def resolver = resolver([problemDetails: true])
+ if (accept) {
+ request.addHeader(HttpHeaders.ACCEPT, accept)
+ }
+
+ when:
+ def modelAndView = resolver.resolveException(request, response, action(new ProblemController()), new IllegalStateException('secret'))
+
+ then:
+ modelAndView != null
+ modelAndView.empty
+ response.status == 500
+ response.contentType == 'application/problem+json'
+ problem() == [title: 'Internal Server Error', status: 500]
+ !response.contentAsString.contains('secret')
+
+ where:
+ client | accept
+ 'names no type' | null
+ 'accepts any type' | '*/*'
+ 'asks for JSON' | 'application/json'
+ 'asks for text' | 'text/plain'
+ 'asks for JSON first' | 'application/json, text/html;q=0.9'
+ }
+
+ void 'an exception is left to the other resolvers for a client that prefers HTML: #accept'() {
+ given:
+ def resolver = resolver([problemDetails: true])
+ request.addHeader(HttpHeaders.ACCEPT, accept)
+
+ expect:
+ resolver.resolveException(request, response, action(new ProblemController()), new IllegalStateException('secret')) == null
+ response.status == 200
+ !response.contentAsString
+
+ where:
+ accept << ['text/html', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'application/json;q=0.5, text/html']
+ }
+
+ void 'without the setting, an exception is left to the other resolvers'() {
+ given:
+ def resolver = resolver(setting)
+
+ expect:
+ resolver.resolveException(request, response, action(new ProblemController()), new IllegalStateException('secret')) == null
+ response.status == 200
+
+ where:
+ setting << [[:], [problemDetails: false]]
+ }
+
+ void 'a handler that is not an action is left to the other resolvers'() {
+ given:
+ def resolver = resolver([problemDetails: true])
+
+ expect:
+ resolver.resolveException(request, response, new Object(), new IllegalStateException('secret')) == null
+ }
+
+ void 'an exception after the response is committed is left to the other resolvers'() {
+ given:
+ def resolver = resolver([problemDetails: true])
+ response.committed = true
+
+ expect:
+ resolver.resolveException(request, response, action(new ProblemController()), new IllegalStateException('secret')) == null
+ }
+
+ void 'the problem has the status and detail #description declares'() {
+ given:
+ def resolver = resolver([problemDetails: true])
+
+ when:
+ resolver.resolveException(request, response, action(new ProblemController()), exception)
+
+ then:
+ response.status == status
+ problem().detail == detail
+
+ where:
+ description | exception | status | detail
+ 'a ResponseStatusException' | new ResponseStatusException(HttpStatus.GONE, 'Withdrawn') | 410 | 'Withdrawn'
+ '@ResponseStatus' | new TeapotException() | 418 | 'Short and stout'
+ '@ResponseStatus of a cause' | new RuntimeException(new TeapotException()) | 418 | 'Short and stout'
+ 'an ErrorResponse' | new ErrorResponseException(HttpStatus.SERVICE_UNAVAILABLE, ProblemDetail.forStatusAndDetail(HttpStatus.SERVICE_UNAVAILABLE, 'Later'), null) | 503 | 'Later'
+ }
+
+ void 'an exception wrapped by a dynamic invocation is written as the exception the action threw'() {
+ given:
+ def resolver = resolver([problemDetails: true])
+ def thrown = new ErrorResponseException(HttpStatus.CONFLICT, ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, 'Taken'), null)
+
+ when:
+ resolver.resolveException(request, response, action(new ProblemController()), new InvokerInvocationException(thrown))
+
+ then:
+ response.status == 409
+ problem().detail == 'Taken'
+ }
+
+ void 'a request that can no longer be answered writes nothing'() {
+ given:
+ def resolver = resolver([problemDetails: true])
+
+ when:
+ def modelAndView = resolver.resolveException(request, response, action(new ProblemController()), new AsyncRequestNotUsableException('gone'))
+
+ then:
+ modelAndView.empty
+ !response.contentAsString
+ }
+
+ void 'an exception a URL mapping names, or whose cause it names, is left to the Grails exception resolver'() {
+ given:
+ def resolver = resolver([problemDetails: true]) {
+ "500"(controller: 'errors', action: 'denied', exception: SecurityException)
+ "500"(controller: 'errors', action: 'serverError')
+ }
+
+ expect:
+ resolver.resolveException(request, response, action(new ProblemController()), new SecurityException('denied')) == null
+ resolver.resolveException(request, response, action(new ProblemController()), new RuntimeException(new SecurityException('denied'))) == null
+
+ and: 'a mapping for the status alone is the error page of a client that prefers HTML'
+ resolver.resolveException(request, response, action(new ProblemController()), new IllegalStateException('secret')) != null
+ response.status == 500
+ }
+
+ void 'the exception handlers of the advice go first, with both settings'() {
+ given:
+ def resolver = resolver([springHandlers: true, problemDetails: true])
+
+ when:
+ resolver.resolveException(request, response, action(new ProblemController()), new IllegalArgumentException('advised'))
+
+ then:
+ response.status == 422
+ problem().detail == 'advised'
+
+ when: 'none of them handles it'
+ response = new MockHttpServletResponse()
+ resolver.resolveException(request, response, action(new ProblemController()), new IllegalStateException('secret'))
+
+ then:
+ response.status == 500
+ problem() == [title: 'Internal Server Error', status: 500]
+ }
+
+ void 'a controller the request has not created yet does not stop an exception being written'() {
+ given:
+ def resolver = resolver([problemDetails: true])
+ def info = new GrailsControllerUrlMappingInfo(new DefaultGrailsControllerClass(ProblemController), Stub(UrlMappingInfo) {
+ getActionName() >> 'index'
+ })
+
+ when:
+ resolver.resolveException(request, response, info, new IllegalStateException('secret'))
+
+ then:
+ response.status == 500
+ problem().status == 500
+ }
+
+ void 'a server error is recorded on the HTTP server observation, and a client error is not'() {
+ given:
+ def resolver = resolver([problemDetails: true])
+ def observation = new ServerRequestObservationContext(request, response)
+ request.setAttribute(ServerHttpObservationFilter.CURRENT_OBSERVATION_CONTEXT_ATTRIBUTE, observation)
+ def serverError = new IllegalStateException('secret')
+
+ when:
+ resolver.resolveException(request, response, action(new ProblemController()), new ResponseStatusException(HttpStatus.GONE))
+
+ then:
+ observation.error == null
+
+ when:
+ response = new MockHttpServletResponse()
+ resolver.resolveException(request, response, action(new ProblemController()), serverError)
+
+ then:
+ observation.error.is(serverError)
+ }
+
+ void 'the request of an unexpected exception is logged, and that of an exception raised on purpose is not'() {
+ given:
+ def resolver = resolver([problemDetails: true])
+ def logCapture = new LogCapture(ActionExceptionHandlerResolver)
+ request.method = 'GET'
+
+ when:
+ resolver.resolveException(request, response, action(new ProblemController()),
+ new ErrorResponseException(HttpStatus.SERVICE_UNAVAILABLE))
+
+ then:
+ response.status == 503
+ logCapture.events.empty
+
+ when:
+ response = new MockHttpServletResponse()
+ resolver.resolveException(request, response, action(new ProblemController()), new IllegalStateException('secret'))
+
+ then:
+ logCapture.events*.formattedMessage == ['IllegalStateException occurred when processing request: [GET] /problem/index']
+
+ cleanup:
+ logCapture.close()
+ }
+
+ void 'an ErrorResponse.Interceptor sees the problem, as it sees one a handler method returns'() {
+ given:
+ interceptors = [new ErrorResponse.Interceptor() {
+ @Override
+ void handleError(ProblemDetail detail, ErrorResponse errorResponse) {
+ detail.instance = URI.create('urn:problem:1')
+ }
+ }]
+ def resolver = resolver([problemDetails: true])
+
+ when:
+ resolver.resolveException(request, response, action(new ProblemController()), new IllegalStateException('secret'))
+
+ then:
+ problem().instance == 'urn:problem:1'
+ }
+
+ void 'a failure to write the problem leaves the exception to the other resolvers'() {
+ given:
+ def resolver = resolver([problemDetails: true])
+ def failing = Spy(response) {
+ getOutputStream() >> { throw new IOException('closed') }
+ }
+
+ expect:
+ resolver.resolveException(request, failing, action(new ProblemController()), new IllegalStateException('secret')) == null
+ }
+
+ private Map problem() {
+ new JsonSlurper().parseText(response.contentAsString) as Map
+ }
+
+ private ActionExceptionHandlerResolver resolver(Map settings, Closure mappings = null) {
+ context = new GenericWebApplicationContext()
+ context.environment.propertySources.addFirst(new MapPropertySource('test',
+ settings.collectEntries { key, value -> ["grails.exceptionresolver.$key".toString(), value] } as Map))
+ List> converters = [new JacksonJsonHttpMessageConverter()]
+ context.registerBean(ProblemControllerAdvice)
+ context.registerBean(ExceptionHandlerExceptionResolver, { new ExceptionHandlerExceptionResolver(messageConverters: converters) })
+ context.registerBean('requestMappingHandlerAdapter', RequestMappingHandlerAdapter, {
+ new RequestMappingHandlerAdapter(messageConverters: converters, errorResponseInterceptors: interceptors)
+ })
+ if (mappings != null) {
+ def grailsContext = new MockApplicationContext()
+ grailsContext.registerMockBean(GrailsApplication.APPLICATION_ID, new DefaultGrailsApplication())
+ def holder = new DefaultUrlMappingsHolder(new DefaultUrlMappingEvaluator(grailsContext).evaluateMappings(mappings))
+ context.registerBean(UrlMappingsHolder.BEAN_ID, UrlMappingsHolder, { holder })
+ }
+ context.registerBean(ActionExceptionHandlerResolver)
+ context.refresh()
+ context.getBean(ActionExceptionHandlerResolver)
+ }
+
+ private GrailsControllerUrlMappingInfo action(Object controller) {
+ request.setAttribute(GrailsApplicationAttributes.CONTROLLER, controller)
+ new GrailsControllerUrlMappingInfo(new DefaultGrailsControllerClass(controller.getClass()), Stub(UrlMappingInfo) {
+ getActionName() >> 'index'
+ })
+ }
+}
+
+class ProblemController {
+
+ def index() {
+ }
+}
+
+@ResponseStatus(code = HttpStatus.I_AM_A_TEAPOT, reason = 'Short and stout')
+class TeapotException extends RuntimeException {
+}
+
+@ControllerAdvice(assignableTypes = ProblemController)
+class ProblemControllerAdvice {
+
+ @ExceptionHandler(IllegalArgumentException)
+ ProblemDetail unprocessable(IllegalArgumentException e) {
+ ProblemDetail.forStatusAndDetail(HttpStatus.UNPROCESSABLE_CONTENT, e.message)
+ }
+}
From 914f10a0d60760fc698a6b0a2730f49fce06db05 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 11:55:41 -0800
Subject: [PATCH 11/78] Document X-Forwarded-Prefix and the buildpacks changes
of Spring Boot 4.2
Spring Boot 4.2 builds its ForwardedHeaderFilter with the X-Forwarded-Prefix
header off, where Spring Boot 4.1 used the constructor that turns it on. An
application behind a proxy that strips a path prefix loses the prefix from its
absolute links and redirects until it sets
spring.mvc.forwarded-headers.use-forwarded-prefix.
bootBuildImage now defaults to the ubuntu-resolute builder, on Ubuntu 26.04, whose
run image the builder no longer pins, and can keep the build cache in an image in
a registry.
---
.../guide/deployment/deploymentLayeredBuilds.adoc | 15 ++++++++++++++-
.../src/en/guide/deployment/deploymentTasks.adoc | 1 +
.../src/en/guide/upgrading/upgrading90x.adoc | 6 ++++++
3 files changed, 21 insertions(+), 1 deletion(-)
diff --git a/grails-doc/src/en/guide/deployment/deploymentLayeredBuilds.adoc b/grails-doc/src/en/guide/deployment/deploymentLayeredBuilds.adoc
index 6f60ce6bf7b..7bf25ce67db 100644
--- a/grails-doc/src/en/guide/deployment/deploymentLayeredBuilds.adoc
+++ b/grails-doc/src/en/guide/deployment/deploymentLayeredBuilds.adoc
@@ -206,8 +206,9 @@ Explicitly selecting `bootJar` matters when the `war` plugin is also applied: Sp
./gradlew clean check bootBuildImage --imageName=myapp:0.1
----
+By default, Spring Boot {springBootVersion} uses the `paketobuildpacks/ubuntu-resolute-builder` builder, and the `paketobuildpacks/ubuntu-resolute-run-tiny:latest` run image, which has no shell.
Use the builder supported by the Spring Boot plugin version in your application, or select a maintained builder and its compatible run image explicitly.
-For repeatable release builds, pin both images to tested digests and schedule rebuilds when they change.
+The builder does not pin the version of its run image, so for repeatable release builds, set both images, pinned to tested digests, and schedule rebuilds when they change.
Check that the builder, run image, and buildpacks support your target CPU architecture and any required native libraries.
Paketo's Java buildpack calculates JVM memory settings from the container memory limit and non-heap requirements.
@@ -215,6 +216,18 @@ Set a container limit and tune its documented `BPL_JVM_*` runtime options for yo
Keep the buildpack launcher as the entry point so its memory calculation, bindings, and runtime configuration execute.
`BP_*` settings configure the image build; deployment-specific configuration and secrets belong at runtime.
When image tags change on every release, use stable, application-specific `buildCache` and `launchCache` volume names if you want to retain buildpack caches across versions.
+To share the build cache between hosts, such as CI runners, keep it in an image in a registry instead of a volume; `launchCache` stays local:
+
+[source,groovy]
+----
+tasks.named('bootBuildImage') {
+ buildCache {
+ image {
+ name = 'registry.example.com/myapp-build-cache:latest'
+ }
+ }
+}
+----
For a local smoke test, supply the application's required external configuration and run the image with a memory limit:
diff --git a/grails-doc/src/en/guide/deployment/deploymentTasks.adoc b/grails-doc/src/en/guide/deployment/deploymentTasks.adoc
index df4852231dd..9ed603d338f 100644
--- a/grails-doc/src/en/guide/deployment/deploymentTasks.adoc
+++ b/grails-doc/src/en/guide/deployment/deploymentTasks.adoc
@@ -192,6 +192,7 @@ Many deployments terminate TLS at a reverse proxy or ingress. Keep certificate r
Configure forwarded-header handling only for a trusted proxy path, and have the boundary proxy remove untrusted client-supplied `Forwarded` and `X-Forwarded-*` headers.
Choose `server.forward-headers-strategy=NATIVE` for supported embedded-container handling or `FRAMEWORK` for Spring's handling, according to your proxy's headers and trust configuration.
`FRAMEWORK` reads the `+X-Forwarded-*+` headers; if your proxy sends the RFC 7239 `Forwarded` header instead, also set `spring.mvc.forwarded-headers.header-format=STANDARD`.
+It ignores `X-Forwarded-Prefix`; if your proxy strips a path prefix and sends that header, also set `spring.mvc.forwarded-headers.use-forwarded-prefix=true`.
Test redirects, absolute URLs, secure cookies, and client-address handling through that proxy. See the link:{springBootHowTo}webserver.html#howto.webserver.use-behind-a-proxy-server[Spring Boot proxy guidance].
To terminate TLS in the embedded server instead, merge settings such as these into `application.yml` and mount the keystore read-only:
diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
index f3bba752809..ea83724e796 100644
--- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
+++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
@@ -51,6 +51,7 @@ The ones most likely to affect a Grails application are:
Spring Framework 7.1's `ForwardedHeaderFilter` reads either the RFC 7239 `Forwarded` header or the `+X-Forwarded-*+` headers, and Spring Boot 4.2 configures it for `+X-Forwarded-*+`.
Before, it read `Forwarded` when the request carried one and `+X-Forwarded-*+` otherwise.
If your reverse proxy sends `Forwarded`, set `spring.mvc.forwarded-headers.header-format: standard`.
+The filter also ignores `X-Forwarded-Prefix` now, where it used to add it to the context path, so if your proxy strips a path prefix and sends that header, absolute links and redirects lose the prefix until you set `spring.mvc.forwarded-headers.use-forwarded-prefix: true`.
Spring Boot 4.2 also registers the filter from its Spring MVC auto-configuration, which backs off when the application declares `@EnableWebMvc`; such an application must now register a `ForwardedHeaderFilter` itself.
* *Embedded Tomcat keeps relative redirect locations relative.*
@@ -108,6 +109,11 @@ The Spring TestContext Framework used to ignore such a class unless its class hi
Grails 8 already logs a warning for each one it ignores, so a test run on Grails 8 shows the affected tests.
Remove the `@Configuration` annotation, or move the class to a top-level class, if the test should not load it.
+* *`bootBuildImage` builds on Ubuntu 26.04.*
+The default builder is `paketobuildpacks/ubuntu-resolute-builder`, in place of `paketobuildpacks/builder-noble-java-tiny`, and images are based on Ubuntu 26.04 instead of 24.04.
+With no `builder` configured, the run image is `paketobuildpacks/ubuntu-resolute-run-tiny:latest`, which still has no shell; with one configured, it is the run image of the builder, which for `ubuntu-resolute-builder` has a shell.
+The builder no longer pins the version of the run image, so set both `builder` and `runImage` to specific versions for repeatable images, or set `builder` to `paketobuildpacks/builder-noble-java-tiny` to keep the previous one.
+
* *The Spring Security plugin no longer saves the requests browsers send on their own.*
A denied request for `/apple-touch-icon.png`, `/manifest.json` or the `/.well-known/appspecific/com.chrome.devtools.json` that Chrome DevTools sends used to be saved, so a login redirected to it instead of to the page the user asked for.
Spring Security 7.2's configuration DSL ignores these paths, which the plugin does not use, so the plugin now ignores them too, with `grails.plugin.springsecurity.requestCache.ignoredPatterns`.
From cf086d970313e28fdf684f536e7bb9e958abc3f9 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 12:23:49 -0800
Subject: [PATCH 12/78] Run the exception handlers before writing a problem
With grails.exceptionresolver.problemDetails alone, an @ExceptionHandler method
was never consulted, so an action's exception became a generic 500 where
ProblemDetailsConfigurer.renderUnhandledExceptions, which the guide offers it in
place of, would have run the method.
A problem is the last resort after those methods, as it is in Spring MVC, so the
setting now turns on grails.exceptionresolver.springHandlers unless the
application sets that.
---
.../main/groovy/grails/config/Settings.groovy | 3 ++-
...itional-spring-configuration-metadata.json | 2 +-
.../en/guide/conf/config/builtInOptions.adoc | 2 +-
.../controllerExceptionHandling.adoc | 2 +-
.../mvc/ActionExceptionHandlerResolver.groovy | 12 +++++++-----
.../ActionExceptionProblemDetailsSpec.groovy | 19 +++++++++++++++++--
6 files changed, 29 insertions(+), 11 deletions(-)
diff --git a/grails-core/src/main/groovy/grails/config/Settings.groovy b/grails-core/src/main/groovy/grails/config/Settings.groovy
index 0ea8762f761..d6b9d6ec767 100644
--- a/grails-core/src/main/groovy/grails/config/Settings.groovy
+++ b/grails-core/src/main/groovy/grails/config/Settings.groovy
@@ -417,7 +417,8 @@ interface Settings {
* Whether an exception a controller action throws, that no {@code @ExceptionHandler} method handles, is written as an
* RFC 9457 problem, as Spring MVC writes one with {@code ProblemDetailsConfigurer.renderUnhandledExceptions}, except
* to a client that prefers HTML or where a URL mapping names the exception, which the Grails exception resolver
- * resolves as without it. Defaults to {@code false}.
+ * resolves as without it. It turns on {@link #SETTING_EXCEPTION_RESOLVER_SPRING_HANDLERS} unless the application sets
+ * that, since a problem is the last resort after those methods. Defaults to {@code false}.
*
* @since 9.1
*/
diff --git a/grails-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/grails-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json
index f30aaf2a109..fcadbeaaa3d 100644
--- a/grails-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json
+++ b/grails-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json
@@ -253,7 +253,7 @@
{
"name": "grails.exceptionresolver.problemDetails",
"type": "java.lang.Boolean",
- "description": "Whether an exception a controller action throws, that no @ExceptionHandler method handles, is written as an RFC 9457 problem, as Spring MVC writes one with ProblemDetailsConfigurer.renderUnhandledExceptions, except to a client that prefers HTML or where a URL mapping names the exception, which the Grails exception resolver resolves as without it.",
+ "description": "Whether an exception a controller action throws, that no @ExceptionHandler method handles, is written as an RFC 9457 problem, as Spring MVC writes one with ProblemDetailsConfigurer.renderUnhandledExceptions, except to a client that prefers HTML or where a URL mapping names the exception, which the Grails exception resolver resolves as without it. It turns on grails.exceptionresolver.springHandlers unless the application sets that.",
"defaultValue": false
},
{
diff --git a/grails-doc/src/en/guide/conf/config/builtInOptions.adoc b/grails-doc/src/en/guide/conf/config/builtInOptions.adoc
index ed1991bb4fc..e75cb409351 100644
--- a/grails-doc/src/en/guide/conf/config/builtInOptions.adoc
+++ b/grails-doc/src/en/guide/conf/config/builtInOptions.adoc
@@ -29,7 +29,7 @@ On the runtime front, i.e. `grails-app/conf/application.yml`, there are quite a
* `grails.enable.native2ascii` - Set this to false if you do not require native2ascii conversion of Grails i18n properties files (default: true).
* `grails.converters.encoding` - The character encoding for converter output (JSON or XML) and for the response content types stamped by the default renderers used by `respond()` (default: 'UTF-8'). JSON that `respond` writes through Spring MVC, with `grails.web.rendering.json.spring` or a named configuration, and problems are written in UTF-8, as Spring MVC writes JSON.
* `grails.exceptionresolver.springHandlers` - Whether an exception a controller action throws is resolved first by the `@ExceptionHandler` methods Spring MVC resolves those of a handler method with, those of the controller and of the `@ControllerAdvice` beans that apply to it, Spring Boot's handler of `spring.mvc.problemdetails.enabled` among them (default: false; true from Grails 10). See <>.
-* `grails.exceptionresolver.problemDetails` - Whether an exception a controller action throws, that no exception handler method handles, is written as an RFC 9457 problem to a client that does not prefer HTML, while the application's error page stays for browsers (default: false). See <>.
+* `grails.exceptionresolver.problemDetails` - Whether an exception a controller action throws, that no exception handler method handles, is written as an RFC 9457 problem to a client that does not prefer HTML, while the application's error page stays for browsers. It turns on `grails.exceptionresolver.springHandlers` unless that is set (default: false). See <>.
* `grails.controllers.responseBody` - Whether Spring MVC writes any value of a controller action annotated `@ResponseBody`, or of an action of a controller annotated so, as the body of the response, as it writes the value of a handler method annotated so, rather than Grails rendering the action's view for a model. A `ResponseEntity`, a `ProblemDetail` and the other values Spring MVC writes whatever a handler method is annotated with are written whatever it says (default: false; true from Grails 10). See <>.
* `grails.views.default.codec` - Sets the default encoding regime for GSPs - can be one of 'none', 'html', or 'base64' (default: 'none'). To reduce risk of XSS attacks, set this to 'html'.
* `grails.views.gsp.encoding` - The file encoding used for GSP source files (default: 'utf-8').
diff --git a/grails-doc/src/en/guide/theWebLayer/controllers/controllerExceptionHandling.adoc b/grails-doc/src/en/guide/theWebLayer/controllers/controllerExceptionHandling.adoc
index 1a7ea4273c8..fd9989d3794 100644
--- a/grails-doc/src/en/guide/theWebLayer/controllers/controllerExceptionHandling.adoc
+++ b/grails-doc/src/en/guide/theWebLayer/controllers/controllerExceptionHandling.adoc
@@ -149,7 +149,7 @@ class BookExceptionAdvice {
Declare the advice as a bean, in `grails-app/conf/spring/resources.groovy` or as a `@Bean` of a configuration class.
-With `grails.exceptionresolver.problemDetails: true`, an exception an action throws that no exception handler method handles is written as an https://www.rfc-editor.org/rfc/rfc9457.html[RFC 9457] problem to a client that does not prefer HTML, using the translation Spring Framework 7.1 adds, and the application's error page stays for browsers:
+With `grails.exceptionresolver.problemDetails: true`, an exception an action throws that no exception handler method handles is written as an https://www.rfc-editor.org/rfc/rfc9457.html[RFC 9457] problem to a client that does not prefer HTML, using the translation Spring Framework 7.1 adds, and the application's error page stays for browsers. A problem is the last resort after those methods, so the setting turns on `grails.exceptionresolver.springHandlers` unless the application sets that to `false`:
[source,yaml]
.grails-app/conf/application.yml
diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionExceptionHandlerResolver.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionExceptionHandlerResolver.groovy
index 88d2dc3a25d..a484bf919bb 100644
--- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionExceptionHandlerResolver.groovy
+++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionExceptionHandlerResolver.groovy
@@ -81,7 +81,8 @@ class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordere
/**
* Whether it resolves exceptions, as {@code grails.exceptionresolver.springHandlers} says, which it reads from the
- * environment of its application context where it is not set.
+ * environment of its application context where it is not set, and which {@code grails.exceptionresolver.problemDetails}
+ * turns on unless the application sets it.
*/
Boolean enabled
@@ -105,14 +106,15 @@ class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordere
@Override
void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext
- if (enabled == null) {
- enabled = applicationContext.environment.getProperty(Settings.SETTING_EXCEPTION_RESOLVER_SPRING_HANDLERS, Boolean,
- Boolean.valueOf(Settings.SETTING_EXCEPTION_RESOLVER_SPRING_HANDLERS_DEFAULT))
- }
if (problemDetails == null) {
problemDetails = applicationContext.environment.getProperty(Settings.SETTING_EXCEPTION_RESOLVER_PROBLEM_DETAILS,
Boolean, false)
}
+ if (enabled == null) {
+ // a problem is the last resort after the exception handler methods, as it is in Spring MVC
+ enabled = applicationContext.environment.getProperty(Settings.SETTING_EXCEPTION_RESOLVER_SPRING_HANDLERS, Boolean,
+ problemDetails || Boolean.valueOf(Settings.SETTING_EXCEPTION_RESOLVER_SPRING_HANDLERS_DEFAULT))
+ }
returnValues = new ActionReturnValues(applicationContext)
problemDetailHandler = new ProblemDetailExceptionHandler(applicationContext)
}
diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionExceptionProblemDetailsSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionExceptionProblemDetailsSpec.groovy
index 8a6319cc87f..eba0b10e463 100644
--- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionExceptionProblemDetailsSpec.groovy
+++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionExceptionProblemDetailsSpec.groovy
@@ -211,9 +211,9 @@ class ActionExceptionProblemDetailsSpec extends Specification {
response.status == 500
}
- void 'the exception handlers of the advice go first, with both settings'() {
+ void 'the exception handlers of the advice go first, with #settings'() {
given:
- def resolver = resolver([springHandlers: true, problemDetails: true])
+ def resolver = resolver(settings)
when:
resolver.resolveException(request, response, action(new ProblemController()), new IllegalArgumentException('advised'))
@@ -229,6 +229,21 @@ class ActionExceptionProblemDetailsSpec extends Specification {
then:
response.status == 500
problem() == [title: 'Internal Server Error', status: 500]
+
+ where:
+ settings << [[problemDetails: true], [springHandlers: true, problemDetails: true]]
+ }
+
+ void 'an application that turns the exception handlers off gets the problem without them'() {
+ given:
+ def resolver = resolver([springHandlers: false, problemDetails: true])
+
+ when:
+ resolver.resolveException(request, response, action(new ProblemController()), new IllegalArgumentException('advised'))
+
+ then:
+ response.status == 500
+ problem() == [title: 'Internal Server Error', status: 500]
}
void 'a controller the request has not created yet does not stop an exception being written'() {
From 9770bdfdf50b197b953c2910ed467a4e7aa5c895 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 12:25:26 -0800
Subject: [PATCH 13/78] Handle what a request can run into while a problem is
written
- A "503" mapping that names AsyncRequestTimeoutException, which the guide
documents, was looked for under 500 and passed over. It is looked for under the
status the Grails exception resolver uses.
- An @ExceptionHandler method that declares what it produces and fails left that
type on the request, so the problem could not be written. Spring MVC removes it
for its own last resort, and this does too.
- A client that went away is logged in a category of its own and no response is
attempted, as in Spring MVC, where the write failure sent a WARN and an error
page to a dead connection, and the exception was logged as a failed request.
- renderView stayed false when the write failed, so an action answering the error
page had what it returned dropped. It is set once the problem is written.
- An action a page includes is left to the other resolvers, so that a problem is
not written into the page.
- The request of a forwarded action is logged by the URI the client asked for, as
the Grails exception resolver logs it.
---
.../mvc/ActionExceptionHandlerResolver.groovy | 47 +++++--
.../web/mapping/mvc/ActionReturnValues.groovy | 3 +-
.../ActionExceptionProblemDetailsSpec.groovy | 118 +++++++++++++++++-
3 files changed, 156 insertions(+), 12 deletions(-)
diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionExceptionHandlerResolver.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionExceptionHandlerResolver.groovy
index a484bf919bb..9458bb9b713 100644
--- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionExceptionHandlerResolver.groovy
+++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionExceptionHandlerResolver.groovy
@@ -36,14 +36,17 @@ import org.springframework.web.ErrorResponse
import org.springframework.web.HttpMediaTypeNotAcceptableException
import org.springframework.web.accept.ContentNegotiationManager
import org.springframework.web.context.request.ServletWebRequest
+import org.springframework.web.context.request.async.AsyncRequestTimeoutException
import org.springframework.web.filter.ServerHttpObservationFilter
import org.springframework.web.method.HandlerMethod
import org.springframework.web.method.annotation.ProblemDetailExceptionHandler
import org.springframework.web.servlet.HandlerExceptionResolver
+import org.springframework.web.servlet.HandlerMapping
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.handler.HandlerExceptionResolverComposite
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver
import org.springframework.web.servlet.support.RequestContextUtils
+import org.springframework.web.util.DisconnectedClientHelper
import grails.config.Settings
import grails.web.mapping.UrlMappingsHolder
@@ -53,6 +56,7 @@ import org.grails.exceptions.ExceptionUtils
import org.grails.web.servlet.mvc.GrailsWebRequest
import org.grails.web.servlet.mvc.exceptions.GrailsMVCException
import org.grails.web.util.GrailsApplicationAttributes
+import org.grails.web.util.WebUtils
/**
* Resolves an exception a controller action throws with the {@code @ExceptionHandler} methods Spring MVC resolves those
@@ -76,6 +80,10 @@ class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordere
/** The name of the bean Spring MVC's content negotiation manager is. */
private static final String MVC_CONTENT_NEGOTIATION_MANAGER = 'mvcContentNegotiationManager'
+ /** Logs a client that went away while a problem was written, in a category of its own, as Spring MVC does. */
+ private static final DisconnectedClientHelper DISCONNECTED_CLIENTS =
+ new DisconnectedClientHelper(ActionExceptionHandlerResolver.name + '.DisconnectedClient')
+
/** Ahead of Spring MVC's resolvers, which its configuration orders at 0, behind Spring Boot's error attributes. */
int order = -1
@@ -138,33 +146,52 @@ class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordere
/**
* Writes an exception as Spring MVC writes one no handler method handles, with Spring MVC's translation of it, which
* logs an unexpected one and never exposes its message. A failure to write it leaves the exception to the other
- * resolvers, as a failure of an exception handler method leaves it in Spring MVC.
+ * resolvers, as a failure of an exception handler method leaves it in Spring MVC. An action a page includes is left
+ * to them too, since a problem written into the page is no answer to the client.
*/
private ModelAndView resolveAsProblem(HttpServletRequest request, HttpServletResponse response, Exception thrown) {
Exception ex = unwrap(thrown)
try {
- if (response.committed || !returnValues.writesErrorResponses() || prefersHtml(request) || isMappedToErrorHandler(ex)) {
+ if (response.committed || WebUtils.isIncludeRequest(request) || !returnValues.writesErrorResponses() ||
+ prefersHtml(request) || isMappedToErrorHandler(ex)) {
return null
}
ErrorResponse errorResponse = problemDetailHandler.handleException(ex, RequestContextUtils.getLocale(request))
+ // what an exception handler method that failed produces, as Spring MVC removes it for its own last resort
+ request.removeAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE)
ModelAndView written = errorResponse == null ? new ModelAndView() : returnValues.writeErrorResponse(errorResponse,
request.getAttribute(GrailsApplicationAttributes.CONTROLLER), request, response)
- if (HttpStatusCode.valueOf(response.status).is5xxServerError()) {
+ if (isServerError(response)) {
recordServerError(request, ex)
// Spring MVC's translation logs an unexpected exception without the request it failed
- if (!(ex instanceof ErrorResponse)) {
- log.error('{} occurred when processing request: [{}] {}', ex.class.simpleName, request.method, request.requestURI)
+ if (!(ex instanceof ErrorResponse) && !DisconnectedClientHelper.isClientDisconnectedException(ex)) {
+ log.error('{} occurred when processing request: [{}] {}', ex.class.simpleName, request.method, requestUri(request))
}
}
return written
}
catch (Exception e) {
+ if (DISCONNECTED_CLIENTS.checkAndLogClientDisconnectedException(e)) {
+ if (isServerError(response)) {
+ recordServerError(request, ex)
+ }
+ return new ModelAndView()
+ }
log.warn('Could not write a problem for an exception of [{}], so leaving it to the other exception resolvers',
- request.requestURI, e)
+ requestUri(request), e)
return null
}
}
+ private static boolean isServerError(HttpServletResponse response) {
+ return HttpStatusCode.valueOf(response.status).is5xxServerError()
+ }
+
+ /** The URI the client asked for, where the action was forwarded to, as the Grails exception resolver logs it. */
+ private static Object requestUri(HttpServletRequest request) {
+ return request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE) ?: request.requestURI
+ }
+
/** As the Grails exception resolver finds the exception an action threw. */
private static Exception unwrap(Exception ex) {
if (ex instanceof InvokerInvocationException || ex instanceof GrailsMVCException) {
@@ -205,13 +232,17 @@ class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordere
new ContentNegotiationManager()
}
- /** Whether the application maps the exception, as a {@code "500"} mapping with an {@code exception} names it. */
+ /**
+ * Whether the application maps the exception, as a {@code "500"} mapping with an {@code exception} names it, under
+ * the status the Grails exception resolver looks for it with, which for an asynchronous timeout is its own.
+ */
private boolean isMappedToErrorHandler(Exception ex) {
if (!applicationContext.containsBean(UrlMappingsHolder.BEAN_ID)) {
return false
}
UrlMappingsHolder urlMappings = applicationContext.getBean(UrlMappingsHolder.BEAN_ID, UrlMappingsHolder)
- int status = HttpStatus.INTERNAL_SERVER_ERROR.value()
+ int status = ex instanceof AsyncRequestTimeoutException ?
+ ((AsyncRequestTimeoutException) ex).statusCode.value() : HttpStatus.INTERNAL_SERVER_ERROR.value()
return urlMappings.matchStatusCode(status, ex) != null || urlMappings.matchStatusCode(status, ExceptionUtils.getRootCause(ex)) != null
}
diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionReturnValues.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionReturnValues.groovy
index bcf2e430b98..391887b5b24 100644
--- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionReturnValues.groovy
+++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionReturnValues.groovy
@@ -206,11 +206,12 @@ class ActionReturnValues {
* @since 9.1
*/
ModelAndView writeErrorResponse(ErrorResponse errorResponse, Object controller, HttpServletRequest request, HttpServletResponse response) {
- GrailsWebRequest.lookup(request)?.renderView = false
MethodParameter returnType = new MethodParameter(RETURNED_ERROR_RESPONSE, -1)
.withContainingClass(controller?.getClass() ?: ActionReturnValues)
ModelAndViewContainer container = new ModelAndViewContainer()
adapter().returnValueHandlers.handleReturnValue(errorResponse, returnType, container, new ServletWebRequest(request, response))
+ // only once it is written: a failure leaves the response to the error page, which an action can answer
+ GrailsWebRequest.lookup(request)?.renderView = false
return container.requestHandled ? new ModelAndView() : viewOf(container)
}
diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionExceptionProblemDetailsSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionExceptionProblemDetailsSpec.groovy
index eba0b10e463..e7d44cab6af 100644
--- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionExceptionProblemDetailsSpec.groovy
+++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionExceptionProblemDetailsSpec.groovy
@@ -21,6 +21,8 @@ package org.grails.web.mapping.mvc
import groovy.json.JsonSlurper
import org.codehaus.groovy.runtime.InvokerInvocationException
+import ch.qos.logback.classic.Level
+
import org.springframework.core.env.MapPropertySource
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
@@ -37,6 +39,7 @@ import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.context.request.async.AsyncRequestNotUsableException
+import org.springframework.web.context.request.async.AsyncRequestTimeoutException
import org.springframework.web.context.support.GenericWebApplicationContext
import org.springframework.web.filter.ServerHttpObservationFilter
import org.springframework.web.server.ResponseStatusException
@@ -47,13 +50,14 @@ import grails.core.DefaultGrailsApplication
import grails.core.GrailsApplication
import grails.web.mapping.UrlMappingInfo
import grails.web.mapping.UrlMappingsHolder
+import org.apache.grails.core.testing.support.LogCapture
import org.grails.core.DefaultGrailsControllerClass
import org.grails.support.MockApplicationContext
import org.grails.web.mapping.DefaultUrlMappingEvaluator
import org.grails.web.mapping.DefaultUrlMappingsHolder
import org.grails.web.servlet.mvc.GrailsWebRequest
import org.grails.web.util.GrailsApplicationAttributes
-import org.apache.grails.core.testing.support.LogCapture
+import org.grails.web.util.WebUtils
import spock.lang.Specification
/**
@@ -68,13 +72,16 @@ class ActionExceptionProblemDetailsSpec extends Specification {
private MockHttpServletResponse response
+ private GrailsWebRequest webRequest
+
private List interceptors = []
void setup() {
request = new MockHttpServletRequest(new MockServletContext())
request.requestURI = '/problem/index'
response = new MockHttpServletResponse()
- new GrailsWebRequest(request, response, request.servletContext)
+ webRequest = new GrailsWebRequest(request, response, request.servletContext)
+ request.setAttribute(GrailsApplicationAttributes.WEB_REQUEST, webRequest)
}
void cleanup() {
@@ -99,6 +106,9 @@ class ActionExceptionProblemDetailsSpec extends Specification {
problem() == [title: 'Internal Server Error', status: 500]
!response.contentAsString.contains('secret')
+ and: 'no view is rendered after it'
+ !webRequest.renderView
+
where:
client | accept
'names no type' | null
@@ -324,7 +334,7 @@ class ActionExceptionProblemDetailsSpec extends Specification {
problem().instance == 'urn:problem:1'
}
- void 'a failure to write the problem leaves the exception to the other resolvers'() {
+ void 'a failure to write the problem leaves the exception to the other resolvers, which can still render a view'() {
given:
def resolver = resolver([problemDetails: true])
def failing = Spy(response) {
@@ -333,6 +343,103 @@ class ActionExceptionProblemDetailsSpec extends Specification {
expect:
resolver.resolveException(request, failing, action(new ProblemController()), new IllegalStateException('secret')) == null
+ webRequest.renderView
+ }
+
+ void 'a client that disconnects while the problem is written gets nothing more, and nothing is logged as a failure'() {
+ given:
+ def resolver = resolver([problemDetails: true])
+ def logCapture = new LogCapture(ActionExceptionHandlerResolver)
+ def disconnected = Spy(response) {
+ getOutputStream() >> { throw new IOException('Broken pipe') }
+ }
+
+ when:
+ def modelAndView = resolver.resolveException(request, disconnected, action(new ProblemController()), new IllegalStateException('secret'))
+
+ then:
+ modelAndView.empty
+ !logCapture.events.any { it.level.isGreaterOrEqual(Level.WARN) && !it.formattedMessage.contains('occurred when processing request') }
+
+ cleanup:
+ logCapture.close()
+ }
+
+ void 'a disconnected client is not logged as a request that failed'() {
+ given:
+ def resolver = resolver([problemDetails: true])
+ def logCapture = new LogCapture(ActionExceptionHandlerResolver)
+
+ when:
+ resolver.resolveException(request, response, action(new ProblemController()), new IOException('Broken pipe'))
+
+ then:
+ response.status == 500
+ !logCapture.events.any { it.level.isGreaterOrEqual(Level.WARN) }
+
+ cleanup:
+ logCapture.close()
+ }
+
+ void 'the request of a forwarded action is logged by the URI the client asked for'() {
+ given:
+ def resolver = resolver([problemDetails: true])
+ def logCapture = new LogCapture(ActionExceptionHandlerResolver)
+ request.method = 'GET'
+ request.setAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE, '/asked/for')
+
+ when:
+ resolver.resolveException(request, response, action(new ProblemController()), new IllegalStateException('secret'))
+
+ then:
+ logCapture.events*.formattedMessage == ['IllegalStateException occurred when processing request: [GET] /asked/for']
+
+ cleanup:
+ logCapture.close()
+ }
+
+ void 'an action a page includes is left to the other resolvers, so that a problem is not written into the page'() {
+ given:
+ def resolver = resolver([problemDetails: true])
+ request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, '/problem/index')
+
+ expect:
+ resolver.resolveException(request, response, action(new ProblemController()), new IllegalStateException('secret')) == null
+ !response.contentAsString
+ }
+
+ void 'an exception handler method that fails does not stop the problem being written in another type'() {
+ given:
+ def resolver = resolver([problemDetails: true])
+
+ when:
+ resolver.resolveException(request, response, action(new ProblemController()), new UnsupportedOperationException('csv'))
+
+ then:
+ response.status == 500
+ response.contentType == 'application/problem+json'
+ }
+
+ void 'an asynchronous timeout a URL mapping names under its own status is left to the Grails exception resolver'() {
+ given:
+ def resolver = resolver([problemDetails: true]) {
+ "503"(controller: 'errors', action: 'timedOut', exception: AsyncRequestTimeoutException)
+ }
+
+ expect:
+ resolver.resolveException(request, response, action(new ProblemController()), new AsyncRequestTimeoutException()) == null
+ }
+
+ void 'an asynchronous timeout no URL mapping names is written as a problem'() {
+ given:
+ def resolver = resolver([problemDetails: true])
+
+ when:
+ resolver.resolveException(request, response, action(new ProblemController()), new AsyncRequestTimeoutException())
+
+ then:
+ response.status == 503
+ problem().status == 503
}
private Map problem() {
@@ -385,4 +492,9 @@ class ProblemControllerAdvice {
ProblemDetail unprocessable(IllegalArgumentException e) {
ProblemDetail.forStatusAndDetail(HttpStatus.UNPROCESSABLE_CONTENT, e.message)
}
+
+ @ExceptionHandler(value = UnsupportedOperationException, produces = 'text/csv')
+ String failing(UnsupportedOperationException e) {
+ throw e
+ }
}
From 711433bc09888c9fe430b4c969a77c755e35d31f Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 13:28:29 -0700
Subject: [PATCH 14/78] Find the method a problem is written as where one is
written
ActionReturnValues looked up the method in its static initializer, which every
web application runs, whether it opts into problem details or not. Without a hint
for it a native image would fail to initialize the class, and with it the handler
adapter. It is now looked up where a problem is written, whose failure leaves the
exception to the other resolvers, and UrlMappingRuntimeHints registers it.
---
.../web/mapping/aot/UrlMappingRuntimeHints.java | 11 +++++++++++
.../grails/web/mapping/mvc/ActionReturnValues.groovy | 7 +++----
.../web/mapping/aot/UrlMappingRuntimeHintsSpec.groovy | 9 +++++++++
3 files changed, 23 insertions(+), 4 deletions(-)
diff --git a/grails-web-url-mappings/src/main/groovy/org/apache/grails/web/mapping/aot/UrlMappingRuntimeHints.java b/grails-web-url-mappings/src/main/groovy/org/apache/grails/web/mapping/aot/UrlMappingRuntimeHints.java
index 08eade865a2..5cf042789db 100644
--- a/grails-web-url-mappings/src/main/groovy/org/apache/grails/web/mapping/aot/UrlMappingRuntimeHints.java
+++ b/grails-web-url-mappings/src/main/groovy/org/apache/grails/web/mapping/aot/UrlMappingRuntimeHints.java
@@ -18,8 +18,11 @@
*/
package org.apache.grails.web.mapping.aot;
+import java.util.List;
+
import org.jspecify.annotations.Nullable;
+import org.springframework.aot.hint.ExecutableMode;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
@@ -56,6 +59,12 @@ public class UrlMappingRuntimeHints implements RuntimeHintsRegistrar {
*/
private static final String MAPPINGS_BUILDER = "org.grails.web.mapping.DefaultUrlMappingEvaluator$UrlMappingBuilder";
+ /**
+ * Whose method an error response is written as the return value of, which is looked up reflectively to tell Spring
+ * MVC the type of the value when {@code grails.exceptionresolver.problemDetails} writes one.
+ */
+ private static final String ACTION_RETURN_VALUES = "org.grails.web.mapping.mvc.ActionReturnValues";
+
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
for (String type : DISPATCHED_TYPES) {
@@ -68,5 +77,7 @@ public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader)
MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.INVOKE_PUBLIC_METHODS,
MemberCategory.ACCESS_DECLARED_FIELDS);
+ hints.reflection().registerTypeIfPresent(classLoader, ACTION_RETURN_VALUES,
+ type -> type.withMethod("returnedErrorResponse", List.of(), ExecutableMode.INVOKE));
}
}
diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionReturnValues.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionReturnValues.groovy
index 391887b5b24..0bb20417adb 100644
--- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionReturnValues.groovy
+++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/ActionReturnValues.groovy
@@ -84,9 +84,6 @@ class ActionReturnValues {
/** The request attribute that holds the action whose asynchronous value the request completes. */
private static final String ASYNC_ACTION = ActionReturnValues.name + '.ASYNC_ACTION'
- /** The method an error response is written as the return value of, where it is not the value of an action. */
- private static final Method RETURNED_ERROR_RESPONSE = ActionReturnValues.getDeclaredMethod('returnedErrorResponse')
-
/** The method of each action of each controller class, by its name. */
private static final Map, Map> ACTIONS = new ConcurrentReferenceHashMap<>()
@@ -206,7 +203,8 @@ class ActionReturnValues {
* @since 9.1
*/
ModelAndView writeErrorResponse(ErrorResponse errorResponse, Object controller, HttpServletRequest request, HttpServletResponse response) {
- MethodParameter returnType = new MethodParameter(RETURNED_ERROR_RESPONSE, -1)
+ // looked up here rather than when the class loads, so that an application that writes none never needs it
+ MethodParameter returnType = new MethodParameter(ActionReturnValues.getDeclaredMethod('returnedErrorResponse'), -1)
.withContainingClass(controller?.getClass() ?: ActionReturnValues)
ModelAndViewContainer container = new ModelAndViewContainer()
adapter().returnValueHandlers.handleReturnValue(errorResponse, returnType, container, new ServletWebRequest(request, response))
@@ -215,6 +213,7 @@ class ActionReturnValues {
return container.requestHandled ? new ModelAndView() : viewOf(container)
}
+ /** The method an error response is written as the return value of, where it is not the value of an action. */
private static ErrorResponse returnedErrorResponse() {
return null
}
diff --git a/grails-web-url-mappings/src/test/groovy/org/apache/grails/web/mapping/aot/UrlMappingRuntimeHintsSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/apache/grails/web/mapping/aot/UrlMappingRuntimeHintsSpec.groovy
index ac709cbb0ce..020f6c60077 100644
--- a/grails-web-url-mappings/src/test/groovy/org/apache/grails/web/mapping/aot/UrlMappingRuntimeHintsSpec.groovy
+++ b/grails-web-url-mappings/src/test/groovy/org/apache/grails/web/mapping/aot/UrlMappingRuntimeHintsSpec.groovy
@@ -27,6 +27,7 @@ import spock.lang.Specification
import grails.web.mapping.LinkGenerator
import grails.web.mapping.UrlMapping
import grails.web.mapping.UrlMappingInfo
+import org.grails.web.mapping.mvc.ActionReturnValues
/**
* Covers the URL mappings being evaluated and used in an image: the types Groovy dispatches on, and the
@@ -49,6 +50,14 @@ class UrlMappingRuntimeHintsSpec extends Specification {
}
}
+ void 'the method a problem is written as the return value of can be found'() {
+ given: 'the method the class looks up'
+ def method = ActionReturnValues.getDeclaredMethod('returnedErrorResponse')
+
+ expect:
+ hints.reflection().getTypeHint(TypeReference.of(ActionReturnValues)).methods().anyMatch { it.name == method.name }
+ }
+
void 'the builder a URL mappings closure is delegated to can be called and read'() {
expect: 'each mapping is a call the closure resolves against the builder, which reads its own fields too'
RuntimeHintsPredicates.reflection()
From 337f89f1922252a4e51f303b2a9547c1aa7188c3 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 13:28:29 -0700
Subject: [PATCH 15/78] Test the error page for a browser, and correct what the
guide says of problems
The two browser rows of the functional spec behaved as their neighbours, because
grails.mime.disable.accept.header.userAgents, which makes Grails resolve any format
for a browser, was not set in the test application, so the first concrete Accept
type was never what decided. The application now sets it.
The guide said an exception caused by an ErrorResponse keeps its status, which only
holds for a ResponseStatusException or @ResponseStatus, and that any other exception
is a 500 without a detail, where Spring's own exceptions keep theirs. It also did not
say that the settings for what the Grails exception resolver logs do not apply, or
that an action a page includes is left to that resolver.
---
grails-doc/src/en/guide/introduction/whatsNew.adoc | 4 ++--
.../controllers/controllerExceptionHandling.adoc | 8 +++++---
.../spring-json-respond/grails-app/conf/application.yml | 6 ++++++
3 files changed, 13 insertions(+), 5 deletions(-)
diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc
index a77eeeb03c1..c1be05c0046 100644
--- a/grails-doc/src/en/guide/introduction/whatsNew.adoc
+++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc
@@ -143,8 +143,8 @@ xref:theWebLayer#controllerExceptionHandling[Declarative Controller Exception Ha
With `grails.exceptionresolver.problemDetails: true`, an exception no such method handles is written as a problem to a
client that does not prefer HTML, with the translation Spring Framework 7.1 adds, which keeps the status and detail of an
-`ErrorResponse` or a `@ResponseStatus` exception and never exposes the message of any other. The application's error page
-stays for browsers, and for an exception a URL mapping names.
+`ErrorResponse` or a `@ResponseStatus` exception and does not expose the message of an unexpected one. The application's
+error page stays for browsers, and for an exception a URL mapping names.
An action can return what a Spring MVC handler method returns to write the response, such as a `ResponseEntity`, a
`ProblemDetail` or a `StreamingResponseBody`, and Spring MVC writes it with the return value handlers of its handler
diff --git a/grails-doc/src/en/guide/theWebLayer/controllers/controllerExceptionHandling.adoc b/grails-doc/src/en/guide/theWebLayer/controllers/controllerExceptionHandling.adoc
index fd9989d3794..014f3dc6b9c 100644
--- a/grails-doc/src/en/guide/theWebLayer/controllers/controllerExceptionHandling.adoc
+++ b/grails-doc/src/en/guide/theWebLayer/controllers/controllerExceptionHandling.adoc
@@ -166,16 +166,18 @@ Content-Type: application/problem+json
{"status":500,"title":"Internal Server Error"}
----
-* An `ErrorResponse`, a `ResponseStatusException` or an exception annotated `@ResponseStatus`, or one caused by such an exception, keeps its status and detail. Any other exception is a `500` without a detail, so its message is never exposed.
+* An `ErrorResponse`, a `ResponseStatusException` or an exception annotated `@ResponseStatus`, or an exception caused by one of the last two, keeps its status and detail.
+* An exception of Spring such as a `TypeMismatchException` or an `HttpMessageNotReadableException` gets the status and detail `ResponseEntityExceptionHandler` gives it.
+* Any other exception is a `500` without a detail, so its message is never exposed.
* The type, title and detail can be customized in the message bundles, with the codes `ErrorResponse` defines.
* The `ResponseBodyAdvice` beans that apply to the controller and the `ErrorResponse.Interceptor` beans apply to it, as to a problem a handler method returns.
-* An unexpected exception is logged at `ERROR`, by Spring's `org.springframework.web.method.annotation.ProblemDetailExceptionHandler` logger with its stack trace, and by Grails with the method and URI of the request.
+* An unexpected exception is logged at `ERROR`, by Spring's `org.springframework.web.method.annotation.ProblemDetailExceptionHandler` logger with its stack trace, and by Grails with the method and URI of the request. The `grails.exceptionresolver` settings for what is logged, such as `logRequestParameters`, apply to what the Grails exception resolver logs, and so not to these.
The Grails exception resolver and the application's error page still resolve an exception for:
* A client that prefers HTML: a request whose format, from its URL or its `Accept` header, is `html`, or, where Grails resolves any format, as for a browser under `grails.mime.disable.accept.header.userAgents`, whose first concrete `Accept` type is HTML. A client that accepts any type, such as `curl`, gets the problem.
* An exception that a URL mapping names, or whose root cause it names, such as `"500"(controller: 'errors', action: 'denied', exception: AccessDeniedException)`. A `"500"` mapping without an `exception` is the error page of the clients that prefer HTML, and does not apply to the others.
-An exception a view throws while it renders is not one an action throws, and goes to the error page for every client.
+An exception a view throws while it renders is not one an action throws, and goes to the error page for every client, and an action that a page includes with `` is left to the Grails exception resolver too, so that a problem is not written into the page.
WARNING: Do not use Spring Framework's `ProblemDetailsConfigurer.renderUnhandledExceptions(true)` in a `WebMvcConfigurer` for this. It makes Spring MVC's resolver, which runs ahead of the Grails exception resolver, answer every exception of every action with a problem, a browser's included, and `"500"` URL mappings no longer apply.
diff --git a/grails-test-examples/hibernate7/spring-json-respond/grails-app/conf/application.yml b/grails-test-examples/hibernate7/spring-json-respond/grails-app/conf/application.yml
index 98d99fa03b9..b71378e43fa 100644
--- a/grails-test-examples/hibernate7/spring-json-respond/grails-app/conf/application.yml
+++ b/grails-test-examples/hibernate7/spring-json-respond/grails-app/conf/application.yml
@@ -106,6 +106,12 @@ grails:
---
# The settings whose defaults later releases change, as an application that opts into them sets them
grails:
+ mime:
+ disable:
+ accept:
+ header:
+ userAgents:
+ - WebKit
web:
rendering:
json:
From ebae2e32a5e9df2296b5b5f23e1773f9ba13ac61 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 13:29:17 -0700
Subject: [PATCH 16/78] Test how the plugin configures the request cache
The wiring in the plugin had no test beyond the default list: a list an application
sets, an empty list, and a class set with requestMatcherBeanClass, which must not be
given a property it may not have, all go through the real plugin now.
The spec that only pinned how Spring's own matcher treats a parsed request path goes.
---
.../RequestCacheConfigurationSpec.groovy | 132 ++++++++++++++++++
.../web/SavedRequestMatcherSpec.groovy | 14 --
.../groovy/specs/SavedRequestSpec.groovy | 1 -
3 files changed, 132 insertions(+), 15 deletions(-)
create mode 100644 grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/RequestCacheConfigurationSpec.groovy
diff --git a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/RequestCacheConfigurationSpec.groovy b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/RequestCacheConfigurationSpec.groovy
new file mode 100644
index 00000000000..61c3e772c58
--- /dev/null
+++ b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/RequestCacheConfigurationSpec.groovy
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * https://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 grails.plugin.springsecurity
+
+import org.springframework.mock.web.MockHttpServletRequest
+import org.springframework.mock.web.MockHttpServletResponse
+import org.springframework.security.web.savedrequest.RequestCache
+import org.springframework.security.web.util.matcher.AnyRequestMatcher
+import spock.lang.Specification
+
+import grails.testing.web.GrailsWebUnitTest
+import grails.web.CamelCaseUrlConverter
+
+/**
+ * What the plugin's {@code requestCache} bean saves, as {@code requestCache.ignoredPatterns} and
+ * {@code requestMatcherBeanClass} configure it.
+ */
+abstract class AbstractRequestCacheConfigurationSpec extends Specification implements GrailsWebUnitTest {
+
+ Set getIncludePlugins() {
+ ['core', 'springSecurityCore'] as Set
+ }
+
+ Closure doWithSpring() {
+ { ->
+ grailsUrlConverter(CamelCaseUrlConverter)
+ }
+ }
+
+ Closure doWithConfig() {
+ { config ->
+ config.grails.plugin.springsecurity.securityConfigType = 'InterceptUrlMap'
+ configure(config.grails.plugin.springsecurity)
+ }
+ }
+
+ protected abstract void configure(Object securityConfig)
+
+ void cleanupSpec() {
+ SpringSecurityUtils.resetSecurityConfig()
+ ReflectionUtils.application = null
+ SpringSecurityUtils.application = null
+ }
+
+ protected boolean saves(String path) {
+ def requestCache = applicationContext.getBean('requestCache', RequestCache)
+ def request = new MockHttpServletRequest('GET', path)
+ def response = new MockHttpServletResponse()
+ requestCache.saveRequest(request, response)
+ requestCache.getRequest(request, response) != null
+ }
+}
+
+class DefaultRequestCacheConfigurationSpec extends AbstractRequestCacheConfigurationSpec {
+
+ protected void configure(Object securityConfig) {
+ }
+
+ void 'by default the requests a browser sends on its own are not saved'() {
+ expect:
+ !saves('/manifest.json')
+ !saves('/.well-known/appspecific/com.chrome.devtools.json')
+ saves('/book/show')
+ }
+}
+
+class CustomIgnoredPatternsConfigurationSpec extends AbstractRequestCacheConfigurationSpec {
+
+ protected void configure(Object securityConfig) {
+ securityConfig.requestCache.ignoredPatterns = ['/poll/**']
+ }
+
+ void 'the patterns an application configures replace the default ones'() {
+ expect:
+ !saves('/poll/status')
+ saves('/manifest.json')
+ }
+}
+
+class NoIgnoredPatternsConfigurationSpec extends AbstractRequestCacheConfigurationSpec {
+
+ protected void configure(Object securityConfig) {
+ securityConfig.requestCache.ignoredPatterns = []
+ }
+
+ void 'no patterns save every request'() {
+ expect:
+ saves('/manifest.json')
+ saves('/book/show')
+ }
+}
+
+class EmptyStringIgnoredPatternsConfigurationSpec extends AbstractRequestCacheConfigurationSpec {
+
+ protected void configure(Object securityConfig) {
+ securityConfig.requestCache.ignoredPatterns = ''
+ }
+
+ void 'an empty value, which an empty YAML list flattens to, saves every request'() {
+ expect:
+ saves('/manifest.json')
+ }
+}
+
+class RequestMatcherBeanClassConfigurationSpec extends AbstractRequestCacheConfigurationSpec {
+
+ protected void configure(Object securityConfig) {
+ securityConfig.requestMatcherBeanClass = AnyRequestMatcher
+ }
+
+ void 'a class configured in place of the default matcher is created without the patterns'() {
+ expect:
+ applicationContext.getBean('requestMatcher') instanceof AnyRequestMatcher
+ saves('/manifest.json')
+ }
+}
diff --git a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/SavedRequestMatcherSpec.groovy b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/SavedRequestMatcherSpec.groovy
index bb131471da6..feb27f59a7a 100644
--- a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/SavedRequestMatcherSpec.groovy
+++ b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/SavedRequestMatcherSpec.groovy
@@ -21,7 +21,6 @@ package grails.plugin.springsecurity.web
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.security.web.savedrequest.HttpSessionRequestCache
-import org.springframework.web.util.ServletRequestPathUtils
import spock.lang.Specification
class SavedRequestMatcherSpec extends Specification {
@@ -81,19 +80,6 @@ class SavedRequestMatcherSpec extends Specification {
savedRequest('/manifest.json', new SavedRequestMatcher()) != null
}
- void 'a request parsed for Spring MVC keeps its parsed path'() {
- given:
- def request = request('/manifest.json')
- def parsed = ServletRequestPathUtils.parseAndCache(request)
-
- when:
- def matched = new SavedRequestMatcher(ignoredPatterns: ['/manifest.json']).matches(request)
-
- then:
- !matched
- ServletRequestPathUtils.getParsedRequestPath(request).is(parsed)
- }
-
private static savedRequest(String path, SavedRequestMatcher matcher) {
def cache = new HttpSessionRequestCache(requestMatcher: matcher, matchingRequestParameterName: null)
def request = request(path)
diff --git a/grails-test-examples/spring-security/core/functional-test-app/src/integration-test/groovy/specs/SavedRequestSpec.groovy b/grails-test-examples/spring-security/core/functional-test-app/src/integration-test/groovy/specs/SavedRequestSpec.groovy
index b720bd70d55..b70dc3d393c 100644
--- a/grails-test-examples/spring-security/core/functional-test-app/src/integration-test/groovy/specs/SavedRequestSpec.groovy
+++ b/grails-test-examples/spring-security/core/functional-test-app/src/integration-test/groovy/specs/SavedRequestSpec.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package specs
import java.net.http.HttpClient
From ecedbbbcb8867ba19921d2d7973d6d407d828902 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 13:29:42 -0700
Subject: [PATCH 17/78] Keep the example application's imports in order and its
headers as the project's
---
.../grails-app/controllers/springjson/BookController.groovy | 2 +-
.../grails-app/controllers/springjson/ErrorsController.groovy | 1 -
.../src/main/groovy/springjson/BookArchivedException.groovy | 1 -
3 files changed, 1 insertion(+), 3 deletions(-)
diff --git a/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/springjson/BookController.groovy b/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/springjson/BookController.groovy
index fa762de68e7..2462dfa91d5 100644
--- a/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/springjson/BookController.groovy
+++ b/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/springjson/BookController.groovy
@@ -30,9 +30,9 @@ import org.springframework.http.ProblemDetail
import org.springframework.http.ResponseEntity
import org.springframework.web.ErrorResponseException
import org.springframework.web.bind.MissingServletRequestParameterException
-import org.springframework.web.server.ResponseStatusException
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.ResponseStatus
+import org.springframework.web.server.ResponseStatusException
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody
import grails.gorm.transactions.Transactional
diff --git a/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/springjson/ErrorsController.groovy b/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/springjson/ErrorsController.groovy
index a4871376902..16d20fffcdd 100644
--- a/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/springjson/ErrorsController.groovy
+++ b/grails-test-examples/hibernate7/spring-json-respond/grails-app/controllers/springjson/ErrorsController.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package springjson
class ErrorsController {
diff --git a/grails-test-examples/hibernate7/spring-json-respond/src/main/groovy/springjson/BookArchivedException.groovy b/grails-test-examples/hibernate7/spring-json-respond/src/main/groovy/springjson/BookArchivedException.groovy
index 0381a2190e0..fb34dcc8e2e 100644
--- a/grails-test-examples/hibernate7/spring-json-respond/src/main/groovy/springjson/BookArchivedException.groovy
+++ b/grails-test-examples/hibernate7/spring-json-respond/src/main/groovy/springjson/BookArchivedException.groovy
@@ -16,7 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package springjson
class BookArchivedException extends RuntimeException {
From bbcc94febaa482d38ae1fb225037f4f47648fd67 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 13:29:43 -0700
Subject: [PATCH 18/78] Test QUERY where its sibling methods are tested, and
correct what the guide says
A QUERY reaches a secured action through the Spring Security plugin's authorization
as a PUT and a PATCH do, and grails-openapi skips a QUERY mapping, which were claimed
but not tested.
The guide said a body binds as a POST's does, which does not hold for a domain class;
that g:form sends a POST, which depends on how the hidden method is resolved; and that
OpenAPI has no operation for QUERY, where this generator writes versions that have
none. FormContentFilter's list of methods is brought up to date where it is repeated.
---
grails-doc/src/en/guide/REST/openApi.adoc | 2 +-
grails-doc/src/en/guide/introduction/whatsNew.adoc | 2 +-
.../en/guide/theWebLayer/urlmappings/mappingHTTP.adoc | 4 ++--
grails-doc/src/en/guide/upgrading/upgrading90x.adoc | 4 ++--
.../groovy/grails/openapi/UrlMappingsDocumentSpec.groovy | 7 +++++--
.../groovy/specs/TestFormParamsControllerSpec.groovy | 9 +++++++++
.../groovy/org/grails/web/config/http/GrailsFilters.java | 2 +-
7 files changed, 21 insertions(+), 9 deletions(-)
diff --git a/grails-doc/src/en/guide/REST/openApi.adoc b/grails-doc/src/en/guide/REST/openApi.adoc
index ac71521808c..90d7f8010fc 100644
--- a/grails-doc/src/en/guide/REST/openApi.adoc
+++ b/grails-doc/src/en/guide/REST/openApi.adoc
@@ -872,7 +872,7 @@ listing. Its other actions are described as any controller's are.
* A mapping that accepts any HTTP method for an action `allowedMethods` does not restrict is
documented as `GET`, because OpenAPI requires a concrete operation.
-* A mapping declared for an HTTP method OpenAPI has no operation for, such as `QUERY`, is skipped, and logged.
+* A mapping declared for an HTTP method the OpenAPI versions this generator writes have no operation for, such as `QUERY`, is skipped, and logged.
* A `RestfulController` is known to be read only, and the resource it serves where it declares no
type argument, from the controller the application serves requests with, which is not created to
be described. So one in a scope other than singleton is described with its write actions, and one
diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc
index c1be05c0046..d707a74d7b6 100644
--- a/grails-doc/src/en/guide/introduction/whatsNew.adoc
+++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc
@@ -81,7 +81,7 @@ The xref:upgrading#upgrading90x[Upgrading from Grails 8 to Grails {grailsMajorVe
==== The HTTP QUERY Method
-Spring Framework 7.1 supports the `QUERY` method of https://www.rfc-editor.org/info/rfc10008/[RFC 10008], a safe, idempotent request with a body. URL mappings gain a `query` prefix for it, next to `get`, `post` and the others, and an action binds the body of a `QUERY` as it binds that of a `POST`:
+Spring Framework 7.1 supports the `QUERY` method of https://www.rfc-editor.org/info/rfc10008/[RFC 10008], a safe, idempotent request with a body. URL mappings gain a `query` prefix for it, next to `get`, `post` and the others, and a command object is bound to the body of a `QUERY`, which is JSON or form-encoded:
[source,groovy]
----
diff --git a/grails-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc b/grails-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc
index 21927df7b85..7d0f74b19d3 100644
--- a/grails-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc
+++ b/grails-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc
@@ -57,6 +57,6 @@ A JSON body is bound to the command object the action takes, and a form-encoded
Other things to know about `QUERY`:
-* An HTML form cannot send it, and `` submits a `POST`. Call it from JavaScript or another HTTP client.
-* `grails-openapi` leaves these mappings out of the document it generates, and logs each one, because OpenAPI has no operation for the method.
+* A browser cannot send it from an HTML form. Call it from JavaScript or another HTTP client.
+* `grails-openapi` leaves these mappings out of the document it generates, and logs each one, because the OpenAPI versions it writes have no operation for the method.
* The Spring Security plugin accepts `QUERY` requests. An application that configures Spring Security with its own configuration DSL instead gets a `StrictHttpFirewall`, which rejects the method until it is added with `setAllowedHttpMethods`, and whichever one it uses, `CsrfFilter` asks a `QUERY` for a token where CSRF protection is on.
diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
index ea83724e796..000f1aad023 100644
--- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
+++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
@@ -1369,10 +1369,10 @@ See <> and <>.
Grails no longer registers a character encoding filter of its own. It used to, and Spring Boot's backed off, so `spring.servlet.encoding` had no effect in a Grails application. Spring Boot's filter now decodes requests: it runs at `Ordered.HIGHEST_PRECEDENCE`, ahead of every other filter, and `spring.servlet.encoding` configures it.
-* The request encoding is now overridden by default, as in any Spring Boot application, so a request that declares a charset of its own is still decoded as UTF-8: its parameters, a body read through `getReader()`, `request.JSON` and `request.XML`, and a JSON or XML body bound to a command object or domain class. The parameters of a PUT, PATCH or DELETE form are the exception, as in Grails 8: the `FormContentFilter` that parses them decodes them with the declared charset, forced or not. To keep the charset a request declares, as Grails 8 did, set `spring.servlet.encoding.force-request: false`.
+* The request encoding is now overridden by default, as in any Spring Boot application, so a request that declares a charset of its own is still decoded as UTF-8: its parameters, a body read through `getReader()`, `request.JSON` and `request.XML`, and a JSON or XML body bound to a command object or domain class. The parameters of a PUT, PATCH, DELETE or QUERY form are the exception, as in Grails 8: the `FormContentFilter` that parses them decodes them with the declared charset, forced or not. To keep the charset a request declares, as Grails 8 did, set `spring.servlet.encoding.force-request: false`.
* Grails 8.1 already registers its encoding filter at `Ordered.HIGHEST_PRECEDENCE`, so an application coming from 8.1 sees no change in where the encoding filter runs. In an application coming from 8.0, filters ordered between `Ordered.HIGHEST_PRECEDENCE + 1` and -181, which used to run before Grails' encoding filter, now run after Spring Boot's, with the request encoding set, as section 5 of <> describes. asset-pipeline's filter at -190 is one: in a packaged application (a WAR or an executable jar) it copies the request's encoding to the precompiled assets it serves, so every asset response now declares a charset, for example `text/css;charset=UTF-8`, and browsers use it for stylesheets and scripts instead of detecting their encoding. A filter among them that reads a request body sent without a charset through `getReader()` now decodes it as UTF-8 instead of ISO-8859-1.
* `grails.filter.encoding` and `grails.filter.forceEncoding` are deprecated. Grails 9 translates them into `spring.servlet.encoding.charset` and `spring.servlet.encoding.force` and logs a warning, and a `spring.servlet.encoding` setting of the application wins over them. Use the Spring Boot properties instead.
-* `GrailsFilters.CHARACTER_ENCODING_FILTER` is deprecated, and its order is now `Ordered.HIGHEST_PRECEDENCE`, the order of Spring Boot's encoding filter, where Grails 8.0 had -180. A filter ordered at `GrailsFilters.CHARACTER_ENCODING_FILTER.order + 1` therefore runs right after the encoding filter, and now also ahead of `FormContentFilter` and of Grails' security headers filter at `GrailsFilters.FIRST`: it no longer sees the parameters of a PUT, PATCH or DELETE form, and a response it sends without continuing the chain gets no security headers. Order it at `Ordered.HIGHEST_PRECEDENCE + 1` instead, or at `GrailsFilters.ASSET_PIPELINE_FILTER.order + 1` to keep the place it had in Grails 8.0.
+* `GrailsFilters.CHARACTER_ENCODING_FILTER` is deprecated, and its order is now `Ordered.HIGHEST_PRECEDENCE`, the order of Spring Boot's encoding filter, where Grails 8.0 had -180. A filter ordered at `GrailsFilters.CHARACTER_ENCODING_FILTER.order + 1` therefore runs right after the encoding filter, and now also ahead of `FormContentFilter` and of Grails' security headers filter at `GrailsFilters.FIRST`: it no longer sees the parameters of a PUT, PATCH, DELETE or QUERY form, and a response it sends without continuing the chain gets no security headers. Order it at `Ordered.HIGHEST_PRECEDENCE + 1` instead, or at `GrailsFilters.ASSET_PIPELINE_FILTER.order + 1` to keep the place it had in Grails 8.0.
* `spring.servlet.encoding.enabled: false` turns the encoding filter off.
* The CAS plugin's single sign-out filter, which reads a parameter of every POST, is registered right after the encoding filter.
* A filter of your own that reads request parameters needs a later order than `Ordered.HIGHEST_PRECEDENCE`, or form input reaches controllers decoded as ISO-8859-1. One registered at exactly `Ordered.HIGHEST_PRECEDENCE` through a `FilterRegistrationBean` runs before the encoding filter.
diff --git a/grails-openapi/src/test/groovy/grails/openapi/UrlMappingsDocumentSpec.groovy b/grails-openapi/src/test/groovy/grails/openapi/UrlMappingsDocumentSpec.groovy
index 5814bd21c10..3b33677baf9 100644
--- a/grails-openapi/src/test/groovy/grails/openapi/UrlMappingsDocumentSpec.groovy
+++ b/grails-openapi/src/test/groovy/grails/openapi/UrlMappingsDocumentSpec.groovy
@@ -162,12 +162,12 @@ class UrlMappingsDocumentSpec extends Specification {
openApi.paths.size() == existing
}
- void 'skips a mapping declared for a method OpenAPI has no operation for'() {
+ void 'skips a mapping declared for the #httpMethod method, which OpenAPI has no operation for'() {
given:
def openApi = new OpenAPI()
def customizer = OpenApiFixture.generator(holderFor {
'/books'(controller: 'book', action: 'index', method: 'GET')
- '/books/report'(controller: 'book', action: 'report', method: 'REPORT')
+ '/books/report'(controller: 'book', action: 'report', method: httpMethod)
})
when:
@@ -178,6 +178,9 @@ class UrlMappingsDocumentSpec extends Specification {
and:
!openApi.paths.containsKey('/books/report')
+
+ where:
+ httpMethod << ['REPORT', 'QUERY']
}
void 'names a greedy parameter for the constraint that binds it'() {
diff --git a/grails-test-examples/spring-security/core/functional-test-app/src/integration-test/groovy/specs/TestFormParamsControllerSpec.groovy b/grails-test-examples/spring-security/core/functional-test-app/src/integration-test/groovy/specs/TestFormParamsControllerSpec.groovy
index c625a48ce12..906f4addbc3 100644
--- a/grails-test-examples/spring-security/core/functional-test-app/src/integration-test/groovy/specs/TestFormParamsControllerSpec.groovy
+++ b/grails-test-examples/spring-security/core/functional-test-app/src/integration-test/groovy/specs/TestFormParamsControllerSpec.groovy
@@ -154,6 +154,15 @@ class TestFormParamsControllerSpec extends Specification implements HttpClientSu
response.body() != "username: ${USERNAME}, password: ${PASSWORD}"
}
+ void 'QUERY request to secured endpoint with parameters as x-www-form-urlencoded'() {
+ when: "A QUERY request with form params is made to a secured endpoint"
+ TestHttpResponse response = exchange('QUERY', '/testFormParams/permitAdmin', "username=${USERNAME}&password=${PASSWORD}", FORM)
+
+ then: "the request is not processed by the controller (redirected to login)"
+ response.statusCode() == 200
+ response.body() != "username: ${USERNAME}, password: ${PASSWORD}"
+ }
+
void 'PATCH request with NULL Content-Type and parameters in the URL'() {
when:
TestHttpResponse response = exchange('PATCH', "/testFormParams/permitAll?username=${USERNAME}&password=${PASSWORD}", '', null)
diff --git a/grails-web-common/src/main/groovy/org/grails/web/config/http/GrailsFilters.java b/grails-web-common/src/main/groovy/org/grails/web/config/http/GrailsFilters.java
index 742282f91df..c2e8d2840a1 100644
--- a/grails-web-common/src/main/groovy/org/grails/web/config/http/GrailsFilters.java
+++ b/grails-web-common/src/main/groovy/org/grails/web/config/http/GrailsFilters.java
@@ -73,7 +73,7 @@ public enum GrailsFilters {
CAS_SINGLE_SIGN_OUT_FILTER(Ordered.HIGHEST_PRECEDENCE + 1),
/**
- * Spring's {@code FormContentFilter}, which parses the form of a PUT, PATCH or DELETE request into request
+ * Spring's {@code FormContentFilter}, which parses the form of a PUT, PATCH, DELETE or QUERY request into request
* parameters: Spring Boot's, at its default order, or Grails' at the same order when Spring Boot registers none.
*/
FORM_CONTENT_FILTER(-9900),
From e4ac4426798449078fa8f116d54a2f789e06f694 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 16:13:18 -0800
Subject: [PATCH 19/78] Build a native image with what traceNativeMetadata
records
traceNativeMetadata merged what it recorded into
src/native/resources/META-INF/native-image, as the guide says, but nothing put that
directory on the classpath the image is built from, so the recording changed nothing.
An image built after a trace started and failed on the first request that needed what
was recorded, with a MissingReflectionRegistrationError for a call the file listed.
The plugin now adds the classpath entry above META-INF, beside the metadata it
generates, and fails the build with the reason if outputDirectory is somewhere an
image cannot read. native-i18n calls a method only that directory registers, named by
a property because GraalVM resolves a lookup of a constant name while it builds the
image, so CI's image fails if the metadata stops reaching it: without the plugin
change it fails with ClassNotFoundException.
---
end-to-end/README.md | 6 ++++
.../grails-app/conf/application.yml | 5 +++
.../init/nativei18n/Application.groovy | 10 +++++-
.../native-image/reachability-metadata.json | 11 ++++++
gradle/rat-root-config.gradle | 1 +
.../en/guide/deployment/deploymentAot.adoc | 4 ++-
.../theWebLayer/urlmappings/mappingHTTP.adoc | 1 +
.../plugin/core/GrailsGradlePlugin.groovy | 34 ++++++++++++++++++
.../core/GrailsNativeImageDefaultsSpec.groovy | 35 +++++++++++++++++++
.../native-defaults-on/build.gradle | 18 ++++++++++
10 files changed, 123 insertions(+), 2 deletions(-)
create mode 100644 end-to-end/native-i18n/src/native/resources/META-INF/native-image/reachability-metadata.json
diff --git a/end-to-end/README.md b/end-to-end/README.md
index b3275dde304..69022165d58 100644
--- a/end-to-end/README.md
+++ b/end-to-end/README.md
@@ -81,6 +81,12 @@ else checks that a plugin's configuration reaches one. On a JVM the file is foun
classes, in its JAR; an image has no JARs, so there it is found only through the copy the build makes
of it under the plugin's name.
+And it calls a method of a JDK class that nothing but its `src/native/resources/META-INF/native-image/reachability-metadata.json`
+registers, which is the file `traceNativeMetadata` merges what it records into. Nothing else checks that what a trace
+recorded reaches an image, and an image built without it starts and fails only on the requests that needed it. The class is
+named by a property, because GraalVM resolves a reflective lookup of a constant name while it builds the image, which needs no
+metadata and would pass whatever this file held.
+
```bash
cd end-to-end
./gradlew :native-i18n:check # the JVM half, part of `check`
diff --git a/end-to-end/native-i18n/grails-app/conf/application.yml b/end-to-end/native-i18n/grails-app/conf/application.yml
index 55e2ec9c1c0..b3c2e54c256 100644
--- a/end-to-end/native-i18n/grails-app/conf/application.yml
+++ b/end-to-end/native-i18n/grails-app/conf/application.yml
@@ -25,3 +25,8 @@ spring:
# Not a base name, so resolving an unknown code to itself proves the rest of
# MessageSourceProperties was bound too - they all arrive together or not at all.
use-code-as-default-message: true
+native:
+ # Named here, so that an image has to find it at runtime: a lookup of a constant name is resolved while the
+ # image is built, and needs no metadata. Registered only by src/native/resources, where a trace records.
+ recorded:
+ type: java.util.zip.Adler32
diff --git a/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy b/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
index cf43229fa42..15e46eb22ab 100644
--- a/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
+++ b/end-to-end/native-i18n/grails-app/init/nativei18n/Application.groovy
@@ -49,7 +49,9 @@ import org.springframework.context.MessageSource
* derived from {@code spring.messages.basename} alone.
*
*
It also reads a value from the plugin's {@code plugin.yml}, which on a JVM is found beside the plugin's
- * classes and in an image only through the copy the build makes of it under the plugin's name.
+ * classes and in an image only through the copy the build makes of it under the plugin's name, and calls a method
+ * that in an image only the metadata in {@code src/native/resources} registers, where {@code traceNativeMetadata}
+ * records.
*
*
Every run is told which environment it should have started in, through the property
* {@code i18n.check.environment}, and fails in any other. An image reads its environment from the build
@@ -121,6 +123,12 @@ class Application extends GrailsAutoConfiguration {
"native.plugin.configuration was '${configured}'")
}
+ // Not a bundle either, but what traceNativeMetadata records, read from where it records it. A JDK class,
+ // because every class of the application is registered from the build output whether this works or not.
+ String recorded = context.environment.getProperty('native.recorded.type')
+ Class> recordedType = Class.forName(recorded)
+ recordedType.getMethod('getValue').invoke(recordedType.getDeclaredConstructor().newInstance())
+
println "i18n-check: in ${expectedEnvironment}, every message bundle resolved, and the plugin configuration was read"
}
catch (Throwable failure) {
diff --git a/end-to-end/native-i18n/src/native/resources/META-INF/native-image/reachability-metadata.json b/end-to-end/native-i18n/src/native/resources/META-INF/native-image/reachability-metadata.json
new file mode 100644
index 00000000000..003d74ec218
--- /dev/null
+++ b/end-to-end/native-i18n/src/native/resources/META-INF/native-image/reachability-metadata.json
@@ -0,0 +1,11 @@
+{
+ "reflection": [
+ {
+ "type": "java.util.zip.Adler32",
+ "methods": [
+ { "name": "", "parameterTypes": [] },
+ { "name": "getValue", "parameterTypes": [] }
+ ]
+ }
+ ]
+}
diff --git a/gradle/rat-root-config.gradle b/gradle/rat-root-config.gradle
index 83403a8d7af..a7c09b10ce5 100644
--- a/gradle/rat-root-config.gradle
+++ b/gradle/rat-root-config.gradle
@@ -178,6 +178,7 @@ tasks.named('rat') {
'**/*.log', // exclude log files
'local-tasks.gradle', // exclude local helper scripts
'**/spring-configuration-metadata.json', // JSON files cannot contain license headers
+ 'end-to-end/native-i18n/src/native/resources/META-INF/native-image/reachability-metadata.json', // JSON files cannot contain license headers
'grails-test-examples/spring-security/cas/test1/src/main/resources/cas/services/*.json', // CAS service registry definitions; JSON files cannot contain license headers
'grails-test-examples/benchmarks/src/reportTest/resources/jmh-golden/**', // byte-exact JMH report fixtures; a license header would alter the compared bytes
] + rootProject.subprojects.collectMany { project ->
diff --git a/grails-doc/src/en/guide/deployment/deploymentAot.adoc b/grails-doc/src/en/guide/deployment/deploymentAot.adoc
index 94f2d79af28..36c8afee8aa 100644
--- a/grails-doc/src/en/guide/deployment/deploymentAot.adoc
+++ b/grails-doc/src/en/guide/deployment/deploymentAot.adoc
@@ -143,7 +143,7 @@ grails {
./gradlew traceNativeMetadata
----
-The result is merged into `src/native/resources/META-INF/native-image`, alongside the source rather than under `build`, because which paths an image was built to cover is worth reviewing and worth committing.
+The result is merged into `src/native/resources/META-INF/native-image`, alongside the source rather than under `build`, because which paths an image was built to cover is worth reviewing and worth committing. `nativeCompile` builds the image with it. A different `outputDirectory` has to be under a `META-INF/native-image` directory, which is where an image reads metadata from, and the build fails if it is not.
`paths` are asked for. `forms` are asked for *and submitted*: the page is read, the fields the form declares are filled in, and they are posted to the action the form names. Submitting matters separately from rendering, because binding a form is a different half of the framework from rendering one — and it is the half that converts. A checkbox arrives as a string and lands on a boolean property, so a form submitted without one never asks the conversion service anything, and the image is built without the answer.
@@ -190,3 +190,5 @@ Redirects are followed, so an application that sends `/` to its real home page r
NOTE: The agent ships with GraalVM rather than with a JDK, and it must trace the archive the image will be built from — which is compiled for GraalVM's Java. The task uses the project toolchain, which for a project that builds an image is already a GraalVM; `grails.nativeMetadata.javaExecutable` points it elsewhere.
WARNING: The agent records only what ran. A path that is not listed is not covered, and it will be missing in the way that only appears when somebody uses that page. Treat the list as the coverage it is, and extend it as the application grows.
+
+The trace sends `GET` and form `POST` requests, so it cannot reach an action restricted to `QUERY`. What the framework does to bind a command object is the same whichever method reaches it, so tracing another action that binds one covers it, and the classes of the application are written down without a trace. The trace also fails on a request that answers with an error, so what the framework does to answer one is registered for you where it writes one itself, as it does for an exception written as an RFC 9457 problem with `grails.exceptionresolver.problemDetails`.
diff --git a/grails-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc b/grails-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc
index 7d0f74b19d3..91ff1ecd0f0 100644
--- a/grails-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc
+++ b/grails-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc
@@ -58,5 +58,6 @@ A JSON body is bound to the command object the action takes, and a form-encoded
Other things to know about `QUERY`:
* A browser cannot send it from an HTML form. Call it from JavaScript or another HTTP client.
+* `traceNativeMetadata` cannot send it. For a native image, trace another action that binds a command object, as the <> describes.
* `grails-openapi` leaves these mappings out of the document it generates, and logs each one, because the OpenAPI versions it writes have no operation for the method.
* The Spring Security plugin accepts `QUERY` requests. An application that configures Spring Security with its own configuration DSL instead gets a `StrictHttpFirewall`, which rejects the method until it is added with `setAllowedHttpMethods`, and whichever one it uses, `CsrfFilter` asks a `QUERY` for a token where CSRF protection is on.
diff --git a/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/core/GrailsGradlePlugin.groovy b/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/core/GrailsGradlePlugin.groovy
index 4043bede5d1..bf2d17fe649 100644
--- a/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/core/GrailsGradlePlugin.groovy
+++ b/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/core/GrailsGradlePlugin.groovy
@@ -1239,6 +1239,9 @@ ${importStatements}
extension.startTimeoutSeconds.convention(TRAINING_START_TIMEOUT_SECONDS)
extension.outputDirectory.convention(project.layout.projectDirectory
.dir('src/native/resources/META-INF/native-image'))
+ project.pluginManager.withPlugin(NATIVE_IMAGE_PLUGIN) {
+ addTracedMetadataToNativeImageClasspath(project, extension)
+ }
project.pluginManager.withPlugin(SPRING_BOOT_PLUGIN) {
TaskProvider> bootJar = project.tasks.named('bootJar')
@@ -1263,6 +1266,37 @@ ${importStatements}
}
}
+ /**
+ * Puts what {@code traceNativeMetadata} recorded on the classpath the image is built from, without which
+ * recording it changes nothing: the image is built, starts, and fails on the first request that needs it.
+ *
+ *
Dynamically, for the reason {@link #addToNativeImageClasspath} is.
+ */
+ @CompileDynamic
+ private static void addTracedMetadataToNativeImageClasspath(Project project, NativeMetadataExtension extension) {
+ def graalvm = project.extensions.findByName('graalvmNative')
+ graalvm?.binaries?.configureEach { binary ->
+ binary.classpath(extension.outputDirectory.map { Directory directory -> nativeMetadataRoot(directory.asFile) })
+ }
+ }
+
+ /**
+ * The classpath entry the metadata in a directory is read from: {@code native-image} looks for it under
+ * {@code META-INF/native-image} of each entry, so a directory anywhere else would never be read.
+ */
+ private static File nativeMetadataRoot(File directory) {
+ File metaInf = directory
+ while (metaInf != null && metaInf.name != 'META-INF') {
+ metaInf = metaInf.parentFile
+ }
+ if (metaInf?.parentFile == null) {
+ throw new GradleException("grails.nativeMetadata.outputDirectory is ${directory}, which an image cannot " +
+ 'read metadata from. Use a directory under META-INF/native-image, as the default ' +
+ 'src/native/resources/META-INF/native-image is.')
+ }
+ metaInf.parentFile
+ }
+
protected void configureBootRunPidFile(Project project) {
// Producer side of the run-app PID contract: the forked app writes its PID to 'run-app.pid'
// under the Gradle build directory. The CLI stop-app command resolves the PID file
diff --git a/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/core/GrailsNativeImageDefaultsSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/core/GrailsNativeImageDefaultsSpec.groovy
index a267eade4cc..2fc47e2dc86 100644
--- a/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/core/GrailsNativeImageDefaultsSpec.groovy
+++ b/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/core/GrailsNativeImageDefaultsSpec.groovy
@@ -71,6 +71,41 @@ class GrailsNativeImageDefaultsSpec extends GradleSpecification {
result.output.contains('INDY_OPTION=true')
}
+ void 'what traceNativeMetadata records is on the classpath the image is built from'() {
+ given:
+ setupTestResourceProject('native-defaults-on')
+
+ when:
+ BuildResult result = executeTask('inspectNativeClasspath')
+
+ then: 'the entry native-image reads META-INF/native-image of, without which recording it changes nothing'
+ result.output.contains('TRACED_METADATA_ON_CLASSPATH=true')
+ }
+
+ void 'metadata recorded under a directory of its own is read from the classpath entry above it'() {
+ given:
+ setupTestResourceProject('native-defaults-on')
+
+ when:
+ BuildResult result = executeTask('inspectNativeClasspath',
+ ['-PfixtureTraceDirectory=recorded/META-INF/native-image/traced', '-PfixtureTraceRoot=recorded'])
+
+ then:
+ result.output.contains('TRACED_METADATA_ON_CLASSPATH=true')
+ }
+
+ void 'metadata recorded where an image cannot read it fails the build with the reason'() {
+ given:
+ GradleRunner runner = setupTestResourceProject('native-defaults-on')
+
+ when:
+ BuildResult result = runner.withArguments(
+ ['inspectNativeClasspath', '-PfixtureTraceDirectory=recorded', '--stacktrace']).forwardOutput().buildAndFail()
+
+ then:
+ result.output.contains('which an image cannot read metadata from')
+ }
+
void 'an application that builds an image and turns invokedynamic off fails the build with the reason'() {
given:
GradleRunner runner = setupTestResourceProject('native-defaults-on')
diff --git a/grails-gradle/plugins/src/test/resources/test-projects/native-defaults-on/build.gradle b/grails-gradle/plugins/src/test/resources/test-projects/native-defaults-on/build.gradle
index eb6be4900a4..edbade1fc1f 100644
--- a/grails-gradle/plugins/src/test/resources/test-projects/native-defaults-on/build.gradle
+++ b/grails-gradle/plugins/src/test/resources/test-projects/native-defaults-on/build.gradle
@@ -34,6 +34,24 @@ if (providers.gradleProperty('fixtureLateTaskIndy').present) {
}
}
+// -PfixtureTraceDirectory records the traced metadata somewhere else, and -PfixtureTraceRoot names the classpath
+// entry expected for it
+if (providers.gradleProperty('fixtureTraceDirectory').present) {
+ grails {
+ nativeMetadata {
+ outputDirectory = layout.projectDirectory.dir(providers.gradleProperty('fixtureTraceDirectory').get())
+ }
+ }
+}
+
+tasks.register('inspectNativeClasspath') {
+ def expected = layout.projectDirectory.dir(providers.gradleProperty('fixtureTraceRoot').getOrElse('src/native/resources'))
+ def classpath = graalvmNative.binaries.named('main').map { it.classpath }
+ doLast {
+ println "TRACED_METADATA_ON_CLASSPATH=${classpath.get().files.contains(expected.asFile)}"
+ }
+}
+
tasks.register('inspectDefaults') {
def indyOption = providers.provider {
Map options = project.tasks.named('compileGroovy', GroovyCompile).get().groovyOptions.optimizationOptions
From ab7e20cb06ddf9c13fec7fecbfd6cfa46ef1a490 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 16:13:18 -0800
Subject: [PATCH 20/78] Call GrailsWebRequest directly when resolving a MIME
type
DefaultMimeTypeResolver is statically compiled, but Groovy compiles a default argument
dynamically even so: the methods without a request called GrailsWebRequest.lookup()
through invokedynamic. Binding a command object and resolving a view both go through
them, so in a native image they needed a reflection hint or a trace, and an error page
rendered through a view can never be traced, since the trace fails on an error.
Written out as overloads, they call it directly.
---
.../web/mime/DefaultMimeTypeResolver.groovy | 27 +++++++-
.../mime/DefaultMimeTypeResolverSpec.groovy | 69 +++++++++++++++++++
2 files changed, 94 insertions(+), 2 deletions(-)
create mode 100644 grails-mimetypes/src/test/groovy/org/grails/web/mime/DefaultMimeTypeResolverSpec.groovy
diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/DefaultMimeTypeResolver.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/DefaultMimeTypeResolver.groovy
index 325367c4436..23ac2ac83a4 100644
--- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/DefaultMimeTypeResolver.groovy
+++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/DefaultMimeTypeResolver.groovy
@@ -33,6 +33,29 @@ import org.grails.web.servlet.mvc.GrailsWebRequest
@CompileStatic
class DefaultMimeTypeResolver implements MimeTypeResolver {
+ /**
+ * Resolve the {@link grails.web.mime.MimeType} to be used for the response of the current request. Written out, as
+ * is {@link #resolveRequestMimeType()}, because Groovy compiles a default argument dynamically even in a statically
+ * compiled class, which in a native image needs a reflection hint that binding a command object and resolving a
+ * view would otherwise depend on.
+ *
+ * @return the {@link grails.web.mime.MimeType}
+ */
+ @Override
+ MimeType resolveResponseMimeType() {
+ resolveResponseMimeType(GrailsWebRequest.lookup())
+ }
+
+ /**
+ * Resolve the {@link MimeType} to be used for the request of the current request.
+ *
+ * @return the {@link MimeType}
+ */
+ @Override
+ MimeType resolveRequestMimeType() {
+ resolveRequestMimeType(GrailsWebRequest.lookup())
+ }
+
/**
* Resolve the {@link grails.web.mime.MimeType} to be used for the response, typically established from the ACCEPT header
*
@@ -40,7 +63,7 @@ class DefaultMimeTypeResolver implements MimeTypeResolver {
* @return the {@link grails.web.mime.MimeType}
*/
@Override
- MimeType resolveResponseMimeType(GrailsWebRequest webRequest = GrailsWebRequest.lookup()) {
+ MimeType resolveResponseMimeType(GrailsWebRequest webRequest) {
if (webRequest != null) {
return HttpServletResponseExtension.getMimeType(webRequest.response)
}
@@ -54,7 +77,7 @@ class DefaultMimeTypeResolver implements MimeTypeResolver {
* @return the {@link MimeType}
*/
@Override
- MimeType resolveRequestMimeType(GrailsWebRequest webRequest = GrailsWebRequest.lookup()) {
+ MimeType resolveRequestMimeType(GrailsWebRequest webRequest) {
if (webRequest != null) {
final allMimeTypes = HttpServletRequestExtension.getMimeTypes(webRequest.request)
if (allMimeTypes) {
diff --git a/grails-mimetypes/src/test/groovy/org/grails/web/mime/DefaultMimeTypeResolverSpec.groovy b/grails-mimetypes/src/test/groovy/org/grails/web/mime/DefaultMimeTypeResolverSpec.groovy
new file mode 100644
index 00000000000..88a92e9b0e5
--- /dev/null
+++ b/grails-mimetypes/src/test/groovy/org/grails/web/mime/DefaultMimeTypeResolverSpec.groovy
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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
+ *
+ * https://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 org.grails.web.mime
+
+import org.springframework.mock.web.MockHttpServletRequest
+import org.springframework.mock.web.MockHttpServletResponse
+import org.springframework.mock.web.MockServletContext
+import org.springframework.web.context.request.RequestContextHolder
+import spock.lang.Specification
+
+import org.grails.web.servlet.mvc.GrailsWebRequest
+
+class DefaultMimeTypeResolverSpec extends Specification {
+
+ private final DefaultMimeTypeResolver resolver = new DefaultMimeTypeResolver()
+
+ void cleanup() {
+ RequestContextHolder.resetRequestAttributes()
+ }
+
+ void 'without a current request nothing is resolved'() {
+ expect:
+ resolver.resolveResponseMimeType() == null
+ resolver.resolveRequestMimeType() == null
+ resolver.resolveResponseMimeType(null) == null
+ resolver.resolveRequestMimeType(null) == null
+ }
+
+ void 'the current request is the one resolved'() {
+ given:
+ def request = new MockHttpServletRequest(new MockServletContext())
+ request.addHeader('Accept', 'application/json')
+ request.contentType = 'application/xml'
+ def webRequest = new GrailsWebRequest(request, new MockHttpServletResponse(), request.servletContext)
+ RequestContextHolder.setRequestAttributes(webRequest)
+
+ expect: 'the same as naming it'
+ resolver.resolveResponseMimeType().name == resolver.resolveResponseMimeType(webRequest).name
+ resolver.resolveRequestMimeType().name == resolver.resolveRequestMimeType(webRequest).name
+
+ and:
+ resolver.resolveResponseMimeType(webRequest) != null
+ resolver.resolveRequestMimeType(webRequest).extension == 'xml'
+ }
+
+ void 'the methods that take no request are compiled to call GrailsWebRequest directly, which needs no reflection hint'() {
+ given: 'a default argument, which this replaces, is compiled dynamically even in a statically compiled class'
+ def bytes = DefaultMimeTypeResolver.getResourceAsStream('DefaultMimeTypeResolver.class').bytes
+
+ expect: 'a direct call names the method and its descriptor in the constant pool, where a dynamic one has only the name'
+ new String(bytes, 'ISO-8859-1').contains('()Lorg/grails/web/servlet/mvc/GrailsWebRequest;')
+ }
+}
From 637a737f9da4ee5a33ffac952de727e35819c862 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 16:13:18 -0800
Subject: [PATCH 21/78] Register HttpMethod for the comparison binding a
command object makes
Binding a command object compares the request's HttpMethod with POST. Groovy's ==
calls compareTo on a Comparable unless the two are the same instance, so it reaches
compareTo reflectively for every method but POST, and a trace that only submits forms
never records it. A GET or QUERY then failed in a native image.
---
.../grails/controllers/aot/ControllerRuntimeHints.java | 6 +++++-
.../controllers/aot/ControllerRuntimeHintsSpec.groovy | 6 ++++++
2 files changed, 11 insertions(+), 1 deletion(-)
diff --git a/grails-controllers/src/main/groovy/org/apache/grails/controllers/aot/ControllerRuntimeHints.java b/grails-controllers/src/main/groovy/org/apache/grails/controllers/aot/ControllerRuntimeHints.java
index d8aacb80b36..e22e67250a5 100644
--- a/grails-controllers/src/main/groovy/org/apache/grails/controllers/aot/ControllerRuntimeHints.java
+++ b/grails-controllers/src/main/groovy/org/apache/grails/controllers/aot/ControllerRuntimeHints.java
@@ -25,6 +25,7 @@
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
+import org.springframework.http.HttpMethod;
import grails.artefact.Controller;
import grails.artefact.controller.support.AllowedMethodsHelper;
@@ -69,7 +70,10 @@ public class ControllerRuntimeHints implements RuntimeHintsRegistrar {
ResponseRenderer.class,
// a view asking who is logged in reaches the request's principal, and Groovy makes that
// call on the interface rather than the implementation the container supplies
- Principal.class
+ Principal.class,
+ // Groovy's == calls compareTo on a Comparable unless the two are the same instance, so binding a command
+ // object reaches this for every method but POST, and a trace that only submits forms never records it
+ HttpMethod.class
};
/**
diff --git a/grails-controllers/src/test/groovy/org/apache/grails/controllers/aot/ControllerRuntimeHintsSpec.groovy b/grails-controllers/src/test/groovy/org/apache/grails/controllers/aot/ControllerRuntimeHintsSpec.groovy
index 32bf2ccba48..d1678f35b9b 100644
--- a/grails-controllers/src/test/groovy/org/apache/grails/controllers/aot/ControllerRuntimeHintsSpec.groovy
+++ b/grails-controllers/src/test/groovy/org/apache/grails/controllers/aot/ControllerRuntimeHintsSpec.groovy
@@ -23,6 +23,7 @@ import grails.artefact.controller.support.AllowedMethodsHelper
import org.springframework.aot.hint.MemberCategory
import org.springframework.aot.hint.RuntimeHints
import org.springframework.aot.hint.TypeReference
+import org.springframework.http.HttpMethod
import spock.lang.Specification
/**
@@ -52,6 +53,11 @@ class ControllerRuntimeHintsSpec extends Specification {
registered(AllowedMethodsHelper)
}
+ void 'the comparison of HTTP methods binding a command object reaches is registered'() {
+ expect: 'Groovy compares two different methods with compareTo, so a trace that only submits forms never records it'
+ registered(HttpMethod)
+ }
+
void 'the controller trait Groovy dispatches through is registered'() {
expect:
registered(grails.artefact.Controller)
From 18e67d2e34286713828da964ff2d36f5efd7ead7 Mon Sep 17 00:00:00 2001
From: Scott Murphy Heiberg
Date: Thu, 5 Nov 2026 16:24:51 -0800
Subject: [PATCH 22/78] Let traceNativeMetadata make requests with any method
and body
paths are asked for with GET and forms are posted as forms, so a trace could not reach
an action restricted to QUERY, or what binds a JSON body or writes a JSON response.
requests makes a request as it is declared, after the forms and in their session:
requests = [[method: 'QUERY', path: '/book/search', contentType: 'application/json',
body: '{"title": "Grails"}', accept: 'application/json']]
One that does not name its method and path, or that names anything else, fails the
trace rather than recording something other than what was meant.
---
.../en/guide/deployment/deploymentAot.adoc | 20 ++++-
.../theWebLayer/urlmappings/mappingHTTP.adoc | 2 +-
.../plugin/aot/NativeMetadataExtension.groovy | 9 +++
.../plugin/aot/TraceNativeMetadataTask.groovy | 59 ++++++++++++++-
.../plugin/core/GrailsGradlePlugin.groovy | 2 +
.../aot/TraceNativeMetadataTaskSpec.groovy | 73 +++++++++++++++++++
.../gradle/plugin/aot/TracedRunFixture.groovy | 5 +-
7 files changed, 165 insertions(+), 5 deletions(-)
diff --git a/grails-doc/src/en/guide/deployment/deploymentAot.adoc b/grails-doc/src/en/guide/deployment/deploymentAot.adoc
index 36c8afee8aa..2fcfc298733 100644
--- a/grails-doc/src/en/guide/deployment/deploymentAot.adoc
+++ b/grails-doc/src/en/guide/deployment/deploymentAot.adoc
@@ -147,6 +147,24 @@ The result is merged into `src/native/resources/META-INF/native-image`, alongsid
`paths` are asked for. `forms` are asked for *and submitted*: the page is read, the fields the form declares are filled in, and they are posted to the action the form names. Submitting matters separately from rendering, because binding a form is a different half of the framework from rendering one — and it is the half that converts. A checkbox arrives as a string and lands on a boolean property, so a form submitted without one never asks the conversion service anything, and the image is built without the answer.
+==== Other methods and bodies
+
+`paths` are asked for with `GET` and `forms` are posted as forms, which reaches neither an action restricted to another method, such as `QUERY`, nor what binds a JSON body or writes a JSON response. `requests` makes a request as it is declared, after the forms and in their session:
+
+[source,groovy]
+----
+grails {
+ nativeMetadata {
+ requests = [
+ [method: 'QUERY', path: '/book/search', contentType: 'application/json', body: '{"title": "Grails"}', accept: 'application/json'],
+ [method: 'DELETE', path: '/book/1']
+ ]
+ }
+}
+----
+
+Each names its `method` and `path`, and may name its `contentType`, `body` and `accept`. A request that does not, or that names anything else, fails the trace, as one that answers with an error does.
+
==== Pages behind a login
Forms are submitted before paths are asked for, whichever order they appear in the configuration, and the session a form establishes is carried through the rest of the trace. That is what makes a protected page traceable: list its login form, and the pages named in `paths` are reached as a signed-in user.
@@ -191,4 +209,4 @@ NOTE: The agent ships with GraalVM rather than with a JDK, and it must trace the
WARNING: The agent records only what ran. A path that is not listed is not covered, and it will be missing in the way that only appears when somebody uses that page. Treat the list as the coverage it is, and extend it as the application grows.
-The trace sends `GET` and form `POST` requests, so it cannot reach an action restricted to `QUERY`. What the framework does to bind a command object is the same whichever method reaches it, so tracing another action that binds one covers it, and the classes of the application are written down without a trace. The trace also fails on a request that answers with an error, so what the framework does to answer one is registered for you where it writes one itself, as it does for an exception written as an RFC 9457 problem with `grails.exceptionresolver.problemDetails`.
+The trace fails on a request that answers with an error, so what the framework does to answer one is registered for you where it writes one itself, as it does for an exception written as an RFC 9457 problem with `grails.exceptionresolver.problemDetails`.
diff --git a/grails-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc b/grails-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc
index 91ff1ecd0f0..149cdc8c34d 100644
--- a/grails-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc
+++ b/grails-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc
@@ -58,6 +58,6 @@ A JSON body is bound to the command object the action takes, and a form-encoded
Other things to know about `QUERY`:
* A browser cannot send it from an HTML form. Call it from JavaScript or another HTTP client.
-* `traceNativeMetadata` cannot send it. For a native image, trace another action that binds a command object, as the <> describes.
+* For a native image, `traceNativeMetadata` reaches it through `requests`, as the <> describes.
* `grails-openapi` leaves these mappings out of the document it generates, and logs each one, because the OpenAPI versions it writes have no operation for the method.
* The Spring Security plugin accepts `QUERY` requests. An application that configures Spring Security with its own configuration DSL instead gets a `StrictHttpFirewall`, which rejects the method until it is added with `setAllowedHttpMethods`, and whichever one it uses, `CsrfFilter` asks a `QUERY` for a token where CSRF protection is on.
diff --git a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/NativeMetadataExtension.groovy b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/NativeMetadataExtension.groovy
index f92f355494d..956b683c07a 100644
--- a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/NativeMetadataExtension.groovy
+++ b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/NativeMetadataExtension.groovy
@@ -45,6 +45,15 @@ abstract class NativeMetadataExtension {
*/
abstract ListProperty getForms()
+ /**
+ * Requests neither a path nor a form can make: a method other than GET and POST, such as QUERY, or a body that
+ * is not a form, such as JSON. Each names its {@code method} and {@code path}, and may name its
+ * {@code contentType}, {@code body} and {@code accept}.
+ *
+ * @since 9.1
+ */
+ abstract ListProperty
*
+ *
A request neither of those can make, with another method or with a body that is not a form, is
+ * declared whole. An action restricted to QUERY answers nothing else, and what writes a JSON response
+ * runs only for a client that asks for one:
Written to the application's sources rather than to the build directory: what an image was
* built from should be reviewable, and a trace is only as good as the paths someone thought of.
*
@@ -94,6 +107,9 @@ import org.gradle.work.DisableCachingByDefault
@DisableCachingByDefault(because = 'Records what a run of the application did, which is not an output of its inputs')
abstract class TraceNativeMetadataTask extends DefaultTask {
+ /** What a request in {@link #getRequests()} may name, so that a misspelt one is not silently left out. */
+ private static final Set REQUEST_KEYS = ['method', 'path', 'contentType', 'body', 'accept'] as Set
+
/** How the agent is asked for, and the only way its output can be merged with what is there. */
private static final String AGENT = 'native-image-agent'
@@ -147,6 +163,14 @@ abstract class TraceNativeMetadataTask extends DefaultTask {
@Input
abstract ListProperty getForms()
+ /**
+ * Requests to make as they are declared.
+ *
+ * @since 9.1
+ */
+ @Input
+ abstract ListProperty